Skip to content

Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.

Merge post_platforms into posts (#397)

Paulo Castellanocb73e41e04ba
diff --git a/.ai/rules/google-business.md b/.ai/rules/google-business.md
index ba23713b9..91e80a812 100644
--- a/.ai/rules/google-business.md
+++ b/.ai/rules/google-business.md
@@ -26,7 +26,7 @@ ReconcileGoogleBusinessPost must call ConnectionVerifier::verify() after a Token
Publish and verify require both location_id (v4) and location_name (v1) via GoogleBusinessResourceName::connectedLocation().
## Local Posts 401 after a live BI verify does not expire the account
-retryAfterExpiredToken calls ConnectionVerifier::verify() then retries fetchRemote. markAsTokenExpired only when verify() itself throws TokenExpiredException. If BI verify succeeds and Local Posts still 401s, deferOrGiveUp without disconnecting — the token still works for the house verify. ReconcileGoogleBusinessPosts only dispatches enabled() pending_review rows. ReconcileGoogleBusinessPost::handle() giveUps immediately when socialAccount is null — disconnect nulls the FK and fetchRemote would TypeError until the 24h ceiling.
+retryAfterExpiredToken calls ConnectionVerifier::verify() then retries fetchRemote. markAsTokenExpired only when verify() itself throws TokenExpiredException. If BI verify succeeds and Local Posts still 401s, deferOrGiveUp without disconnecting — the token still works for the house verify. ReconcileGoogleBusinessPosts only dispatches Google Business posts in pending_review with a platform_post_id. ReconcileGoogleBusinessPost::handle() giveUps immediately when socialAccount is null — disconnect nulls the FK and fetchRemote would TypeError until the 24h ceiling.
## Pre-2.0 scheduled targets skip the publish-time media recheck
-post_platforms.scheduled_before_media_checks is set only by migration 2026_10_06_112101 on targets that were pending/publishing/retrying on a scheduled, pending approval or publishing post at deploy. failForInvalidMedia() returns early for them so they publish what main published (main had no publish-time media check; publishers truncate to first/take(n) and networks accept wider video ratios). Never set it from app code; new posts, drafts and failed targets always get the 2.0 recheck. Remove the column once no marked unpublished target is left.
+posts.scheduled_before_media_checks (copied from post_platforms when posts and their destinations were merged) is set only by migration 2026_10_06_112101 on targets that were pending/publishing/retrying on a scheduled, pending approval or publishing post at deploy. failForInvalidMedia() returns early for them so they publish what main published (main had no publish-time media check; publishers truncate to first/take(n) and networks accept wider video ratios). Never set it from app code; new posts, drafts and failed targets always get the 2.0 recheck. Remove the column once no marked unpublished target is left.
diff --git a/.ai/rules/index.md b/.ai/rules/index.md
index 718a3634c..cfa50321f 100644
--- a/.ai/rules/index.md
+++ b/.ai/rules/index.md
@@ -15,11 +15,11 @@ Before planning or editing, find the row whose globs match the file's path and r
| resources/js/** | .ai/rules/js.md |
| app/Actions/Media/**, app/Models/Media.php | .ai/rules/media.md |
| app/Http/Middleware/App/HandleInertiaRequests.php | .ai/rules/middleware-app.md |
-| app/Jobs/PostHog/**, app/Models/PostPlatform.php, database/migrations/**, app/Models/SocialAccount.php | .ai/rules/migrations.md |
+| app/Jobs/PostHog/**, app/Models/Post.php, database/migrations/**, app/Models/SocialAccount.php | .ai/rules/migrations.md |
| app/Jobs/PostHog/** | .ai/rules/post-hog.md |
| app/Enums/PostPlatform/ContentType.php | .ai/rules/post-platform.md |
| app/Actions/Post/FinalizePostPublication.php, app/Jobs/PublishPost.php, app/Actions/Post/UpdatePost.php, app/Actions/Post/** | .ai/rules/post.md |
| app/Enums/SocialAccount/Platform.php | .ai/rules/social-account.md |
-| app/Services/Social/GoogleBusinessPublisher.php, app/Support/Social/GoogleBusinessDerivativeCleaner.php, app/Actions/Post/DeletePost.php, app/Actions/Post/UpdatePost.php, app/Support/Social/AbandonGoogleBusinessReview.php, app/Actions/Workspace/PurgeWorkspace.php, app/Http/Controllers/Auth/SocialController.php, app/Support/Social/ThreadProgress.php, app/Support/ThreadReplies.php, app/Services/Social/Concerns/PublishesThreads.php, app/Services/Social/FacebookPublisher.php, app/Services/Social/InstagramPublisher.php | .ai/rules/social.md |
+| app/Services/Social/GoogleBusinessPublisher.php, app/Support/Social/GoogleBusinessDerivativeCleaner.php, app/Actions/Post/DeletePost.php, app/Actions/Post/UpdatePost.php, app/Actions/Workspace/PurgeWorkspace.php, app/Http/Controllers/Auth/SocialController.php, app/Support/Social/ThreadProgress.php, app/Support/ThreadReplies.php, app/Services/Social/Concerns/PublishesThreads.php, app/Services/Social/FacebookPublisher.php, app/Services/Social/InstagramPublisher.php | .ai/rules/social.md |
| app/Support/PostPlatformMetaRules.php | .ai/rules/support.md |
| app/Mcp/Tools/** | .ai/rules/tools.md |
diff --git a/.ai/rules/jobs.md b/.ai/rules/jobs.md
index faada987e..32a92fc54 100644
--- a/.ai/rules/jobs.md
+++ b/.ai/rules/jobs.md
@@ -8,7 +8,7 @@ paths:
# Jobs
## GBP reconcile must settle permanent API errors
-ReconcileGoogleBusinessPost must not rethrow GoogleBusinessPublishException. Permanent categories (NOT_FOUND, PERMISSION_DENIED, INVALID_ARGUMENT, Unknown) reject the target immediately and call FinalizePostPublication. Only ServerError, RateLimit, and ConnectionException defer until REVIEW_CEILING_HOURS. Throwing leaves last_reconciled_at stale, the 5-minute sweep re-dispatches, RecoverStuckPosts treats PendingReview as still-active, and the post sticks forever. failed() is the safety net if the worker dies mid-review — it must deferOrGiveUp (respect the 24h ceiling), never giveUp immediately. Job $timeout must exceed HasSocialHttpClient's 120s HTTP timeout. RecoverStuckPosts may only fail PendingReview after the same 24h ceiling timed from submitted_at — never created_at (a scheduled draft can be days old before it enters review) and never the 1h publishing timeout. Reconcile must refresh-and-retry on TokenExpiredException the same way PublishToSocialPlatform does; if verify() itself dies, mark the social account token-expired before deferring. If Business Information verify succeeds and Local Posts still 401s, defer without markAsTokenExpired — the token is still valid for the house verify. A 401 must not sit in review for 24h while a refresh would have settled it. JPEG derivatives stay on disk while LocalPostState is Processing/Scheduled so Google can fetch sourceUrl; settle(), RecoverStuckPosts' 1h publishing timeout, a disabled GBP target, and the expired-review path prune them. Reconcile must giveUp immediately when socialAccount is null (disconnect nulls the FK and would TypeError in fetchRemote). When RecoverStuckPosts finishes a post (no still-active targets), call FinalizePostPublication so the owner is notified — do not mark the post Failed/Published by hand. Never compare raw PROCESSING/SCHEDULED/LIVE strings — use App\Enums\GoogleBusiness\LocalPostState.
+ReconcileGoogleBusinessPost must not rethrow GoogleBusinessPublishException. Permanent categories (NOT_FOUND, PERMISSION_DENIED, INVALID_ARGUMENT, Unknown) reject the target immediately and call FinalizePostPublication. Only ServerError, RateLimit, and ConnectionException defer until REVIEW_CEILING_HOURS. Throwing leaves last_reconciled_at stale, the 5-minute sweep re-dispatches, RecoverStuckPosts treats PendingReview as still-active, and the post sticks forever. failed() is the safety net if the worker dies mid-review — it must deferOrGiveUp (respect the 24h ceiling), never giveUp immediately. Job $timeout must exceed HasSocialHttpClient's 120s HTTP timeout. RecoverStuckPosts may only fail PendingReview after the same 24h ceiling timed from submitted_at — never created_at (a scheduled draft can be days old before it enters review) and never the 1h publishing timeout. Reconcile must refresh-and-retry on TokenExpiredException the same way PublishToSocialPlatform does; if verify() itself dies, mark the social account token-expired before deferring. If Business Information verify succeeds and Local Posts still 401s, defer without markAsTokenExpired — the token is still valid for the house verify. A 401 must not sit in review for 24h while a refresh would have settled it. JPEG derivatives stay on disk while LocalPostState is Processing/Scheduled so Google can fetch sourceUrl; settle(), RecoverStuckPosts' 1h publishing timeout and the expired-review path prune them. Reconcile must giveUp immediately when socialAccount is null (disconnect nulls the FK and would TypeError in fetchRemote). When RecoverStuckPosts settles a post's publication, call FinalizePostPublication so the owner is notified — do not mark the post Failed/Published by hand. Never compare raw PROCESSING/SCHEDULED/LIVE strings — use App\Enums\GoogleBusiness\LocalPostState.
## Notifications are email only
There is no in-app notification system: the `notifications` table, bell, broadcast event, presence heartbeat and WorkspaceUserChannel were removed in September 2026. SendNotification(user, type, mailable) only sends the Mailable, gated by User::wantsEmailFor(). User uses RoutesNotifications, not Notifiable (no database channel). A new post note (not an edit, delete or reaction) emails every workspace member except its author (NotifyPostNoteAdded → PostNoteAdded, Type::PostNoteAdded); there are no @mentions in notes. Do not reintroduce an in-app channel.
diff --git a/.ai/rules/media.md b/.ai/rules/media.md
index 2af2ccb34..60322a441 100644
--- a/.ai/rules/media.md
+++ b/.ai/rules/media.md
@@ -7,10 +7,10 @@ paths:
# Media
## Media rows have one owner; write via SyncOwnedMedia, delete via DeleteOwnedMedia
-Every media row has exactly one owner (post_id, idea_id, rss_feed_item_id, a workspace temporary upload, or a mediable logo/avatar); the Media saving guard enforces it and owner FKs are restrictOnDelete, so never cascade media. posts.media / ideas.media are written only by SyncOwnedMedia (inside MediaCopyBatch::run) and by AdoptWorkspaceLibrary::adopt (the one-off library migration). Rows are deleted through DeleteOwnedMedia (locked in id order, files removed after commit by DeleteOrphanedMediaFiles); the only direct deleters are PurgeUserAccess (user avatars, files after commit) and HasMedia::clearMediaCollection (logo/avatar replacement). A temporary upload is adopted (moved) once; every later use copies it. The same holds for rows of an owner the batch deletes before commit (`MediaCopyBatch::releaseOwner`, used by RecoverEmptyDraft). The library collection ('assets') is read only by the adoption (media:adopt-library / release:trypost-2) — no code may write it; the fold_legacy_workspace_media_into_library migration moved the legacy 'ai-generated' workspace rows into it once.
+Every media row has exactly one owner (post_id, idea_id, rss_feed_item_id, a workspace temporary upload, or a mediable logo/avatar); the Media saving guard enforces it and owner FKs are restrictOnDelete, so never cascade media. posts.media / ideas.media are written only by SyncOwnedMedia (inside MediaCopyBatch::run) and by AdoptWorkspaceLibrary::adopt (the one-off library migration). Rows are deleted through DeleteOwnedMedia (locked in id order, files removed after commit by DeleteOrphanedMediaFiles); the only direct deleters are PurgeUserAccess (user avatars, files after commit) and HasMedia::clearMediaCollection (logo/avatar replacement). A temporary upload is adopted (moved) once; every later use copies it. The same holds for rows of an owner the batch deletes before commit (`MediaCopyBatch::releaseOwner`, used by RecoverEmptyDraft). The library collection ('assets') is read only by the adoption (media:adopt-library) — no code may write it; the fold_legacy_workspace_media_into_library migration moved the legacy 'ai-generated' workspace rows into it once.
## A save never resolves another workspace's media
Every save resolves media ids and upload tokens within the owner's workspace (ResolveWorkspaceMedia); only the owner's own stored items and same-workspace duplicate/recovery items pass through without a row. media:adopt-library relies on this: it computes the library rows other workspaces reference once per adoption window and trusts that map in the locked delete, which is only safe if no save can create a new cross-workspace reference.
## Thread reply media is owned by the post; write target meta before SyncOwnedMedia
-Media in meta.thread_replies[*].media are medias rows owned by the post (post_id), like posts.media. SyncOwnedMedia::execute reads the post's stored thread replies, resolves/adopts/copies their items, writes the canonical items back to the PostPlatform meta, and keeps those rows when deleting the post's unused rows. So any caller that changes a target's meta must save it BEFORE calling SyncOwnedMedia (UpdatePost::updateChannelPost does), or new reply uploads are never adopted and old reply rows are not released.
+Media in meta.thread_replies[*].media are medias rows owned by the post (post_id), like posts.media. SyncOwnedMedia::execute reads the post's stored thread replies, resolves/adopts/copies their items, writes the canonical items back to the post's meta, and keeps those rows when deleting the post's unused rows. So any caller that changes the post's meta must save it BEFORE calling SyncOwnedMedia (UpdatePost::updateChannelPost does), or new reply uploads are never adopted and old reply rows are not released.
diff --git a/.ai/rules/migrations.md b/.ai/rules/migrations.md
index 5f4d3bbc5..607a168fd 100644
--- a/.ai/rules/migrations.md
+++ b/.ai/rules/migrations.md
@@ -1,7 +1,7 @@
---
paths:
- 'app/Jobs/PostHog/**'
- - app/Models/PostPlatform.php
+ - app/Models/Post.php
- 'database/migrations/**'
- app/Models/SocialAccount.php
---
@@ -9,7 +9,7 @@ paths:
# Migrations
## Keep publishing activity lookup scoped and minimal
-Account publishing activity must scope through indexed account workspace/post IDs before ordering PostPlatform rows. Its migration only adds conventional Laravel indexes and must not change PostPlatform.published_at precision. PostHog snapshot retries must keep progressive backoff so transient outages do not exhaust attempts immediately.
+Account publishing activity must scope through the account's workspaces (index posts(workspace_id, publish_status, published_at)) before ordering posts. Its migration only adds conventional Laravel indexes and must not change posts.published_at precision. PostHog snapshot retries must keep progressive backoff so transient outages do not exhaust attempts immediately.
## Enum-backed column defaults use the enum
Columns backed by a PHP enum are plain `string` columns (never `$table->enum()`, which breaks PG/MySQL parity), cast to the enum on the model. Their migration default must reference the enum, not a literal: `->default(Theme::DEFAULT->value)` (give the enum a `DEFAULT` constant, like `App\Enums\User\Locale::DEFAULT`), and the model's `$attributes` uses the same constant. If an enum is later deleted, the migrations that import it must be edited in the same change (as done for ImageStyle in 2026_05_07_231552).
diff --git a/.ai/rules/post-hog.md b/.ai/rules/post-hog.md
index acdaf1df5..a4cd03ceb 100644
--- a/.ai/rules/post-hog.md
+++ b/.ai/rules/post-hog.md
@@ -6,4 +6,4 @@ paths:
# Post Hog
## Serialize account publishing snapshots at the final send
-Publishing activity uses SyncAccountPublishingActivity with per-account debounce and overlap protection. It must re-query the latest confirmed PostPlatform when it executes and send the group update in that same job; routing the snapshot through SendEvent can reorder payloads and regress the account's last publication. The backfill command must reuse this job.
+Publishing activity uses SyncAccountPublishingActivity with per-account debounce and overlap protection. It must re-query the latest confirmed published post (publish_status published) when it executes and send the group update in that same job; routing the snapshot through SendEvent can reorder payloads and regress the account's last publication. The backfill command must reuse this job.
diff --git a/.ai/rules/post.md b/.ai/rules/post.md
index 1dcb773cd..3356a6c48 100644
--- a/.ai/rules/post.md
+++ b/.ai/rules/post.md
@@ -9,16 +9,16 @@ paths:
# Post
## FinalizePostPublication is the only post settler
-handle() takes the Post, not a dummy PostPlatform. Every path that can finish the last enabled target must call it: PublishToSocialPlatform, ReconcileGoogleBusinessPost, RecoverStuckPosts, PublishPost::failed, and AbandonGoogleBusinessReview (disconnect / disable during pending_review). No enabled targets on a draft or scheduled post is a no-op — do not mark the post published. A Publishing post with no enabled targets is abandoned in-flight: mark it Failed so it does not sit non-editable forever. Do not mark the post Published / PartiallyPublished / Failed by hand outside Finalize. The one exception is the one-off release split (posts:split-legacy-active), which derives already-settled statuses quietly, with no events or notifications.
+handle() takes the Post. Every path that can finish the post's publication must call it: PublishToSocialPlatform, ReconcileGoogleBusinessPost, RecoverStuckPosts, PublishPost (also for a post without a channel) and PublishPost::failed. It settles from `posts.publish_status` (published → Published; failed/rejected → Failed); a post without a channel whose publication is not finished is a no-op unless it is Publishing, which becomes Failed (with `posts.errors.choose_channel` when it still has a destination snapshot) so it does not sit non-editable forever. Do not mark the post Published / Failed by hand outside Finalize. Finalize keeps the publish time the publisher wrote (`markAsPublished()` only fills `published_at` when it is empty).
## Finalize is idempotent once the post is settled
-handle() lockForUpdates the post and returns without notifying when status is already Published, PartiallyPublished, or Failed (Status::isSettled()). RecoverStuckPosts and ReconcileGoogleBusinessPost can both finish the last target at the 24h ceiling; the second call must not send a second email. Dispatch SendNotification only after the transaction commits.
+handle() lockForUpdates the post and returns without notifying when status is already Published or Failed (Status::isSettled()). RecoverStuckPosts and ReconcileGoogleBusinessPost can both finish the post at the 24h ceiling; the second call must not send a second email. Dispatch SendNotification only after the transaction commits.
-## Unchecked destination abandons pending_review with target_disabled
-Abandoning a GBP pending_review because the post destination was unchecked uses posts.errors.target_disabled.
+## Google Business reviews end through reconcile or the 24h ceiling
+A GBP pending_review ends when ReconcileGoogleBusinessPost settles it or when RecoverStuckPosts::failExpiredReview rejects it at the 24h ceiling (prunes the JPEG, then Finalize). Disconnecting a channel deletes its posts, so no review is left without an account.
-## One enabled destination per new post
-New draft/scheduled posts are independent per social account: use CreatePosts/CreateChannelPost, with one enabled PostPlatform per Post; do not revive grouped CreatePost/SyncPostPlatforms writes. Editing uses UpdatePost and may change content type within the same account, never the social account. posts:split-legacy-active (release:trypost-2) splits editable and settled multi-target posts, moving each enabled target to its own post with the status of that target; only in-flight aggregates and settled posts with an unfinished target stay grouped. A split original may retain disabled placeholder targets, so count enabled targets when deciding if it is editable.
+## One destination per post, stored on the post
+A post has at most one destination, stored on the post itself (`posts.social_account_id`, `platform`, `content_type`, `meta`, and the publication fields). Create through CreatePosts/CreateChannelPost; never reintroduce a targets table or grouped writes. Editing uses UpdatePost and may change content type within the same account, never the social account. A legacy draft without a channel (platform null) stays editable as a draft (content, media, labels) and is turned into a channel post only through RecoverEmptyDraft; scheduling or publishing it fails with posts.errors.choose_channel.
## No per-destination validation inside a repurpose batch
ProcessRepurposeItem creates all posts of one run in a single all-or-nothing transaction (CreatePosts batch + SyncOwnedMedia). Never add per-destination/per-platform validation inside CreateChannelPost or SyncOwnedMedia: one bad destination would roll back the whole run, and repurpose items are never retried. Destination health stays a publish-time failure (AGENTS.md "Repurpose account health"); platform rules belong in the FormRequests/CreatePosts validation for user-driven flows.
diff --git a/.ai/rules/social.md b/.ai/rules/social.md
index 4c4cdb172..49961f621 100644
--- a/.ai/rules/social.md
+++ b/.ai/rules/social.md
@@ -4,7 +4,6 @@ paths:
- app/Support/Social/GoogleBusinessDerivativeCleaner.php
- app/Actions/Post/DeletePost.php
- app/Actions/Post/UpdatePost.php
- - app/Support/Social/AbandonGoogleBusinessReview.php
- app/Actions/Workspace/PurgeWorkspace.php
- app/Http/Controllers/Auth/SocialController.php
- app/Support/Social/ThreadProgress.php
@@ -17,10 +16,10 @@ paths:
# Social
## GBP JPEG must outlive PROCESSING
-Google fetches Local Post sourceUrl after create while LocalPostState is Processing/Scheduled/Unspecified. Keep the JPEG derivative on disk until reconcile settle() or RecoverStuckPosts fails the target. Deleting in publish() finally races PHOTO_FETCH_FAILED. Live/Rejected on the create response may prune immediately. Path is deterministic: google-business-derivatives/{postPlatformId}.jpg. Wire values live on App\Enums\GoogleBusiness\LocalPostState — never compare raw PROCESSING/SCHEDULED strings. RecoverStuckPosts must prune the JPEG on the 1h Publishing/Pending/Retrying timeout (the worker can die after writing the file and before PendingReview), on a disabled GBP target (reconcile and the 24h ceiling skip `enabled=false`), and again on the 24h review ceiling. UpdatePost mass-updates `enabled=false` (observers never fire): abandon any GBP still in pending_review that is not in the kept set, then prune leftover JPEGs after commit. Disconnect deletes the channel's posts (`DeleteChannelPosts`) before the account delete and prunes their JPEGs, so no pending_review row is left with a null account. DeletePost and PurgeWorkspace must prune every Google Business PostPlatform JPEG before the row disappears — a user delete during pending_review or a workspace wipe would otherwise leak the file, and a DB cascade on post_platforms does not fire Eloquent observers.
+Google fetches Local Post sourceUrl after create while LocalPostState is Processing/Scheduled/Unspecified. Keep the JPEG derivative on disk until reconcile settle() or RecoverStuckPosts fails the post. Deleting in publish() finally races PHOTO_FETCH_FAILED. Live/Rejected on the create response may prune immediately. Path is deterministic: GoogleBusinessDerivativeCleaner::pathFor($post) = google-business-derivatives/{post id}.jpg. Wire values live on App\Enums\GoogleBusiness\LocalPostState — never compare raw PROCESSING/SCHEDULED strings. RecoverStuckPosts must prune the JPEG on the 1h Publishing/Pending/Retrying timeout (the worker can die after writing the file and before PendingReview) and again on the 24h review ceiling. Disconnect deletes the channel's posts (`DeleteChannelPosts`) before the account delete and prunes their JPEGs, so no pending_review row is left with a null account. DeletePost and PurgeWorkspace must prune every Google Business post JPEG before the row disappears — a user delete during pending_review or a workspace wipe would otherwise leak the file, and a DB cascade does not fire Eloquent observers.
## Thread checkpoints resume, never re-post
-Bluesky/Mastodon/X thread segments already live are checkpointed in post_platforms.error_context.thread_progress (ThreadProgress) after each segment, so any retry (incl. posts:retry, which keeps them) resumes from the next segment. A resume keeps the stored root hash: the root is the target's identity even if the same text would now hash differently. Never clear thread_progress on retry and never re-post a checkpointed segment. thread_reply_ids lists the reply ids so ImportExternalPosts skips TryPost's own replies.
+Bluesky/Mastodon/X thread segments already live are checkpointed in posts.error_context.thread_progress (ThreadProgress) after each segment, so any retry (incl. posts:retry, which keeps them) resumes from the next segment. A resume keeps the stored root hash: the root is the post's identity even if the same text would now hash differently. Never clear thread_progress on retry and never re-post a checkpointed segment. thread_reply_ids lists the reply ids so ImportExternalPosts skips TryPost's own replies.
## No server-side aspect ratio crop or meta.aspect_ratio
-Removed October 2026 by user decision: the Facebook and Instagram publishers send every image at its own ratio, and there is no `meta.aspect_ratio` (rule, enum, crop helper and composer radios are gone; migration 2026_10_04_202400 strips stored keys, except on IG feed / FB post targets that will publish without user action (pending/publishing/retrying on a scheduled, pending approval or publishing post), whose crop the one-off `posts:bake-aspect-ratio-crops` release step bakes into the post's media with main's crop math before dropping the key, so pre-2.0 scheduled posts publish the image they were planned with; drafts and failed targets are not baked, keep their original image and lose the key (owner decision 2026-10-06); `MediaOptimizer::cropToAspectRatio` exists only for that step). Instagram feed images outside 3:4–1.91:1 are caught at save by ContentTypeCompatibleWithMedia and fixed per image in the media editor; Facebook feed accepts any ratio. Stories still go through FitsImageToCanvas. Do not reintroduce a ratio selector or a publish-time crop.
+Removed October 2026 by user decision: the Facebook and Instagram publishers send every image at its own ratio, and there is no `meta.aspect_ratio` (rule, enum, crop helper and composer radios are gone; migration 2026_10_04_202400 strips stored keys; the one-off 2.0 release step that baked pending crops into the media was removed after TryPost 2.0). Instagram feed images outside 3:4–1.91:1 are caught at save by ContentTypeCompatibleWithMedia and fixed per image in the media editor; Facebook feed accepts any ratio. Stories still go through FitsImageToCanvas. Do not reintroduce a ratio selector or a publish-time crop.
diff --git a/.ai/rules/support.md b/.ai/rules/support.md
index a26e69c8f..8ef76a514 100644
--- a/.ai/rules/support.md
+++ b/.ai/rules/support.md
@@ -6,4 +6,4 @@ paths:
# Support
## Never use a cross-field Laravel rule (required_unless, required_if, etc.) for a single platform's conditional meta field
-`rules()` is shared by every platform via `platforms.*.meta.*` wildcards. Rules like `required_unless`/`required_if` are Laravel "implicit" rules — they validate even when the field itself is absent from the request. Adding one scoped in spirit to a single platform (e.g. `call_to_action.url` required_unless action_type is NONE/CALL, meant only for Google Business Profile) breaks every OTHER platform's create/update through web, API, and MCP, because their requests never send that field at all and the implicit rule still fires. The correct pattern (already used by Pinterest's `board_id`, Discord's `channel_id`): keep the field's `rules()` entry unconditional (`sometimes|nullable|...`), and enforce "required" semantics only in `requiredMetaViolation()`'s `match(true)` block, which is evaluated per the resolved `Platform` of the row being checked. This bug shipped once (fixed in commit 8887b3f3) and broke Pinterest/Discord/TikTok post updates — the task reviewer that approved the original `rules()` entry didn't catch it because it only reviewed Google Business's own test coverage, not sibling platforms'.
+`rules($prefix)` is shared by every platform (`meta.*` on a single post, `destinations.*.meta.*` in batches). Rules like `required_unless`/`required_if` are Laravel "implicit" rules — they validate even when the field itself is absent from the request. Adding one scoped in spirit to a single platform (e.g. `call_to_action.url` required_unless action_type is NONE/CALL, meant only for Google Business Profile) breaks every OTHER platform's create/update through web, API, and MCP, because their requests never send that field at all and the implicit rule still fires. The correct pattern (already used by Pinterest's `board_id`, Discord's `channel_id`): keep the field's `rules()` entry unconditional (`sometimes|nullable|...`), and enforce "required" semantics only in `requiredMetaViolation()`'s `match(true)` block, which is evaluated per the resolved `Platform` of the row being checked. This bug shipped once (fixed in commit 8887b3f3) and broke Pinterest/Discord/TikTok post updates — the task reviewer that approved the original `rules()` entry didn't catch it because it only reviewed Google Business's own test coverage, not sibling platforms'.
diff --git a/AGENTS.md b/AGENTS.md
index c66a636f6..5a31bde8a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -436,13 +436,10 @@ approval, failed, sent and imported) goes with its media. There is no orphaned
history — a post without a channel is a history that no longer exists.
- Quiet: no `post.deleted` webhook or notification per post.
-- A legacy post with another live, enabled target keeps that target and loses
- only this one (a Publishing post is re-settled through `FinalizePostPublication`).
+- It deletes by `posts.social_account_id`, without a workspace clause: a post
+ has one channel, so every post pointing at the account goes.
- Analytics publications stay and are only unlinked, never dismissed, so
reconnecting the same identity re-imports its recent posts once.
-- Orphans left by disconnects before this rule are removed once by the release
- script (`release:trypost-2`, step `posts:purge-orphaned`, in
- `app/Console/Commands/Scripts/`), through the same action.
## Member permissions and post approvals
@@ -488,11 +485,16 @@ publishes directly.
- A repurpose item created by a member who requires approval stays marked
Published while its posts are pending approval: the item records the hand-off to
the queue, not the network publication.
-- Approval emails go through `SendNotification` with `Type::Collaboration`.
- Requests email every approver except the requester, list only the posts still
- pending when the job runs and are dropped when none is; decisions are grouped
- per `post_group_id`, approver and requester by `NotifyApprovalDecision`
- (cache + one unique delayed job).
+- Approval emails go through `SendNotification` with `Type::Collaboration`, one
+ email per post (owner decision October 2026): posts created together for
+ several channels are separate posts, each approved on its own, so they are
+ never grouped by `post_group_id`. A request emails every approver except the
+ requester and is dropped when its post is no longer pending; a decision
+ (`NotifyApprovalDecision`) emails the requester once it commits and is dropped
+ when its post was deleted.
+- The published and failed emails (`FinalizePostPublication::notify()`) go to
+ every member of the workspace (owner decision October 2026; the owner is always
+ a member); each user's notification preferences still decide whether it is sent.
## UI locale (`users.locale`)
@@ -747,13 +749,52 @@ TryPost runs on **both PostgreSQL and MySQL**. Cloud runs PostgreSQL; a self-hos
- **JSON object key order is not preserved.** MySQL reorders object keys on storage (by length, then lexicographically); PostgreSQL keeps insertion order. Assert JSON read back from the database with `toEqual` (recursive, order-independent), never `toBe`/`assertSame`. Array *element* order is preserved on both.
- **`$table->timestamp()` tops out at 2038-01-19.** PostgreSQL has no such limit, so 2038-01-19 is the app's ceiling: nothing written to a `timestamp()` column may go past it — scheduled posts, expiry sentinels and test fixtures alike. `2037-12-31` reads as "far future" and works on both. Do not widen a column to escape the limit without a deliberate decision; it changes what self-hosted MySQL installs can store.
- **Raw query-builder reads carry no Eloquent cast**, so the driver's native shape leaks through: `DB::table(...)->value('some_bool')` is `true` on PostgreSQL and `1` on MySQL. Read through the model, or use `assertDatabaseHas`.
- - **Identifier quoting differs** — PostgreSQL emits `"post_platforms"`, MySQL emits backticks. Never match logged SQL (`DB::listen`) against a quoted identifier.
+ - **Identifier quoting differs** — PostgreSQL emits `"posts"`, MySQL emits backticks. Never match logged SQL (`DB::listen`) against a quoted identifier.
- **MySQL refuses to drop the only index backing a foreign key** (SQLSTATE `1553`). A migration `down()` that drops a unique whose leftmost prefix is an FK column must create a standalone index for that column first.
- **DDL implicitly commits**, which defeats `RefreshDatabase`'s rollback: schema changes made inside a test leak into the tests that follow. Keep them idempotent.
-## Per-Platform Post Meta (`PostPlatform.meta`)
-
-- All `platforms.*.meta` validation (the parent array rule AND every per-platform sub-key: TikTok `privacy_level`/flags, Pinterest `board_id`, Discord `channel_id`/`mentions`/`embeds`, etc.) lives in ONE place: `App\Support\PostPlatformMetaRules`.
+## One destination per post (`posts` carries its channel)
+
+A post has at most one channel, stored on the post row: `social_account_id`,
+`platform`, `content_type`, `meta`, the channel snapshot (`platform_name`,
+`platform_username`, `platform_avatar`) and the publication result
+(`publish_status`, `platform_post_id`, `platform_url`, `error_message`,
+`error_context`, `thread_reply_ids`, `submitted_at`, `last_reconciled_at`,
+`retry_at`, `connection_warning_sent_at`). The `post_platforms` table was merged
+into `posts` in October 2026 (owner decision); never reintroduce a targets table,
+an `enabled` flag or posts with several channels. Posts created together share
+`post_group_id`.
+
+- **Two status columns.** `posts.status` is the lifecycle (draft,
+ pending_approval, scheduled, publishing, published, failed). `posts.publish_status`
+ (`App\Enums\Post\PublishStatus`) is the network side (pending, publishing,
+ retrying, pending_review, published, failed, rejected). Publishers write
+ `publish_status` through the `markPublication*()` methods; only
+ `FinalizePostPublication` moves `status` to published or failed. There is no
+ `partially_published`.
+- **Publication writes have their own clock.** `writePublication()` (and every
+ `markPublication*()`) sets `publication_updated_at` and leaves `updated_at`
+ alone, so a publish attempt never moves the post's `updated_at` (API, webhooks)
+ and a label or note never moves the publication clock. System writes by query
+ (`toBase()->update`) follow the same rule.
+- **A draft may have no channel.** Drafts written before every post had one
+ channel keep `platform` null. They stay editable as drafts and become channel
+ posts only through `RecoverEmptyDraft`; scheduling or publishing one fails with
+ `posts.errors.choose_channel`. `platform`/`content_type` therefore stay nullable.
+ `Post::hasDestination()` (platform set) and `Post::hasChannel()` (account still
+ there) are the two checks.
+- **Not fillable on purpose:** `social_account_id`, `platform_post_id`,
+ `publish_status`, `scheduled_before_media_checks` — set them
+ with `forceCreate`/`forceFill` in `CreateChannelPost`, `ImportExternalPosts` and
+ the publication methods only.
+- **Public contract:** API, MCP and webhook payloads carry the channel fields at
+ the top of the post (no `platforms[]`); inputs take top-level
+ `social_account_id` / `content_type` / `meta`, and validation errors are keyed
+ `meta.*` (`destinations.{i}.meta.*` in batches).
+
+## Per-Platform Post Meta (`posts.meta`)
+
+- All `meta` validation (the parent array rule AND every per-platform sub-key: TikTok `privacy_level`/flags, Pinterest `board_id`, Discord `channel_id`/`mentions`/`embeds`, etc.) lives in ONE place: `App\Support\PostPlatformMetaRules`.
- Every post create/update entry point — web (`App\Http\Requests\App\Post\UpdatePostRequest`), public API (`App\Http\Requests\Api\Post\{Store,Update}PostRequest`), and MCP (`App\Mcp\Tools\Post\{Create,Update}PostTool`) — spreads `...PostPlatformMetaRules::rules()`. NEVER add a per-platform meta rule inline to a single request/tool.
- Why: `FormRequest::validated()` (and MCP `$request->validate()`) STRIPS any key without a rule. A meta field defined in only one entry point is silently dropped everywhere else — which is exactly how Discord/Pinterest/TikTok meta was lost via API/MCP before this was centralized.
- Required-on-publish (meta a platform needs to publish, e.g. Discord `channel_id`) also lives there: `addRequiredOnPublishErrors()` for request-driven flows (web/API update `withValidator`), `assertStoredPostPublishable()` for flows that publish stored state without resubmitting platforms (MCP `PublishPostTool`). Add new required-meta rules to `requiredMetaViolation()`, not inline.
@@ -776,8 +817,8 @@ TryPost runs on **both PostgreSQL and MySQL**. Cloud runs PostgreSQL; a self-hos
- Reply media rows are owned by the post like its root media. `SyncOwnedMedia` resolves them from the post's stored `meta.thread_replies` and writes the canonical items back, so write the target's meta **before** calling it; it never deletes a row a reply still uses. Every segment's checkpoint hash covers its media ids.
- In the composer each post of a thread shows its own media under it; the toolbar, paste, drop and the toolbar upload button add to the active post.
- X replies go through `POST /2/tweets` with `reply.in_reply_to_tweet_id` on the previous segment. X restricts API replies (February 2026) to posts whose author summoned the replier; replying to your own post is the case that stays allowed. Each reply is billed as a post.
-- Each segment already live is checkpointed in `post_platforms.error_context.thread_progress` (`App\Support\Social\ThreadProgress`), so a retry resumes instead of re-posting, and a resume keeps the root hash. `posts:retry` keeps the live segments.
-- `post_platforms.thread_reply_ids` lists the reply ids so `ImportExternalPosts` does not import TryPost's own replies as new posts.
+- Each segment already live is checkpointed in `posts.error_context.thread_progress` (`App\Support\Social\ThreadProgress`), so a retry resumes instead of re-posting, and a resume keeps the root hash. `posts:retry` keeps the live segments.
+- `posts.thread_reply_ids` lists the reply ids so `ImportExternalPosts` does not import TryPost's own replies as new posts.
## Composer steps
@@ -787,7 +828,7 @@ TryPost runs on **both PostgreSQL and MySQL**. Cloud runs PostgreSQL; a self-hos
## Link preview card
-- `meta.link_preview === false` (the × on the card) is honoured only by the Facebook post, Bluesky and LinkedIn publishers, through `PostPlatform::attachesLinkPreview()`. Threads has no ×: its API always cards the first link.
+- `meta.link_preview === false` (the × on the card) is honoured only by the Facebook post, Bluesky and LinkedIn publishers, through `Post::attachesLinkPreview()`. Threads has no ×: its API always cards the first link.
- "Replace link preview with media" goes through `LinkPreviewMediaController`.
## YouTube
@@ -835,7 +876,7 @@ Browser tests live in `tests/Browser` and run on `pestphp/pest-plugin-browser` d
## Eloquent Models & Morph Map
-- EVERY Eloquent model in `app/Models` MUST be registered in `Relation::enforceMorphMap([...])` inside `AppServiceProvider::configureMorphMap()`, keyed by a camelCase alias (e.g. `'postPlatform' => PostPlatform::class`).
+- EVERY Eloquent model in `app/Models` MUST be registered in `Relation::enforceMorphMap([...])` inside `AppServiceProvider::configureMorphMap()`, keyed by a camelCase alias (e.g. `'postTemplate' => PostTemplate::class`).
- When you add a new model, add it to the morph map in the same change. `tests/Unit/MorphMapTest.php` fails if any model is missing.
- The alias is persisted in polymorphic columns, so never rename or remove an existing alias for a model that has stored rows.
diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md
index ecb0eeab5..4acdc438f 100644
--- a/DEPLOYMENT.md
+++ b/DEPLOYMENT.md
@@ -1,416 +1,161 @@
-# Deploy da branch `codex/independent-social-posts`
+# Deploy da fusão de `post_platforms` em `posts`
-Roteiro completo para levar esta branch à produção, na ordem. Todos os comandos, variáveis e
-agendamentos citados aqui já existem na branch, incluindo os da importação de
-posts externos.
+Roteiro para levar à produção a branch `feat/merge-post-platforms-into-posts`, na
+ordem. Cada post passa a guardar o seu canal e o resultado da publicação na
+própria linha de `posts`; a tabela `post_platforms` é copiada para `posts` e
+removida no mesmo deploy.
-O roteiro detalhado da mídia (snapshot do bucket, Google Drive/Photos, Canva, HEIC,
-testes manuais e comunicação) continua em
-[`MEDIA_INTEGRATIONS_SETUP.md` §7](MEDIA_INTEGRATIONS_SETUP.md). Este arquivo
-referencia aquela seção em vez de repeti-la.
+> **Pré-requisito antes do merge:** marcar a `main` atual (o 2.0 que está no ar,
+> `311767990`) com a tag e a release `v2.0.0`. Hoje a última tag é a `v1.1.0`, e
+> sem a `v2.0.0` o self-hosted não tem por onde passar pelo `release:trypost-2`,
+> que esta versão remove.
+
+O roteiro do deploy do TryPost 2.0 (`release:trypost-2`) fica na tag `v2.0.0`.
+Self-hosted que ainda está na `v1.1.0` **precisa passar por ela antes**: atualizar
+para a `v2.0.0`, rodar `php artisan release:trypost-2 --force` e só então
+atualizar para esta versão. A primeira migration desta versão para com uma
+mensagem explicando isso se encontrar posts com mais de um canal.
+
+Por ser um deploy só (sem releases intermediários), ele roda **em manutenção, com
+todas as filas drenadas**: nenhum job antigo, guardando o id de um destino que
+deixa de existir, pode sobrar para o código novo.
---
## 1. Antes do deploy
-> **Snapshot do storage (R2/S3) ou versionamento ligado, sem exceção.** A adoção da
-> biblioteca de mídia (passo 3 do `release:trypost-2`) apaga arquivos que só
-> existiam na biblioteca, e não há ferramenta de export. Detalhes em
-> `MEDIA_INTEGRATIONS_SETUP.md` §7.1.
-
-1. **Snapshot do storage** (acima).
-2. **Ensaio numa cópia da produção**, depois do `migrate`:
+1. **Ensaio numa cópia da produção** (banco e bucket próprios), com o código desta
+ branch:
```bash
- php artisan release:trypost-2 --dry-run # mostra o que cada passo faria, não muda nada
+ php artisan migrate --force
```
- > **Nunca rode `--force` numa cópia do banco que aponta para o bucket de
- > produção.** A adoção apaga da cópia as linhas da biblioteca e, em seguida, os
- > arquivos que nenhuma linha *da cópia* usa; os posts de produção ainda usam esses
- > arquivos, e a perda só volta pelo snapshot. Para ensaiar de verdade (saída e
- > tempo), a cópia precisa de **um bucket só dela** (uma cópia do bucket, ou
- > `FILESYSTEM_DISK=local` sem credenciais de produção). Sem isso, só `--dry-run`.
+ As quatro migrations novas (`2026_10_08_2229*`) devem terminar sem erro. A
+ primeira resolve sozinha os restos do split do 2.0: apaga os destinos cuja
+ conta sumiu e os destinos desligados que nunca publicaram, transforma em rascunho os posts não
+ publicados sem canal, apaga (com a mídia, sem webhook) os posts publicados sem
+ canal (os arquivos só depois do commit, e só os que nenhuma outra mídia usa)
+ e resolve os `partially_published` com um destino só. Ela **para**, sem
+ mudar nada, se ainda houver: post com mais de um destino, destino desligado
+ que publicou, `partially_published` com destino em andamento ou destino de
+ outro workspace. A mensagem diz quantos de cada.
+
+ Na cópia de produção de 09/10/2026 eram 45.520 destinos desligados, 478
+ rascunhos e 1 post com falha sem canal, e 139 posts publicados sem canal (em 4
+ workspaces, com 236 arquivos), apagados por decisão do Paulo.
+ Anote quanto tempo o `migrate` levou (estimativa: 20–60 s para ~20 mil posts).
+2. **Se o ensaio parou na primeira migration**, resolva os casos na produção antes
+ do deploy (com o código que está no ar):
```bash
- php artisan release:trypost-2 --force # só numa cópia com bucket próprio
+ php artisan posts:split-legacy-active
+ php artisan posts:audit-legacy --strict
```
- O dry-run mostra quantos posts o passo 1 apagaria e quantos destinos tiraria, a
- tabela do `posts:audit-legacy` (o passo 2 divide os "Editable with multiple
- enabled targets"), o plano da adoção por workspace e a auditoria atual da mídia.
-3. **Imagem Docker** reconstruída com o `docker/Dockerfile` novo (Imagick + HEIC).
-4. **Variáveis de ambiente** (seção 2).
-5. **Conte os posts agendados do Instagram com mais de 5 hashtags** (só leitura):
+ O que sobrar (alvo preso em revisão, mídia que não copiou) é tratado à mão.
+3. **Script de deploy do Forge**: adicione, depois de `$RESTART_QUEUES()`,
```bash
- php artisan tinker --execute '$tag = "/(?:^|[^\p{L}\p{N}_&#\/])#(?=[\p{N}_]*\p{L})[\p{L}\p{N}_]+/u"; echo App\Models\PostPlatform::query()->where("enabled", true)->whereIn("platform", ["instagram", "instagram-facebook"])->where("content_type", "!=", "instagram_story")->whereHas("post", fn ($post) => $post->where("status", "scheduled"))->with("post:id,content")->get()->filter(fn ($target) => preg_match_all($tag, html_entity_decode(preg_replace("/<[^>]+>/", " ", (string) $target->post->content))) > 5)->count(), PHP_EOL;'
+ $FORGE_PHP artisan horizon:terminate
```
- Troque `->count()` por `->pluck("post_id")` para ver quais são. O comando roda
- com o código que está em produção hoje (não depende de nada desta branch). O
- limite de 5 hashtags vale só ao salvar (web, API e MCP): esses posts continuam
- publicando, mas quem abrir um deles para editar precisa tirar as hashtags a
- mais antes de salvar. Stories não contam (a legenda não é enviada).
-
-## 2. Variáveis de ambiente
-
-As da mídia estão em `MEDIA_INTEGRATIONS_SETUP.md` §7.2. Novas desta branch:
-
-| Variável | Padrão | Para quê | Status |
-| --- | --- | --- | --- |
-| `TELEGRAM_DEEP_LINK` | `https://t.me` | Link do bot no fluxo de conectar o Telegram | já existe |
-| `EXTERNAL_POSTS_IMPORT_LIMIT` | `50` | Quantos posts mais recentes por canal viram post em Enviados (`0` desliga a importação) | já existe |
-| `X_EXTERNAL_POSTS_IMPORT_DAYS` | `30` | No X, importar só os posts dos últimos N dias | já existe |
-| `EXTERNAL_POSTS_MATCH_WINDOW_MINUTES` | `120` | Minutos em torno de um post da rede em que um post do TryPost com o mesmo texto é tratado como esse post, em vez de importar uma cópia | nova |
-| `EXTERNAL_POSTS_MEDIA_REQUESTS_PER_MINUTE` | `30` | Chamadas por minuto, por rede, para buscar as mídias dos posts importados (orçamento separado do Analytics) | nova |
-| `PUBLICATION_DISCOVERY_INTERVAL_HOURS` | `3` | Intervalo da busca de posts novos nas redes | já existe |
-| `HORIZON_MEDIA_ADOPTION_PROCESSES` | `20` | Processos do supervisor `media-adoption` em produção, que adota a biblioteca em paralelo no passo 3 do release | nova |
-| `X_PUBLICATION_DISCOVERY_INTERVAL_HOURS` | `24` | Mesmo intervalo, só para o X (cobra por leitura) | já existe |
-| `PUBLICATION_DISCOVERY_OVERLAP_HOURS` | `6` | Margem para trás em cada busca, para não perder post atrasado | já existe |
-
-Depois de mudar variáveis:
-
-```bash
-php artisan config:clear
-```
+ Sem ele o Horizon reinicia os workers dentro da pasta do release antigo e
+ continua rodando o código antigo. Vale para todo deploy, não só este. Confira
+ também que `storage/` é compartilhado entre releases (`readlink releases/*/storage`).
+4. **Comunicação**: avise os usuários do horário da janela (alguns minutos sem
+ publicar; os posts agendados para a janela saem logo depois). Avise quem usa a
+ API, o MCP ou webhooks sobre a mudança de contrato (seção 4) **antes** do deploy.
-## 3. Deploy, na ordem
+## 2. Deploy, na ordem
-1. **Deploy** normal. Ele roda `php artisan migrate --force` (esquema: grupos de
- posts, recorrência, origem do post, aprovações etc.).
- - `widen_content_on_posts_table`: `posts.content` vira `mediumText` para caber o post longo do X (25000 caracteres).
- - **PostgreSQL** (Cloud): não reescreve a tabela; é instantâneo.
- - **MySQL** (self-hosted): `TEXT` → `MEDIUMTEXT` **recria a tabela `posts`**
- (`ALGORITHM=COPY`), e as escritas em `posts` ficam bloqueadas enquanto ela é
- copiada. Numa tabela grande, planeje uma janela de manutenção e meça antes o
- tempo numa cópia do banco com o mesmo tamanho.
- - O `down()` falha (ou corta o texto) depois que algum post passar de 64 KB.
- - `add_thread_reply_ids_to_post_platforms_table`: coluna JSON nula
- (`thread_reply_ids`), instantânea nos dois bancos.
-2. **Passos únicos do release**, num comando só:
+1. No release atual:
```bash
- php artisan release:trypost-2 --force
+ php artisan down --retry=60 --secret=<token>
+ ```
+ Web, Horizon e scheduler param (nenhum agendamento usa `evenInMaintenanceMode`).
+2. **Drene todas as filas** com o código antigo (o `--force` processa mesmo em
+ manutenção):
+ ```bash
+ php artisan queue:work redis --queue=social-linkedin,social-linkedin-page,social-x,social-tiktok,social-youtube,social-facebook,social-instagram,social-instagram-facebook,social-threads,social-pinterest,social-bluesky,social-mastodon,social-telegram,social-discord,social-google_business,default,posthog,broadcasts,analytics,webhooks,media-imports,media-adoption,rss-feeds --force --stop-when-empty
+ ```
+ Confira a lista de filas em `config/horizon.php`. Espere também os jobs com
+ atraso das filas `social-*`, `default`, `broadcasts`, `posthog` e `webhooks`
+ (até 10 minutos, os retries de rede indisponível) e rode o comando de novo até
+ o Redis não ter nada em `queues:<essas filas>:delayed` nem em
+ `queues:*:reserved`. Os atrasados da fila `analytics` (métricas de stories, até
+ 24 h) só carregam ids de publicação e podem ficar.
+ Os jobs que já falharam (`failed_jobs`) com o código antigo não podem ser
+ reexecutados depois do deploy (a classe `PostPlatform` deixa de existir):
+ reexecute-os antes ou descarte-os.
+ Confirme que não sobrou comando agendado rodando:
+ `ps -ef | grep "[a]rtisan" | grep -v horizon`.
+ E que nenhum post ficou publicando sem job (deve dar 0; o que sobrar o
+ `RecoverStuckPosts` falharia depois de 1 h). As consultas abaixo são de
+ PostgreSQL (Cloud); no MySQL troque `now() - interval '1 hour'` por
+ `now() - interval 1 hour`:
+ ```sql
+ select count(*) from post_platforms
+ where status in ('publishing', 'retrying') and retry_at is null
+ and updated_at > now() - interval '1 hour';
+ ```
+ E que nenhum post do Google Business está em revisão (deve dar 0; o JPEG de um
+ post em revisão tem o id do destino antigo no nome e ficaria órfão no bucket):
+ ```sql
+ select count(*) from post_platforms
+ where platform = 'google_business' and status = 'pending_review';
+ ```
+3. Deploy pelo Forge, com o build **antes** do `migrate`, para um build quebrado
+ falhar antes de qualquer escrita:
+ `composer install` → `artisan optimize` → `npm ci && npm run build` →
+ `artisan migrate --force` → `$ACTIVATE_RELEASE()` → `$RESTART_QUEUES()` →
+ `artisan horizon:terminate` → `artisan reverb:restart`.
+4. Teste rápido pelo link secreto, ainda em manutenção: abrir a página de publicar,
+ abrir um post enviado e um agendado, salvar um rascunho.
+5. ```bash
+ php artisan up
```
-3. **Acompanhe o Horizon** até as filas `analytics` e `media-imports` drenarem
- (backfill do Analytics, importação dos posts externos e das mídias deles).
-4. **Checagens pós-deploy** (seção 6).
-
-O `release:trypost-2` para com erro, sem fazer nada, se houver migration pendente.
-Roda os passos nesta ordem, imprime a saída de cada um e termina com uma tabela de
-resumo:
-
-| # | Passo | Comando reaproveitado |
-| --- | --- | --- |
-| 1 | Apaga os posts que ficaram sem canal por desconexões antigas (agora desconectar apaga os posts do canal); num post com outro canal vivo, só tira o destino morto | `posts:purge-orphaned` |
-| 2 | Divide posts antigos com várias redes em um post por rede, ligados pelo mesmo `post_group_id`: rascunhos e agendados, e também os já terminados (publicado, parcialmente publicado, falhou). Cada post terminado fica com o status do próprio destino (publicado → `published`, falhou/rejeitado → `failed`); `partially_published` deixa de existir | `posts:split-legacy-active` |
-| 3 | Biblioteca de mídia antiga → mídia por post e por ideia: um `AdoptWorkspaceLibraryJob` por workspace na fila `media-adoption` (em paralelo no Horizon), e o comando **espera** até terminar | `media:adopt-library` |
-| 4 | Backfill do Analytics + importação dos posts externos (assíncrono, seção 5) | `analytics:backfill-existing` |
-| 5 | Busca imediata dos stories do Instagram (assíncrono) | `analytics:dispatch-publication-discovery --platform=instagram --platform=instagram-facebook` |
-| 6 | Auditoria da mídia (só leitura), comparada com a de antes do release | `AuditMedia` |
-
-- **A ordem importa.** Purgar antes de dividir: um post com um destino num canal
- apagado e outro num canal vivo perde só o destino morto e mantém o id (dividido
- antes, a metade morta podia levar o id original junto). Purgar antes de adotar
- evita copiar mídia de posts que vão ser apagados. A divisão dá a cada post novo
- as próprias mídias (arquivo e linha), antes ou depois da adoção, então a adoção
- no boot do Docker não atrapalha.
-- **Como a divisão trata o histórico.** O destino (`post_platforms`) é **movido**
- para o post novo, nunca copiado: link do post na rede, erro, `published_at`,
- métricas e o vínculo do Analytics (`analytics_publications.post_platform_id`)
- continuam no mesmo registro. Cada post novo ganha o mesmo texto, autor, origem,
- datas, etiquetas, notas e as próprias mídias. Destinos desligados não viram post
- e ficam no post original, como histórico de um destino que nunca rodou. Posts em
- `publishing` e posts terminados com algum destino ainda em andamento (ex.: Google
- Business em revisão) ficam como estão; o comando diz quantos. Um post
- `partially_published` que ficou com um só destino (o outro era de um canal
- apagado e saiu no passo 1) passa a ter o status desse destino. Nada disso dispara
- e-mail, webhook ou evento.
-- **Rodar de novo é seguro:** cada passo pula o que já foi feito. Se um passo
- falhar, o comando segue para os outros, mostra o resumo e sai com código
- diferente de 0; corrija e rode de novo.
-- **O backfill (passo 4) é despachado uma vez só.** Os jobs dele podem ficar horas
- esperando por causa do `--backfill-delay`; despachar de novo antes deles rodarem
- leria cada conta duas vezes (o X cobra por leitura). O comando guarda no cache
- quando despachou (na tabela `cache` do banco, não no Redis: sobrevive a um flush
- e viaja junto com um snapshot do banco) e, nas próximas rodadas, pula o passo
- ("Skipped: already dispatched at …"). Para despachar de novo de propósito:
- `--rerun-backfill`.
-- **Adoção (passo 3).** O comando enfileira um job por workspace com biblioteca na
- fila `media-adoption` e fica esperando, com uma linha de progresso a cada 15s
- (`N/M workspace(s) done, X library row(s) left, Y stopped`). Só segue para os
- passos 4–6 quando todos terminam ou quando passa o `--adoption-timeout` (padrão
- `21600`, 6h). Dentro de um workspace a cópia é sequencial (um job por workspace:
- a biblioteca só é apagada depois de todas as cópias, e dividir um workspace em
- vários jobs quebraria essa garantia). Um workspace com post em `Publishing` é
- tentado de novo pelo próprio job (a cada 5 min, por até 6h). Ao fim da espera:
- - ainda rodando: fica para o job, que continua sozinho; o resumo diz quantos;
- - parado com biblioteca sobrando (o job desistiu, ou os arquivos não foram
- achados no disco): o passo falha, o resumo lista os workspaces e o comando sai
- com código diferente de 0; veja o log, corrija e rode
- `php artisan media:adopt-library --force`.
-
- Rodar o release de novo com jobs ainda na fila não duplica nada (job único por
- workspace) e volta a esperar.
-- **Tempo da adoção.** Cada cópia no R2 levou ~1,9s na cópia de produção
- (sequencial). Tempo total ≈ cópias × 1,9s ÷ processos do supervisor
- `media-adoption`, limitado pelo maior workspace (um workspace roda num processo
- só). Exemplo: ~14,6 mil cópias com 20 processos ≈ 14.600 × 1,9 ÷ 20 ≈ 23 min.
- No release, deixe `HORIZON_MEDIA_ADOPTION_PROCESSES` em 20 (padrão em produção;
- dá para subir para 30–40 se o servidor aguentar) e reinicie o Horizon
- (`php artisan horizon:terminate`) **antes** de rodar o comando, para o supervisor
- novo existir.
-- **Opções repassadas ao backfill:** `--backfill-chunk=50 --backfill-delay=300`
- (contas por lote e segundos entre lotes; padrão `100` e `0`) e
- `--include-unsubscribed`.
-- **Como ler a auditoria (passo 6).** Antes do passo 1 o comando tira uma foto
- rápida (só banco e a listagem do bucket, sem conferir arquivo por arquivo, então
- não atrasa os passos de dados). No fim, depois dos passos de dados, roda a
- auditoria completa, que confere o arquivo de cada mídia no bucket: conte com
- **uns 10 a 30 minutos** em produção (um pedido ao R2 por mídia; o resumo mostra o
- tempo). Ela mostra por checagem quantos achados são **esperados** e quantos são
- **inesperados**. Esperados:
- - os que já estavam na foto de antes (sujeira antiga, não do release);
- - itens de post que apontam para uma linha da biblioteca que ficou (usada por
- post de outro workspace, ou de um workspace que ficou para a fila);
- - itens que apontam para uma mídia que não existe mais, **só** se ela já era da
- biblioteca ou já estava sumida antes do release;
- - arquivos sem linha que tinham linha antes do release (exclusão na fila do
- `DeleteMediaFiles`), e mídias de antes do release sem arquivo (a foto não
- confere arquivos).
-
- Qualquer outra coisa, como uma mídia ainda usada por um post que o release
- apagou, é **inesperada**: aparece uma por linha (`unexpected json_drift: … media_id=…`)
- e faz o comando sair com código diferente de 0.
-
-Migrations que entram nesta branch (entre outras):
-
-- `add_post_group_id_to_posts_table`: posts criados juntos compartilham um grupo.
-- `add_recurrence_to_posts_table` e `add_recurrence_origin_at_to_posts_table`: posts recorrentes.
-- `add_origin_to_posts_table`, `change_platform_url_to_text_on_post_platforms_table` e `add_post_dismissed_at_to_analytics_publications_table`: origem do post (`trypost` | `network`), permalinks longos e posts importados apagados pelo usuário (não voltam).
-- `add_permissions_to_user_workspace_and_invites_tables` → `drop_role_from_user_workspace_and_invites_tables`:
- os papéis Admin / Member / Viewer viram duas flags por membro e por convite
- (`is_admin`, `requires_approval`). Admin → admin; Member → publica direto;
- Viewer → precisa de aprovação; o dono da conta vira admin. Rodam juntas, nessa
- ordem; a segunda apaga a coluna `role`.
-- `add_approval_columns_to_posts_table`: `approval_requested_at`, `approved_by`,
- `approved_at`, `approval_queue_position` e o novo status `pending_approval`.
-- `add_approval_requested_by_to_posts_table`: `approval_requested_by`, quem pediu
- a aprovação (pode não ser o autor: um membro que edita um post já aprovado de
- outra pessoa). Vira `null` se o usuário for apagado; aí vale o autor do post.
-- `add_collaboration_to_notification_preferences_table`: preferência
- "Colaboração" (ligada por padrão).
-- `flatten_replies_and_drop_reactions_from_post_notes_table`: notas ficam
- simples (sem respostas nem reações). Respostas viram notas normais do mesmo
- post, na ordem em que foram criadas; as colunas `parent_id` e `reactions` são
- apagadas (reações somem).
-- `fold_legacy_workspace_media_into_library`: as imagens de IA antigas (coleção
- `ai-generated`, algumas gravadas com `App\Models\Workspace` em vez do alias
- `workspace`) entram na biblioteca, para a adoção copiá-las para os posts que as
- usam e apagar as que nenhum post usa. Linhas `assets` gravadas com o nome da
- classe também passam a ser adotadas. Linhas de outras coleções (ex.: `logo`) e de
- workspaces que não existem mais ficam como estão.
-- `make_time_format_required_on_users_table`: `users.time_format` passa a ser
- obrigatório (12h ou 24h; acaba o "seguir o idioma"). Quem estava sem formato
- recebe o que já via: `12h` em inglês, `24h` nos outros idiomas. Ninguém percebe
- mudança.
-
-Sem migração de dados para a fila: posts já na fila mantêm os horários que têm
-(a fila não é mais compactada nos primeiros horários livres), então nada muda
-para quem já tem posts enfileirados.
-
-## 4. Filas e scheduler
-
-Os workers/Horizon precisam consumir todas estas filas (`config/horizon.php`):
-
-| Fila | Para quê |
-| --- | --- |
-| `default`, `posthog`, `broadcasts` | App em geral |
-| `webhooks` | Webhooks de saída |
-| `analytics` | Analytics e, com a importação, a criação dos posts externos |
-| `media-imports` | Google Drive, Photos, Canva e, com a importação, as mídias dos posts externos |
-| `media-adoption` | Adoção da biblioteca de mídia (só neste release). Supervisor próprio no Horizon; em produção até `HORIZON_MEDIA_ADOPTION_PROCESSES` processos (padrão 20) |
-| `rss-feeds` | Feeds RSS |
-
-Com `queue:work` em vez de Horizon:
-
-```bash
-php artisan queue:work --queue=default,posthog,broadcasts,webhooks,analytics,media-imports,media-adoption,rss-feeds
-```
-
-Agendamentos (o scheduler já cuida, só confirme que ele está rodando):
-
-| Quando (UTC) | O quê | Status |
-| --- | --- | --- |
-| a cada 3h (X: a cada 24h, às 00:00) | Busca posts novos nas redes: importa para Enviados e Analytics | já existe |
-| 02:00 | Snapshot de seguidores | já existe |
-| 03:00 | Atualização das métricas dos últimos 30 dias (X: 20) | já existe |
-| 23:30 / 00:30 | Fechamento do snapshot do dia / recuperação do dia anterior | já existe |
-| de hora em hora | `media:prune-uploads` | já existe |
-| diário | `posts:prune-history` | já existe |
-| a cada 5 min | `rss-feeds:poll`, `repurposes:poll` | já existe |
-
-## 5. Backfill do Analytics + importação dos posts externos
-
-É o passo 4 do `release:trypost-2`, depois da divisão dos posts e da adoção da biblioteca. A ordem importa: o
-backfill primeiro liga os posts que o TryPost já publicou às publicações do
-Analytics e só então importa os posts feitos direto nas redes. Ao contrário, um
-post do TryPost viraria um "importado" duplicado.
-
-O comando despacha tudo e termina, não fica parado esperando. O que acontece por
-conta:
-
-1. O Analytics busca o histórico de **365 dias** (no X, no máximo 3.200 posts).
-2. Os **50 posts mais recentes** de cada canal (no X, os dos **últimos 30 dias**)
- viram post em Enviados e no calendário, com origem `network`.
-3. As mídias completas desses posts (carrossel, vídeo, capa) são baixadas para o
- bucket na fila `media-imports`.
-4. As métricas são buscadas pelo Analytics.
-5. No Instagram, os **stories** entram também, mas só os que estão no ar (últimas
- 24 horas): a API não devolve stories mais antigos. Eles têm um limite próprio
- de 50, separado de feed e reels. Para contas que já tinham feito o backfill, o
- passo 5 do release traz os que estão no ar na hora; depois disso a busca de
- posts novos (a cada 3h) cuida deles.
-
-Rodar de novo é seguro: nenhum post é criado em dobro, e mídias já baixadas não são
-baixadas outra vez.
-
-O resumo do backfill tem uma linha por contador:
-
-- `accounts_dispatched`: contas que tiveram o backfill despachado.
-- `publications_to_link`: publicações do TryPost sem registro no Analytics, que o comando liga a ele.
-- `posts_imported`: posts importados que existem agora. É a contagem atual; a
- importação é assíncrona, então o número cresce enquanto as filas drenam.
-- `historical_identity_unrecoverable`: publicações antigas sem canal associado, cuja
- identidade não dá para recuperar e que por isso ficam fora do Analytics.
-
-## 6. Depois do deploy
-
-- A auditoria da mídia já roda no fim do `release:trypost-2` (esperados ×
- inesperados, seção 3). Se algum workspace ficou para a fila, rode o
- `release:trypost-2 --force` de novo quando os `AdoptWorkspaceLibraryJob` zerarem
- (o backfill não é despachado de novo).
-- Confira em alguns canais que Enviados e o calendário mostram os posts importados,
- com mídia e métricas.
-- **Limite do X por conta.** Contas do X com assinatura paga (Basic, Premium,
- PremiumPlus) ou verificadas como empresa passam a ter 25000 caracteres. O plano
- de cada conta é lido na próxima verificação da conexão (diária) ou ao reconectar;
- até lá, a conta segue com 280. Para valer na hora:
- `php artisan social:check-connections` (opcional).
-- **Título do YouTube.** Sem título preenchido, o título é a primeira linha não
- vazia do texto (sem `<` e `>`, até 100 caracteres). Ele não ganha mais ` #Shorts`
- no fim e não é mais cortado no primeiro `.`.
-
-### Canais desconectados
-
-- Rodar `php artisan posts:purge-orphaned` de novo deve imprimir `0 orphaned post(s) deleted, 0 orphaned target(s) removed from posts on other channels.`
-- Desconectar um canal apaga todos os posts dele, sem disparar o webhook `post.deleted`
- para cada post; reconectar a mesma conta importa de novo os posts recentes.
-
-### Aprovação de posts
-
-- Em Configurações → Membros, confira que quem era Viewer aparece como
- "Precisa de aprovação" e quem era Admin aparece como Admin.
-- Com um membro que precisa de aprovação: crie um post na fila e confira que ele
- aparece na aba Aprovações (e não na Fila), que o e-mail chega para os
- aprovadores e que "Adicionar à fila" coloca o post no próximo horário.
-- `posts:process-scheduled` nunca publica `pending_approval`; nada a configurar.
-- Em uma automação de repurpose criada por um membro que precisa de aprovação, o
- item continua marcado como Publicado enquanto os posts dele aguardam aprovação:
- o item representa o envio à fila, não a publicação nas redes.
-
-## 7. Se precisar voltar atrás
-
-Apagar só os posts importados (origem `network`) e as mídias deles. O Analytics fica
-intacto: as publicações apenas voltam a ficar sem ligação.
-
-Antes, defina `EXTERNAL_POSTS_IMPORT_LIMIT=0` e rode `php artisan config:clear`;
-sem isso a próxima busca importa os posts de novo.
-
-```bash
-php artisan posts:purge-imported # já existe
-php artisan posts:purge-imported --workspace=<uuid>
-```
-
-### Aprovação de posts: papéis
-
-O `migrate:rollback` das migrations de papéis recria a coluna `role` em
-`user_workspace` e em `invites` e preenche pelas flags: `is_admin` →
-Admin; `requires_approval` → Viewer; os demais → Member. O dono da conta volta
-como Admin. Posts em `pending_approval` não existem no esquema antigo: antes de
-voltar atrás, aprove ou rejeite todos (ou mova-os para rascunho), senão ficam com
-um status desconhecido.
-
-As outras migrations da aprovação também voltam atrás sem perda fora delas:
-
-- `add_approval_requested_by_to_posts_table`: o `down()` apaga a chave
- estrangeira e a coluna `approval_requested_by`.
-- `add_approval_columns_to_posts_table`: o `down()` apaga `approved_by` (com a
- chave estrangeira), `approval_requested_at`, `approved_at` e
- `approval_queue_position`. Quem aprovou e quando se perde.
-- `add_collaboration_to_notification_preferences_table`: o `down()` apaga a
- preferência `collaboration`; os e-mails de aprovação deixam de existir junto com
- o código.
-
-## 8. Teste manual antes do release
-
-- **X:** uma sincronização real com uma conta de verdade, conferindo os campos
- `note_tweet` (texto longo) e as variantes de mídia.
-- **Threads:** um carrossel, conferindo a expansão de `children{}`.
-- **Pinterest:** um pin, conferindo a imagem 1200x e o `video_url`.
-
-## 9. Comunicação
-
-Changelog, docs.trypost.it, instruções do MCP e e-mail do release:
-`MEDIA_INTEGRATIONS_SETUP.md` §7.6. Somar a isso:
-
-- Enviados e o calendário passam a mostrar também os posts feitos direto nas redes
- (últimos 50 por canal; no X, último mês).
-- A API e o MCP ganham o campo `origin` (`trypost` | `network`) nos posts.
-- Fuso horário: quem já tinha conta fica em **UTC** (a produção nunca guardou fuso), e os
- canais existentes ganham a grade de horários em UTC. Isso é intencional: no changelog e no
- e-mail do release, peça para cada um conferir o fuso em Configurações → Preferências e o fuso
- de cada canal em Configurações do canal. Cadastros novos já detectam o fuso do navegador.
-
-Aprovação de posts (mudança que quebra compatibilidade para quem lê o status):
-
-- Novo status `pending_approval` em posts na API e no MCP. Posts criados ou
- editados por um membro que precisa de aprovação terminam nesse status em vez de
- `scheduled` / `publishing`.
-- Novos endpoints `POST /api/posts/{post}/approve` (aceita `scheduled_at` ou
- `publish_now`) e `POST /api/posts/{post}/reject`; novas tools MCP
- `approve-post-tool` e `reject-post-tool`; `list-posts-tool` filtra
- `pending_approval`.
-- Os papéis Admin / Member / Viewer deixam de existir: a API e o MCP não expõem
- membros nem convites, então só a documentação e o changelog mudam.
-- Atualizar docs.trypost.it (membros e aprovações, API de posts) e o changelog.
-
-## 10. Comandos avulsos (opcional/manual)
-
-Os comandos que o `release:trypost-2` usa, e os de diagnóstico e de reversão deste
-release, ficam em `app/Console/Commands/Scripts/`. Só servem para rodar um passo
-isolado, ensaiar ou investigar; o deploy normal não precisa deles.
-
-```bash
-php artisan posts:audit-legacy [--strict] # contagens dos posts antigos, só leitura
-php artisan posts:purge-orphaned [--workspace=<uuid>] # passo 1
-php artisan posts:split-legacy-active # passo 2
-php artisan media:adopt-library --dry-run # o que a adoção faria, por workspace
-php artisan media:adopt-library --force # adoção pela fila (AdoptWorkspaceLibraryJob), em vez do passo 3
-php artisan analytics:backfill-existing [--workspace=<uuid>] [--include-unsubscribed] [--platforms=instagram,facebook] [--chunk=100] [--delay=0] # passo 4
-php artisan media:audit [--json] # passo 6
-php artisan posts:purge-imported [--workspace=<uuid>] # reversão (seção 7)
-```
-
-Exemplos do backfill isolado:
-
-```bash
-# Um workspace só (bom para testar primeiro)
-php artisan analytics:backfill-existing --workspace=<uuid>
-
-# Só algumas redes (ex.: deixar o X, que cobra por leitura, para depois)
-php artisan analytics:backfill-existing --platforms=instagram,instagram-facebook,facebook,threads
-php artisan analytics:backfill-existing --platforms=x --chunk=10 --delay=600
-```
-
-`analytics:dispatch-publication-discovery` (passo 5) não é avulso: o scheduler usa,
-então fica em `app/Console/Commands/Analytics/`.
-**Depois do release, a pasta `app/Console/Commands/Scripts/` pode ser apagada
-inteira** (com os testes dos comandos dela e as menções em
-`docker/entrypoint.sh`, `README.md` e `MEDIA_INTEGRATIONS_SETUP.md`), na mesma
-limpeza da issue #376 (fallback do `PostAtRisk`).
+## 3. Depois do deploy
+
+- Horizon sem jobs falhos novos.
+- Um post de teste publicado em cada rede conectada no workspace de testes.
+- Um webhook de teste (`post.published`) e o email de "publicado".
+- Os posts agendados para os minutos da janela saíram.
+- `post_platforms` não existe mais e `analytics_publications.post_platform_id` foi
+ removida.
+
+### Se algo falhar
+
+- **Antes do `up`** (migration, build ou teste rápido): ou corrija para frente com
+ o app em manutenção, ou apague a linha da migration que falhou em `migrations` e
+ volte o release; as migrations podem rodar de novo (a cópia é idempotente e limpa
+ cópias de destinos que sumiram).
+- **Depois do `up`**: só correção para frente. O código novo grava a publicação só
+ em `posts`; voltar o código antigo republicaria posts que já saíram.
+
+## 4. Mudança de contrato (API, MCP, webhooks)
+
+Muda de uma vez, sem formato de compatibilidade:
+
+- **Objeto Post** (API `GET/POST/PUT /posts`, tools de post do MCP): sem
+ `platforms[]`. No topo: `publish_status`, `social_account`, `platform`,
+ `content_type`, `meta`, `platform_url`, `error_message`, `display_name`,
+ `display_username`, `display_avatar`.
+- **Criar post** (API `POST /posts`, `create-post-tool`): `social_account_id`,
+ `content_type` e `meta` no topo. Enviar `platforms` é erro de validação.
+- **Editar post** (API `PUT /posts/{id}`, `update-post-tool`): `content_type` e
+ `meta` no topo; `platforms` é recusado.
+- **Erros de validação**: `meta.*` e `content_type` (antes `platforms.0.*`); nos
+ lotes, `destinations.{i}.meta.*`.
+- **Status**: `partially_published` deixa de existir; o resultado na rede fica em
+ `publish_status` (`pending`, `publishing`, `retrying`, `pending_review`,
+ `published`, `failed`, `rejected`).
+- **Preview** (API e `preview-post-tool`) e **métricas** (API e
+ `get-post-metrics-tool`): um objeto só, sem `platforms[]` nem `post_platform_id`.
+- **Analytics**: publicações e relatório trazem `post_id` (sem `post_platform_id`).
+- **Repurpose**: cada post do item traz `platform` e `publish_status`.
+- **Webhooks**: o payload `post.*` traz os campos do canal no topo (incluindo
+ `social_account_id` e `platform_post_id`, sem `error_context`). O evento
+ `post.partially_published` foi removido; webhooks que o assinavam passam a
+ assinar `post.published` e `post.failed`. Entregas que já estavam na fila e o
+ replay de logs antigos reenviam o payload no formato antigo.
+
+Páginas da docs.trypost.it a atualizar: objeto Post e endpoints (create, update,
+list, show, preview, attach media), erros de validação, status, Webhooks (payload e
+lista de eventos), Repurpose items, métricas do post, publicações e relatório de
+Analytics, e a página do MCP.
diff --git a/README.md b/README.md
index 95db5dd70..37b852f0b 100644
--- a/README.md
+++ b/README.md
@@ -86,7 +86,8 @@ Posts publish natively through each platform's official API.
Self-hosting media maintenance:
-- `php artisan release:trypost-2 --force` runs the one-off data steps of the 2.0 release once, after `php artisan migrate`: it splits multi-channel posts, purges posts of channels disconnected earlier, copies the old media library onto the posts and ideas that use it (then deletes the library) and queues the analytics backfill. Run it with a queue worker running. The individual commands live in `app/Console/Commands/Scripts/`.
+- Upgrading from v1.x: upgrade to v2.0.0 first and run `php artisan release:trypost-2 --force` there (with a queue worker running). Later versions merge each post's channel into the post and no longer ship that command; their first migration stops and explains what is left if you skip v2.0.0.
+- Before upgrading past v2.0.0, stop the scheduler and let every queue drain (including delayed jobs), so no job queued by the old version is left for the new one.
- `php artisan media:prune-uploads` deletes unused uploads older than `MEDIA_UPLOAD_RETENTION_HOURS` (24 by default) and stale publish crops. The scheduler runs it hourly.
- `php artisan posts:prune-history` deletes published posts, and their media, older than `POST_HISTORY_RETENTION_DAYS` (730 by default). The scheduler runs it daily; analytics are kept.
diff --git a/app/Actions/Analytics/BuildChannelMetricSeries.php b/app/Actions/Analytics/BuildChannelMetricSeries.php
index 09303e587..1388cb562 100644
--- a/app/Actions/Analytics/BuildChannelMetricSeries.php
+++ b/app/Actions/Analytics/BuildChannelMetricSeries.php
@@ -10,7 +10,7 @@ use App\Enums\Analytics\MetricAvailability;
use App\Enums\Analytics\MetricKey;
use App\Enums\User\WeekStart;
use App\Models\AnalyticsAccountDailySnapshot;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Support\Analytics\PeriodBuckets;
use Carbon\CarbonImmutable;
@@ -139,7 +139,7 @@ class BuildChannelMetricSeries
private function publications(SocialAccount $channel, string $accountKey, CarbonImmutable $start, CarbonImmutable $end, ?PublicationFilter $filter): iterable
{
return $this->latestSnapshots->execute($channel->workspace_id, [$accountKey], $start, $end)
- ->leftJoin((new PostPlatform)->getTable().' as destination', 'destination.id', '=', 'publication.post_platform_id')
+ ->leftJoin((new Post)->getTable().' as destination', 'destination.id', '=', 'publication.post_id')
->when($filter !== null, fn (Builder $filtered): Builder => $filter->apply($filtered))
->select([
'publication.id', 'publication.provider_published_at',
diff --git a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php b/app/Actions/Analytics/BuildPublicationAnalyticsReport.php
index 69b07d30e..b882eb5e7 100644
--- a/app/Actions/Analytics/BuildPublicationAnalyticsReport.php
+++ b/app/Actions/Analytics/BuildPublicationAnalyticsReport.php
@@ -9,7 +9,7 @@ use App\Dto\Analytics\PublicationFilter;
use App\Enums\Analytics\MetricAvailability;
use App\Enums\Analytics\MetricKey;
use App\Enums\User\WeekStart;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\Workspace;
use App\Support\Analytics\MetricComparison;
use App\Support\Analytics\PeriodBuckets;
@@ -140,11 +140,11 @@ class BuildPublicationAnalyticsReport
public function query(Workspace $workspace, CarbonImmutable $start, CarbonImmutable $end, ?array $accountKeys = null, ?PublicationFilter $filter = null): Builder
{
return $this->latestSnapshots->execute($workspace->id, $accountKeys, $start, $end)
- ->leftJoin((new PostPlatform)->getTable().' as destination', 'destination.id', '=', 'publication.post_platform_id')
+ ->leftJoin((new Post)->getTable().' as destination', 'destination.id', '=', 'publication.post_id')
->when($filter !== null, fn (Builder $filtered): Builder => $filter->apply($filtered))
->select([
'publication.id', 'publication.social_account_key', 'publication.social_account_id',
- 'publication.post_platform_id', 'destination.post_id', 'publication.platform', 'publication.network',
+ 'publication.post_id', 'publication.platform', 'publication.network',
'publication.account_display_name', 'publication.account_username',
'publication.account_avatar_url', 'publication.remote_id',
'publication.provider_published_at', 'publication.origin', 'publication.content_type',
@@ -296,7 +296,6 @@ class BuildPublicationAnalyticsReport
return array_map(function (object $row): array {
return [
'id' => $row->id,
- 'post_platform_id' => $row->post_platform_id,
'post_id' => $row->post_id,
'social_account_key' => $row->social_account_key,
'platform' => $row->platform,
diff --git a/app/Actions/Analytics/ListChannelPublicationPerformance.php b/app/Actions/Analytics/ListChannelPublicationPerformance.php
index 79f72ee4e..9ff321b1c 100644
--- a/app/Actions/Analytics/ListChannelPublicationPerformance.php
+++ b/app/Actions/Analytics/ListChannelPublicationPerformance.php
@@ -8,7 +8,7 @@ use App\Dto\Analytics\DateRange;
use App\Dto\Analytics\PublicationFilter;
use App\Enums\Analytics\MetricAvailability;
use App\Enums\Analytics\MetricKey;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Support\Analytics\ChannelMetrics;
use App\Support\Analytics\EngagementRate;
@@ -50,10 +50,10 @@ class ListChannelPublicationPerformance
$paginator = $this->latestSnapshots
->execute($channel->workspace_id, [$accountKey ?? $this->accountKey->for($channel)], $range->startsAt(), $range->endsAt())
- ->leftJoin((new PostPlatform)->getTable().' as destination', 'destination.id', '=', 'publication.post_platform_id')
+ ->leftJoin((new Post)->getTable().' as destination', 'destination.id', '=', 'publication.post_id')
->when($filter !== null, fn (Builder $filtered): Builder => $filter->apply($filtered))
->select([
- 'publication.id', 'destination.post_id', 'publication.excerpt', 'publication.preview_metadata', 'publication.permalink',
+ 'publication.id', 'publication.post_id', 'publication.excerpt', 'publication.preview_metadata', 'publication.permalink',
'publication.provider_published_at', 'publication.content_type',
'metric.reactions_count', 'metric.comments_count', 'metric.views_count', 'metric.shares_count',
'metric.saves_count', 'metric.reach_count', 'metric.engagement_count', 'metric.exposure_count',
diff --git a/app/Actions/Analytics/ReadPublicationAnalytics.php b/app/Actions/Analytics/ReadPublicationAnalytics.php
index ee49ad844..d8b85149b 100644
--- a/app/Actions/Analytics/ReadPublicationAnalytics.php
+++ b/app/Actions/Analytics/ReadPublicationAnalytics.php
@@ -10,12 +10,11 @@ use App\Enums\Analytics\MetricKey;
use App\Enums\Analytics\MetricPrecision;
use App\Enums\Analytics\MetricTimeBasis;
use App\Enums\Analytics\MetricUnit;
-use App\Enums\PostPlatform\Status;
+use App\Enums\Post\PublishStatus;
use App\Enums\SocialAccount\Platform;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Workspace;
use App\Support\Analytics\EngagementRate;
use Illuminate\Support\Collection;
@@ -35,45 +34,42 @@ class ReadPublicationAnalytics
return $this->latestForPublication($publication);
}
- /** @return Collection<int, array<string, mixed>> */
- public function forPost(Post $post): Collection
+ /** @return array<string, mixed> */
+ public function forPost(Post $post): array
{
- $destinations = $post->postPlatforms
- ->where('enabled', true)
- ->values();
- $details = $this->latestForPost($post, $destinations);
-
- return $destinations->map(fn (PostPlatform $destination): array => [
- 'post_platform_id' => $destination->id,
- 'platform' => $destination->platform->value,
- 'status' => $destination->status->value,
- 'platform_post_id' => $destination->platform_post_id,
- 'platform_url' => $destination->platform_url,
- 'metrics' => $this->visibleDetail(data_get($details, $destination->id, $this->unavailable('not_collected'))),
- ]);
+ return [
+ 'post_id' => $post->id,
+ 'platform' => $post->platform?->value,
+ 'publish_status' => $post->publish_status->value,
+ 'platform_post_id' => $post->platform_post_id,
+ 'platform_url' => $post->platform_url,
+ 'metrics' => $this->metricsFor($post),
+ ];
}
/** @return array<string, mixed> */
- public function forPlatform(PostPlatform $postPlatform): array
+ public function metricsFor(Post $post): array
{
- return $this->visibleDetail($this->latestForPostPlatform($postPlatform));
+ return $this->visibleDetail($this->latestFor($post));
}
/**
- * @param Collection<int, PostPlatform> $destinations
+ * The latest metrics of each post, keyed by post id.
+ *
+ * @param Collection<int, Post> $posts
* @return array<string, array<string, mixed>>
*/
- public function latestForPost(Post $post, Collection $destinations): array
+ public function latestForPosts(string $workspaceId, Collection $posts): array
{
- $eligible = $destinations->filter(fn (PostPlatform $destination): bool => $this->isCollectable($destination));
+ $eligible = $posts->filter(fn (Post $post): bool => $this->isCollectable($post));
$publications = $eligible->isEmpty() ? collect() : AnalyticsPublication::query()
->available()
- ->where('workspace_id', $post->workspace_id)
- ->whereIn('post_platform_id', $eligible->pluck('id'))
+ ->where('workspace_id', $workspaceId)
+ ->whereIn('post_id', $eligible->pluck('id'))
->whereIn('platform', Platform::analyticsValues())
->get()
- ->keyBy('post_platform_id');
+ ->keyBy('post_id');
$snapshots = collect();
@@ -94,42 +90,42 @@ class ReadPublicationAnalytics
->keyBy('publication_id');
}
- return $destinations->mapWithKeys(function (PostPlatform $destination) use ($publications, $snapshots): array {
- if ($destination->status !== Status::Published || ! $destination->platform_post_id) {
- return [$destination->id => $this->unavailable('not_published')];
+ return $posts->mapWithKeys(function (Post $post) use ($publications, $snapshots): array {
+ if ($post->publish_status !== PublishStatus::Published || ! $post->platform_post_id) {
+ return [$post->id => $this->unavailable('not_published')];
}
- if (! in_array($destination->platform->value, Platform::analyticsValues(), true)) {
- return [$destination->id => $this->unavailable('platform_not_supported')];
+ if (! in_array($post->platform?->value, Platform::analyticsValues(), true)) {
+ return [$post->id => $this->unavailable('platform_not_supported')];
}
- $publication = $publications->get($destination->id)?->setRelation(
+ $publication = $publications->get($post->id)?->setRelation(
'socialAccount',
- $destination->relationLoaded('socialAccount') ? $destination->socialAccount : null,
+ $post->relationLoaded('socialAccount') ? $post->socialAccount : null,
);
- return [$destination->id => $publication
+ return [$post->id => $publication
? $this->detail($publication, $snapshots->get($publication->id))
: $this->unavailable('not_collected')];
})->all();
}
/** @return array<string, mixed> */
- public function latestForPostPlatform(PostPlatform $postPlatform): array
+ public function latestFor(Post $post): array
{
- if ($postPlatform->status !== Status::Published || ! $postPlatform->platform_post_id) {
+ if ($post->publish_status !== PublishStatus::Published || ! $post->platform_post_id) {
return $this->unavailable('not_published');
}
- if (! in_array($postPlatform->platform->value, Platform::analyticsValues(), true)) {
+ if (! in_array($post->platform?->value, Platform::analyticsValues(), true)) {
return $this->unavailable('platform_not_supported');
}
$publication = AnalyticsPublication::query()
->with('socialAccount')
->available()
- ->where('workspace_id', $postPlatform->post->workspace_id)
- ->where('post_platform_id', $postPlatform->id)
+ ->where('workspace_id', $post->workspace_id)
+ ->where('post_id', $post->id)
->whereIn('platform', Platform::analyticsValues())
->first();
@@ -148,11 +144,11 @@ class ReadPublicationAnalytics
return $this->detail($publication, $snapshot);
}
- private function isCollectable(PostPlatform $destination): bool
+ private function isCollectable(Post $post): bool
{
- return $destination->status === Status::Published
- && filled($destination->platform_post_id)
- && in_array($destination->platform->value, Platform::analyticsValues(), true);
+ return $post->publish_status === PublishStatus::Published
+ && filled($post->platform_post_id)
+ && in_array($post->platform?->value, Platform::analyticsValues(), true);
}
/**
@@ -178,7 +174,7 @@ class ReadPublicationAnalytics
'reason' => null,
'publication' => [
'id' => $publication->id,
- 'post_platform_id' => $publication->post_platform_id,
+ 'post_id' => $publication->post_id,
'social_account_key' => $publication->social_account_key,
'platform' => $publication->platform->value,
'origin' => $publication->origin->value,
diff --git a/app/Actions/Analytics/SyncTryPostPublication.php b/app/Actions/Analytics/SyncTryPostPublication.php
index f219eb292..d8d6b6aa9 100644
--- a/app/Actions/Analytics/SyncTryPostPublication.php
+++ b/app/Actions/Analytics/SyncTryPostPublication.php
@@ -8,7 +8,7 @@ use App\Dto\Analytics\TryPostPublicationIdentity;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\PostPlatform\ContentType;
use App\Models\AnalyticsPublication;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\ContentSanitizer;
use Illuminate\Support\Str;
@@ -21,10 +21,10 @@ class SyncTryPostPublication
private readonly UpsertAnalyticsPublication $publications,
) {}
- public function handle(PostPlatform $postPlatform): AnalyticsPublication
+ public function handle(Post $post): AnalyticsPublication
{
- $postPlatform->loadMissing(['post', 'socialAccount']);
- $account = $postPlatform->socialAccount;
+ $post->loadMissing('socialAccount');
+ $account = $post->socialAccount;
if (! $account) {
throw new LogicException('A live social account is required to capture publication identity.');
@@ -32,28 +32,28 @@ class SyncTryPostPublication
return $this->fromIdentity(
TryPostPublicationIdentity::fromAccount($account, $this->accountKeys->for($account)),
- $postPlatform,
+ $post,
$account,
);
}
public function fromIdentity(
TryPostPublicationIdentity $identity,
- PostPlatform $postPlatform,
+ Post $post,
?SocialAccount $liveAccount = null,
): AnalyticsPublication {
return $this->publications->tryPost(
$identity,
- $postPlatform,
- $this->normalizedContentType($postPlatform),
- $this->excerpt($postPlatform),
+ $post,
+ $this->normalizedContentType($post),
+ $this->excerpt($post),
$liveAccount,
);
}
- private function normalizedContentType(PostPlatform $postPlatform): PublicationContentType
+ private function normalizedContentType(Post $post): PublicationContentType
{
- $specializedType = match ($postPlatform->content_type) {
+ $specializedType = match ($post->content_type) {
ContentType::InstagramReel, ContentType::FacebookReel => PublicationContentType::Reel,
ContentType::InstagramStory, ContentType::FacebookStory => PublicationContentType::Story,
ContentType::YouTubeShort => PublicationContentType::Short,
@@ -66,7 +66,7 @@ class SyncTryPostPublication
return $specializedType;
}
- $media = $postPlatform->post?->media_items;
+ $media = $post->media_items;
if (! $media || $media->isEmpty()) {
return PublicationContentType::Text;
@@ -81,9 +81,9 @@ class SyncTryPostPublication
: PublicationContentType::Image;
}
- private function excerpt(PostPlatform $postPlatform): ?string
+ private function excerpt(Post $post): ?string
{
- $content = app(ContentSanitizer::class)->plainText((string) $postPlatform->post?->content);
+ $content = app(ContentSanitizer::class)->plainText((string) $post->content);
return $content === '' ? null : Str::limit($content, 500);
}
diff --git a/app/Actions/Analytics/UpsertAnalyticsPublication.php b/app/Actions/Analytics/UpsertAnalyticsPublication.php
index e424bee2e..f9a6ec6a8 100644
--- a/app/Actions/Analytics/UpsertAnalyticsPublication.php
+++ b/app/Actions/Analytics/UpsertAnalyticsPublication.php
@@ -13,10 +13,8 @@ use App\Enums\Analytics\PublicationOrigin;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use DateTimeInterface;
-use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;
use LogicException;
@@ -55,23 +53,23 @@ class UpsertAnalyticsPublication
public function tryPost(
TryPostPublicationIdentity $identity,
- PostPlatform $postPlatform,
+ Post $post,
PublicationContentType $contentType,
?string $excerpt,
?SocialAccount $liveAccount = null,
): AnalyticsPublication {
return $this->persist(
identity: $identity,
- providerPostId: (string) $postPlatform->platform_post_id,
- providerPublishedAt: ($postPlatform->published_at ?? $postPlatform->updated_at)->toImmutable(),
+ providerPostId: (string) $post->platform_post_id,
+ providerPublishedAt: ($post->published_at ?? $post->publication_updated_at ?? $post->updated_at)->toImmutable(),
origin: PublicationOrigin::TryPost,
contentType: $contentType,
- providerContentType: $postPlatform->content_type->value,
- permalink: $postPlatform->platform_url,
+ providerContentType: $post->content_type->value,
+ permalink: $post->platform_url,
excerpt: $excerpt,
previewMetadata: null,
providerMetadata: null,
- postPlatformId: $postPlatform->id,
+ postId: $post->id,
liveAccount: $liveAccount,
);
}
@@ -81,7 +79,7 @@ class UpsertAnalyticsPublication
DB::transaction(function () use ($publication, $remoteId): void {
$current = AnalyticsPublication::query()->lockForUpdate()->findOrFail($publication->id);
- if ($current->remote_id === $remoteId || ! $current->post_platform_id) {
+ if ($current->remote_id === $remoteId || ! $current->post_id) {
return;
}
@@ -94,8 +92,8 @@ class UpsertAnalyticsPublication
->first();
if ($discovered) {
- if ($discovered->post_platform_id && $discovered->post_platform_id !== $current->post_platform_id) {
- $this->deleteImportedPost($discovered->post_platform_id);
+ if ($discovered->post_id && $discovered->post_id !== $current->post_id) {
+ $this->deleteImportedPost($discovered->post_id);
}
$discovered->dailySnapshots()->lockForUpdate()->reorder()->lazyById(100)->each(function (AnalyticsPublicationDailySnapshot $snapshot) use ($current): void {
@@ -137,20 +135,21 @@ class UpsertAnalyticsPublication
$current->remote_id = $remoteId;
$current->save();
- PostPlatform::query()->whereKey($current->post_platform_id)->update([
+ Post::query()->whereKey($current->post_id)->toBase()->update([
'platform_post_id' => $remoteId,
'platform_url' => $current->permalink,
+ 'publication_updated_at' => now(),
]);
$publication->setRawAttributes($current->getAttributes(), true);
});
}
- private function deleteImportedPost(string $postPlatformId): void
+ private function deleteImportedPost(string $postId): void
{
$post = Post::query()
->imported()
- ->whereHas('postPlatforms', fn (Builder $query): Builder => $query->whereKey($postPlatformId))
+ ->whereKey($postId)
->lockForUpdate()
->first();
@@ -177,7 +176,7 @@ class UpsertAnalyticsPublication
?string $excerpt,
?array $previewMetadata,
?array $providerMetadata,
- ?string $postPlatformId = null,
+ ?string $postId = null,
?DateTimeInterface $providerSyncedAt = null,
?SocialAccount $liveAccount = null,
): AnalyticsPublication {
@@ -195,7 +194,7 @@ class UpsertAnalyticsPublication
$excerpt,
$previewMetadata,
$providerMetadata,
- $postPlatformId,
+ $postId,
$providerSyncedAt,
$liveAccount,
true,
@@ -212,7 +211,7 @@ class UpsertAnalyticsPublication
$excerpt,
$previewMetadata,
$providerMetadata,
- $postPlatformId,
+ $postId,
$providerSyncedAt,
$liveAccount,
false,
@@ -235,12 +234,12 @@ class UpsertAnalyticsPublication
?string $excerpt,
?array $previewMetadata,
?array $providerMetadata,
- ?string $postPlatformId,
+ ?string $postId,
?DateTimeInterface $providerSyncedAt,
?SocialAccount $liveAccount,
bool $mayCreate,
): AnalyticsPublication {
- return DB::transaction(function () use ($contentType, $excerpt, $identity, $liveAccount, $mayCreate, $origin, $permalink, $postPlatformId, $previewMetadata, $providerContentType, $providerMetadata, $providerPostId, $providerPublishedAt, $providerSyncedAt): AnalyticsPublication {
+ return DB::transaction(function () use ($contentType, $excerpt, $identity, $liveAccount, $mayCreate, $origin, $permalink, $postId, $previewMetadata, $providerContentType, $providerMetadata, $providerPostId, $providerPublishedAt, $providerSyncedAt): AnalyticsPublication {
$identityFields = [
'workspace_id' => $identity->workspaceId,
'social_account_key' => $identity->socialAccountKey,
@@ -252,9 +251,9 @@ class UpsertAnalyticsPublication
->lockForUpdate()
->first();
- if (! $publication && $postPlatformId) {
+ if (! $publication && $postId) {
$publication = AnalyticsPublication::query()
- ->where('post_platform_id', $postPlatformId)
+ ->where('post_id', $postId)
->lockForUpdate()
->first();
}
@@ -275,7 +274,7 @@ class UpsertAnalyticsPublication
$values = [
'social_account_id' => $liveAccount?->id
?? SocialAccount::query()->whereKey($identity->socialAccountId)->value('id'),
- 'post_platform_id' => $postPlatformId ?? $publication->post_platform_id,
+ 'post_id' => $postId ?? $publication->post_id,
'platform_user_id' => $identity->platformUserId,
'platform' => $identity->platform,
'provider_published_at' => $providerPublishedAt,
diff --git a/app/Actions/Media/SyncOwnedMedia.php b/app/Actions/Media/SyncOwnedMedia.php
index 4b190b5b5..8606603d8 100644
--- a/app/Actions/Media/SyncOwnedMedia.php
+++ b/app/Actions/Media/SyncOwnedMedia.php
@@ -8,11 +8,9 @@ use App\Dto\MediaItem;
use App\Models\Idea;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\Media\MediaCopyBatch;
use App\Support\ThreadReplies;
use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
@@ -51,25 +49,27 @@ class SyncOwnedMedia
* owner (duplicate, recovery) that may pass through without a row, like
* the owner's own stored items do (spec 7.2: missing files are left as is).
*
- * A post's thread replies (`meta.thread_replies` of its targets) own media
- * too: their items are synced the same way and written back to the reply,
- * and their rows are kept, so write the target's meta before calling this.
+ * A post's thread replies (`meta.thread_replies`) own media too: their
+ * items are synced the same way and written back to the reply, and their
+ * rows are kept, so save the post's meta before calling this. Their errors
+ * are keyed under `$metaErrorKey` (`meta`, or `destinations.{n}.meta` in a
+ * batch), whichever list the root media came from.
*
* @param list<array<string, mixed>> $items
* @param list<array<string, mixed>> $legacyItems
* @return list<array<string, mixed>>
*/
- public static function execute(Post|Idea $owner, array $items, MediaCopyBatch $batch, string $errorKey = 'media', array $legacyItems = []): array
+ public static function execute(Post|Idea $owner, array $items, MediaCopyBatch $batch, string $errorKey = 'media', array $legacyItems = [], string $metaErrorKey = 'meta'): array
{
$ownerColumn = $owner instanceof Post ? 'post_id' : 'idea_id';
$locked = $owner::query()->whereKey($owner->getKey())->lockForUpdate()->firstOrFail();
$workspace = $owner->workspace;
$items = self::withoutRepeats(array_values($items));
- $threads = $owner instanceof Post ? self::threadsOf($owner) : collect();
- $replyItems = $threads->flatMap(fn (array $replies): array => array_merge([], ...array_column($replies, 'media')))->all();
- $ids = self::column([...$items, ...$replyItems], 'id');
- $uploadTokens = self::column([...$items, ...$replyItems], 'upload_token');
+ $replies = $locked instanceof Post ? ThreadReplies::of($locked->meta) : [];
+ $submitted = [...$items, ...self::replyMedia($replies)];
+ $ids = self::column($submitted, 'id');
+ $uploadTokens = self::column($submitted, 'upload_token');
self::lockRows($workspace->id, $ownerColumn, $owner->getKey(), $ids, $uploadTokens);
$rows = ResolveWorkspaceMedia::execute($workspace, $ids, lockForUpdate: true);
@@ -116,37 +116,23 @@ class SyncOwnedMedia
};
$final = $sync($items, $errorKey);
- $kept = self::column($final, 'id');
- $replyErrorKey = Str::beforeLast($errorKey, 'media').'meta.thread_replies';
-
- foreach ($threads as $postPlatformId => $replies) {
- foreach ($replies as $index => $reply) {
- $replies[$index]['media'] = $sync(self::withoutRepeats($reply['media']), "{$replyErrorKey}.{$index}.media");
- $kept = [...$kept, ...self::column($replies[$index]['media'], 'id')];
- }
-
- $postPlatform = $owner->postPlatforms()->whereKey($postPlatformId)->firstOrFail();
- $postPlatform->forceFill(['meta' => [...($postPlatform->meta ?? []), 'thread_replies' => $replies]])->save();
- }
+ $replies = collect($replies)
+ ->map(fn (array $reply, int $index): array => [
+ ...$reply,
+ 'media' => $sync(self::withoutRepeats($reply['media']), "{$metaErrorKey}.thread_replies.{$index}.media"),
+ ])
+ ->all();
+ $kept = self::column([...$final, ...self::replyMedia($replies)], 'id');
DeleteOwnedMedia::forRows($owner->ownedMedia()->whereNotIn('id', $kept)->pluck('id')->all());
- $owner->forceFill(['media' => $final])->save();
+ $owner->update($replies === [] ? ['media' => $final] : [
+ 'media' => $final,
+ 'meta' => [...($locked->meta ?? []), 'thread_replies' => $replies],
+ ]);
return $final;
}
- /**
- * The thread replies of each of the post's targets that has any.
- *
- * @return Collection<string, list<array{text: string, media: list<array<string, mixed>>}>>
- */
- private static function threadsOf(Post $post): Collection
- {
- return $post->postPlatforms()->get()
- ->mapWithKeys(fn (PostPlatform $postPlatform): array => [$postPlatform->id => ThreadReplies::of($postPlatform->meta)])
- ->filter(fn (array $replies): bool => $replies !== []);
- }
-
/**
* @param list<string> $ids
* @param list<string> $uploadTokens
@@ -298,6 +284,15 @@ class SyncOwnedMedia
return $owned;
}
+ /**
+ * @param list<array{media: list<array<string, mixed>>}> $replies
+ * @return list<array<string, mixed>>
+ */
+ private static function replyMedia(array $replies): array
+ {
+ return array_merge([], ...array_column($replies, 'media'));
+ }
+
/**
* @param list<array<string, mixed>> $items
* @return list<string>
diff --git a/app/Actions/Post/AppendPostMedia.php b/app/Actions/Post/AppendPostMedia.php
index 834df2c12..2b1b4f020 100644
--- a/app/Actions/Post/AppendPostMedia.php
+++ b/app/Actions/Post/AppendPostMedia.php
@@ -7,7 +7,6 @@ namespace App\Actions\Post;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\User;
use App\Support\Media\MediaCopyBatch;
use App\Support\PostApproval;
@@ -37,11 +36,9 @@ class AppendPostMedia
throw ValidationException::withMessages(['post' => PostStatusRules::editBlockedMessage()]);
}
- $post->postPlatforms()->enabled()->get()
- ->filter(fn (PostPlatform $target): bool => ContentType::derivesFromMedia($target->platform))
- ->each(fn (PostPlatform $target): bool => $target->update([
- 'content_type' => ContentType::forMedia($target->platform, $post->media ?? []),
- ]));
+ if ($post->hasDestination() && ContentType::derivesFromMedia($post->platform)) {
+ $post->update(['content_type' => ContentType::forMedia($post->platform, $post->media ?? [])]);
+ }
if ($post->status === PostStatus::Scheduled && PostApproval::isRequired($post->workspace, $actor, $post->status->value)) {
UpdatePost::execute($post->workspace, $post, ['status' => $post->status->value], $actor);
diff --git a/app/Actions/Post/Approval/NotifyApprovalDecision.php b/app/Actions/Post/Approval/NotifyApprovalDecision.php
index 567087202..2aa863fc1 100644
--- a/app/Actions/Post/Approval/NotifyApprovalDecision.php
+++ b/app/Actions/Post/Approval/NotifyApprovalDecision.php
@@ -4,45 +4,33 @@ declare(strict_types=1);
namespace App\Actions\Post\Approval;
+use App\Enums\Notification\Type;
use App\Enums\Post\ApprovalDecision;
-use App\Jobs\Post\SendApprovalDecisionEmail;
+use App\Jobs\SendNotification;
+use App\Mail\PostApproved;
+use App\Mail\PostRejected;
use App\Models\Post;
use App\Models\User;
-use Illuminate\Contracts\Cache\LockTimeoutException;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
final class NotifyApprovalDecision
{
- public const GROUPING_SECONDS = 60;
-
/**
- * Collects a decision for the member who asked for approval (see
- * Post::approvalRequester()); the cards of one request (same post_group_id)
- * decided within the grouping window share one email.
+ * Emails the member who asked for approval (see Post::approvalRequester())
+ * about one post, once the decision commits. Deciding your own request
+ * sends nothing.
*/
public static function execute(Post $post, ApprovalDecision $decision, User $approver, ?User $requester): void
{
- if ($requester === null || $requester->id === $approver->id) {
+ if (blank($requester) || $requester->id === $approver->id) {
return;
}
- $group = $post->post_group_id ?? $post->id;
- $key = "post-approval-decision:{$group}:{$decision->value}:{$approver->id}:{$requester->id}";
-
- DB::afterCommit(function () use ($key, $post, $requester, $approver, $decision): void {
- try {
- Cache::lock("{$key}:lock", 10)->block(5, function () use ($key, $post): void {
- Cache::put($key, array_values(array_unique([...Cache::get($key, []), $post->id])), now()->addDay());
- });
- } catch (LockTimeoutException $exception) {
- report($exception);
-
- return;
- }
-
- SendApprovalDecisionEmail::dispatch($key, $requester, $approver, $decision)
- ->delay(now()->addSeconds(self::GROUPING_SECONDS));
- });
+ SendNotification::dispatch(
+ $requester,
+ Type::Collaboration,
+ $decision === ApprovalDecision::Approved
+ ? new PostApproved($post->id, $approver, $requester)
+ : new PostRejected($post->id, $approver),
+ )->afterCommit();
}
}
diff --git a/app/Actions/Post/Approval/NotifyApprovalRequested.php b/app/Actions/Post/Approval/NotifyApprovalRequested.php
index 584d5ea93..b0682ca2e 100644
--- a/app/Actions/Post/Approval/NotifyApprovalRequested.php
+++ b/app/Actions/Post/Approval/NotifyApprovalRequested.php
@@ -14,8 +14,9 @@ use Illuminate\Support\Collection;
final class NotifyApprovalRequested
{
/**
- * One email per approver for one request; the posts created together for
- * several channels are listed in the same email. Never emails the requester.
+ * One email per post for every approver: posts created together for
+ * several channels are separate posts, each approved on its own. Never
+ * emails the requester.
*
* @param Collection<int, Post> $posts
*/
@@ -23,18 +24,16 @@ final class NotifyApprovalRequested
{
$workspace = $posts->first()?->workspace;
- if ($workspace === null) {
+ if (blank($workspace)) {
return;
}
- $postIds = $posts->pluck('id')->values()->all();
+ $approvers = $workspace->approvers()->reject(fn (User $approver): bool => $approver->id === $requester->id);
- $workspace->approvers()
- ->reject(fn (User $approver): bool => $approver->id === $requester->id)
- ->each(fn (User $approver) => SendNotification::dispatch(
- $approver,
- Type::Collaboration,
- new PostApprovalRequested($postIds, $requester, $approver),
- )->afterCommit());
+ $posts->each(fn (Post $post) => $approvers->each(fn (User $approver) => SendNotification::dispatch(
+ $approver,
+ Type::Collaboration,
+ new PostApprovalRequested($post->id, $requester, $approver),
+ )->afterCommit()));
}
}
diff --git a/app/Actions/Post/BakeLegacyAspectRatioCrops.php b/app/Actions/Post/BakeLegacyAspectRatioCrops.php
deleted file mode 100644
index 35e765fa5..000000000
--- a/app/Actions/Post/BakeLegacyAspectRatioCrops.php
+++ /dev/null
@@ -1,282 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Actions\Post;
-
-use App\Actions\Media\SyncOwnedMedia;
-use App\Dto\MediaItem;
-use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
-use App\Enums\SocialAccount\Platform;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Services\Media\MediaOptimizer;
-use App\Support\Media\ImageDimensions;
-use App\Support\Media\MediaCopyBatch;
-use App\Support\Social\PublishCheckpoint;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Storage;
-use Throwable;
-
-/**
- * Before TryPost 2.0 the Facebook and Instagram publishers center-cropped every
- * image to the target's `meta.aspect_ratio` at publish time; 2.0 publishes
- * images at their own ratio and drops the key. This one-off release step bakes
- * that crop into the media of every target that will publish without user
- * action (a scheduled or queued post, one pending approval, or one already
- * publishing, while the target is pending, publishing or retrying), with the
- * crop math the publishers used (`MediaOptimizer::cropToAspectRatio`), so a
- * post scheduled before the deploy publishes the image it would have
- * published. A recurring series continues from its scheduled occurrence, so
- * the next occurrence copies the baked image. Drafts and failed targets are
- * not baked: they publish only after the user acts, keep their original image
- * and lose the key like every other row, and their image is cropped, if at
- * all, in the media editor.
- *
- * Instagram feed crops every image (single or carousel); a Facebook post crops
- * its images only when the first item is an image. An image already at the
- * ratio is left as it is, as the publishers did. The cropped file becomes a
- * temporary upload that `SyncOwnedMedia` moves into the post. A post with more
- * than one enabled target is skipped: its media is shared with a destination
- * that did not crop, so it keeps its key until `posts:split-legacy-active`
- * gives each target its own post and a later run bakes it. Once handled, the
- * target's key is dropped; at the end the key is dropped from every row except
- * posts that were skipped or failed, so a rerun retries only those.
- */
-final class BakeLegacyAspectRatioCrops
-{
- public const string META_KEY = 'aspect_ratio';
-
- public const string ORIGINAL = 'original';
-
- /**
- * @var array<string, float>
- */
- private const array RATIOS = ['1:1' => 1.0, '4:5' => 4 / 5, '16:9' => 16 / 9];
-
- private const float FALLBACK_RATIO = 1.0;
-
- private const float RATIO_TOLERANCE = 0.001;
-
- private const int CHUNK = 100;
-
- /**
- * @return Builder<PostPlatform>
- */
- public static function candidates(): Builder
- {
- return PostPlatform::query()
- ->enabled()
- ->whereIn('platform', [Platform::Facebook, Platform::Instagram, Platform::InstagramFacebook])
- ->whereIn('content_type', [ContentType::InstagramFeed, ContentType::FacebookPost])
- ->whereNotNull('meta->'.self::META_KEY)
- ->where('meta->'.self::META_KEY, '!=', self::ORIGINAL)
- ->whereIn('status', [Status::Pending, Status::Publishing, Status::Retrying])
- ->whereHas('post', fn (Builder $post): Builder => $post->whereIn('status', [PostStatus::Scheduled, PostStatus::PendingApproval, PostStatus::Publishing]));
- }
-
- public static function pending(): int
- {
- return self::candidates()->distinct()->count('post_id');
- }
-
- /**
- * @return array{baked_posts: int, baked_images: int, skipped_posts: list<string>, unreadable_images: list<string>, failed_posts: list<string>, stripped_targets: int}
- */
- public static function execute(): array
- {
- $result = ['baked_posts' => 0, 'baked_images' => 0, 'skipped_posts' => [], 'unreadable_images' => [], 'failed_posts' => [], 'stripped_targets' => 0];
-
- Post::query()
- ->whereIn('id', self::candidates()->select('post_id'))
- ->select('id')
- ->orderBy('id')
- ->chunkById(self::CHUNK, function ($posts) use (&$result): void {
- foreach ($posts as $candidate) {
- try {
- $outcome = MediaCopyBatch::run(fn (MediaCopyBatch $batch): array => self::bakePost($candidate->id, $batch));
- } catch (Throwable $exception) {
- report($exception);
- $result['failed_posts'][] = $candidate->id;
-
- continue;
- }
-
- if (data_get($outcome, 'skipped')) {
- $result['skipped_posts'][] = $candidate->id;
- }
-
- $baked = (int) data_get($outcome, 'baked', 0);
- $result['baked_images'] += $baked;
- $result['baked_posts'] += $baked > 0 ? 1 : 0;
- $result['unreadable_images'] = [...$result['unreadable_images'], ...data_get($outcome, 'unreadable', [])];
- }
- });
-
- $result['stripped_targets'] = self::stripRemaining([...$result['failed_posts'], ...$result['skipped_posts']]);
-
- return $result;
- }
-
- /**
- * @return array{baked: int, skipped: bool, unreadable: list<string>}
- */
- private static function bakePost(string $postId, MediaCopyBatch $batch): array
- {
- $outcome = ['baked' => 0, 'skipped' => false, 'unreadable' => []];
- $post = Post::query()->lockForUpdate()->find($postId);
-
- if ($post === null) {
- return $outcome;
- }
-
- $targets = $post->postPlatforms()->enabled()->orderBy('id')->lockForUpdate()->get();
- $target = self::candidates()->where('post_id', $post->id)->first();
-
- if ($target === null) {
- return $outcome;
- }
-
- if ($targets->count() > 1) {
- return [...$outcome, 'skipped' => true];
- }
-
- if (PublishCheckpoint::instagramWorkflow($target->error_context) === null) {
- $ratio = self::RATIOS[(string) data_get($target->meta, self::META_KEY)] ?? self::FALLBACK_RATIO;
- $outcome = self::bakeMedia($post, $target, $ratio, $batch);
- }
-
- self::strip($target->id, $target->meta);
-
- return $outcome;
- }
-
- /**
- * @return array{baked: int, skipped: bool, unreadable: list<string>}
- */
- private static function bakeMedia(Post $post, PostPlatform $target, float $ratio, MediaCopyBatch $batch): array
- {
- $outcome = ['baked' => 0, 'skipped' => false, 'unreadable' => []];
- $items = array_values($post->media ?? []);
- $first = data_get($items, 0);
- $cropsImages = match ($target->content_type) {
- ContentType::InstagramFeed => true,
- ContentType::FacebookPost => is_array($first) && MediaItem::fromArray($first)->isImage(),
- default => false,
- };
-
- if (! $cropsImages) {
- return $outcome;
- }
-
- $baked = [];
-
- foreach ($items as $item) {
- if (! is_array($item) || ! MediaItem::fromArray($item)->isImage()) {
- $baked[] = $item;
-
- continue;
- }
-
- $bytes = rescue(fn (): ?string => Storage::get((string) data_get($item, 'path')), null, report: false);
- $dimensions = is_string($bytes) ? ImageDimensions::fromBytes($bytes) : null;
-
- if ($dimensions === null) {
- $outcome['unreadable'][] = "{$post->id}:".data_get($item, 'id');
- $baked[] = $item;
-
- continue;
- }
-
- if (abs(data_get($dimensions, 'width') / data_get($dimensions, 'height') - $ratio) < self::RATIO_TOLERANCE) {
- $baked[] = $item;
-
- continue;
- }
-
- $upload = self::croppedUpload($post, $item, $bytes, $ratio, $batch);
- $baked[] = [
- ...array_intersect_key($item, array_flip(['meta', 'source', 'source_meta'])),
- 'id' => $upload->id,
- 'upload_token' => $upload->upload_token,
- ];
- $outcome['baked']++;
- }
-
- if ($outcome['baked'] > 0) {
- $updatedAt = $post->getRawOriginal('updated_at');
- SyncOwnedMedia::execute($post, $baked, $batch);
- Post::query()->whereKey($post->id)->toBase()->update(['updated_at' => $updatedAt]);
- }
-
- return $outcome;
- }
-
- /**
- * @param array<string, mixed> $item
- */
- private static function croppedUpload(Post $post, array $item, string $bytes, float $ratio, MediaCopyBatch $batch): Media
- {
- $input = tempnam(sys_get_temp_dir(), 'bake_in_');
-
- try {
- file_put_contents($input, $bytes);
- $cropped = app(MediaOptimizer::class)->cropToAspectRatio($input, $ratio);
-
- try {
- $name = pathinfo((string) (data_get($item, 'original_filename') ?: data_get($item, 'path')), PATHINFO_FILENAME);
- $upload = $post->workspace->addMediaFromPath($cropped, "{$name}.jpg", Media::COLLECTION_UPLOADS, mimeType: 'image/jpeg');
- $batch->rememberCopy($upload->path);
- $upload->issueUploadToken();
-
- return $upload;
- } finally {
- @unlink($cropped);
- }
- } finally {
- @unlink($input);
- }
- }
-
- /**
- * @param array<string, mixed>|null $meta
- */
- private static function strip(string $postPlatformId, ?array $meta): void
- {
- $meta = (array) $meta;
- unset($meta[self::META_KEY]);
-
- PostPlatform::query()->whereKey($postPlatformId)->toBase()->update(['meta' => json_encode($meta)]);
- }
-
- /**
- * @param list<string> $keptPostIds
- */
- private static function stripRemaining(array $keptPostIds): int
- {
- $stripped = 0;
-
- DB::table('post_platforms')
- ->whereNotNull('meta->'.self::META_KEY)
- ->when($keptPostIds !== [], fn ($query) => $query->whereNotIn('post_id', $keptPostIds))
- ->select(['id', 'meta'])
- ->chunkById(500, function ($rows) use (&$stripped): void {
- foreach ($rows as $row) {
- $meta = json_decode((string) $row->meta, true);
-
- if (! is_array($meta)) {
- continue;
- }
-
- self::strip($row->id, $meta);
- $stripped++;
- }
- });
-
- return $stripped;
- }
-}
diff --git a/app/Actions/Post/BuildCalendarPageProps.php b/app/Actions/Post/BuildCalendarPageProps.php
index 9154d3d2e..707235cfa 100644
--- a/app/Actions/Post/BuildCalendarPageProps.php
+++ b/app/Actions/Post/BuildCalendarPageProps.php
@@ -65,11 +65,8 @@ class BuildCalendarPageProps
return $workspaceAccounts ??= $channel ? collect() : $workspace->socialAccounts()->get();
};
- $scopedPosts = fn (): Builder => BuildPublishPageProps::cardQuery($workspace->posts(), $scopedChannelIds, $labelIds, $untagged)
- ->when($scopedChannelIds !== null, fn (Builder $query) => $query->whereHas(
- 'postPlatforms',
- fn (Builder $platforms) => $platforms->enabled()->whereIn('social_account_id', $scopedChannelIds),
- ))
+ $scopedPosts = fn (): Builder => BuildPublishPageProps::cardQuery($workspace->posts(), $labelIds, $untagged)
+ ->onChannels($scopedChannelIds)
->visiblePendingApprovalsFor(BuildPublishPageProps::pendingApprovalsRequester($request->user(), $workspace));
$range = [$rangeStart->utc(), $rangeEnd->utc()];
diff --git a/app/Actions/Post/BuildPublishPageProps.php b/app/Actions/Post/BuildPublishPageProps.php
index b9763fb03..bd6aba380 100644
--- a/app/Actions/Post/BuildPublishPageProps.php
+++ b/app/Actions/Post/BuildPublishPageProps.php
@@ -47,7 +47,6 @@ class BuildPublishPageProps
public const SENT_STATUSES = [
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
];
@@ -93,7 +92,7 @@ class BuildPublishPageProps
$tab = $resolveTab($request->query('tab'), $focusedPostId);
- $cards = fn (): Builder => self::cardQuery(clone $basePosts, $scopedChannelIds, $labelIds, $untagged);
+ $cards = fn (): Builder => self::cardQuery(clone $basePosts, $labelIds, $untagged);
$hasDataResult = null;
$hasData = function () use (&$hasDataResult, $tab, $workspace, $channel, $requester): bool {
@@ -183,10 +182,7 @@ class BuildPublishPageProps
*/
private static function hasData(string $tab, Workspace $workspace, ?SocialAccount $channel, ?User $requester): bool
{
- $posts = $workspace->posts()->when($channel !== null, fn (Builder $query) => $query->whereHas(
- 'postPlatforms',
- fn (Builder $platforms) => $platforms->enabled()->where('social_account_id', $channel->id),
- ));
+ $posts = $workspace->posts()->when(filled($channel), fn (Builder $query) => $query->where('posts.social_account_id', $channel->id));
return match ($tab) {
self::TAB_QUEUE => $posts->where(fn (Builder $query) => $query
@@ -288,16 +284,13 @@ class BuildPublishPageProps
}
/**
- * @param list<string>|null $channelIds
* @param list<string> $labelIds
*/
- public static function cardQuery(HasMany $basePosts, ?array $channelIds, array $labelIds, bool $untagged): Builder
+ public static function cardQuery(HasMany $basePosts, array $labelIds, bool $untagged): Builder
{
return $basePosts->getQuery()
->with([
- 'postPlatforms' => fn ($platforms) => $platforms->enabled()
- ->when($channelIds !== null, fn ($platforms) => $platforms->whereIn('social_account_id', $channelIds))
- ->with('socialAccount'),
+ 'socialAccount',
'user.avatarMedia',
'labels',
])
@@ -411,13 +404,9 @@ class BuildPublishPageProps
$post->unsetRelation('approvalRequestedBy');
$post->setAttribute('can_delete', $deletable[$authorship] && ! PostStatusRules::blocksDeletion($post));
- foreach ($post->postPlatforms as $platform) {
- $account = $platform->socialAccount;
-
- if ($account === null) {
- continue;
- }
+ $account = $post->socialAccount;
+ if (filled($account)) {
$hasSchedule[$account->id] ??= $account->hasPostingSchedule();
$account->setAttribute('has_posting_schedule', $hasSchedule[$account->id]);
}
@@ -436,15 +425,10 @@ class BuildPublishPageProps
return;
}
- $metrics = app(ReadPublicationAnalytics::class)->latestForPost(
- $first,
- $posts->flatMap(fn (Post $post) => $post->postPlatforms)->values(),
- );
+ $metrics = app(ReadPublicationAnalytics::class)->latestForPosts($first->workspace_id, $posts->values());
foreach ($posts as $post) {
- $post->setAttribute('metrics', $post->postPlatforms
- ->mapWithKeys(fn ($platform): array => [$platform->id => data_get($metrics, $platform->id)])
- ->all());
+ $post->setAttribute('metrics', data_get($metrics, $post->id));
}
}
}
diff --git a/app/Actions/Post/CreateChannelPost.php b/app/Actions/Post/CreateChannelPost.php
index 7779b3df4..2dff0ed42 100644
--- a/app/Actions/Post/CreateChannelPost.php
+++ b/app/Actions/Post/CreateChannelPost.php
@@ -6,10 +6,10 @@ namespace App\Actions\Post;
use App\Actions\Media\SyncOwnedMedia;
use App\Actions\Post\Queue\ReflowChannelQueue;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
@@ -24,7 +24,7 @@ use Illuminate\Validation\ValidationException;
class CreateChannelPost
{
/**
- * Create one post with exactly one publishing target from a resolved destination.
+ * Create one post for one channel from a resolved destination.
* A destination with a `queue` position is enqueued on its channel, so the caller
* must hold that channel's queue lock and run this inside a DB transaction.
* The destination's media ends owned by the new post (see SyncOwnedMedia).
@@ -41,7 +41,7 @@ class CreateChannelPost
$position = data_get($destination, 'queue');
$pending = $status === PostStatus::PendingApproval;
- $post = $workspace->posts()->create([
+ $post = $workspace->posts()->forceCreate([
'post_group_id' => data_get($destination, 'post_group_id') ?? (string) Str::uuid7(),
'user_id' => $user->id,
'content' => $destination['content'],
@@ -58,15 +58,11 @@ class CreateChannelPost
? Carbon::parse($destination['scheduled_at'])->utc()
: null,
...($pending ? PostApproval::transition(PostStatus::Draft, PostStatus::PendingApproval, $user, $position instanceof QueuePosition ? $position : null) : []),
- ]);
-
- $post->postPlatforms()->create([
'social_account_id' => $account->id,
'platform' => $account->platform,
...$account->channelSnapshot(),
'content_type' => $destination['content_type'],
- 'status' => PostPlatformStatus::Pending,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Pending,
'meta' => PostPlatformMetaRules::normalize($destination['meta'] ?? []),
]);
@@ -76,6 +72,7 @@ class CreateChannelPost
$batch,
data_get($destination, 'media_error_key', 'media'),
data_get($destination, 'legacy_media', []),
+ data_get($destination, 'meta_error_key', 'meta'),
);
if ($destination['label_ids'] !== []) {
diff --git a/app/Actions/Post/DeleteChannelPosts.php b/app/Actions/Post/DeleteChannelPosts.php
index 631bce726..bd1075380 100644
--- a/app/Actions/Post/DeleteChannelPosts.php
+++ b/app/Actions/Post/DeleteChannelPosts.php
@@ -5,158 +5,52 @@ declare(strict_types=1);
namespace App\Actions\Post;
use App\Actions\Media\DeleteOwnedMedia;
-use App\Enums\Post\Status as PostStatus;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
-use Closure;
-use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
/**
* Deletes every post of a channel that is going away, whatever its status or
- * origin, quietly: no post.deleted webhook, notification or observer. A legacy
- * post that still publishes through another channel only loses this channel's
- * target. Analytics publications stay and are unlinked by the FK, so the same
+ * origin, quietly: no post.deleted webhook, notification or observer.
+ * Analytics publications stay and are unlinked by the FK, so the same
* identity connected again imports its posts afresh.
*/
class DeleteChannelPosts
{
- /**
- * @return array{deleted_posts: int, detached_targets: int}
- */
- public static function forAccount(SocialAccount $account): array
- {
- return self::purge(
- fn (Builder $targets): Builder => $targets->where('social_account_id', $account->id),
- fn (Builder $live): Builder => $live->where('social_account_id', '!=', $account->id),
- $account->workspace_id,
- );
- }
-
- /**
- * Targets left without an account by a disconnect from before channels
- * took their posts with them.
- *
- * @return array{deleted_posts: int, detached_targets: int}
- */
- public static function orphaned(?string $workspaceId = null): array
- {
- return self::purge(self::orphanedTargets(...), self::anyChannel(...), $workspaceId);
- }
-
- /**
- * What `orphaned()` would delete and detach, without changing anything.
- *
- * @return array{deleted_posts: int, detached_targets: int}
- */
- public static function orphanedPlan(?string $workspaceId = null): array
+ public static function forAccount(SocialAccount $account): int
{
- [$posts, $liveElsewhere] = self::scopes(self::orphanedTargets(...), self::anyChannel(...), $workspaceId);
-
- return [
- 'deleted_posts' => $posts()->whereDoesntHave('postPlatforms', $liveElsewhere)->count(),
- 'detached_targets' => self::orphanedTargets(PostPlatform::query())
- ->whereIn('post_id', $posts()->whereHas('postPlatforms', $liveElsewhere)->select('id'))
- ->count(),
- ];
- }
-
- /**
- * @param Builder<PostPlatform> $targets
- * @return Builder<PostPlatform>
- */
- private static function orphanedTargets(Builder $targets): Builder
- {
- return $targets->whereNull('social_account_id');
- }
-
- /**
- * @param Builder<PostPlatform> $targets
- * @return Builder<PostPlatform>
- */
- private static function anyChannel(Builder $targets): Builder
- {
- return $targets;
- }
-
- /**
- * The posts that have a target on the channel, and the scope of their
- * targets that still publish elsewhere.
- *
- * @param Closure(Builder<PostPlatform>): Builder<PostPlatform> $channelTargets
- * @param Closure(Builder<PostPlatform>): Builder<PostPlatform> $otherChannels
- * @return array{0: Closure(): Builder<Post>, 1: Closure(Builder<PostPlatform>): Builder<PostPlatform>}
- */
- private static function scopes(Closure $channelTargets, Closure $otherChannels, ?string $workspaceId): array
- {
- return [
- fn (): Builder => Post::query()
- ->when($workspaceId !== null, fn (Builder $query): Builder => $query->where('workspace_id', $workspaceId))
- ->whereHas('postPlatforms', $channelTargets),
- fn (Builder $targets): Builder => $otherChannels($targets->enabled()->whereNotNull('social_account_id')),
- ];
- }
-
- /**
- * @param Closure(Builder<PostPlatform>): Builder<PostPlatform> $channelTargets
- * @param Closure(Builder<PostPlatform>): Builder<PostPlatform> $otherChannels
- * @return array{deleted_posts: int, detached_targets: int}
- */
- private static function purge(Closure $channelTargets, Closure $otherChannels, ?string $workspaceId): array
- {
- [$posts, $liveElsewhere] = self::scopes($channelTargets, $otherChannels, $workspaceId);
-
$deletedPosts = 0;
- $posts()
- ->whereDoesntHave('postPlatforms', $liveElsewhere)
- ->select('id')
- ->chunkById(PruneExpiredPostHistory::CHUNK, function (Collection $chunk) use (&$deletedPosts): void {
- $ids = $chunk->modelKeys();
-
- self::pruneGoogleBusinessImages(PostPlatform::query()->whereIn('post_id', $ids));
+ Post::query()
+ ->where('social_account_id', $account->id)
+ ->select(['id', 'platform'])
+ ->chunkById(PruneExpiredPostHistory::CHUNK, function (Collection $posts) use (&$deletedPosts): void {
+ self::pruneGoogleBusinessImages($posts);
- DB::transaction(function () use ($ids): void {
- DeleteOwnedMedia::forPosts($ids);
- Post::query()->whereKey($ids)->delete();
+ DB::transaction(function () use ($posts): void {
+ DeleteOwnedMedia::forPosts($posts->modelKeys());
+ Post::query()->whereKey($posts->modelKeys())->delete();
});
- $deletedPosts += count($ids);
- });
-
- $detachedTargets = 0;
-
- $posts()
- ->whereHas('postPlatforms', $liveElsewhere)
- ->select(['id', 'status'])
- ->chunkById(PruneExpiredPostHistory::CHUNK, function (Collection $chunk) use ($channelTargets, &$detachedTargets): void {
- $targets = $channelTargets(PostPlatform::query()->whereIn('post_id', $chunk->modelKeys()));
-
- self::pruneGoogleBusinessImages(clone $targets);
- $detachedTargets += $targets->delete();
-
- $chunk
- ->filter(fn (Post $post): bool => $post->status === PostStatus::Publishing)
- ->each(fn (Post $post) => app(FinalizePostPublication::class)->handle($post));
+ $deletedPosts += $posts->count();
});
- return ['deleted_posts' => $deletedPosts, 'detached_targets' => $detachedTargets];
+ return $deletedPosts;
}
/**
* Deletes the images once the caller's transaction commits, so a rolled
* back disconnect keeps them.
*
- * @param Builder<PostPlatform> $targets
+ * @param Collection<int, Post> $posts
*/
- private static function pruneGoogleBusinessImages(Builder $targets): void
+ private static function pruneGoogleBusinessImages(Collection $posts): void
{
- $ids = $targets->where('platform', Platform::GoogleBusiness)->pluck('id');
+ $googleBusiness = $posts->filter(fn (Post $post): bool => $post->platform === Platform::GoogleBusiness)->values();
- DB::afterCommit(fn () => $ids->each(fn (string $id) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($id)));
+ DB::afterCommit(fn () => $googleBusiness->each(fn (Post $post) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($post)));
}
}
diff --git a/app/Actions/Post/DeletePost.php b/app/Actions/Post/DeletePost.php
index b1f058015..8603827d1 100644
--- a/app/Actions/Post/DeletePost.php
+++ b/app/Actions/Post/DeletePost.php
@@ -37,20 +37,16 @@ class DeletePost
throw ValidationException::withMessages(['post' => __('posts.flash.cannot_delete_published')]);
}
- $googleBusinessIds = $post->postPlatforms()
- ->where('platform', Platform::GoogleBusiness)
- ->pluck('id');
-
AnalyticsPublication::query()
- ->whereIn('post_platform_id', $post->postPlatforms()->pluck('id')->all())
+ ->where('post_id', $post->id)
->update(['post_dismissed_at' => now()]);
DeleteOwnedMedia::forPosts([$postId]);
$post->delete();
- DB::afterCommit(fn () => $googleBusinessIds->each(
- fn (string $id) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($id),
- ));
+ if ($post->platform === Platform::GoogleBusiness) {
+ DB::afterCommit(fn () => app(GoogleBusinessDerivativeCleaner::class)->cleanup($post));
+ }
return true;
});
diff --git a/app/Actions/Post/DuplicatePost.php b/app/Actions/Post/DuplicatePost.php
index 4acce903e..60d2184f8 100644
--- a/app/Actions/Post/DuplicatePost.php
+++ b/app/Actions/Post/DuplicatePost.php
@@ -7,7 +7,6 @@ namespace App\Actions\Post;
use App\Enums\Post\CreatedVia;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\User;
use App\Support\Media\MediaCopyBatch;
use App\Support\PostPlatformMetaRules;
@@ -15,29 +14,21 @@ use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException;
/**
- * Duplicate one account's version into an independent draft.
+ * Duplicate a post into an independent draft for the same channel.
*/
class DuplicatePost
{
- public static function execute(Post $original, User $user, ?string $targetId = null): Post
+ public static function execute(Post $original, User $user): Post
{
- return MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($original, $user, $targetId): Post {
- $targets = $original->postPlatforms()
- ->enabled()
- ->whereHas('socialAccount')
- ->get();
- $target = $targetId === null && $targets->count() === 1
- ? $targets->first()
- : $targets->firstWhere('id', $targetId);
-
- if ($target === null) {
+ return MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($original, $user): Post {
+ if (blank($original->socialAccount)) {
throw ValidationException::withMessages([
- 'post_platform_id' => __('validation.exists', ['attribute' => 'post platform']),
+ 'post' => __('posts.errors.choose_channel'),
]);
}
return CreateChannelPost::execute($original->workspace, $user, [
- ...self::destination($original, $target),
+ ...self::destination($original),
'status' => PostStatus::Draft->value,
'created_via' => CreatedVia::Web,
], $batch);
@@ -45,12 +36,12 @@ class DuplicatePost
}
/**
- * The original's content, media, labels and per-platform settings for one target,
- * ready for CreateChannelPost.
+ * The original's content, media, labels, channel and settings, ready for
+ * CreateChannelPost.
*
* @return array<string, mixed>
*/
- public static function destination(Post $original, PostPlatform $target): array
+ public static function destination(Post $original): array
{
return [
'content' => $original->content,
@@ -59,9 +50,9 @@ class DuplicatePost
'meta' => data_get($item, 'meta'),
...array_intersect_key($item, array_flip(['source', 'source_meta'])),
], $original->media ?? []),
- 'social_account_id' => $target->social_account_id,
- 'content_type' => $target->content_type->value,
- 'meta' => Arr::except($target->meta ?? [], PostPlatformMetaRules::SYSTEM_KEYS),
+ 'social_account_id' => $original->social_account_id,
+ 'content_type' => $original->content_type->value,
+ 'meta' => Arr::except($original->meta ?? [], PostPlatformMetaRules::SYSTEM_KEYS),
'label_ids' => $original->labels()->pluck('workspace_labels.id')->all(),
'legacy_media' => $original->media ?? [],
];
diff --git a/app/Actions/Post/FinalizePostPublication.php b/app/Actions/Post/FinalizePostPublication.php
index fb42cf8d9..97c2f346b 100644
--- a/app/Actions/Post/FinalizePostPublication.php
+++ b/app/Actions/Post/FinalizePostPublication.php
@@ -5,18 +5,18 @@ declare(strict_types=1);
namespace App\Actions\Post;
use App\Enums\Notification\Type;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Jobs\SendNotification;
use App\Mail\PostPublished;
use App\Mail\PostPublishFailed;
use App\Models\Post;
-use App\Models\PostPlatform;
+use App\Models\User;
use Illuminate\Support\Facades\DB;
/**
- * Settles a post once every enabled target has reached a terminal state, and
- * notifies the owner once. Shared by PublishToSocialPlatform, PublishPost::failed,
+ * Settles a post once its publication has reached a terminal state, and
+ * notifies the workspace once. Shared by PublishToSocialPlatform, PublishPost::failed,
* RecoverStuckPosts, and ReconcileGoogleBusinessPost.
*/
class FinalizePostPublication
@@ -26,7 +26,7 @@ class FinalizePostPublication
/** @var array{post: Post, successful: bool}|null $outcome */
$outcome = DB::transaction(function () use ($post): ?array {
$post = Post::query()
- ->with(['workspace.owner', 'postPlatforms.socialAccount'])
+ ->with(['workspace', 'socialAccount'])
->whereKey($post->id)
->lockForUpdate()
->first();
@@ -35,32 +35,25 @@ class FinalizePostPublication
return null;
}
- $targets = $post->postPlatforms->where('enabled', true);
-
- if ($targets->isEmpty()) {
+ if (! $post->hasChannel() && $post->publish_status->isInFlight()) {
if ($post->status !== PostStatus::Publishing) {
return null;
}
+ $post->markPublicationFailed(__('posts.errors.choose_channel'));
$post->markAsFailed();
return ['post' => $post, 'successful' => false];
}
- $finished = $targets->filter(fn (PostPlatform $target): bool => $target->status->isFinished());
- $published = $finished->where('status', PostPlatformStatus::Published);
- $failed = $finished->reject(fn (PostPlatform $target): bool => $target->status === PostPlatformStatus::Published);
-
- if ($finished->count() < $targets->count()) {
+ if (! $post->publish_status->isFinished()) {
return null;
}
- $successful = $failed->isEmpty();
+ $successful = $post->publish_status === PublishStatus::Published;
if ($successful) {
$post->markAsPublished();
- } elseif ($published->isNotEmpty()) {
- $post->markAsPartiallyPublished();
} else {
$post->markAsFailed();
}
@@ -77,18 +70,17 @@ class FinalizePostPublication
$this->notify($outcome['post'], $outcome['successful']);
}
+ /**
+ * Emails every member of the workspace (the owner is always one); each
+ * one's notification preferences decide whether it is sent.
+ */
private function notify(Post $post, bool $successful): void
{
- $owner = $post->workspace->owner;
-
- if (! $owner) {
- return;
- }
-
- SendNotification::dispatch(
- user: $owner,
- type: $successful ? Type::PostPublished : Type::PostFailed,
- mailable: $successful ? new PostPublished($post) : new PostPublishFailed($post),
- );
+ $post->workspace->members()->get()
+ ->each(fn (User $member) => SendNotification::dispatch(
+ user: $member,
+ type: $successful ? Type::PostPublished : Type::PostFailed,
+ mailable: $successful ? new PostPublished($post) : new PostPublishFailed($post),
+ ));
}
}
diff --git a/app/Actions/Post/HostInlineMedia.php b/app/Actions/Post/HostInlineMedia.php
index 3e9b380e8..fcb28df4e 100644
--- a/app/Actions/Post/HostInlineMedia.php
+++ b/app/Actions/Post/HostInlineMedia.php
@@ -48,13 +48,19 @@ class HostInlineMedia
}
}
- return self::threadReplies($workspace, $data, 'destinations', $fetched);
+ foreach (data_get($data, 'destinations', []) as $index => $destination) {
+ if (is_array(data_get($destination, 'meta'))) {
+ $data['destinations'][$index]['meta'] = self::threadReplies($workspace, data_get($destination, 'meta'), "destinations.{$index}.meta", $fetched);
+ }
+ }
+
+ return $data;
}
/**
- * Host the media of a single post request and of the thread replies of
- * its targets (`platforms.*.meta.thread_replies.*.media`), so a URL is
- * accepted wherever a post takes media.
+ * Host the media of a single post request and of its thread replies
+ * (`meta.thread_replies.*.media`), so a URL is accepted wherever a post
+ * takes media.
*
* @param array<MediaType> $allowedTypes
* @param array<string, mixed> $data
@@ -70,7 +76,11 @@ class HostInlineMedia
$data['media'] = self::execute($workspace, $allowedTypes, $data['media'], fetched: $fetched);
}
- return self::threadReplies($workspace, $data, 'platforms', $fetched);
+ if (is_array(data_get($data, 'meta'))) {
+ $data['meta'] = self::threadReplies($workspace, data_get($data, 'meta'), 'meta', $fetched);
+ }
+
+ return $data;
}
/**
@@ -146,37 +156,29 @@ class HostInlineMedia
}
/**
- * Host the reply media of every target listed under `$listKey` that
- * carries a URL. Replies sent only as ids or upload tokens are left for
- * the save to resolve, as before.
- *
- * @param array<string, mixed> $data
+ * @param array<string, mixed> $meta
* @param array<string, string> $fetched
* @return array<string, mixed>
- *
- * @throws ValidationException
*/
- private static function threadReplies(Workspace $workspace, array $data, string $listKey, array &$fetched): array
+ private static function threadReplies(Workspace $workspace, array $meta, string $errorPrefix, array &$fetched): array
{
- foreach ((array) data_get($data, $listKey, []) as $target => $entry) {
- foreach ((array) data_get($entry, 'meta.thread_replies', []) as $index => $reply) {
- $media = (array) data_get($reply, 'media', []);
+ foreach ((array) data_get($meta, 'thread_replies', []) as $index => $reply) {
+ $media = (array) data_get($reply, 'media', []);
- if (! collect($media)->contains(fn (mixed $item): bool => filled(data_get($item, 'url')))) {
- continue;
- }
-
- $data[$listKey][$target]['meta']['thread_replies'][$index]['media'] = self::execute(
- $workspace,
- MediaType::cases(),
- $media,
- "{$listKey}.{$target}.meta.thread_replies.{$index}.media",
- $fetched,
- );
+ if (! collect($media)->contains(fn (mixed $item): bool => filled(data_get($item, 'url')))) {
+ continue;
}
+
+ $meta['thread_replies'][$index]['media'] = self::execute(
+ $workspace,
+ MediaType::cases(),
+ $media,
+ "{$errorPrefix}.thread_replies.{$index}.media",
+ $fetched,
+ );
}
- return $data;
+ return $meta;
}
/**
diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.php
index 22e757c43..ccccf9102 100644
--- a/app/Actions/Post/ImportExternalPosts.php
+++ b/app/Actions/Post/ImportExternalPosts.php
@@ -8,13 +8,12 @@ use App\Actions\Analytics\UpsertAnalyticsPublication;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Analytics\PublicationOrigin;
use App\Enums\Post\Origin;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Models\AnalyticsPublication;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Social\ContentSanitizer;
use App\Support\PostHistoryRetention;
@@ -107,8 +106,8 @@ class ImportExternalPosts
->orderByDesc('provider_published_at')
->orderByDesc('id')
->limit($limit)
- ->get(['id', 'post_platform_id', 'post_dismissed_at'])
- ->filter(fn (AnalyticsPublication $publication): bool => $publication->post_platform_id === null && $publication->post_dismissed_at === null)
+ ->get(['id', 'post_id', 'post_dismissed_at'])
+ ->filter(fn (AnalyticsPublication $publication): bool => blank($publication->post_id) && blank($publication->post_dismissed_at))
->pluck('id')
->values()
->all();
@@ -119,15 +118,15 @@ class ImportExternalPosts
return DB::transaction(function () use ($account, $publicationId): ?string {
$publication = AnalyticsPublication::query()->lockForUpdate()->find($publicationId);
- if ($publication === null || $publication->post_platform_id !== null || $publication->post_dismissed_at !== null) {
+ if (blank($publication) || filled($publication->post_id) || filled($publication->post_dismissed_at)) {
return null;
}
$existing = self::tryPostTarget($account, $publication);
if ($existing !== null) {
- if (! AnalyticsPublication::query()->where('post_platform_id', $existing->id)->exists()) {
- $publication->update(['post_platform_id' => $existing->id]);
+ if (! AnalyticsPublication::query()->where('post_id', $existing->id)->exists()) {
+ $publication->update(['post_id' => $existing->id]);
}
return null;
@@ -141,14 +140,14 @@ class ImportExternalPosts
return null;
}
- $postPlatform = Post::withoutEvents(fn (): PostPlatform => self::createPost($account, $publication));
- $publication->update(['post_platform_id' => $postPlatform->id]);
+ $post = Post::withoutEvents(fn (): Post => self::createPost($account, $publication));
+ $publication->update(['post_id' => $post->id]);
- return $postPlatform->post_id;
+ return $post->id;
});
}
- private static function tryPostTarget(SocialAccount $account, AnalyticsPublication $publication): ?PostPlatform
+ private static function tryPostTarget(SocialAccount $account, AnalyticsPublication $publication): ?Post
{
$remoteIds = collect([
$publication->remote_id,
@@ -156,10 +155,10 @@ class ImportExternalPosts
$account->platform === Platform::Facebook ? data_get($publication->provider_metadata, 'photo_id') : null,
])->filter(fn (mixed $id): bool => is_string($id) && filled($id))->values()->all();
- return PostPlatform::query()
+ return Post::query()
->where('social_account_id', $account->id)
->whereIn('platform_post_id', $remoteIds)
- ->whereHas('post', fn (Builder $post): Builder => $post->where('workspace_id', $account->workspace_id))
+ ->where('workspace_id', $account->workspace_id)
->first();
}
@@ -171,7 +170,7 @@ class ImportExternalPosts
{
$remoteId = $publication->remote_id;
- return filled($remoteId) && PostPlatform::query()
+ return filled($remoteId) && Post::query()
->where('social_account_id', $account->id)
->where(fn (Builder $query): Builder => $query
->whereJsonContains('thread_reply_ids', $remoteId)
@@ -197,14 +196,14 @@ class ImportExternalPosts
if ($targets->count() > 1
|| blank(Str::squish((string) $publication->excerpt))
- || $targets->contains(fn (PostPlatform $target): bool => $target->status !== PostPlatformStatus::Published)) {
+ || $targets->contains(fn (Post $target): bool => $target->publish_status !== PublishStatus::Published)) {
if (! Cache::add("import-external-posts:ambiguous:{$publication->id}", true, now()->addDay())) {
return true;
}
Log::warning('External publication identity is ambiguous; not imported.', [
'analytics_publication_id' => $publication->id,
- 'post_platform_ids' => $targets->modelKeys(),
+ 'post_ids' => $targets->modelKeys(),
]);
return true;
@@ -218,17 +217,18 @@ class ImportExternalPosts
return true;
}
- $publication->update(['post_platform_id' => $target->id]);
- PostPlatform::query()->whereKey($target->id)->update([
+ $publication->update(['post_id' => $target->id]);
+ Post::query()->whereKey($target->id)->toBase()->update([
'platform_post_id' => $publication->remote_id,
'platform_url' => $publication->permalink ?? $target->platform_url,
+ 'publication_updated_at' => now(),
]);
return true;
}
/**
- * @return Collection<int, PostPlatform>
+ * @return Collection<int, Post>
*/
private static function matchingTryPostTargets(SocialAccount $account, AnalyticsPublication $publication): Collection
{
@@ -241,22 +241,22 @@ class ImportExternalPosts
$publishedAt = $publication->provider_published_at->toImmutable();
- return PostPlatform::query()
+ return Post::query()
->where('social_account_id', $account->id)
- ->enabled()
->where(fn (Builder $query): Builder => self::matchingPublicationState($query, $account->platform, $publishedAt, $window))
->whereIn('content_type', self::compatibleContentTypes(ContentType::fromPublication($account->platform, $publication->content_type)))
- ->whereHas('post', fn (Builder $post): Builder => $post->createdInTryPost()->where('workspace_id', $account->workspace_id))
+ ->createdInTryPost()
+ ->where('workspace_id', $account->workspace_id)
->where(fn (Builder $query): Builder => $query
->whereDoesntHave('analyticsPublication')
->orWhereHas('analyticsPublication', fn (Builder $linked): Builder => $linked
->where('origin', PublicationOrigin::TryPost)
->whereNull('provider_synced_at')
- ->whereColumn('analytics_publications.remote_id', 'post_platforms.platform_post_id')))
- ->with(['post:id,content', 'analyticsPublication'])
+ ->whereColumn('analytics_publications.remote_id', 'posts.platform_post_id')))
+ ->with('analyticsPublication')
->get()
- ->filter(fn (PostPlatform $target): bool => self::sameText(
- $target->content_type->isCaptionless() ? '' : (string) $target->post?->content,
+ ->filter(fn (Post $target): bool => self::sameText(
+ $target->content_type->isCaptionless() ? '' : (string) $target->content,
$text,
$account->platform,
))
@@ -267,18 +267,18 @@ class ImportExternalPosts
{
$interval = [$publishedAt->subMinutes($window), $publishedAt->addMinutes($window)];
- $query->where(fn (Builder $sent): Builder => $sent->published()->whereBetween('published_at', $interval));
+ $query->where(fn (Builder $sent): Builder => $sent->publicationPublished()->whereBetween('published_at', $interval));
if (! in_array($platform, [Platform::Instagram, Platform::InstagramFacebook], true)) {
return $query;
}
return $query->orWhere(fn (Builder $pending): Builder => $pending
- ->whereBetween('updated_at', $interval)
+ ->whereBetween('publication_updated_at', $interval)
->where(fn (Builder $state): Builder => $state
- ->where('status', PostPlatformStatus::Publishing)
+ ->where('publish_status', PublishStatus::Publishing)
->orWhere(fn (Builder $retry): Builder => $retry
- ->where('status', PostPlatformStatus::Retrying)
+ ->where('publish_status', PublishStatus::Retrying)
->whereNotNull('error_context->'.PublishCheckpoint::INSTAGRAM_WORKFLOW.'->container_id'))));
}
@@ -322,11 +322,9 @@ class ImportExternalPosts
&& Str::startsWith($sent, $truncated);
}
- private static function createPost(SocialAccount $account, AnalyticsPublication $publication): PostPlatform
+ private static function createPost(SocialAccount $account, AnalyticsPublication $publication): Post
{
- $publishedAt = $publication->provider_published_at;
-
- $post = Post::query()->create([
+ return Post::query()->forceCreate([
'workspace_id' => $account->workspace_id,
'post_group_id' => (string) Str::uuid7(),
'user_id' => null,
@@ -334,19 +332,14 @@ class ImportExternalPosts
'media' => [],
'status' => PostStatus::Published,
'origin' => Origin::Network,
- 'published_at' => $publishedAt,
- ]);
-
- return $post->postPlatforms()->create([
+ 'published_at' => $publication->provider_published_at,
'social_account_id' => $account->id,
'platform' => $account->platform,
...$account->channelSnapshot(),
'content_type' => ContentType::fromPublication($account->platform, $publication->content_type),
- 'status' => PostPlatformStatus::Published,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Published,
'platform_post_id' => $publication->remote_id,
'platform_url' => $publication->permalink,
- 'published_at' => $publishedAt,
'meta' => [],
]);
}
diff --git a/app/Actions/Post/PruneExpiredPostHistory.php b/app/Actions/Post/PruneExpiredPostHistory.php
index 06cf5f542..94283fbb3 100644
--- a/app/Actions/Post/PruneExpiredPostHistory.php
+++ b/app/Actions/Post/PruneExpiredPostHistory.php
@@ -18,7 +18,7 @@ class PruneExpiredPostHistory
public static function execute(CarbonInterface $cutoff, bool $dryRun = false): int
{
$query = Post::query()
- ->whereIn('status', [Status::Published, Status::PartiallyPublished])
+ ->where('status', Status::Published)
->whereNotNull('published_at')
->where('published_at', '<', $cutoff);
diff --git a/app/Actions/Post/Queue/BuildQueueTimeline.php b/app/Actions/Post/Queue/BuildQueueTimeline.php
index cc2f3a55f..cf3a2c4dd 100644
--- a/app/Actions/Post/Queue/BuildQueueTimeline.php
+++ b/app/Actions/Post/Queue/BuildQueueTimeline.php
@@ -27,16 +27,15 @@ class BuildQueueTimeline
->where('workspace_id', $workspace->id)
->holdingSlot()
->whereBetween('scheduled_at', [now(), $until])
- ->whereHas('postPlatforms', fn ($platforms) => $platforms->enabled()->whereIn('social_account_id', $channelIds))
+ ->whereIn('social_account_id', $channelIds)
->matchingLabelFilter($labelIds, $untagged)
- ->with(['postPlatforms' => fn ($platforms) => $platforms->enabled()->whereIn('social_account_id', $channelIds)->orderBy('created_at')->orderBy('id')])
->get();
$items = [];
$occupied = [];
foreach ($posts as $post) {
- $channelId = data_get($post->postPlatforms->first(), 'social_account_id');
+ $channelId = $post->social_account_id;
if ($channelId === null) {
continue;
diff --git a/app/Actions/Post/Queue/ListTakenSlots.php b/app/Actions/Post/Queue/ListTakenSlots.php
index d15b22891..db25f5b2d 100644
--- a/app/Actions/Post/Queue/ListTakenSlots.php
+++ b/app/Actions/Post/Queue/ListTakenSlots.php
@@ -5,9 +5,7 @@ declare(strict_types=1);
namespace App\Actions\Post\Queue;
use App\Models\Post;
-use App\Models\PostPlatform;
use Carbon\CarbonInterface;
-use Illuminate\Database\Eloquent\Builder;
class ListTakenSlots
{
@@ -21,22 +19,18 @@ class ListTakenSlots
*/
public static function handle(array $channelIds, CarbonInterface $from, CarbonInterface $until): array
{
- $taken = PostPlatform::query()
- ->enabled()
- ->whereIn('post_platforms.social_account_id', $channelIds)
- ->whereHas('post', fn (Builder $post): Builder => $post->holdingSlot()
- ->where('scheduled_at', '>=', $from)
- ->where('scheduled_at', '<', $until))
- ->select('post_platforms.social_account_id')
- ->addSelect(['slot_at' => Post::query()->select('scheduled_at')->whereColumn('posts.id', 'post_platforms.post_id')])
- ->withCasts(['slot_at' => 'datetime'])
- ->get()
+ $taken = Post::query()
+ ->whereIn('social_account_id', $channelIds)
+ ->holdingSlot()
+ ->where('scheduled_at', '>=', $from)
+ ->where('scheduled_at', '<', $until)
+ ->get(['social_account_id', 'scheduled_at'])
->groupBy('social_account_id');
return collect($channelIds)
->mapWithKeys(fn (string $channelId): array => [$channelId => $taken->get($channelId, collect())
- ->sortBy(fn (PostPlatform $platform): int => $platform->slot_at->getTimestamp())
- ->map(fn (PostPlatform $platform): string => $platform->slot_at->toIso8601ZuluString())
+ ->sortBy(fn (Post $post): int => $post->scheduled_at->getTimestamp())
+ ->map(fn (Post $post): string => $post->scheduled_at->toIso8601ZuluString())
->unique()
->values()
->all()])
diff --git a/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php b/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php
index d635f88b9..969a75e3e 100644
--- a/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php
+++ b/app/Actions/Post/Queue/MoveChannelPostToQueueSlot.php
@@ -33,10 +33,6 @@ class MoveChannelPostToQueueSlot
throw ValidationException::withMessages(['slot_at' => __('posts.errors.queue_order_stale')]);
}
- if ($post->postPlatforms()->enabled()->count() !== 1) {
- throw ValidationException::withMessages(['queue' => __('posts.errors.queue_legacy_post')]);
- }
-
UpdatePost::execute($channel->workspace, $post, [
'status' => PostStatus::Scheduled->value,
'queue_slot' => $slotAt->utc()->toIso8601String(),
diff --git a/app/Actions/Post/Queue/ReflowChannelQueue.php b/app/Actions/Post/Queue/ReflowChannelQueue.php
index 7b0031d5d..436b80b85 100644
--- a/app/Actions/Post/Queue/ReflowChannelQueue.php
+++ b/app/Actions/Post/Queue/ReflowChannelQueue.php
@@ -170,7 +170,7 @@ class ReflowChannelQueue
$posts = $insert ? $queued->push($insert) : $queued;
DB::transaction(function () use ($posts, $targets): void {
- foreach ($posts as $post) {
+ foreach ($posts->sortBy('id', SORT_STRING) as $post) {
$slot = $targets[$post->id] ?? null;
if ($slot === null) {
diff --git a/app/Actions/Post/Queue/ReorderChannelQueue.php b/app/Actions/Post/Queue/ReorderChannelQueue.php
index b21128509..f0007bec4 100644
--- a/app/Actions/Post/Queue/ReorderChannelQueue.php
+++ b/app/Actions/Post/Queue/ReorderChannelQueue.php
@@ -35,12 +35,14 @@ class ReorderChannelQueue
$slots = $queued->pluck('scheduled_at')->sort()->values();
- DB::transaction(function () use ($postIds, $queued, $slots): void {
- foreach (array_values($postIds) as $index => $postId) {
+ $slotsById = collect(array_values($postIds))->mapWithKeys(fn (string $postId, int $index): array => [$postId => $slots[$index]]);
+
+ DB::transaction(function () use ($queued, $slotsById): void {
+ foreach ($slotsById->sortKeys(SORT_STRING) as $postId => $slot) {
$post = $queued->get($postId);
- if (! $post->scheduled_at->equalTo($slots[$index])) {
- ReflowChannelQueue::updateIfScheduled($post, ['scheduled_at' => $slots[$index]]);
+ if (! $post->scheduled_at->equalTo($slot)) {
+ ReflowChannelQueue::updateIfScheduled($post, ['scheduled_at' => $slot]);
}
}
});
diff --git a/app/Actions/Post/RecoverEmptyDraft.php b/app/Actions/Post/RecoverEmptyDraft.php
index 85261411c..9ef0bf0f1 100644
--- a/app/Actions/Post/RecoverEmptyDraft.php
+++ b/app/Actions/Post/RecoverEmptyDraft.php
@@ -34,7 +34,7 @@ class RecoverEmptyDraft
beforeCreate: function (MediaCopyBatch $batch) use ($workspace, $legacy, &$locked): void {
$locked = $workspace->posts()->lockForUpdate()->findOrFail($legacy->id);
- if ($locked->status !== Status::Draft || $locked->postPlatforms()->enabled()->exists()) {
+ if ($locked->status !== Status::Draft || $locked->hasChannel()) {
throw ValidationException::withMessages([
'recover_post_id' => __('validation.in', ['attribute' => 'recovery post']),
]);
diff --git a/app/Actions/Post/ScheduleNextOccurrence.php b/app/Actions/Post/ScheduleNextOccurrence.php
index 8af576b69..f72c9dc30 100644
--- a/app/Actions/Post/ScheduleNextOccurrence.php
+++ b/app/Actions/Post/ScheduleNextOccurrence.php
@@ -7,7 +7,6 @@ namespace App\Actions\Post;
use App\Enums\Post\RecurrenceFrequency;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\Media\MediaCopyBatch;
use App\Support\PostingSchedule;
use App\Support\Timezone;
@@ -39,7 +38,7 @@ class ScheduleNextOccurrence
}
$current = $post->currentOccurrence();
- $targets = $post->postPlatforms()->enabled()->whereHas('socialAccount')->with('socialAccount')->get();
+ $targets = filled($post->loadMissing('socialAccount')->socialAccount) ? collect([$post]) : collect();
$author = $post->user;
$user = $author !== null && ($author->ownsAccountOf($post->workspace) || $author->belongsToWorkspace($post->workspace))
? $author
@@ -57,7 +56,7 @@ class ScheduleNextOccurrence
$ceiling = CarbonImmutable::parse(PostingSchedule::MAX_INSTANT, 'UTC');
$plans = $targets
- ->map(function (PostPlatform $target) use ($post, $current, $frequency, $interval, $remaining): array {
+ ->map(function (Post $target) use ($post, $current, $frequency, $interval, $remaining): array {
[$origin, $index] = self::position($post->recurrence_origin_at, $current, $frequency, $interval, Timezone::normalize($target->socialAccount->timezone));
$steps = 1;
@@ -84,7 +83,7 @@ class ScheduleNextOccurrence
$groupId = (string) Str::uuid7();
$occurrences = $plans->map(function (array $plan) use ($post, $user, $batch, $groupId, $frequency, $interval): Post {
$occurrence = CreateChannelPost::execute($post->workspace, $user, [
- ...DuplicatePost::destination($post, $plan['target']),
+ ...DuplicatePost::destination($post),
'post_group_id' => $groupId,
'status' => PostStatus::Scheduled->value,
'scheduled_at' => $plan['next']->utc()->toIso8601String(),
diff --git a/app/Actions/Post/UpdatePost.php b/app/Actions/Post/UpdatePost.php
index c01070feb..ee1e4d985 100644
--- a/app/Actions/Post/UpdatePost.php
+++ b/app/Actions/Post/UpdatePost.php
@@ -14,11 +14,8 @@ use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\User;
use App\Models\Workspace;
use App\Support\Media\MediaCopyBatch;
@@ -26,12 +23,9 @@ use App\Support\PostApproval;
use App\Support\PostCompositionValidator;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
-use App\Support\Social\AbandonGoogleBusinessReview;
-use App\Support\Social\GoogleBusinessDerivativeCleaner;
use Carbon\Carbon;
use Carbon\CarbonInterface;
use Illuminate\Support\Arr;
-use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class UpdatePost
@@ -64,60 +58,45 @@ class UpdatePost
throw ValidationException::withMessages(['social_account_id' => __('validation.in', ['attribute' => 'social account'])]);
}
- if ($post->postPlatforms()->enabled()->count() === 1) {
- $selectedTarget = $post->postPlatforms()->enabled()->sole();
- if (array_key_exists('platforms', $data)) {
- if (count($data['platforms']) !== 1 || data_get($data, 'platforms.0.id') !== $selectedTarget->id
- || array_key_exists('content_type', $data) || array_key_exists('meta', $data)) {
- throw ValidationException::withMessages(['platforms' => __('validation.in', ['attribute' => 'platforms'])]);
- }
-
- $data = [
- ...Arr::except($data, ['platforms']),
- ...Arr::only($data['platforms'][0], ['content_type', 'meta']),
- ];
- }
-
- return self::updateChannelPost($workspace, $post, $data, $actor);
+ if (array_key_exists('platforms', $data)) {
+ throw ValidationException::withMessages(['platforms' => __('validation.prohibited', ['attribute' => 'platforms'])]);
}
- if (filled(data_get($data, 'queue'))) {
- throw ValidationException::withMessages(['queue' => __('posts.errors.queue_legacy_post')]);
+ return $post->hasChannel()
+ ? self::updateChannelPost($workspace, $post, $data, $actor)
+ : self::updateDraftWithoutChannel($post, $data);
+ }
+
+ /**
+ * A draft written before posts had one channel each can still be edited,
+ * but it stays a draft: it goes out only after the composer turns it into
+ * a post for a channel (RecoverEmptyDraft).
+ *
+ * @param array<string, mixed> $data
+ * @return array{post: Post, action: PostAction|null}
+ */
+ private static function updateDraftWithoutChannel(Post $post, array $data): array
+ {
+ $status = (string) data_get($data, 'status', $post->status->value);
+
+ if ($status !== PostStatus::Draft->value || filled(data_get($data, 'queue')) || filled(data_get($data, 'queue_slot'))) {
+ throw ValidationException::withMessages(['status' => __('posts.errors.choose_channel')]);
}
if (array_key_exists('content_type', $data) || array_key_exists('meta', $data)) {
- return self::updateChannelPost($workspace, $post, $data, $actor);
+ throw ValidationException::withMessages(['content_type' => __('posts.errors.choose_channel')]);
}
- return MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($workspace, $post, $data, $actor): array {
+ return MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($post, $data): array {
if (self::finalizedMeanwhile($post)) {
return ['post' => $post, 'action' => PostAction::Finalized];
}
- $occurrence = $post->currentOccurrence();
- $previousStatus = $post->status;
- $scheduledAt = $post->scheduled_at;
- if (data_get($data, 'scheduled_at')) {
- $scheduledAt = Carbon::parse(data_get($data, 'scheduled_at'))->utc();
- }
-
- $status = (string) data_get($data, 'status', $post->status->value);
- $storedStatus = PostApproval::isRequired($workspace, $actor, $status)
- ? PostStatus::PendingApproval
- : PostStatus::from($status);
- $publishRequest = ($storedStatus === PostStatus::PendingApproval || $previousStatus === PostStatus::PendingApproval)
- && $status === PostStatus::Publishing->value;
-
$post->update([
'content' => data_get($data, 'content', $post->content),
- 'status' => $storedStatus,
- 'scheduled_at' => $publishRequest ? null : $scheduledAt,
- 'schedule_mode' => match (true) {
- $storedStatus === PostStatus::Scheduled => ScheduleMode::Custom,
- $storedStatus === PostStatus::PendingApproval && ! $publishRequest && $scheduledAt !== null => ScheduleMode::Custom,
- default => null,
- },
- ...PostApproval::transition($previousStatus, $storedStatus, $actor),
+ 'scheduled_at' => array_key_exists('scheduled_at', $data) && filled(data_get($data, 'scheduled_at'))
+ ? Carbon::parse(data_get($data, 'scheduled_at'))->utc()
+ : $post->scheduled_at,
]);
if (Arr::has($data, 'media')) {
@@ -128,65 +107,7 @@ class UpdatePost
$post->labels()->sync(data_get($data, 'label_ids', []));
}
- if (Arr::has($data, 'platforms')) {
- $post->postPlatforms()->update(['enabled' => false]);
-
- foreach (data_get($data, 'platforms', []) as $platformData) {
- $updateData = ['enabled' => true];
-
- if (data_get($platformData, 'content_type') !== null) {
- $updateData['content_type'] = data_get($platformData, 'content_type');
- }
-
- if (data_get($platformData, 'meta') !== null) {
- $postPlatform = $post->postPlatforms()->where('id', data_get($platformData, 'id'))->first();
-
- if ($postPlatform) {
- $updateData['meta'] = PostPlatformMetaRules::forStorage($postPlatform->meta ?? [], PostPlatformMetaRules::normalize(array_filter(
- array_merge($postPlatform->meta ?? [], data_get($platformData, 'meta') ?? []),
- fn (mixed $value): bool => $value !== null,
- )));
- }
- }
-
- $post->postPlatforms()
- ->where('id', data_get($platformData, 'id'))
- ->update($updateData);
- }
- }
-
- if (in_array($post->status, [PostStatus::Scheduled, PostStatus::Publishing], true)) {
- PostPlatformMetaRules::assertStoredPostPublishable(
- $post,
- collect(data_get($data, 'platforms', []))->pluck('id')->all(),
- );
- }
-
- if (Arr::has($data, 'platforms')) {
- $post->postPlatforms()
- ->disabled()
- ->where('platform', Platform::GoogleBusiness)
- ->where('status', PlatformStatus::PendingReview)
- ->get()
- ->each(fn (PostPlatform $platform) => AbandonGoogleBusinessReview::execute(
- $platform,
- __('posts.errors.target_disabled'),
- ['category' => 'target_disabled'],
- ));
-
- $disabledGoogleBusinessIds = $post->postPlatforms()
- ->disabled()
- ->where('platform', Platform::GoogleBusiness)
- ->pluck('id');
-
- DB::afterCommit(function () use ($disabledGoogleBusinessIds): void {
- $disabledGoogleBusinessIds->each(
- fn (string $id) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($id),
- );
- });
- }
-
- return self::finish($post, $previousStatus, $storedStatus, $occurrence, $actor);
+ return ['post' => $post, 'action' => null];
});
}
@@ -196,17 +117,8 @@ class UpdatePost
*/
private static function updateChannelPost(Workspace $workspace, Post $post, array $data, ?User $actor): array
{
- if (array_key_exists('platforms', $data)) {
- throw ValidationException::withMessages(['platforms' => __('validation.in', ['attribute' => 'platforms'])]);
- }
-
- if ($post->postPlatforms()->enabled()->count() !== 1) {
- throw ValidationException::withMessages(['post' => PostStatusRules::editBlockedMessage()]);
- }
-
- $target = $post->postPlatforms()->enabled()->sole();
$position = filled(data_get($data, 'queue')) ? QueuePosition::from(data_get($data, 'queue')) : null;
- $channel = $target->socialAccount;
+ $channel = $post->socialAccount;
if ($position !== null && ! $channel?->hasPostingSchedule()) {
throw ValidationException::withMessages(['queue' => __('posts.errors.queue_requires_schedule')]);
@@ -239,7 +151,7 @@ class UpdatePost
$queueSlot = $position === null && ! $keepsPending ? data_get($data, 'queue_slot') : null;
$meta = PostPlatformMetaRules::normalize(array_filter(
- array_merge($target->meta ?? [], data_get($data, 'meta') ?? []),
+ array_merge($post->meta ?? [], data_get($data, 'meta') ?? []),
fn (mixed $value): bool => $value !== null,
));
$scheduledAt = match (true) {
@@ -262,7 +174,7 @@ class UpdatePost
default => $post->schedule_mode ?? ScheduleMode::Custom,
};
$storedStatus = $pending ? PostStatus::PendingApproval : PostStatus::from($status);
- $resolved = PostCompositionValidator::validate($workspace, [
+ $resolved = PostCompositionValidator::forSinglePost(fn (): array => PostCompositionValidator::validate($workspace, [
'status' => $status,
'queue' => $keepsPending ? null : $position?->value,
'content' => array_key_exists('content', $data) ? $data['content'] : $post->content,
@@ -270,14 +182,14 @@ class UpdatePost
'scheduled_at' => $keepsPending ? null : $scheduledAt,
'label_ids' => data_get($data, 'label_ids') ?? $post->labels()->pluck('workspace_labels.id')->all(),
'destinations' => [[
- 'social_account_id' => $target->social_account_id,
+ 'social_account_id' => $post->social_account_id,
'content_type' => data_get($data, 'content_type')
- ?? (array_key_exists('media', $data) && ContentType::derivesFromMedia($target->platform) ? null : $target->content_type->value),
+ ?? (array_key_exists('media', $data) && ContentType::derivesFromMedia($post->platform) ? null : $post->content_type->value),
'meta' => $meta,
]],
- ], $post->media ?? []);
+ ], $post->media ?? []));
- $write = fn (): array => MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($post, $target, $channel, $data, $resolved, $scheduledAt, $mode, $position, $pending, $approvesHolder, $previousStatus, $storedStatus, $actor): array {
+ $write = fn (): array => MediaCopyBatch::run(function (MediaCopyBatch $batch) use ($post, $channel, $data, $resolved, $scheduledAt, $mode, $position, $pending, $approvesHolder, $previousStatus, $storedStatus, $actor): array {
if (self::finalizedMeanwhile($post)) {
return ['post' => $post, 'action' => PostAction::Finalized];
}
@@ -292,10 +204,8 @@ class UpdatePost
'scheduled_at' => $scheduledAt && ! $slotLost ? Carbon::parse($scheduledAt)->utc() : null,
'schedule_mode' => $mode,
...PostApproval::transition($previousStatus, $storedStatus, $actor, $pending ? $position : null),
- ]);
- $target->update([
'content_type' => $destination['content_type'],
- 'meta' => PostPlatformMetaRules::forStorage($target->meta ?? [], $destination['meta']),
+ 'meta' => PostPlatformMetaRules::forStorage($post->meta ?? [], $destination['meta']),
]);
SyncOwnedMedia::execute($post, $destination['media'], $batch);
@@ -312,7 +222,7 @@ class UpdatePost
return ($position === null && ! $approvesHolder) || $pending
? $write()
- : ReflowChannelQueue::withLock([$target->social_account_id], $write);
+ : ReflowChannelQueue::withLock([$post->social_account_id], $write);
}
/**
diff --git a/app/Actions/Repurpose/ListRepurposeItems.php b/app/Actions/Repurpose/ListRepurposeItems.php
index 30637a149..0cc1d2eb3 100644
--- a/app/Actions/Repurpose/ListRepurposeItems.php
+++ b/app/Actions/Repurpose/ListRepurposeItems.php
@@ -17,7 +17,7 @@ class ListRepurposeItems
public static function execute(Repurpose $repurpose, ?int $page = null): LengthAwarePaginator
{
return $repurpose->items()
- ->with('posts.postPlatforms:id,post_id,platform,enabled,status')
+ ->with('posts:id,repurpose_item_id,platform,publish_status')
->orderByDesc(DB::raw('coalesce(source_created_at, created_at)'))
->paginate((int) config('app.pagination.default'), page: $page);
}
diff --git a/app/Actions/SocialAccount/ApplyChannelDefaults.php b/app/Actions/SocialAccount/ApplyChannelDefaults.php
index 826c575e1..4a6b594b0 100644
--- a/app/Actions/SocialAccount/ApplyChannelDefaults.php
+++ b/app/Actions/SocialAccount/ApplyChannelDefaults.php
@@ -6,21 +6,16 @@ namespace App\Actions\SocialAccount;
use App\Models\SocialAccount;
use App\Support\Timezone;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Eloquent\Collection;
/**
* A channel starts with a usable posting setup: a time zone, a
* three-a-week goal and the network's recommended slots. New channels get it
- * when they connect; channels connected before posting schedules existed get
- * it once through `backfill()` (release:trypost-2).
+ * when they connect.
*/
class ApplyChannelDefaults
{
public const int GOAL = 3;
- public const int CHUNK = 100;
-
/**
* Quiet write: no observer, event or PostHog call, and the channel queue
* is not reflowed.
@@ -33,41 +28,4 @@ class ApplyChannelDefaults
'posting_schedule' => app(GeneratePostingSchedule::class)->handle($account->platform, self::GOAL),
])->saveQuietly();
}
-
- /**
- * Channels without a posting schedule, which `backfill()` sets up.
- */
- public static function pending(): int
- {
- return self::withoutSchedule()->count();
- }
-
- /**
- * Gives every channel without a posting schedule the defaults, in its
- * workspace owner's time zone (UTC when the owner has none). A channel
- * that already has a schedule is never touched.
- */
- public static function backfill(): int
- {
- $count = 0;
-
- self::withoutSchedule()
- ->with('workspace.owner')
- ->chunkById(self::CHUNK, function (Collection $accounts) use (&$count): void {
- foreach ($accounts as $account) {
- self::execute($account, $account->workspace?->owner?->timezone);
- $count++;
- }
- });
-
- return $count;
- }
-
- /**
- * @return Builder<SocialAccount>
- */
- private static function withoutSchedule(): Builder
- {
- return SocialAccount::query()->withoutGlobalScopes()->whereNull('posting_schedule');
- }
}
diff --git a/app/Actions/SocialAccount/CountPostsSentThisWeek.php b/app/Actions/SocialAccount/CountPostsSentThisWeek.php
index 3c75dffc8..bbd848999 100644
--- a/app/Actions/SocialAccount/CountPostsSentThisWeek.php
+++ b/app/Actions/SocialAccount/CountPostsSentThisWeek.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Actions\SocialAccount;
use App\Enums\User\WeekStart;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Support\Timezone;
@@ -19,10 +19,9 @@ class CountPostsSentThisWeek
{
$now = now(Timezone::normalize($channel->timezone));
- return PostPlatform::query()
+ return Post::query()
->where('social_account_id', $channel->id)
- ->enabled()
- ->published()
+ ->publicationPublished()
->whereNotNull('published_at')
->whereBetween('published_at', [
$now->startOfWeek($weekStart->firstDay())->utc(),
diff --git a/app/Actions/SocialAccount/ListInstagramGridPosts.php b/app/Actions/SocialAccount/ListInstagramGridPosts.php
index 7d4514768..205cf69f5 100644
--- a/app/Actions/SocialAccount/ListInstagramGridPosts.php
+++ b/app/Actions/SocialAccount/ListInstagramGridPosts.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Actions\SocialAccount;
use App\Enums\PostPlatform\ContentType;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use Illuminate\Pagination\LengthAwarePaginator;
@@ -16,17 +16,15 @@ use Illuminate\Pagination\LengthAwarePaginator;
class ListInstagramGridPosts
{
/**
- * @return LengthAwarePaginator<int, PostPlatform>
+ * @return LengthAwarePaginator<int, Post>
*/
public static function execute(SocialAccount $account): LengthAwarePaginator
{
- return PostPlatform::query()
- ->select(['id', 'post_id', 'content_type', 'published_at'])
+ return Post::query()
+ ->select(['id', 'media', 'content_type', 'published_at'])
->where('social_account_id', $account->id)
- ->enabled()
- ->published()
+ ->publicationPublished()
->whereIn('content_type', [ContentType::InstagramFeed, ContentType::InstagramReel])
- ->with('post:id,media')
->orderByDesc('published_at')
->orderByDesc('id')
->paginate((int) config('app.pagination.default'));
diff --git a/app/Actions/SocialAccount/StoreTelegramReactions.php b/app/Actions/SocialAccount/StoreTelegramReactions.php
index 050a5d9b5..b1623c94b 100644
--- a/app/Actions/SocialAccount/StoreTelegramReactions.php
+++ b/app/Actions/SocialAccount/StoreTelegramReactions.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Actions\SocialAccount;
use App\Enums\SocialAccount\Platform;
-use App\Models\PostPlatform;
+use App\Models\Post;
class StoreTelegramReactions
{
@@ -24,13 +24,13 @@ class StoreTelegramReactions
return;
}
- $postPlatform = PostPlatform::query()
+ $post = Post::query()
->where('platform', Platform::Telegram->value)
->where('platform_post_id', $messageId)
->whereHas('socialAccount', fn ($query) => $query->where('meta->chat_id', $chatId))
->first();
- if ($postPlatform === null) {
+ if (blank($post)) {
return;
}
@@ -41,6 +41,6 @@ class StoreTelegramReactions
'count' => (int) data_get($reaction, 'total_count'),
], is_array($rawReactions) ? $rawReactions : []));
- $postPlatform->update(['meta' => [...$postPlatform->meta ?? [], 'reactions' => $reactions]]);
+ $post->writePublication(['meta' => [...$post->meta ?? [], 'reactions' => $reactions]]);
}
}
diff --git a/app/Actions/Workspace/PurgeWorkspace.php b/app/Actions/Workspace/PurgeWorkspace.php
index 271cf0a3d..1feb1f2b5 100644
--- a/app/Actions/Workspace/PurgeWorkspace.php
+++ b/app/Actions/Workspace/PurgeWorkspace.php
@@ -6,7 +6,7 @@ namespace App\Actions\Workspace;
use App\Actions\Media\DeleteOwnedMedia;
use App\Enums\SocialAccount\Platform;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\Workspace;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
@@ -18,11 +18,10 @@ class PurgeWorkspace
*/
public static function execute(Workspace $workspace): void
{
- PostPlatform::query()
+ $workspace->posts()
->where('platform', Platform::GoogleBusiness)
- ->whereIn('post_id', $workspace->posts()->select('id'))
- ->pluck('id')
- ->each(fn (string $id) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($id));
+ ->select(['id'])
+ ->each(fn (Post $post) => app(GoogleBusinessDerivativeCleaner::class)->cleanup($post));
DeleteOwnedMedia::forWorkspace($workspace);
$workspace->delete();
diff --git a/app/Console/Commands/CheckUpcomingPostConnections.php b/app/Console/Commands/CheckUpcomingPostConnections.php
index 11caf182d..709f444ce 100644
--- a/app/Console/Commands/CheckUpcomingPostConnections.php
+++ b/app/Console/Commands/CheckUpcomingPostConnections.php
@@ -4,10 +4,9 @@ declare(strict_types=1);
namespace App\Console\Commands;
-use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
+use App\Enums\Post\PublishStatus;
use App\Jobs\VerifyUpcomingPostConnections;
-use App\Models\PostPlatform;
+use App\Models\Post;
use Illuminate\Console\Command;
class CheckUpcomingPostConnections extends Command
@@ -18,23 +17,20 @@ class CheckUpcomingPostConnections extends Command
public function handle(): void
{
- $workspaceIds = PostPlatform::query()
- ->where('post_platforms.status', PostPlatformStatus::Pending)
- ->enabled()
+ $workspaceIds = Post::query()
+ ->scheduled()
+ ->whereBetween('scheduled_at', [now(), now()->addHour()])
+ ->where('publish_status', PublishStatus::Pending)
->whereHas('socialAccount')
->where(function ($query) {
- $query->whereNull('post_platforms.connection_warning_sent_at')
- ->orWhere('post_platforms.connection_warning_sent_at', '<', now()->subDay());
+ $query->whereNull('connection_warning_sent_at')
+ ->orWhere('connection_warning_sent_at', '<', now()->subDay());
})
- ->join('posts', 'posts.id', '=', 'post_platforms.post_id')
- ->where('posts.status', PostStatus::Scheduled)
- ->whereBetween('posts.scheduled_at', [now(), now()->addHour()])
->distinct()
- ->pluck('posts.workspace_id');
+ ->pluck('workspace_id');
foreach ($workspaceIds as $workspaceId) {
VerifyUpcomingPostConnections::dispatch($workspaceId);
}
-
}
}
diff --git a/app/Console/Commands/ProcessScheduledPosts.php b/app/Console/Commands/ProcessScheduledPosts.php
index 9f762c898..61b7bc619 100644
--- a/app/Console/Commands/ProcessScheduledPosts.php
+++ b/app/Console/Commands/ProcessScheduledPosts.php
@@ -8,7 +8,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Jobs\PublishPost;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\Social\LimitRetryPolicy;
use Illuminate\Console\Command;
use Throwable;
@@ -41,26 +40,26 @@ class ProcessScheduledPosts extends Command
}
/**
- * Targets a network refused for a limit wait in the database, not in a
+ * Posts a network refused for a limit wait in the database, not in a
* delayed job, so a worker restart never loses them. Clearing retry_at
- * claims the target, so each retry is dispatched once.
+ * claims the post, so each retry is dispatched once.
*/
private function dispatchDueLimitRetries(): void
{
- PostPlatform::query()
- ->enabled()
+ Post::query()
->dueForLimitRetry()
- ->each(function (PostPlatform $postPlatform): void {
+ ->each(function (Post $post): void {
try {
- $claimed = PostPlatform::query()
- ->whereKey($postPlatform->id)
+ $claimed = Post::query()
+ ->whereKey($post->id)
->dueForLimitRetry()
- ->update(['retry_at' => null]);
+ ->toBase()
+ ->update(['retry_at' => null, 'publication_updated_at' => now()]);
if ($claimed) {
PublishToSocialPlatform::dispatch(
- $postPlatform,
- LimitRetryPolicy::UNIQUE_ATTEMPT_OFFSET + LimitRetryPolicy::retriesSoFar($postPlatform->error_context),
+ $post,
+ LimitRetryPolicy::UNIQUE_ATTEMPT_OFFSET + LimitRetryPolicy::retriesSoFar($post->error_context),
);
}
} catch (Throwable $exception) {
diff --git a/app/Console/Commands/ReconcileGoogleBusinessPosts.php b/app/Console/Commands/ReconcileGoogleBusinessPosts.php
index 1e576643d..b6ed0ba73 100644
--- a/app/Console/Commands/ReconcileGoogleBusinessPosts.php
+++ b/app/Console/Commands/ReconcileGoogleBusinessPosts.php
@@ -4,10 +4,10 @@ declare(strict_types=1);
namespace App\Console\Commands;
-use App\Enums\PostPlatform\Status;
+use App\Enums\Post\PublishStatus;
use App\Enums\SocialAccount\Platform;
use App\Jobs\ReconcileGoogleBusinessPost;
-use App\Models\PostPlatform;
+use App\Models\Post;
use Illuminate\Console\Command;
class ReconcileGoogleBusinessPosts extends Command
@@ -17,24 +17,23 @@ class ReconcileGoogleBusinessPosts extends Command
protected $description = 'Settle Google Business Profile posts still awaiting review';
/**
- * Google clears review in minutes, so a target checked moments ago has
+ * Google clears review in minutes, so a post checked moments ago has
* nothing new to say. Keeps a five-minute schedule from re-polling every
- * pending target on every tick.
+ * pending post on every tick.
*/
private const RECHECK_AFTER_MINUTES = 5;
public function handle(): int
{
- PostPlatform::query()
- ->enabled()
+ Post::query()
->where('platform', Platform::GoogleBusiness)
- ->where('status', Status::PendingReview)
+ ->where('publish_status', PublishStatus::PendingReview)
->whereNotNull('platform_post_id')
->where(function ($query): void {
$query->whereNull('last_reconciled_at')
->orWhere('last_reconciled_at', '<=', now()->subMinutes(self::RECHECK_AFTER_MINUTES));
})
- ->each(fn (PostPlatform $postPlatform) => ReconcileGoogleBusinessPost::dispatch($postPlatform));
+ ->each(fn (Post $post) => ReconcileGoogleBusinessPost::dispatch($post));
return self::SUCCESS;
}
diff --git a/app/Console/Commands/RecoverStuckPosts.php b/app/Console/Commands/RecoverStuckPosts.php
index 1bd7722ad..6664b7def 100644
--- a/app/Console/Commands/RecoverStuckPosts.php
+++ b/app/Console/Commands/RecoverStuckPosts.php
@@ -5,15 +5,12 @@ declare(strict_types=1);
namespace App\Console\Commands;
use App\Actions\Post\FinalizePostPublication;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Enums\SocialAccount\Platform;
-use App\Events\PostPlatformStatusUpdated;
+use App\Events\PostStatusUpdated;
use App\Exceptions\Social\ErrorCategory;
use App\Jobs\ReconcileGoogleBusinessPost;
use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Support\Social\AbandonGoogleBusinessReview;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use App\Support\Social\TikTokPhotoDerivativeCleaner;
use Illuminate\Console\Command;
@@ -37,110 +34,67 @@ class RecoverStuckPosts extends Command
->where('status', PostStatus::Publishing)
->where('updated_at', '<=', now()->subHour())
->each(function (Post $post): void {
- $stalePlatforms = $post->postPlatforms()
- ->enabled()
- ->whereIn('status', [PlatformStatus::Publishing, PlatformStatus::Pending, PlatformStatus::Retrying])
- ->whereNull('retry_at')
- ->where('updated_at', '<=', now()->subHour())
- ->get();
-
- $stalePlatforms->each(function (PostPlatform $postPlatform): void {
- $this->tiktokPhotoDerivativeCleaner->cleanupUnlessPublishInFlight(
- $postPlatform->error_context,
- $postPlatform->id,
- );
- $this->googleBusinessDerivativeCleaner->cleanup($postPlatform->id);
-
- $postPlatform->update([
- 'status' => PlatformStatus::Failed,
+ $stale = $post->publish_status->isInFlight()
+ && blank($post->retry_at)
+ && (blank($post->publication_updated_at) || $post->publication_updated_at->lessThanOrEqualTo(now()->subHour()));
+
+ if ($stale) {
+ $this->tiktokPhotoDerivativeCleaner->cleanupUnlessPublishInFlight($post->error_context, $post->id);
+ $this->googleBusinessDerivativeCleaner->cleanup($post);
+
+ $post->writePublication([
+ 'publish_status' => PublishStatus::Failed,
'error_message' => __('posts.errors.publishing_timed_out'),
'error_context' => [
- ...($postPlatform->error_context ?? []),
+ ...($post->error_context ?? []),
'category' => ErrorCategory::Timeout->value,
'failed_at' => now()->toIso8601String(),
],
]);
- });
-
- $this->pruneDisabledGoogleBusinessDerivatives($post);
- $this->failExpiredReviews($post);
-
- // Delayed platform-unavailable retries keep the platform Retrying with a
- // fresh updated_at — do not finalize the post while that work is still live.
- $stillActive = $post->postPlatforms()
- ->enabled()
- ->whereIn('status', [
- PlatformStatus::Publishing,
- PlatformStatus::Pending,
- PlatformStatus::Retrying,
- PlatformStatus::PendingReview,
- ])
- ->exists();
-
- if ($stillActive) {
- return;
}
- app(FinalizePostPublication::class)->handle($post);
-
- $stalePlatforms->each(fn (PostPlatform $postPlatform) => PostPlatformStatusUpdated::dispatch($postPlatform->fresh()));
- });
- }
-
- /**
- * A switched-off GBP target is skipped by reconcile and the 24h ceiling.
- * Abandon the review so the parent can settle, and prune the JPEG.
- */
- private function pruneDisabledGoogleBusinessDerivatives(Post $post): void
- {
- $post->postPlatforms()
- ->disabled()
- ->where('platform', Platform::GoogleBusiness)
- ->get()
- ->each(function (PostPlatform $postPlatform): void {
- if ($postPlatform->status === PlatformStatus::PendingReview) {
- AbandonGoogleBusinessReview::execute(
- $postPlatform,
- __('posts.errors.target_disabled'),
- ['category' => 'target_disabled'],
- );
+ $this->failExpiredReview($post);
+ // A delayed platform-unavailable retry keeps the post Retrying
+ // with a fresh clock: do not finalize while that work is live.
+ if (! $post->publish_status->isFinished()) {
return;
}
- $this->googleBusinessDerivativeCleaner->cleanup($postPlatform->id);
+ app(FinalizePostPublication::class)->handle($post);
+
+ if ($stale) {
+ PostStatusUpdated::dispatch($post->fresh());
+ }
});
}
/**
* PendingReview is supposed to last up to Google's review ceiling, timed
* from submitted_at only. A scheduled draft can be days old before it
- * enters review — created_at must not trip the ceiling. Rows without
- * submitted_at stay in review until reconcile or a later recover after
- * markAsPendingReview writes the clock.
+ * enters review, so created_at must not trip the ceiling. A post without
+ * submitted_at stays in review until reconcile or a later recover after
+ * markPublicationPendingReview writes the clock.
*/
- private function failExpiredReviews(Post $post): void
+ private function failExpiredReview(Post $post): void
{
$cutoff = now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS);
- $post->postPlatforms()
- ->enabled()
- ->where('status', PlatformStatus::PendingReview)
- ->where('submitted_at', '<=', $cutoff)
- ->get()
- ->each(function (PostPlatform $postPlatform): void {
- $postPlatform->markAsRejected(
- (string) $postPlatform->platform_post_id,
- $postPlatform->platform_url,
- __('posts.errors.review_unconfirmed'),
- [
- ...($postPlatform->error_context ?? []),
- 'category' => 'review_unconfirmed',
- 'failed_at' => now()->toIso8601String(),
- ],
- );
- $this->googleBusinessDerivativeCleaner->cleanup($postPlatform->id);
- PostPlatformStatusUpdated::dispatch($postPlatform->fresh());
- });
+ if ($post->publish_status !== PublishStatus::PendingReview || blank($post->submitted_at) || $post->submitted_at->greaterThan($cutoff)) {
+ return;
+ }
+
+ $post->markPublicationRejected(
+ (string) $post->platform_post_id,
+ $post->platform_url,
+ __('posts.errors.review_unconfirmed'),
+ [
+ ...($post->error_context ?? []),
+ 'category' => 'review_unconfirmed',
+ 'failed_at' => now()->toIso8601String(),
+ ],
+ );
+ $this->googleBusinessDerivativeCleaner->cleanup($post);
+ PostStatusUpdated::dispatch($post->fresh());
}
}
diff --git a/app/Console/Commands/RetryFailedPost.php b/app/Console/Commands/RetryFailedPost.php
index ffcdbcc4a..6bfe0d249 100644
--- a/app/Console/Commands/RetryFailedPost.php
+++ b/app/Console/Commands/RetryFailedPost.php
@@ -4,28 +4,25 @@ declare(strict_types=1);
namespace App\Console\Commands;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Exceptions\Social\ErrorCategory;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\Social\PublishCheckpoint;
use App\Support\Social\ThreadProgress;
use App\Support\Social\TikTokPhotoDerivativeCleaner;
use Illuminate\Console\Command;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class RetryFailedPost extends Command
{
protected $signature = 'posts:retry
- {post : ID of the post whose failed platforms should be retried}';
+ {post : ID of the failed post to retry}';
- protected $description = 'Retry failed platforms, resuming in-flight remote publishes when a checkpoint exists';
+ protected $description = 'Retry a failed post, resuming an in-flight remote publish when a checkpoint exists';
public function __construct(
private readonly TikTokPhotoDerivativeCleaner $tiktokPhotoDerivativeCleaner,
@@ -35,7 +32,7 @@ class RetryFailedPost extends Command
public function handle(): int
{
- $post = Post::query()->find((string) $this->argument('post'));
+ $post = Post::query()->with('socialAccount')->find((string) $this->argument('post'));
if (! $post) {
$this->error('Post not found.');
@@ -44,125 +41,82 @@ class RetryFailedPost extends Command
}
if (! $this->isRetryable($post)) {
- $this->error('Only failed or partially published posts can be retried.');
-
- return self::FAILURE;
- }
-
- $failedPlatforms = $this->failedPlatforms($post);
-
- if ($failedPlatforms->isEmpty()) {
- $this->warn('No failed enabled platforms matched this post.');
+ $this->error('Only failed posts with a channel can be retried.');
return self::FAILURE;
}
$this->table(
- ['Post platform ID', 'Platform', 'Account', 'Last error', 'Mode'],
- $failedPlatforms->map(fn (PostPlatform $postPlatform): array => [
- $postPlatform->id,
- $postPlatform->platform->value,
- $postPlatform->display_username ?? '—',
- $postPlatform->error_message ?? '—',
- $this->resumableContext($postPlatform->error_context) === null ? 'New' : 'Resume',
- ])->all(),
+ ['Post ID', 'Platform', 'Account', 'Last error', 'Mode'],
+ [[
+ $post->id,
+ $post->platform->value,
+ $post->display_username ?? '—',
+ $post->error_message ?? '—',
+ $this->resumableContext($post->error_context) === null ? 'New' : 'Resume',
+ ]],
);
- if (! $this->confirm('Queue publish attempts for these failed platforms?')) {
-
+ if (! $this->confirm('Queue a publish attempt for this post?')) {
return self::SUCCESS;
}
- $retryEntries = $this->prepareRetryEntries($post);
+ $originalContext = $this->prepareRetry($post);
- if ($retryEntries === []) {
+ if ($originalContext === false) {
$this->warn('The post changed while the command was running; nothing was retried.');
return self::FAILURE;
}
- foreach ($retryEntries as $entry) {
- if ($entry['platform'] === SocialPlatform::TikTok && PublishCheckpoint::tiktokPublishId($entry['error_context']) === null) {
- $this->tiktokPhotoDerivativeCleaner->cleanup($entry['original_error_context'], $entry['id']);
- }
+ $post->refresh();
- $postPlatform = PostPlatform::query()->findOrFail($entry['id']);
- PublishToSocialPlatform::dispatch($postPlatform);
+ if ($post->platform === SocialPlatform::TikTok && blank(PublishCheckpoint::tiktokPublishId($post->error_context))) {
+ $this->tiktokPhotoDerivativeCleaner->cleanup($originalContext, $post->id);
}
- Log::info('Failed post platforms queued for manual retry', [
- 'post_id' => $post->id,
- 'post_platform_ids' => array_column($retryEntries, 'id'),
- ]);
+ PublishToSocialPlatform::dispatch($post);
+
+ Log::info('Failed post queued for manual retry', ['post_id' => $post->id]);
return self::SUCCESS;
}
private function isRetryable(Post $post): bool
{
- return in_array($post->status, [PostStatus::Failed, PostStatus::PartiallyPublished], true);
+ return $post->status === PostStatus::Failed
+ && $post->publish_status === PublishStatus::Failed
+ && $post->hasChannel();
}
/**
- * @return Collection<int, PostPlatform>
- */
- private function failedPlatforms(Post $post, bool $lockForUpdate = false): Collection
- {
- return PostPlatform::query()
- ->with('socialAccount')
- ->where('post_id', $post->id)
- ->enabled()
- ->where('status', PlatformStatus::Failed)
- ->when($lockForUpdate, fn (Builder $query) => $query->lockForUpdate())
- ->get();
- }
-
- /**
- * @return list<array{
- * id: string,
- * platform: SocialPlatform,
- * error_context: array<string, mixed>|null,
- * original_error_context: array<string, mixed>|null
- * }>
+ * Returns the error context the failure left, or false when the post is
+ * no longer retryable.
+ *
+ * @return array<string, mixed>|null|false
*/
- private function prepareRetryEntries(Post $post): array
+ private function prepareRetry(Post $post): array|null|false
{
- return DB::transaction(function () use ($post): array {
- $lockedPost = Post::query()->lockForUpdate()->find($post->id);
+ return DB::transaction(function () use ($post): array|null|false {
+ $locked = Post::query()->lockForUpdate()->find($post->id);
- if (! $lockedPost || ! $this->isRetryable($lockedPost)) {
- return [];
+ if (! $locked || ! $this->isRetryable($locked)) {
+ return false;
}
- $platforms = $this->failedPlatforms($lockedPost, lockForUpdate: true);
-
- if ($platforms->isEmpty()) {
- return [];
- }
+ $originalContext = $locked->error_context;
- $entries = [];
-
- foreach ($platforms as $postPlatform) {
- $nextContext = $this->resumableContext($postPlatform->error_context);
- $entries[] = [
- 'id' => $postPlatform->id,
- 'platform' => $postPlatform->platform,
- 'error_context' => $nextContext,
- 'original_error_context' => $postPlatform->error_context,
- ];
-
- $postPlatform->update([
- 'status' => PlatformStatus::Pending,
- 'platform_post_id' => null,
- 'platform_url' => null,
- 'error_message' => null,
- 'error_context' => $nextContext,
- 'published_at' => null,
- ]);
- }
- $lockedPost->update(['status' => PostStatus::Publishing]);
+ $locked->writePublication([
+ 'publish_status' => PublishStatus::Pending,
+ 'platform_post_id' => null,
+ 'platform_url' => null,
+ 'error_message' => null,
+ 'error_context' => $this->resumableContext($originalContext),
+ 'published_at' => null,
+ ]);
+ $locked->update(['status' => PostStatus::Publishing]);
- return $entries;
+ return $originalContext;
});
}
diff --git a/app/Console/Commands/Scripts/AuditLegacyPosts.php b/app/Console/Commands/Scripts/AuditLegacyPosts.php
deleted file mode 100644
index 20b0d0b99..000000000
--- a/app/Console/Commands/Scripts/AuditLegacyPosts.php
+++ /dev/null
@@ -1,53 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Enums\Post\Status;
-use App\Models\Post;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-
-#[Signature('posts:audit-legacy {--strict : Fail if posts cannot safely use the independent composer}')]
-#[Description('Report legacy post target counts and blockers without changing data')]
-class AuditLegacyPosts extends Command
-{
- public function handle(): int
- {
- $active = Post::query()->whereIn('status', [Status::Draft, Status::Scheduled]);
- $multiTarget = (clone $active)->whereHas('postPlatforms', fn ($query) => $query->enabled(), '>', 1)->count();
- $zeroTargetDrafts = Post::query()->draft()
- ->whereDoesntHave('postPlatforms', fn ($query) => $query->enabled())->count();
- $zeroTargetScheduled = Post::query()->scheduled()
- ->whereDoesntHave('postPlatforms', fn ($query) => $query->enabled())->count();
- $unavailableScheduled = Post::query()->scheduled()
- ->whereHas('postPlatforms', fn ($query) => $query->enabled()->where(function ($target): void {
- $target->whereNull('social_account_id')
- ->orWhereDoesntHave('socialAccount');
- }))->count();
- $settledAggregates = Post::query()
- ->whereIn('status', [Status::Published, Status::PartiallyPublished, Status::Failed])
- ->whereHas('postPlatforms', fn ($query) => $query->enabled(), '>', 1)->count();
- $inFlightAggregates = Post::query()->where('status', Status::Publishing)
- ->whereHas('postPlatforms', fn ($query) => $query->enabled(), '>', 1)->count();
-
- $this->table(['Category', 'Posts'], [
- ['Editable with multiple enabled targets', $multiTarget],
- ['Draft with no enabled target (recoverable)', $zeroTargetDrafts],
- ['Scheduled with no enabled target (blocker)', $zeroTargetScheduled],
- ['Scheduled with an unavailable target (blocker)', $unavailableScheduled],
- ['Settled with multiple enabled targets (split, each post takes its target status)', $settledAggregates],
- ['In-flight aggregate (left running, not split)', $inFlightAggregates],
- ]);
-
- if ($this->option('strict') && ($multiTarget > 0 || $zeroTargetScheduled > 0 || $unavailableScheduled > 0)) {
- $this->error('Legacy post audit found unresolved blockers.');
-
- return self::FAILURE;
- }
-
- return self::SUCCESS;
- }
-}
diff --git a/app/Console/Commands/Scripts/BackfillExistingAnalytics.php b/app/Console/Commands/Scripts/BackfillExistingAnalytics.php
deleted file mode 100644
index 17b64e122..000000000
--- a/app/Console/Commands/Scripts/BackfillExistingAnalytics.php
+++ /dev/null
@@ -1,139 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Enums\Analytics\SyncCollector;
-use App\Enums\Analytics\SyncStatus;
-use App\Enums\SocialAccount\Platform;
-use App\Jobs\Analytics\BackfillTryPostPublications;
-use App\Jobs\Analytics\BootstrapAccountAnalytics;
-use App\Jobs\Analytics\CollectAccountDailySnapshot;
-use App\Models\Account;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use Carbon\CarbonImmutable;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-use Illuminate\Database\Eloquent\Builder;
-
-#[Signature('analytics:backfill-existing {--workspace= : Limit rollout to one workspace UUID} {--include-unsubscribed : Explicitly include workspaces not recognized as subscribed by Cashier} {--platforms= : Comma-separated platforms to include, e.g. instagram,facebook} {--chunk=100 : Accounts per dispatch batch} {--delay=0 : Seconds between batches}')]
-#[Description('Manually dispatch historical analytics backfills, which also import external posts, for existing accounts and publications')]
-class BackfillExistingAnalytics extends Command
-{
- public function handle(): int
- {
- $platforms = $this->platforms();
-
- if ($platforms === null) {
- return self::FAILURE;
- }
-
- $workspaceId = $this->option('workspace');
- $includeUnsubscribed = (bool) $this->option('include-unsubscribed');
- $batchSize = max(1, (int) $this->option('chunk'));
- $delay = max(0, (int) $this->option('delay'));
- $staleBefore = CarbonImmutable::now('UTC')->subHours(2);
- $date = CarbonImmutable::now('UTC')->toDateString();
- $orphaned = 0;
- $linked = 0;
- $accounts = 0;
- $imported = 0;
-
- Workspace::query()
- ->with('account.subscriptions')
- ->when($workspaceId, fn (Builder $query): Builder => $query->whereKey($workspaceId))
- ->reorder()
- ->lazyById(100)
- ->filter(fn (Workspace $workspace): bool => $includeUnsubscribed || $workspace->account->subscribed(Account::SUBSCRIPTION_NAME))
- ->chunk(100)
- ->each(function ($workspaces) use ($batchSize, $date, $delay, $platforms, $staleBefore, &$accounts, &$imported, &$linked, &$orphaned): void {
- $ids = $workspaces->pluck('id')->all();
- $inWorkspaces = fn (Builder $post): Builder => $post->whereIn('workspace_id', $ids);
- $onPlatforms = fn (Builder $query, string $column): Builder => $query->when($platforms !== [], fn (Builder $scoped): Builder => $scoped->whereIn($column, $platforms));
-
- $onPlatforms(PostPlatform::query(), 'post_platforms.platform')
- ->published()
- ->includedInAnalytics()
- ->whereNotNull('social_account_id')
- ->whereDoesntHave('analyticsPublication')
- ->whereHas('post', $inWorkspaces)
- ->lazyById(100)
- ->chunk(100)
- ->each(function ($chunk) use (&$linked): void {
- BackfillTryPostPublications::dispatch($chunk->pluck('id')->map(fn ($id): string => (string) $id)->values()->all());
- $linked += $chunk->count();
- });
-
- $orphaned += $onPlatforms(PostPlatform::query(), 'post_platforms.platform')
- ->published()
- ->includedInAnalytics()
- ->whereNull('social_account_id')
- ->whereHas('post', $inWorkspaces)
- ->count();
-
- $onPlatforms(SocialAccount::query(), 'platform')
- ->connected()
- ->includedInAnalytics()
- ->whereIn('workspace_id', $ids)
- ->where(function (Builder $query) use ($staleBefore): void {
- $query->whereDoesntHave('analyticsSyncStates', fn (Builder $states): Builder => $states->forCollector(SyncCollector::PublicationBackfill))
- ->orWhereHas('analyticsSyncStates', fn (Builder $states): Builder => $states
- ->forCollector(SyncCollector::PublicationBackfill)
- ->where(function (Builder $state): void {
- $state->whereIn('status', [SyncStatus::Pending, SyncStatus::Running])
- ->orWhere(fn (Builder $failed): Builder => $failed
- ->where('status', SyncStatus::Failed)
- ->where('last_error_category', 'queue_failed'));
- })
- ->where('updated_at', '<', $staleBefore));
- })
- ->with(['analyticsSyncStates' => fn ($query) => $query->forCollector(SyncCollector::PublicationBackfill)])
- ->lazyById(100)
- ->each(function (SocialAccount $account) use ($batchSize, $date, $delay, &$accounts): void {
- $wait = intdiv($accounts, $batchSize) * $delay;
-
- if ($account->analyticsSyncStates->isEmpty()) {
- CollectAccountDailySnapshot::dispatch($account->id, $date)->delay($wait);
- }
-
- BootstrapAccountAnalytics::dispatch($account->id)->delay($wait);
- $accounts++;
- });
-
- $imported += Post::query()
- ->imported()
- ->whereIn('workspace_id', $ids)
- ->when($platforms !== [], fn (Builder $query): Builder => $query->whereHas('postPlatforms', fn (Builder $targets): Builder => $targets->whereIn('platform', $platforms)))
- ->count();
- });
-
- $this->info("accounts_dispatched={$accounts}");
- $this->info("publications_to_link={$linked}");
- $this->info("posts_imported={$imported}");
- $this->info("historical_identity_unrecoverable={$orphaned}");
-
- return self::SUCCESS;
- }
-
- /**
- * @return list<string>|null
- */
- private function platforms(): ?array
- {
- $values = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('platforms')))));
- $unknown = array_values(array_filter($values, fn (string $value): bool => Platform::tryFrom($value) === null));
-
- if ($unknown !== []) {
- $this->error('Unknown platforms: '.implode(', ', $unknown));
-
- return null;
- }
-
- return $values;
- }
-}
diff --git a/app/Console/Commands/Scripts/BakeAspectRatioCropsCommand.php b/app/Console/Commands/Scripts/BakeAspectRatioCropsCommand.php
deleted file mode 100644
index 1608ac32c..000000000
--- a/app/Console/Commands/Scripts/BakeAspectRatioCropsCommand.php
+++ /dev/null
@@ -1,41 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Actions\Post\BakeLegacyAspectRatioCrops;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-
-#[Signature('posts:bake-aspect-ratio-crops')]
-#[Description('Bake the pre-2.0 Facebook/Instagram aspect ratio crop into the media of every scheduled or in-flight target, then drop meta.aspect_ratio')]
-class BakeAspectRatioCropsCommand extends Command
-{
- public function handle(): int
- {
- $result = BakeLegacyAspectRatioCrops::execute();
-
- $this->info("Baked {$result['baked_images']} cropped image(s) into {$result['baked_posts']} post(s); dropped the aspect ratio from {$result['stripped_targets']} other target(s).");
-
- if ($result['skipped_posts'] !== []) {
- $ids = implode(', ', $result['skipped_posts']);
- $this->warn('Left '.count($result['skipped_posts'])." post(s) with more than one enabled target uncropped for now (their media is shared; they keep their aspect ratio until a run after posts:split-legacy-active): {$ids}");
- }
-
- if ($result['unreadable_images'] !== []) {
- $ids = implode(', ', $result['unreadable_images']);
- $this->warn('Left '.count($result['unreadable_images'])." image(s) whose file could not be read uncropped (post:media): {$ids}");
- }
-
- if ($result['failed_posts'] !== []) {
- $ids = implode(', ', $result['failed_posts']);
- $this->error('Failed to bake '.count($result['failed_posts'])." post(s), which keep their aspect ratio; run the command again: {$ids}");
-
- return self::FAILURE;
- }
-
- return self::SUCCESS;
- }
-}
diff --git a/app/Console/Commands/Scripts/PurgeOrphanedPostsCommand.php b/app/Console/Commands/Scripts/PurgeOrphanedPostsCommand.php
deleted file mode 100644
index 3d72ff78a..000000000
--- a/app/Console/Commands/Scripts/PurgeOrphanedPostsCommand.php
+++ /dev/null
@@ -1,33 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Actions\Post\DeleteChannelPosts;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-use Illuminate\Support\Str;
-
-#[Signature('posts:purge-orphaned {--workspace= : Only purge this workspace UUID}')]
-#[Description('Delete posts whose channel was disconnected before disconnecting deleted them, and their media')]
-class PurgeOrphanedPostsCommand extends Command
-{
- public function handle(): int
- {
- $workspaceId = $this->option('workspace');
-
- if (filled($workspaceId) && ! Str::isUuid($workspaceId)) {
- $this->error('The --workspace option must be a workspace UUID.');
-
- return self::FAILURE;
- }
-
- $result = DeleteChannelPosts::orphaned(filled($workspaceId) ? $workspaceId : null);
-
- $this->info("{$result['deleted_posts']} orphaned post(s) deleted, {$result['detached_targets']} orphaned target(s) removed from posts on other channels.");
-
- return self::SUCCESS;
- }
-}
diff --git a/app/Console/Commands/Scripts/ReleaseTryPost2.php b/app/Console/Commands/Scripts/ReleaseTryPost2.php
deleted file mode 100644
index b044accfe..000000000
--- a/app/Console/Commands/Scripts/ReleaseTryPost2.php
+++ /dev/null
@@ -1,506 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Actions\Media\AdoptWorkspaceLibrary;
-use App\Actions\Media\AuditMedia;
-use App\Actions\Post\BakeLegacyAspectRatioCrops;
-use App\Actions\Post\DeleteChannelPosts;
-use App\Actions\SocialAccount\ApplyChannelDefaults;
-use App\Enums\SocialAccount\Platform;
-use App\Jobs\Media\AdoptWorkspaceLibraryJob;
-use App\Models\Media;
-use App\Models\Workspace;
-use Illuminate\Bus\UniqueLock;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-use Illuminate\Console\ConfirmableTrait;
-use Illuminate\Database\Eloquent\Collection;
-use Illuminate\Database\Migrations\Migrator;
-use Illuminate\Support\Facades\Artisan;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Sleep;
-use Illuminate\Support\Str;
-use Symfony\Component\Console\Output\BufferedOutput;
-use Throwable;
-
-/**
- * The one-off data steps of the TryPost 2.0 release, in order. Every step is
- * safe to run again; the analytics backfill is dispatched once per install.
- *
- * Orphaned posts are purged first, so a post with a target on a deleted
- * channel keeps its id (the dead target is dropped instead of being split off)
- * and their library media is not copied only to be deleted. The split gives
- * every copy its own media whether or not the library was adopted already.
- * The aspect ratio crops are baked after the split (each post then has its
- * own media) and before the adoption, which then adopts the baked post as it
- * is.
- *
- * Never rehearse it with `--force` on a database copy that points at the
- * production bucket: the adoption deletes library files no row of the copy
- * references, and production posts still use them. Give the copy its own
- * bucket (or a local disk), or rehearse with `--dry-run` only.
- */
-#[Signature('release:trypost-2
- {--force : Run without confirmation in production}
- {--dry-run : Print what each step would do without changing anything (the only safe rehearsal against the production bucket)}
- {--backfill-chunk=100 : Accounts per analytics backfill batch}
- {--backfill-delay=0 : Seconds between analytics backfill batches}
- {--include-unsubscribed : Also backfill workspaces Cashier does not see as subscribed}
- {--rerun-backfill : Dispatch the analytics backfill again even if an earlier run already did}
- {--adoption-timeout=21600 : Seconds to wait for the queued library adoption before moving on (its jobs keep going)}')]
-#[Description('Run the one-off data steps of the TryPost 2.0 release (safe to run again). Rehearse on a copy only with its own bucket, or with --dry-run')]
-class ReleaseTryPost2 extends Command
-{
- use ConfirmableTrait;
-
- public const int STEPS = 8;
-
- public const int ADOPTION_POLL_SECONDS = 15;
-
- public const string BACKFILL_DISPATCHED_KEY = 'release:trypost-2:backfill-dispatched-at';
-
- /** @var list<array{string, string, string}> */
- private array $summary = [];
-
- /** @var list<string> */
- private array $failedWorkspaces = [];
-
- public function handle(Migrator $migrator): int
- {
- $pending = $this->pendingMigrations($migrator);
-
- if ($pending !== []) {
- $count = count($pending);
- $this->error("{$count} pending migration(s). Run `php artisan migrate --force` (part of the deploy) first:");
- $this->line(collect($pending)->map(fn (string $name): string => " {$name}")->implode(PHP_EOL));
-
- return self::FAILURE;
- }
-
- $dryRun = (bool) $this->option('dry-run');
-
- if (! $dryRun && ! $this->confirmToProceed()) {
- return self::FAILURE;
- }
-
- $this->info('Baseline media audit (database and bucket listing only, read-only)...');
- $before = $this->snapshot();
-
- $chunk = max(1, (int) $this->option('backfill-chunk'));
- $delay = max(0, (int) $this->option('backfill-delay'));
- $unsubscribed = $this->option('include-unsubscribed') ? ' --include-unsubscribed' : '';
- $instagram = Platform::Instagram->value;
- $instagramFacebook = Platform::InstagramFacebook->value;
-
- $this->runReleaseStep('Purge posts of disconnected channels', 'posts:purge-orphaned', preview: function (): string {
- $plan = DeleteChannelPosts::orphanedPlan();
-
- return "would delete {$plan['deleted_posts']} post(s) and detach {$plan['detached_targets']} target(s)";
- });
- $this->runReleaseStep('Split legacy multi-target posts', 'posts:split-legacy-active', preview: function (): string {
- $this->call('posts:audit-legacy');
-
- return 'splits the "Editable" and "Settled" multiple-target posts above; in-flight ones stay';
- });
- $this->runReleaseStep('Bake legacy aspect ratio crops', 'posts:bake-aspect-ratio-crops', preview: function (): string {
- $pending = BakeLegacyAspectRatioCrops::pending();
-
- return "would bake the aspect ratio crop of {$pending} scheduled or in-flight post(s)";
- });
-
- if ($dryRun) {
- $this->runReleaseStep('Media library adoption', 'media:adopt-library --dry-run', readOnly: true);
- } else {
- $this->adoptLibrary();
- }
-
- $this->channelDefaults();
- $this->backfill("analytics:backfill-existing --chunk={$chunk} --delay={$delay}{$unsubscribed}");
- $this->runReleaseStep('Instagram stories discovery (queued)', "analytics:dispatch-publication-discovery --platform={$instagram} --platform={$instagramFacebook}");
- $unexpected = $this->audit($before);
-
- $this->newLine();
- $this->table(['Step', 'Status', 'Result'], $this->summary);
-
- if ($dryRun) {
- $this->info('Dry run: nothing was changed. The audit shows the state before the release.');
-
- return self::SUCCESS;
- }
-
- $failedSteps = collect($this->summary)->filter(fn (array $row): bool => $row[1] === 'failed')->count();
-
- if ($failedSteps > 0 || $unexpected > 0) {
- $this->error("Release finished with problems: {$failedSteps} failed step(s), {$unexpected} unexpected audit finding(s). Fix them and run the command again; finished steps are no-ops.");
-
- return self::FAILURE;
- }
-
- $this->info('Release steps done. Watch the analytics and media-imports queues in Horizon until they drain.');
-
- return self::SUCCESS;
- }
-
- /**
- * Queues one `AdoptWorkspaceLibraryJob` per workspace with library media
- * (its own queue, so Horizon adopts them in parallel), then waits until
- * every library is adopted, every remaining job has stopped, or
- * `--adoption-timeout` passes. A workspace still adopting at the timeout
- * keeps its job (it retries on its own); one whose job stopped with
- * library media left fails the step.
- */
- private function adoptLibrary(): void
- {
- $title = 'Media library adoption (queued)';
- $this->heading($title);
-
- $workspaces = Workspace::query()
- ->whereIn('id', Media::query()->where('collection', Media::LIBRARY_COLLECTION)->whereNotNull('workspace_id')->select('workspace_id'))
- ->orderBy('id')
- ->get();
-
- if ($workspaces->isEmpty()) {
- $this->line(' No library media to adopt.');
- $this->summary[] = [$title, 'ok', 'no library media'];
-
- return;
- }
-
- $total = $workspaces->count();
-
- if (! $this->queueAdoption($total)) {
- $this->failedWorkspaces = $workspaces->modelKeys();
- $this->summary[] = [$title, 'failed', "{$total} workspace(s) could not be queued, run media:adopt-library --force"];
-
- return;
- }
-
- $timeout = max(0, (int) $this->option('adoption-timeout'));
- $started = now();
- $deadline = $started->addSeconds($timeout);
-
- while (true) {
- $progress = $this->adoptionProgress($workspaces);
- $done = $total - count($progress['running']) - count($progress['stopped']);
- $stopped = count($progress['stopped']);
- $elapsed = (int) $started->diffInSeconds(now());
- $this->line(" {$done}/{$total} workspace(s) done, {$progress['rows']} library row(s) left, {$stopped} stopped ({$elapsed}s)");
-
- if ($progress['running'] === [] || now()->greaterThanOrEqualTo($deadline)) {
- break;
- }
-
- Sleep::for(self::ADOPTION_POLL_SECONDS)->seconds();
- }
-
- $running = count($progress['running']);
- $result = "{$done} of {$total} workspace(s) adopted in {$elapsed}s";
-
- if ($stopped > 0) {
- $this->failedWorkspaces = $progress['stopped'];
- $ids = implode(', ', $progress['stopped']);
- $this->error(" {$stopped} workspace(s) stopped with library media left: {$ids}. See the log, fix the cause and run media:adopt-library --force.");
- }
-
- if ($running > 0) {
- $this->warn(" {$running} workspace(s) still adopting after {$elapsed}s; their jobs keep going on the media-adoption queue.");
- }
-
- $this->summary[] = match (true) {
- $stopped > 0 => [$title, 'failed', "{$result}; {$stopped} workspace(s) stopped with library media left: ".implode(', ', $progress['stopped'])],
- $running > 0 => [$title, 'queued', "{$result}; {$running} workspace(s) still adopting on the queue"],
- default => [$title, 'ok', $result],
- };
- }
-
- /**
- * A workspace is done once every library row left is one another
- * workspace still uses (the foreign references `media:adopt-library`
- * cached); otherwise it is running while its job's unique lock is held,
- * and stopped once the job ended without finishing.
- *
- * @param Collection<int, Workspace> $workspaces
- * @return array{rows: int, running: list<string>, stopped: list<string>}
- */
- private function adoptionProgress(Collection $workspaces): array
- {
- $kept = Cache::get(AdoptWorkspaceLibrary::FOREIGN_REFERENCES_CACHE_KEY, []);
- $left = Media::query()
- ->where('collection', Media::LIBRARY_COLLECTION)
- ->whereIn('workspace_id', $workspaces->modelKeys())
- ->toBase()
- ->get(['id', 'workspace_id'])
- ->reject(fn (object $row): bool => isset($kept[$row->workspace_id][$row->id]))
- ->groupBy('workspace_id');
- $progress = ['rows' => $left->flatten(1)->count(), 'running' => [], 'stopped' => []];
-
- foreach ($workspaces->whereIn('id', $left->keys()->all()) as $workspace) {
- $lock = Cache::lock(UniqueLock::getKey(new AdoptWorkspaceLibraryJob($workspace)), 1);
- $held = ! $lock->get();
-
- if (! $held) {
- $lock->release();
- }
-
- $progress[$held ? 'running' : 'stopped'][] = $workspace->id;
- }
-
- return $progress;
- }
-
- /**
- * Dispatches the adoption jobs through `media:adopt-library` (which
- * skips workspaces whose job is still queued); false when that fails.
- */
- private function queueAdoption(int $count): bool
- {
- $this->line(" Queueing AdoptWorkspaceLibraryJob for {$count} workspace(s) on the media-adoption queue.");
-
- try {
- $this->call('media:adopt-library', ['--force' => true]);
-
- return true;
- } catch (Throwable $exception) {
- report($exception);
- $this->error(" Could not queue AdoptWorkspaceLibraryJob: {$exception->getMessage()}");
-
- return false;
- }
- }
-
- /**
- * Channels connected before posting schedules existed get what a new
- * channel gets (owner time zone, goal 3, the network's recommended slots);
- * a channel that already has a schedule is never touched.
- */
- private function channelDefaults(): void
- {
- $title = 'Channel posting defaults';
- $this->heading($title);
-
- if ($this->option('dry-run')) {
- $pending = ApplyChannelDefaults::pending();
- $this->line(" Would set up {$pending} channel(s) without a posting schedule.");
- $this->summary[] = [$title, 'dry run', "would set up {$pending} channel(s)"];
-
- return;
- }
-
- try {
- $count = ApplyChannelDefaults::backfill();
- } catch (Throwable $exception) {
- report($exception);
- $this->error(" Failed: {$exception->getMessage()}");
- $this->summary[] = [$title, 'failed', $exception->getMessage()];
-
- return;
- }
-
- $this->line(" Set up {$count} channel(s) without a posting schedule.");
- $this->summary[] = [$title, 'ok', "{$count} channel(s) set up"];
- }
-
- /**
- * Dispatched once per install: its jobs may wait hours behind
- * `--backfill-delay`, and a second dispatch before they start would read
- * every account twice (X bills per read).
- */
- private function backfill(string $command): void
- {
- $title = 'Analytics backfill and external posts import (queued)';
- $dispatchedAt = Cache::store('database')->get(self::BACKFILL_DISPATCHED_KEY);
-
- if ($dispatchedAt !== null && ! $this->option('rerun-backfill')) {
- $this->heading($title);
- $this->line(" Skipped: already dispatched at {$dispatchedAt}. Pass --rerun-backfill to dispatch it again.");
- $this->summary[] = [$title, 'skipped', "already dispatched at {$dispatchedAt}"];
-
- return;
- }
-
- if ($this->runReleaseStep($title, $command) && ! $this->option('dry-run')) {
- Cache::store('database')->forever(self::BACKFILL_DISPATCHED_KEY, now()->toIso8601String());
- }
- }
-
- /**
- * The state the final audit is compared with: the audit without its
- * per-row storage requests (only the final audit checks every file, after
- * the data steps), and the rows that existed before the release.
- *
- * @return array{report: array<string, list<array<string, string>>>, ids: array<string, true>, paths: array<string, true>, dangling: array<string, true>}
- */
- private function snapshot(): array
- {
- $report = AuditMedia::execute(checkMissingFiles: false);
- $ids = [];
- $paths = [];
- $dangling = [];
-
- Media::query()->toBase()->select(['id', 'path', 'collection'])->chunkById(AuditMedia::CHUNK, function ($rows) use (&$ids, &$paths, &$dangling): void {
- foreach ($rows as $row) {
- $ids[$row->id] = true;
- $paths[$row->path] = true;
-
- if ($row->collection === Media::LIBRARY_COLLECTION) {
- $dangling[$row->id] = true;
- }
- }
- });
-
- foreach ($report['json_drift'] as $finding) {
- if ($finding['problem'] === 'json_without_row') {
- $dangling[$finding['media_id']] = true;
- }
- }
-
- return ['report' => $report, 'ids' => $ids, 'paths' => $paths, 'dangling' => $dangling];
- }
-
- /**
- * Compares the final media audit with the snapshot. A finding is expected
- * when it was already there; when an item points at a library row the
- * adoption kept (another workspace uses it, or it was left to the queued
- * job); when an item points at a row that is gone but was a library row or
- * already dangling before the release; when a file without a row belonged
- * to a row before the release (its deletion is queued); or when a row from
- * before the release has no file (the snapshot does not check files).
- * Anything else, such as a referenced row the release deleted, is
- * unexpected.
- *
- * @param array{report: array<string, list<array<string, string>>>, ids: array<string, true>, paths: array<string, true>, dangling: array<string, true>} $before
- */
- private function audit(array $before): int
- {
- $title = 'Media audit (read-only)';
- $this->heading($title);
-
- $started = microtime(true);
- $report = $this->option('dry-run') ? $before['report'] : AuditMedia::execute();
- $seconds = number_format(microtime(true) - $started, 1);
- $fingerprint = fn (array $finding): string => json_encode(collect($finding)->sortKeys()->all());
- $known = collect($before['report'])->map(fn (array $findings): array => array_flip(array_map($fingerprint, $findings)))->all();
- $collections = collect($report['json_drift'] ?? [])
- ->pluck('media_id')
- ->filter(fn (string $id): bool => Str::isUuid($id))
- ->chunk(1000)
- ->flatMap(fn ($ids) => Media::query()->whereIn('id', $ids->all())->pluck('collection', 'id'))
- ->all();
-
- $isExpected = fn (string $check, array $finding): bool => isset($known[$check][$fingerprint($finding)])
- || ($check === 'json_drift' && $finding['problem'] === 'json_without_row' && match ($collections[$finding['media_id']] ?? null) {
- null => isset($before['dangling'][$finding['media_id']]),
- Media::LIBRARY_COLLECTION => true,
- default => false,
- })
- || ($check === 'orphaned_files' && isset($before['paths'][$finding['path']]))
- || ($check === 'missing_files' && isset($before['ids'][$finding['media_id']]));
-
- $rows = [];
- $unexpected = [];
-
- foreach ($report as $check => $findings) {
- $surprises = array_values(array_filter($findings, fn (array $finding): bool => ! $isExpected($check, $finding)));
- $rows[] = [$check, count($findings) - count($surprises), count($surprises)];
-
- foreach ($surprises as $finding) {
- $unexpected[] = "{$check}: ".collect($finding)->map(fn (string $value, string $key): string => "{$key}={$value}")->implode(' ');
- }
- }
-
- $this->table(['Check', 'Expected', 'Unexpected'], $rows);
-
- foreach ($unexpected as $line) {
- $this->line(" unexpected {$line}");
- }
-
- $expected = collect($rows)->sum(1);
- $count = count($unexpected);
- $status = match (true) {
- $this->option('dry-run') => 'dry run',
- $count === 0 => 'ok',
- default => 'findings',
- };
- $this->summary[] = [$title, $status, "{$expected} expected, {$count} unexpected in {$seconds}s"];
-
- return $count;
- }
-
- /**
- * Runs one existing command, echoing its output. In a dry run a write
- * step only prints what it would do (and its preview); a read-only one
- * runs.
- *
- * @param (callable(): string)|null $preview
- */
- private function runReleaseStep(string $title, string $command, bool $readOnly = false, ?callable $preview = null): bool
- {
- $this->heading($title);
-
- if ($this->option('dry-run') && ! $readOnly) {
- $this->line(" Would run: php artisan {$command}");
- $detail = $preview !== null ? $preview() : "php artisan {$command}";
- $this->line(" {$detail}");
- $this->summary[] = [$title, 'dry run', $detail];
-
- return true;
- }
-
- $buffer = new BufferedOutput;
-
- try {
- $code = Artisan::call($command, [], $buffer);
- } catch (Throwable $exception) {
- report($exception);
- $this->output->write($buffer->fetch());
- $this->error(" Failed: {$exception->getMessage()}");
- $this->summary[] = [$title, 'failed', $exception->getMessage()];
-
- return false;
- }
-
- $output = $buffer->fetch();
- $this->output->write($output);
-
- $digest = collect(explode(PHP_EOL, $output))
- ->map(fn (string $line): string => trim($line))
- ->reject(fn (string $line): bool => $line === '' || Str::startsWith($line, ['+', '|']))
- ->implode('; ');
-
- $status = match (true) {
- $code !== self::SUCCESS => 'failed',
- $this->option('dry-run') => 'dry run',
- default => 'ok',
- };
- $this->summary[] = [$title, $status, $digest !== '' ? $digest : 'done'];
-
- return $code === self::SUCCESS;
- }
-
- private function heading(string $title): void
- {
- $step = count($this->summary) + 1;
- $steps = self::STEPS;
-
- $this->newLine();
- $this->info("[{$step}/{$steps}] {$title}");
- }
-
- /**
- * @return list<string>
- */
- private function pendingMigrations(Migrator $migrator): array
- {
- if (! $migrator->repositoryExists()) {
- return ['migrations table'];
- }
-
- $files = $migrator->getMigrationFiles([database_path('migrations'), ...$migrator->paths()]);
-
- return array_values(array_diff(array_keys($files), $migrator->getRepository()->getRan()));
- }
-}
diff --git a/app/Console/Commands/Scripts/SplitLegacyActivePosts.php b/app/Console/Commands/Scripts/SplitLegacyActivePosts.php
deleted file mode 100644
index a1b8d3ce1..000000000
--- a/app/Console/Commands/Scripts/SplitLegacyActivePosts.php
+++ /dev/null
@@ -1,221 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Console\Commands\Scripts;
-
-use App\Actions\Media\SyncOwnedMedia;
-use App\Enums\Post\Status;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostNote;
-use App\Models\PostPlatform;
-use App\Support\Media\MediaCopyBatch;
-use Illuminate\Console\Attributes\Description;
-use Illuminate\Console\Attributes\Signature;
-use Illuminate\Console\Command;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Support\Str;
-use Illuminate\Validation\ValidationException;
-
-#[Signature('posts:split-legacy-active')]
-#[Description('Split editable and settled multi-target posts into one post per enabled target and group every multi-target post')]
-class SplitLegacyActivePosts extends Command
-{
- private const int UNFINISHED = -1;
-
- public function handle(): int
- {
- $splitPosts = 0;
- $createdPosts = 0;
- $unfinishedPosts = 0;
-
- Post::query()
- ->where(fn (Builder $query) => $query
- ->where(fn (Builder $multiTarget) => $multiTarget
- ->whereIn('status', [Status::Draft, Status::Scheduled, Status::Published, Status::PartiallyPublished, Status::Failed])
- ->whereHas('postPlatforms', fn ($targets) => $targets->enabled(), '>', 1))
- ->orWhere('status', Status::PartiallyPublished))
- ->select('id')
- ->orderBy('id')
- ->chunkById(100, function ($posts) use (&$splitPosts, &$createdPosts, &$unfinishedPosts): void {
- foreach ($posts as $candidate) {
- try {
- $clones = MediaCopyBatch::run(fn (MediaCopyBatch $batch): int => $this->splitPost($candidate->id, $batch));
- } catch (ValidationException) {
- $this->warn("Post {$candidate->id} was not split: a media file could not be copied.");
-
- continue;
- }
-
- if ($clones === self::UNFINISHED) {
- $unfinishedPosts++;
-
- continue;
- }
-
- if ($clones > 0) {
- $splitPosts++;
- $createdPosts += $clones;
- }
- }
- });
-
- $this->info("Split {$splitPosts} original posts and created {$createdPosts} independent posts.");
-
- if ($unfinishedPosts > 0) {
- $this->warn("Left {$unfinishedPosts} settled post(s) with an unfinished target as they are.");
- }
-
- $groupedPosts = 0;
-
- Post::query()
- ->whereNull('post_group_id')
- ->has('postPlatforms', '>', 1)
- ->select('id')
- ->orderBy('id')
- ->chunkById(100, function ($posts) use (&$groupedPosts): void {
- foreach ($posts as $post) {
- $groupedPosts += Post::query()
- ->whereKey($post->id)
- ->whereNull('post_group_id')
- ->toBase()
- ->update(['post_group_id' => (string) Str::uuid7()]);
- }
- });
-
- $this->info("Grouped {$groupedPosts} multi-target posts.");
-
- return self::SUCCESS;
- }
-
- /**
- * Each copy keeps every item of the original, in order and as it is
- * (items without an id or repeated ones included); only an item pointing
- * at a row the original owns (an adopted library or an edit) is swapped
- * for the copy's own copy of that row. Library rows and missing files are
- * left for the adoption, which copies them per post.
- *
- * A settled post (published, partially published, failed) is split too:
- * each post takes the status of its own target, and the target row moves
- * with its permalink, error and analytics link. Disabled targets stay on
- * the original as the history of a destination that never ran. A settled
- * post with a target still in flight is left as it is (UNFINISHED).
- */
- private function splitPost(string $postId, MediaCopyBatch $batch): int
- {
- $post = Post::query()->lockForUpdate()->findOrFail($postId);
- $settled = $post->status->isSettled();
-
- if (! $settled && ! in_array($post->status, [Status::Draft, Status::Scheduled], true)) {
- return 0;
- }
-
- $targets = $post->postPlatforms()->enabled()->orderBy('id')->lockForUpdate()->get();
- $statuses = $settled ? $targets->map(fn (PostPlatform $target): ?Status => self::postStatusFor($target->status))->values() : collect();
-
- if ($statuses->contains(null)) {
- return self::UNFINISHED;
- }
-
- if ($settled && $targets->count() === 1) {
- $this->settleOriginal($post, $statuses->first(), $targets->first());
- }
-
- if ($targets->count() <= 1) {
- return 0;
- }
-
- if ($post->post_group_id === null) {
- $groupId = (string) Str::uuid7();
- Post::query()->whereKey($post->id)->toBase()->update(['post_group_id' => $groupId]);
- $post->forceFill(['post_group_id' => $groupId])->syncOriginal();
- }
-
- $items = array_values($post->media ?? []);
- $ownedIds = Media::query()
- ->where('post_id', $post->id)
- ->whereIn('id', collect($items)->map(fn (mixed $item): mixed => data_get($item, 'id'))->filter(fn (mixed $id): bool => is_string($id) && Str::isUuid($id))->unique()->values()->all())
- ->orderBy('id')
- ->pluck('id')
- ->all();
- $labelIds = $post->labels()->pluck('workspace_labels.id')->all();
- $notes = $post->notes()->orderBy('id')->get();
-
- foreach ($targets->skip(1) as $index => $target) {
- $clone = Post::withoutEvents(function () use ($post, $settled, $statuses, $index, $target): Post {
- $clone = $post->replicate();
- $clone->status = $settled ? $statuses[$index] : $post->status;
- $clone->published_at = $settled ? $target->published_at : $post->published_at;
- $clone->created_at = $post->created_at;
- $clone->updated_at = $post->updated_at;
- $clone->saveQuietly();
-
- return $clone;
- });
- $this->copyOwnedMedia($clone, $items, $ownedIds, $batch);
- $clone->labels()->sync($labelIds);
-
- foreach ($notes as $note) {
- PostNote::withoutEvents(function () use ($note, $clone): void {
- $copy = $note->replicate();
- $copy->post_id = $clone->id;
- $copy->created_at = $note->created_at;
- $copy->updated_at = $note->updated_at;
- $copy->saveQuietly();
- });
- }
-
- PostPlatform::query()->whereKey($target->id)->toBase()->update(['post_id' => $clone->id]);
- Post::query()->whereKey($clone->id)->toBase()->update(['updated_at' => $post->getRawOriginal('updated_at')]);
- }
-
- if ($settled) {
- $this->settleOriginal($post, $statuses->first(), $targets->first());
- }
-
- return $targets->count() - 1;
- }
-
- /**
- * @param list<mixed> $items
- * @param list<string> $ownedIds
- */
- private function copyOwnedMedia(Post $clone, array $items, array $ownedIds, MediaCopyBatch $batch): void
- {
- if ($ownedIds === []) {
- return;
- }
-
- $copies = array_combine($ownedIds, SyncOwnedMedia::execute($clone, array_map(fn (string $id): array => ['id' => $id], $ownedIds), $batch));
-
- $clone->forceFill(['media' => array_map(function (mixed $item) use ($copies): mixed {
- $copy = is_array($item) ? ($copies[data_get($item, 'id')] ?? null) : null;
-
- return $copy === null ? $item : [...$item, 'id' => $copy['id'], 'path' => $copy['path'], 'url' => $copy['url']];
- }, $items)])->saveQuietly();
- }
-
- private static function postStatusFor(PostPlatformStatus $status): ?Status
- {
- return match ($status) {
- PostPlatformStatus::Published => Status::Published,
- PostPlatformStatus::Failed, PostPlatformStatus::Rejected => Status::Failed,
- default => null,
- };
- }
-
- /**
- * The original keeps its first target: its status and publish time come
- * from that target. Query-builder writes, so no event fires and
- * `updated_at` stays.
- */
- private function settleOriginal(Post $post, Status $status, PostPlatform $target): void
- {
- Post::query()->whereKey($post->id)->toBase()->update([
- 'status' => $status->value,
- 'published_at' => $target->getRawOriginal('published_at'),
- ]);
- }
-}
diff --git a/app/Dto/Analytics/PublicationFilter.php b/app/Dto/Analytics/PublicationFilter.php
index 39a9084bb..e6dd2ba54 100644
--- a/app/Dto/Analytics/PublicationFilter.php
+++ b/app/Dto/Analytics/PublicationFilter.php
@@ -14,7 +14,7 @@ use Illuminate\Database\Query\Builder;
/**
* Narrows a channel's publications by the labels of their TryPost post and by post type.
*
- * Expects the publication query aliased as `publication`, left-joined to its post platform as `destination`.
+ * Expects the publication query aliased as `publication`, left-joined to its post as `destination`.
* A publication with a post platform takes that post platform's content type; one without (published
* outside TryPost and never imported) is typed through ContentType::fromPublication(), and an unknown
* publication type matches no post type. A publication without a post carries no labels, so it only
@@ -77,7 +77,7 @@ final readonly class PublicationFilter
*/
private function posts(): EloquentBuilder
{
- return Post::query()->select('posts.id')->whereColumn('posts.id', 'destination.post_id');
+ return Post::query()->select('posts.id')->whereColumn('posts.id', 'destination.id');
}
/**
diff --git a/app/Enums/PostPlatform/Status.php b/app/Enums/Post/PublishStatus.php
similarity index 66%
rename from app/Enums/PostPlatform/Status.php
rename to app/Enums/Post/PublishStatus.php
index 3c6789504..d8c5fb9dc 100644
--- a/app/Enums/PostPlatform/Status.php
+++ b/app/Enums/Post/PublishStatus.php
@@ -2,9 +2,9 @@
declare(strict_types=1);
-namespace App\Enums\PostPlatform;
+namespace App\Enums\Post;
-enum Status: string
+enum PublishStatus: string
{
case Pending = 'pending';
case Publishing = 'publishing';
@@ -14,7 +14,9 @@ enum Status: string
case Failed = 'failed';
case Rejected = 'rejected';
- /** Published, failed, or rejected — counts toward settling the parent post. */
+ public const self DEFAULT = self::Pending;
+
+ /** Published, failed, or rejected — the post can be settled. */
public function isFinished(): bool
{
return match ($this) {
@@ -28,4 +30,10 @@ enum Status: string
{
return $this->isFinished() || $this === self::PendingReview;
}
+
+ /** Still to be sent or being sent: pending, publishing or retrying. */
+ public function isInFlight(): bool
+ {
+ return ! $this->isClosed();
+ }
}
diff --git a/app/Enums/Post/Status.php b/app/Enums/Post/Status.php
index 851de05ee..c4afe00ba 100644
--- a/app/Enums/Post/Status.php
+++ b/app/Enums/Post/Status.php
@@ -11,7 +11,6 @@ enum Status: string
case Scheduled = 'scheduled';
case Publishing = 'publishing';
case Published = 'published';
- case PartiallyPublished = 'partially_published';
case Failed = 'failed';
public function label(): string
@@ -22,7 +21,6 @@ enum Status: string
self::Scheduled => __('posts.status.scheduled'),
self::Publishing => __('posts.status.publishing'),
self::Published => __('posts.status.published'),
- self::PartiallyPublished => __('posts.status.partially_published'),
self::Failed => __('posts.status.failed'),
};
}
@@ -35,16 +33,15 @@ enum Status: string
self::Scheduled => 'blue',
self::Publishing => 'yellow',
self::Published => 'green',
- self::PartiallyPublished => 'orange',
self::Failed => 'red',
};
}
- /** Published, partially published, or failed — Finalize must not notify again. */
+ /** Published or failed — Finalize must not notify again. */
public function isSettled(): bool
{
return match ($this) {
- self::Published, self::PartiallyPublished, self::Failed => true,
+ self::Published, self::Failed => true,
default => false,
};
}
diff --git a/app/Enums/Webhook/EventType.php b/app/Enums/Webhook/EventType.php
index 664b7d57d..6116b1897 100644
--- a/app/Enums/Webhook/EventType.php
+++ b/app/Enums/Webhook/EventType.php
@@ -12,7 +12,6 @@ enum EventType: string
case PostScheduled = 'post.scheduled';
case PostUnscheduled = 'post.unscheduled';
case PostPublished = 'post.published';
- case PostPartiallyPublished = 'post.partially_published';
case PostFailed = 'post.failed';
case PostDeleted = 'post.deleted';
@@ -21,7 +20,6 @@ enum EventType: string
return match ($status) {
PostStatus::Scheduled => self::PostScheduled,
PostStatus::Published => self::PostPublished,
- PostStatus::PartiallyPublished => self::PostPartiallyPublished,
PostStatus::Failed => self::PostFailed,
PostStatus::Draft => $previous === PostStatus::Scheduled ? self::PostUnscheduled : null,
PostStatus::PendingApproval => $previous === PostStatus::Scheduled ? self::PostUnscheduled : null,
diff --git a/app/Events/PostPlatformStatusUpdated.php b/app/Events/PostStatusUpdated.php
similarity index 67%
rename from app/Events/PostPlatformStatusUpdated.php
rename to app/Events/PostStatusUpdated.php
index b4f540c33..51b4f4dc3 100644
--- a/app/Events/PostPlatformStatusUpdated.php
+++ b/app/Events/PostStatusUpdated.php
@@ -4,18 +4,18 @@ declare(strict_types=1);
namespace App\Events;
-use App\Models\PostPlatform;
+use App\Models\Post;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
-class PostPlatformStatusUpdated implements ShouldBroadcast
+class PostStatusUpdated implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
- public function __construct(public PostPlatform $postPlatform) {}
+ public function __construct(public Post $post) {}
public function broadcastAs(): string
{
@@ -25,8 +25,7 @@ class PostPlatformStatusUpdated implements ShouldBroadcast
public function broadcastOn(): array
{
return [
- new PrivateChannel("post.{$this->postPlatform->post_id}"),
- new PrivateChannel("workspace.{$this->postPlatform->post->workspace_id}"),
+ new PrivateChannel("workspace.{$this->post->workspace_id}"),
];
}
@@ -36,7 +35,7 @@ class PostPlatformStatusUpdated implements ShouldBroadcast
public function broadcastWith(): array
{
return [
- 'post_id' => $this->postPlatform->post_id,
+ 'post_id' => $this->post->id,
];
}
diff --git a/app/Http/Controllers/Api/ChannelQueueController.php b/app/Http/Controllers/Api/ChannelQueueController.php
index ca0378e36..a10a43258 100644
--- a/app/Http/Controllers/Api/ChannelQueueController.php
+++ b/app/Http/Controllers/Api/ChannelQueueController.php
@@ -32,7 +32,7 @@ class ChannelQueueController extends Controller
$request->user(),
);
- $post = Post::query()->with(['postPlatforms.socialAccount', 'labels'])->findOrFail($request->validated('post_id'));
+ $post = Post::query()->with(['socialAccount', 'labels'])->findOrFail($request->validated('post_id'));
return new PostResource($post);
}
diff --git a/app/Http/Controllers/Api/PlatformController.php b/app/Http/Controllers/Api/PlatformController.php
index 0ec9edf16..d0f2d08f1 100644
--- a/app/Http/Controllers/Api/PlatformController.php
+++ b/app/Http/Controllers/Api/PlatformController.php
@@ -12,7 +12,7 @@ class PlatformController extends Controller
{
/**
* Index of platforms with their valid content_types and publishing
- * constraints — used by clients to build correct `platforms[].content_type`
+ * constraints — used by clients to build correct `content_type`
* payloads for `POST /api/posts` and `PUT /api/posts/{id}`.
*/
public function contentTypes(): JsonResponse
diff --git a/app/Http/Controllers/Api/PostApprovalController.php b/app/Http/Controllers/Api/PostApprovalController.php
index a355d7f29..7fff48fa8 100644
--- a/app/Http/Controllers/Api/PostApprovalController.php
+++ b/app/Http/Controllers/Api/PostApprovalController.php
@@ -17,7 +17,7 @@ class PostApprovalController extends Controller
{
/** @var Post $approved */
$approved = data_get(ApprovePost::execute($post, $request->user(), $request->validated()), 'post');
- $approved->load(['postPlatforms.socialAccount', 'labels']);
+ $approved->load(['socialAccount', 'labels']);
return new PostResource($approved);
}
@@ -27,7 +27,7 @@ class PostApprovalController extends Controller
$this->authorize('approve', $post);
$rejected = RejectPost::execute($post, $request->user());
- $rejected->load(['postPlatforms.socialAccount', 'labels']);
+ $rejected->load(['socialAccount', 'labels']);
return new PostResource($rejected);
}
diff --git a/app/Http/Controllers/Api/PostController.php b/app/Http/Controllers/Api/PostController.php
index 99fa0892f..bda9755aa 100644
--- a/app/Http/Controllers/Api/PostController.php
+++ b/app/Http/Controllers/Api/PostController.php
@@ -28,11 +28,13 @@ use App\Http\Resources\Api\PostResource;
use App\Models\Media;
use App\Models\Post;
use App\Services\Post\MediaAttacher;
+use App\Support\PostCompositionValidator;
use App\Support\PostStatusRules;
use App\Support\Requests\Post\PostMediaRequestRules;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
+use Illuminate\Support\Arr;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
@@ -48,7 +50,7 @@ class PostController extends Controller
->visiblePendingApprovalsFor(BuildPublishPageProps::pendingApprovalsRequester($user, $workspace))
->onChannels(data_get($filters, 'channels') ?: null)
->matchingLabelFilter(data_get($filters, 'labels'), data_get($filters, 'untagged'))
- ->with(['postPlatforms.socialAccount', 'user', 'approvalRequestedBy', 'approver', 'labels'])
+ ->with(['socialAccount', 'user', 'approvalRequestedBy', 'approver', 'labels'])
->latestScheduledFirst()
->paginate((int) config('app.pagination.default'));
@@ -66,7 +68,7 @@ class PostController extends Controller
->exists();
abort_unless($visible, Response::HTTP_NOT_FOUND);
- $post->load(['postPlatforms.socialAccount', 'user', 'labels']);
+ $post->load(['socialAccount', 'user', 'labels']);
return new PostResource($post);
}
@@ -78,7 +80,7 @@ class PostController extends Controller
$data = HostInlineMedia::forPost($workspace, Post::allowedMediaTypesFor($request->selectedPlatforms()), $data);
- $post = CreatePosts::execute($workspace, $request->user(), [
+ $post = PostCompositionValidator::forSinglePost(fn (): Post => CreatePosts::execute($workspace, $request->user(), [
'status' => $data['status'] ?? 'draft',
'content' => $data['content'] ?? '',
'media' => $data['media'] ?? [],
@@ -87,10 +89,10 @@ class PostController extends Controller
'queue_slot' => $data['queue_slot'] ?? null,
'label_ids' => $data['label_ids'] ?? [],
'created_via' => CreatedVia::Api,
- 'destinations' => [$data['platforms'][0]],
- ])->sole();
+ 'destinations' => [Arr::only($data, ['social_account_id', 'content_type', 'meta'])],
+ ])->sole());
- $post->load(['postPlatforms.socialAccount', 'labels']);
+ $post->load(['socialAccount', 'labels']);
return (new PostResource($post))
->response()
@@ -107,7 +109,7 @@ class PostController extends Controller
return response()->json([
'posts' => $posts->map(function (Post $post): array {
- $post->load(['postPlatforms.socialAccount', 'labels']);
+ $post->load(['socialAccount', 'labels']);
return (new PostResource($post))->resolve();
})->all(),
@@ -132,7 +134,7 @@ class PostController extends Controller
}
$updated = data_get($result, 'post');
- $updated->load(['postPlatforms.socialAccount', 'labels']);
+ $updated->load(['socialAccount', 'labels']);
return new PostResource($updated);
}
@@ -158,7 +160,7 @@ class PostController extends Controller
AppendPostMedia::execute($post, [MediaItem::fromMedia($media)->toArray()], $request->user());
- $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
+ $post->refresh()->load(['socialAccount', 'labels']);
return new PostResource($post);
}
@@ -173,7 +175,7 @@ class PostController extends Controller
AppendPostMedia::execute($post, [MediaItem::fromMedia($media, $request->validated('alt'))->toArray()], $request->user());
- $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
+ $post->refresh()->load(['socialAccount', 'labels']);
return new PostResource($post);
}
@@ -182,7 +184,7 @@ class PostController extends Controller
{
$result = app(MediaAttacher::class)->attachFromUrls($post, $request->validated('urls'), $request->user());
- $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
+ $post->refresh()->load(['socialAccount', 'labels']);
return new PostMediaAttachResource($post, $result);
}
@@ -191,7 +193,7 @@ class PostController extends Controller
{
$this->authorize('view', $post);
- $post->load(['postPlatforms.socialAccount']);
+ $post->load(['socialAccount']);
return new PostMetricsResource($post);
}
@@ -200,7 +202,7 @@ class PostController extends Controller
{
$this->authorize('view', $post);
- $post->load(['postPlatforms.socialAccount']);
+ $post->load(['socialAccount']);
return new PostPreviewResource($post);
}
diff --git a/app/Http/Controllers/Api/PostRecurrenceController.php b/app/Http/Controllers/Api/PostRecurrenceController.php
index 10a2e3b02..08661e24d 100644
--- a/app/Http/Controllers/Api/PostRecurrenceController.php
+++ b/app/Http/Controllers/Api/PostRecurrenceController.php
@@ -29,6 +29,6 @@ class PostRecurrenceController extends Controller
private function resource(Post $post): PostResource
{
- return new PostResource($post->fresh(['postPlatforms.socialAccount', 'labels']));
+ return new PostResource($post->fresh(['socialAccount', 'labels']));
}
}
diff --git a/app/Http/Controllers/App/Concerns/RendersPublishPage.php b/app/Http/Controllers/App/Concerns/RendersPublishPage.php
index 485d08d4f..f011c3ab4 100644
--- a/app/Http/Controllers/App/Concerns/RendersPublishPage.php
+++ b/app/Http/Controllers/App/Concerns/RendersPublishPage.php
@@ -29,7 +29,7 @@ trait RendersPublishPage
if (is_string($editPostId) && Str::isUuid($editPostId)) {
$composerPost = $workspace->posts()
- ->with(['postPlatforms' => fn ($query) => $query->enabled()->with('socialAccount'), 'labels'])
+ ->with(['socialAccount', 'labels'])
->findOrFail($editPostId);
$this->authorize('update', $composerPost);
$composerPost->unsetRelation('user')->unsetRelation('approvalRequestedBy');
@@ -111,12 +111,10 @@ trait RendersPublishPage
private function canOpenComposer(Post $post): bool
{
- $targets = $post->postPlatforms()->enabled()->get();
-
- if ($targets->isEmpty()) {
+ if (! $post->hasChannel()) {
return $post->status === PostStatus::Draft;
}
- return $targets->count() === 1 && $targets->first()->social_account_id !== null;
+ return true;
}
}
diff --git a/app/Http/Controllers/App/PostController.php b/app/Http/Controllers/App/PostController.php
index af183649c..fc675d0ed 100644
--- a/app/Http/Controllers/App/PostController.php
+++ b/app/Http/Controllers/App/PostController.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace App\Http\Controllers\App;
-use App\Actions\Analytics\ReadPublicationAnalytics;
use App\Actions\Post\BuildCalendarPageProps;
use App\Actions\Post\CreatePosts;
use App\Actions\Post\DeletePost;
@@ -18,9 +17,7 @@ use App\Http\Controllers\App\Concerns\RendersPublishPage;
use App\Http\Requests\App\Post\StorePostRequest;
use App\Http\Requests\App\Post\UpdatePostRequest;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\PostStatusRules;
-use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
@@ -137,17 +134,6 @@ class PostController extends Controller
->with('created_post_ids', $posts->pluck('id')->all());
}
- public function platformMetrics(Request $request, Post $post, PostPlatform $postPlatform): JsonResponse
- {
- $this->authorize('view', $post);
-
- if ($postPlatform->post_id !== $post->id) {
- abort(404);
- }
-
- return response()->json(app(ReadPublicationAnalytics::class)->forPlatform($postPlatform));
- }
-
public function edit(Request $request, Post $post): Response|RedirectResponse
{
$workspace = $request->user()->currentWorkspace;
@@ -245,9 +231,9 @@ class PostController extends Controller
{
$this->authorize('duplicate', $post);
- $post->load(['postPlatforms', 'labels']);
+ $post->load(['socialAccount', 'labels']);
- $copy = DuplicatePost::execute($post, $request->user(), $request->input('post_platform_id'));
+ $copy = DuplicatePost::execute($post, $request->user());
return redirect($this->publishPageReturnUrl(['edit' => $copy->id]) ?? route('app.posts.edit', $copy));
}
diff --git a/app/Http/Controllers/App/PostGroupController.php b/app/Http/Controllers/App/PostGroupController.php
index 8a60e92b6..22b2e1626 100644
--- a/app/Http/Controllers/App/PostGroupController.php
+++ b/app/Http/Controllers/App/PostGroupController.php
@@ -25,7 +25,7 @@ class PostGroupController extends Controller
fn ($query) => $query->whereKey($post->id),
)
->with([
- 'postPlatforms' => fn ($platforms) => $platforms->enabled()->with('socialAccount'),
+ 'socialAccount',
'user.avatarMedia',
'labels',
])
@@ -34,7 +34,7 @@ class PostGroupController extends Controller
->sortBy(fn (Post $sibling): array => [
$sibling->scheduled_at === null ? 1 : 0,
$sibling->scheduled_at?->getTimestamp() ?? 0,
- $sibling->postPlatforms->first()?->socialAccount?->position ?? PHP_INT_MAX,
+ $sibling->socialAccount?->position ?? PHP_INT_MAX,
])
->values();
diff --git a/app/Http/Requests/Api/Post/SetPostRecurrenceRequest.php b/app/Http/Requests/Api/Post/SetPostRecurrenceRequest.php
index 9371e7089..d8289a462 100644
--- a/app/Http/Requests/Api/Post/SetPostRecurrenceRequest.php
+++ b/app/Http/Requests/Api/Post/SetPostRecurrenceRequest.php
@@ -7,7 +7,6 @@ namespace App\Http\Requests\Api\Post;
use App\Enums\Post\RecurrenceFrequency;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\PostingSchedule;
use App\Support\Timezone;
use Carbon\CarbonImmutable;
@@ -68,11 +67,10 @@ class SetPostRecurrenceRequest extends FormRequest
$frequency = RecurrenceFrequency::from($this->string('frequency')->toString());
$steps = $this->integer('interval') * $this->integer('times');
$ceiling = CarbonImmutable::parse(PostingSchedule::MAX_INSTANT, 'UTC');
- $tooFar = $post->postPlatforms()->enabled()->with('socialAccount')->get()
- ->contains(fn (PostPlatform $target): bool => $frequency->advance(
- $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($target->socialAccount?->timezone)),
- $steps,
- )->greaterThan($ceiling));
+ $tooFar = $post->hasDestination() && $frequency->advance(
+ $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($post->socialAccount?->timezone)),
+ $steps,
+ )->greaterThan($ceiling);
if ($tooFar) {
$validator->errors()->add('times', __('posts.recurrence.errors.too_far'));
diff --git a/app/Http/Requests/Api/Post/UpdatePostRequest.php b/app/Http/Requests/Api/Post/UpdatePostRequest.php
index 337995bbc..21d00894c 100644
--- a/app/Http/Requests/Api/Post/UpdatePostRequest.php
+++ b/app/Http/Requests/Api/Post/UpdatePostRequest.php
@@ -15,11 +15,6 @@ class UpdatePostRequest extends FormRequest
return true;
}
- protected function prepareForValidation(): void
- {
- $this->replace(PostRequestRules::updateInput($this->route('post'), $this->all()));
- }
-
public function rules(): array
{
return PostRequestRules::update($this->user()->currentWorkspace, $this->route('post'), $this->all());
diff --git a/app/Http/Requests/App/Post/StorePostRequest.php b/app/Http/Requests/App/Post/StorePostRequest.php
index 3ba079d62..cae1a5043 100644
--- a/app/Http/Requests/App/Post/StorePostRequest.php
+++ b/app/Http/Requests/App/Post/StorePostRequest.php
@@ -4,7 +4,9 @@ declare(strict_types=1);
namespace App\Http\Requests\App\Post;
+use App\Enums\Post\Status;
use Illuminate\Foundation\Http\FormRequest;
+use Illuminate\Validation\Rule;
class StorePostRequest extends FormRequest
{
@@ -19,7 +21,7 @@ class StorePostRequest extends FormRequest
public function rules(): array
{
return [
- 'status' => ['required', 'in:draft,scheduled,publishing'],
+ 'status' => ['required', Rule::in([Status::Draft->value, Status::Scheduled->value, Status::Publishing->value])],
'content' => ['sometimes', 'nullable', 'string'],
'media' => ['sometimes', 'array'],
'scheduled_at' => ['nullable', 'date'],
diff --git a/app/Http/Requests/App/Post/UpdatePostRecurrenceRequest.php b/app/Http/Requests/App/Post/UpdatePostRecurrenceRequest.php
index c09862c69..57fb7e7fa 100644
--- a/app/Http/Requests/App/Post/UpdatePostRecurrenceRequest.php
+++ b/app/Http/Requests/App/Post/UpdatePostRecurrenceRequest.php
@@ -7,7 +7,6 @@ namespace App\Http\Requests\App\Post;
use App\Enums\Post\RecurrenceFrequency;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Support\PostingSchedule;
use App\Support\Timezone;
use Carbon\CarbonImmutable;
@@ -69,11 +68,10 @@ class UpdatePostRecurrenceRequest extends FormRequest
$frequency = RecurrenceFrequency::from($this->string('frequency')->toString());
$steps = $this->integer('interval') * $this->integer('times');
$ceiling = CarbonImmutable::parse(PostingSchedule::MAX_INSTANT, 'UTC');
- $tooFar = $post->postPlatforms()->enabled()->with('socialAccount')->get()
- ->contains(fn (PostPlatform $target): bool => $frequency->advance(
- $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($target->socialAccount?->timezone)),
- $steps,
- )->greaterThan($ceiling));
+ $tooFar = $post->hasDestination() && $frequency->advance(
+ $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($post->socialAccount?->timezone)),
+ $steps,
+ )->greaterThan($ceiling);
if ($tooFar) {
$validator->errors()->add('times', __('posts.recurrence.errors.too_far'));
diff --git a/app/Http/Requests/App/Post/UpdatePostRequest.php b/app/Http/Requests/App/Post/UpdatePostRequest.php
index b0c2ebb26..22382d3a7 100644
--- a/app/Http/Requests/App/Post/UpdatePostRequest.php
+++ b/app/Http/Requests/App/Post/UpdatePostRequest.php
@@ -6,19 +6,18 @@ namespace App\Http\Requests\App\Post;
use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
use App\Rules\ContentFitsPlatformLimits;
use App\Rules\ContentTypeCompatibleWithMedia;
+use App\Rules\ContentTypeMatchesPostChannel;
use App\Rules\PostContentFitsMaxLength;
use App\Support\PostMediaRules;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
use Illuminate\Foundation\Http\FormRequest;
-use Illuminate\Support\Collection;
+use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
+use Inertia\Inertia;
class UpdatePostRequest extends FormRequest
{
@@ -27,8 +26,20 @@ class UpdatePostRequest extends FormRequest
return true;
}
+ /**
+ * A tab opened before posts and their destinations were merged still
+ * sends `platforms[]`; reload it instead of dropping the edit.
+ */
+ protected function prepareForValidation(): void
+ {
+ if ($this->has('platforms')) {
+ throw new HttpResponseException(Inertia::location(url()->previous()));
+ }
+ }
+
public function rules(): array
{
+ $post = $this->route('post');
$status = $this->input('status');
$enforcesMediaCompatibility = in_array(
@@ -36,6 +47,7 @@ class UpdatePostRequest extends FormRequest
[Status::Scheduled->value, Status::Publishing->value],
true,
);
+ $target = $post->socialAccount ?? $post->platform;
return [
'status' => ['required', 'string', Rule::in([Status::Draft->value, Status::Scheduled->value, Status::Publishing->value])],
@@ -45,22 +57,23 @@ class UpdatePostRequest extends FormRequest
new PostContentFitsMaxLength,
Rule::when(
$enforcesMediaCompatibility,
- [new ContentFitsPlatformLimits($this->resolveSelectedPlatforms(), PostPlatformMetaRules::metaByKey($this->input('platforms', []), 'id'), PostPlatformMetaRules::contentTypesByKey($this->input('platforms', []), 'id', $this->storedContentTypes()))]
+ [new ContentFitsPlatformLimits(
+ collect(filled($target) ? ['post' => $target] : []),
+ ['post' => $this->effectiveMeta()],
+ ['post' => $this->input('content_type') ?? $post->content_type?->value],
+ )]
),
],
...PostMediaRules::hostedRules(),
- 'scheduled_at' => PostStatusRules::scheduledAtRules($this->route('post'), $status, $this->filled('queue')),
+ 'scheduled_at' => PostStatusRules::scheduledAtRules($post, $status, $this->filled('queue')),
'queue' => PostStatusRules::queueRules(),
'social_account_id' => ['prohibited'],
- 'content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],
- 'meta' => ['sometimes', 'array'],
- 'platforms' => ['sometimes', 'array'],
- 'platforms.*.id' => ['required', 'uuid', Rule::exists('post_platforms', 'id')->where('post_id', $this->route('post')->id)],
- 'platforms.*.content_type' => [
- $enforcesMediaCompatibility ? 'required' : 'sometimes',
+ 'content_type' => [
+ 'sometimes',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
- Rule::when($enforcesMediaCompatibility, [new ContentTypeCompatibleWithMedia(workspace: $this->route('post')->workspace)]),
+ new ContentTypeMatchesPostChannel($post),
+ Rule::when($enforcesMediaCompatibility, [new ContentTypeCompatibleWithMedia(workspace: $post->workspace)]),
],
...PostPlatformMetaRules::rules(),
'label_ids' => ['sometimes', 'array'],
@@ -87,25 +100,13 @@ class UpdatePostRequest extends FormRequest
public function withValidator(Validator $validator): void
{
$validator->after(function (Validator $validator): void {
- if (! $this->isPublishingOrScheduling()) {
+ $post = $this->route('post');
+
+ if (! $this->isPublishingOrScheduling() || ! $post->hasDestination()) {
return;
}
- $platforms = $this->input('platforms', []);
- $ids = collect($platforms)->pluck('id')->filter()->all();
-
- $platformsById = $this->route('post')
- ->postPlatforms()
- ->with('socialAccount')
- ->whereIn('id', $ids)
- ->get()
- ->mapWithKeys(fn (PostPlatform $postPlatform): array => [$postPlatform->id => $postPlatform->socialAccount ?? $postPlatform->platform]);
-
- PostPlatformMetaRules::addRequiredOnPublishErrors(
- $validator,
- $platforms,
- fn ($platform) => $platformsById[data_get($platform, 'id')] ?? null,
- );
+ PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, $this->effectiveMeta());
});
}
@@ -119,33 +120,12 @@ class UpdatePostRequest extends FormRequest
}
/**
- * @return Collection<int|string, Platform|SocialAccount>
+ * The meta the save would store: the submitted keys over the stored ones.
+ *
+ * @return array<string, mixed>
*/
- /**
- * @return array<string, string|null>
- */
- private function storedContentTypes(): array
- {
- return $this->route('post')->postPlatforms()->pluck('content_type', 'id')
- ->map(fn (?ContentType $contentType): ?string => $contentType?->value)
- ->all();
- }
-
- private function resolveSelectedPlatforms(): Collection
+ private function effectiveMeta(): array
{
- $ids = collect($this->input('platforms', []))->pluck('id')->filter()->all();
-
- if (empty($ids)) {
- return collect();
- }
-
- return $this->route('post')
- ->postPlatforms()
- ->whereIn('id', $ids)
- ->with('socialAccount')
- ->get()
- ->mapWithKeys(fn (PostPlatform $postPlatform): array => [
- $postPlatform->id => $postPlatform->socialAccount ?? $postPlatform->platform,
- ]);
+ return [...($this->route('post')->meta ?? []), ...(array) $this->input('meta', [])];
}
}
diff --git a/app/Http/Resources/Api/PostMetricsResource.php b/app/Http/Resources/Api/PostMetricsResource.php
index e2fa6abd2..d72664610 100644
--- a/app/Http/Resources/Api/PostMetricsResource.php
+++ b/app/Http/Resources/Api/PostMetricsResource.php
@@ -18,9 +18,6 @@ class PostMetricsResource extends JsonResource
*/
public function toArray(Request $request): array
{
- return [
- 'post_id' => $this->id,
- 'platforms' => app(ReadPublicationAnalytics::class)->forPost($this->resource)->all(),
- ];
+ return app(ReadPublicationAnalytics::class)->forPost($this->resource);
}
}
diff --git a/app/Http/Resources/Api/PostPlatformResource.php b/app/Http/Resources/Api/PostPlatformResource.php
deleted file mode 100644
index 3995c87c6..000000000
--- a/app/Http/Resources/Api/PostPlatformResource.php
+++ /dev/null
@@ -1,35 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Http\Resources\Api;
-
-use Illuminate\Http\Request;
-use Illuminate\Http\Resources\Json\JsonResource;
-
-class PostPlatformResource extends JsonResource
-{
- /**
- * @return array<string, mixed>
- */
- public function toArray(Request $request): array
- {
- return [
- 'id' => $this->id,
- 'platform' => $this->platform?->value,
- 'content_type' => $this->content_type?->value,
- 'meta' => $this->meta,
- 'status' => $this->status?->value,
- 'enabled' => $this->enabled,
- 'platform_url' => $this->platform_url,
- 'published_at' => $this->published_at?->format('Y-m-d H:i:s'),
- 'error_message' => $this->error_message,
- // Display fields fall back to snapshots (platform_name/username/avatar)
- // so deleted accounts still render correctly in the post history.
- 'display_name' => $this->display_name,
- 'display_username' => $this->display_username,
- 'display_avatar' => $this->display_avatar,
- 'social_account' => new SocialAccountResource($this->whenLoaded('socialAccount')),
- ];
- }
-}
diff --git a/app/Http/Resources/Api/PostResource.php b/app/Http/Resources/Api/PostResource.php
index 44825305a..9bb12ca67 100644
--- a/app/Http/Resources/Api/PostResource.php
+++ b/app/Http/Resources/Api/PostResource.php
@@ -42,7 +42,16 @@ class PostResource extends JsonResource
'remaining' => $this->recurrence_remaining,
] : null,
'origin' => $this->origin->value,
- 'platforms' => PostPlatformResource::collection($this->whenLoaded('postPlatforms')),
+ 'publish_status' => $this->publish_status->value,
+ 'platform' => $this->platform?->value,
+ 'content_type' => $this->content_type?->value,
+ 'meta' => $this->meta,
+ 'platform_url' => $this->platform_url,
+ 'error_message' => $this->error_message,
+ 'display_name' => $this->display_name,
+ 'display_username' => $this->display_username,
+ 'display_avatar' => $this->display_avatar,
+ 'social_account' => new SocialAccountResource($this->whenLoaded('socialAccount')),
'labels' => LabelResource::collection($this->whenLoaded('labels')),
'created_at' => $this->created_at->format('Y-m-d H:i:s'),
'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
diff --git a/app/Http/Resources/Api/RepurposeItemResource.php b/app/Http/Resources/Api/RepurposeItemResource.php
index ec4bd3938..78929d7d8 100644
--- a/app/Http/Resources/Api/RepurposeItemResource.php
+++ b/app/Http/Resources/Api/RepurposeItemResource.php
@@ -25,14 +25,8 @@ class RepurposeItemResource extends JsonResource
'error' => $this->error,
'posts' => $this->whenLoaded('posts', fn () => $this->posts->map(fn ($post) => [
'id' => $post->id,
- 'platforms' => $post->postPlatforms
- ->where('enabled', true)
- ->map(fn ($postPlatform) => [
- 'platform' => $postPlatform->platform?->value,
- 'status' => $postPlatform->status?->value,
- ])
- ->filter(fn (array $entry): bool => $entry['platform'] !== null)
- ->values(),
+ 'platform' => $post->platform?->value,
+ 'publish_status' => $post->publish_status->value,
])->values()),
'created_at' => $this->created_at->toIso8601String(),
'updated_at' => $this->updated_at->toIso8601String(),
diff --git a/app/Http/Resources/App/HandleInertiaRequests/SidebarChannelResource.php b/app/Http/Resources/App/HandleInertiaRequests/SidebarChannelResource.php
index 1ccb4b05b..1b59e4b26 100644
--- a/app/Http/Resources/App/HandleInertiaRequests/SidebarChannelResource.php
+++ b/app/Http/Resources/App/HandleInertiaRequests/SidebarChannelResource.php
@@ -18,11 +18,9 @@ class SidebarChannelResource
public static function collection(Workspace $workspace): array
{
return $workspace->socialAccounts()
- ->withCount(['postPlatforms as scheduled_posts_count' => fn (Builder $query) => $query
- ->where('enabled', true)
- ->whereHas('post', fn (Builder $post) => $post
- ->where('workspace_id', $workspace->id)
- ->where('status', PostStatus::Scheduled))])
+ ->withCount(['posts as scheduled_posts_count' => fn (Builder $query) => $query
+ ->where('workspace_id', $workspace->id)
+ ->where('status', PostStatus::Scheduled)])
->get()
->map(fn (SocialAccount $account): array => [
'id' => $account->id,
diff --git a/app/Http/Resources/App/InstagramGridTileResource.php b/app/Http/Resources/App/InstagramGridTileResource.php
index 8dac2b01c..f653f4b50 100644
--- a/app/Http/Resources/App/InstagramGridTileResource.php
+++ b/app/Http/Resources/App/InstagramGridTileResource.php
@@ -7,13 +7,13 @@ namespace App\Http\Resources\App;
use App\Dto\MediaItem;
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
-use App\Models\PostPlatform;
+use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/**
- * @mixin PostPlatform
+ * @mixin Post
*/
class InstagramGridTileResource extends JsonResource
{
@@ -24,12 +24,12 @@ class InstagramGridTileResource extends JsonResource
*/
public function toArray(Request $request): array
{
- $visuals = $this->post->mediaItems
+ $visuals = $this->mediaItems
->filter(fn (MediaItem $item): bool => $item->isImage() || $item->isVideo())
->values();
return [
- 'id' => $this->post_id,
+ 'id' => $this->id,
'published_at' => $this->published_at,
'kind' => $this->kind($visuals),
'items' => $visuals->map(fn (MediaItem $item): array => [
diff --git a/app/Http/Resources/App/PostCardResource.php b/app/Http/Resources/App/PostCardResource.php
index aa61c9e6a..f13efe779 100644
--- a/app/Http/Resources/App/PostCardResource.php
+++ b/app/Http/Resources/App/PostCardResource.php
@@ -21,7 +21,13 @@ class PostCardResource extends JsonResource
*/
public function toArray(Request $request): array
{
- $card = $this->resource->toArray();
+ $card = [
+ ...$this->resource->toArray(),
+ 'failure' => $this->resource->error_context === null ? null : [
+ 'category' => data_get($this->resource->error_context, 'category'),
+ 'failed_at' => data_get($this->resource->error_context, 'failed_at'),
+ ],
+ ];
if ($this->resource->relationLoaded('user')) {
$card['user'] = $this->user === null ? null : [
diff --git a/app/Jobs/Analytics/BackfillTryPostPublications.php b/app/Jobs/Analytics/BackfillTryPostPublications.php
deleted file mode 100644
index f69fa2ad6..000000000
--- a/app/Jobs/Analytics/BackfillTryPostPublications.php
+++ /dev/null
@@ -1,69 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Jobs\Analytics;
-
-use App\Actions\Analytics\ResolveAnalyticsAccountKey;
-use App\Actions\Analytics\SyncTryPostPublication;
-use App\Dto\Analytics\TryPostPublicationIdentity;
-use App\Models\PostPlatform;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Queue\Queueable;
-use Illuminate\Support\Facades\Log;
-use Throwable;
-
-class BackfillTryPostPublications implements ShouldQueue
-{
- use Queueable;
-
- public int $tries = 3;
-
- /** @return list<int> */
- public function backoff(): array
- {
- return [60, 300];
- }
-
- /** @param list<string> $postPlatformIds */
- public function __construct(public array $postPlatformIds)
- {
- $this->onQueue('analytics');
- }
-
- public function handle(SyncTryPostPublication $sync, ResolveAnalyticsAccountKey $accountKeys): void
- {
- $identities = [];
-
- PostPlatform::query()
- ->published()
- ->includedInAnalytics()
- ->whereIn('id', $this->postPlatformIds)
- ->whereNotNull('social_account_id')
- ->with(['post', 'socialAccount'])
- ->get()
- ->each(function (PostPlatform $postPlatform) use ($sync, $accountKeys, &$identities): void {
- $account = $postPlatform->socialAccount;
-
- if (! $account) {
- return;
- }
-
- $identities[$account->id] ??= TryPostPublicationIdentity::fromAccount(
- $account,
- $accountKeys->for($account),
- );
-
- $sync->fromIdentity($identities[$account->id], $postPlatform, $account);
- });
- }
-
- public function failed(?Throwable $exception): void
- {
- Log::error('Analytics TryPost publication backfill failed', [
- 'first_post_platform_id' => $this->postPlatformIds[0] ?? null,
- 'post_platform_count' => count($this->postPlatformIds),
- 'exception' => $exception,
- ]);
- }
-}
diff --git a/app/Jobs/Analytics/CollectPublicationMetrics.php b/app/Jobs/Analytics/CollectPublicationMetrics.php
index f2bae2e66..981415bfe 100644
--- a/app/Jobs/Analytics/CollectPublicationMetrics.php
+++ b/app/Jobs/Analytics/CollectPublicationMetrics.php
@@ -111,7 +111,7 @@ class CollectPublicationMetrics implements ShouldQueue
$collector = $collectors->for($publication->platform);
if ($collector instanceof TikTokPublicationMetricsCollector
- && $publication->post_platform_id
+ && $publication->post_id
&& ! ctype_digit($publication->remote_id)) {
$publications->reconcileRemoteId($publication, $collector->publicVideoId($publication));
}
diff --git a/app/Jobs/Analytics/SyncTryPostPublication.php b/app/Jobs/Analytics/SyncTryPostPublication.php
index 8f619188d..0578ebbb6 100644
--- a/app/Jobs/Analytics/SyncTryPostPublication.php
+++ b/app/Jobs/Analytics/SyncTryPostPublication.php
@@ -7,7 +7,7 @@ namespace App\Jobs\Analytics;
use App\Actions\Analytics\QueuePublicationMetricsForPage;
use App\Actions\Analytics\SyncTryPostPublication as SyncTryPostPublicationAction;
use App\Dto\Analytics\TryPostPublicationIdentity;
-use App\Models\PostPlatform;
+use App\Models\Post;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
@@ -17,23 +17,22 @@ class SyncTryPostPublication implements ShouldQueue
public function __construct(
public TryPostPublicationIdentity $identity,
- public string $postPlatformId,
+ public string $postId,
) {
$this->onQueue('analytics');
}
public function handle(SyncTryPostPublicationAction $sync, QueuePublicationMetricsForPage $metrics): void
{
- $postPlatform = PostPlatform::query()
- ->published()
- ->with('post')
- ->find($this->postPlatformId);
+ $post = Post::query()
+ ->publicationPublished()
+ ->find($this->postId);
- if (! $postPlatform || ! filled($postPlatform->platform_post_id)) {
+ if (! $post || ! filled($post->platform_post_id)) {
return;
}
- $publication = $sync->fromIdentity($this->identity, $postPlatform);
+ $publication = $sync->fromIdentity($this->identity, $post);
$metrics->queue($publication);
}
}
diff --git a/app/Jobs/Post/ImportExternalPostMedia.php b/app/Jobs/Post/ImportExternalPostMedia.php
index 9ec65f192..debaac000 100644
--- a/app/Jobs/Post/ImportExternalPostMedia.php
+++ b/app/Jobs/Post/ImportExternalPostMedia.php
@@ -15,7 +15,6 @@ use App\Jobs\Media\ImportRemoteMedia;
use App\Models\AnalyticsPublication;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Media\RemoteMediaImporter;
@@ -117,7 +116,7 @@ class ImportExternalPostMedia implements ShouldBeUnique, ShouldQueue
private function platform(): ?Platform
{
- return once(fn (): ?Platform => PostPlatform::query()->where('post_id', $this->postId)->value('platform'));
+ return once(fn (): ?Platform => Post::query()->find($this->postId, ['id', 'platform'])?->platform);
}
/**
@@ -127,10 +126,9 @@ class ImportExternalPostMedia implements ShouldBeUnique, ShouldQueue
{
$post = Post::query()
->imported()
- ->with(['postPlatforms.socialAccount', 'postPlatforms.analyticsPublication'])
+ ->with(['socialAccount', 'analyticsPublication'])
->find($this->postId);
- $target = $post?->postPlatforms->first();
- $publication = $target?->analyticsPublication;
+ $publication = $post?->analyticsPublication;
if ($post === null
|| $publication === null
@@ -139,7 +137,7 @@ class ImportExternalPostMedia implements ShouldBeUnique, ShouldQueue
return [null, null, null];
}
- return [$post, $publication, $target->socialAccount];
+ return [$post, $publication, $post->socialAccount];
}
/**
diff --git a/app/Jobs/Post/SendApprovalDecisionEmail.php b/app/Jobs/Post/SendApprovalDecisionEmail.php
deleted file mode 100644
index fc2353753..000000000
--- a/app/Jobs/Post/SendApprovalDecisionEmail.php
+++ /dev/null
@@ -1,62 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Jobs\Post;
-
-use App\Enums\Notification\Type;
-use App\Enums\Post\ApprovalDecision;
-use App\Jobs\SendNotification;
-use App\Mail\PostApproved;
-use App\Mail\PostRejected;
-use App\Models\Post;
-use App\Models\User;
-use Illuminate\Contracts\Cache\LockTimeoutException;
-use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
-use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Foundation\Queue\Queueable;
-use Illuminate\Support\Facades\Cache;
-
-class SendApprovalDecisionEmail implements ShouldBeUniqueUntilProcessing, ShouldQueue
-{
- use Queueable;
-
- public int $uniqueFor = 3600;
-
- public bool $deleteWhenMissingModels = true;
-
- public function __construct(
- public string $key,
- public User $requester,
- public User $approver,
- public ApprovalDecision $decision,
- ) {}
-
- public function uniqueId(): string
- {
- return $this->key;
- }
-
- public function handle(): void
- {
- try {
- $postIds = Cache::lock("{$this->key}:lock", 10)->block(5, fn (): array => Cache::pull($this->key, []));
- } catch (LockTimeoutException) {
- $this->release(5);
-
- return;
- }
-
- if ($postIds === [] || ! Post::query()->whereIn('id', $postIds)->exists()) {
- return;
- }
-
- SendNotification::dispatch(
- $this->requester,
- Type::Collaboration,
- $this->decision === ApprovalDecision::Approved
- ? new PostApproved($postIds, $this->approver, $this->requester)
- : new PostRejected($postIds, $this->approver),
- );
- }
-}
diff --git a/app/Jobs/PostHog/SyncAccountPublishingActivity.php b/app/Jobs/PostHog/SyncAccountPublishingActivity.php
index 749a79213..ad0369a57 100644
--- a/app/Jobs/PostHog/SyncAccountPublishingActivity.php
+++ b/app/Jobs/PostHog/SyncAccountPublishingActivity.php
@@ -6,7 +6,7 @@ namespace App\Jobs\PostHog;
use App\Models\Account;
use App\Models\Post;
-use App\Models\PostPlatform;
+use App\Models\Workspace;
use App\Services\PostHogService;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -67,23 +67,19 @@ class SyncAccountPublishingActivity implements ShouldBeUniqueUntilProcessing, Sh
return;
}
- $postIds = Post::query()
- ->select('posts.id')
- ->whereRelation('workspace', 'account_id', $account->id);
-
- $latestPublication = PostPlatform::query()
- ->published()
+ $latestPublication = Post::query()
+ ->whereIn('workspace_id', Workspace::query()->select('id')->where('account_id', $account->id))
+ ->publicationPublished()
->whereNotNull('published_at')
- ->whereIn('post_id', $postIds)
->latest('published_at')
- ->latest('updated_at')
+ ->latest('publication_updated_at')
->latest('id')
->first();
$postHog->groupIdentifyNow('account', (string) $account->id, [
'last_post_published_at' => $latestPublication?->published_at?->toIso8601String(),
- 'last_post_published_network' => $latestPublication?->platform->network(),
- 'last_published_post_id' => $latestPublication?->post_id,
+ 'last_post_published_network' => $latestPublication?->platform?->network(),
+ 'last_published_post_id' => $latestPublication?->id,
]);
}
}
diff --git a/app/Jobs/PublishPost.php b/app/Jobs/PublishPost.php
index 0ac71b320..ea788f2a9 100644
--- a/app/Jobs/PublishPost.php
+++ b/app/Jobs/PublishPost.php
@@ -23,9 +23,13 @@ class PublishPost implements ShouldQueue
{
$this->post->markAsPublishing();
- foreach ($this->post->postPlatforms()->enabled()->get() as $postPlatform) {
- PublishToSocialPlatform::dispatch($postPlatform);
+ if (! $this->post->hasChannel()) {
+ app(FinalizePostPublication::class)->handle($this->post);
+
+ return;
}
+
+ PublishToSocialPlatform::dispatch($this->post);
}
public function failed(?Throwable $exception): void
diff --git a/app/Jobs/PublishToSocialPlatform.php b/app/Jobs/PublishToSocialPlatform.php
index cdeef1867..7692c9f55 100644
--- a/app/Jobs/PublishToSocialPlatform.php
+++ b/app/Jobs/PublishToSocialPlatform.php
@@ -7,15 +7,15 @@ namespace App\Jobs;
use App\Actions\Post\FinalizePostPublication;
use App\Enums\GoogleBusiness\LocalPostState;
use App\Enums\Media\Type as MediaType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
+use App\Enums\Post\PublishStatus;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
-use App\Events\PostPlatformStatusUpdated;
+use App\Events\PostStatusUpdated;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\SocialPublishException;
use App\Exceptions\TokenExpiredException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Rules\ContentTypeCompatibleWithMedia;
use App\Services\Social\BlueskyPublisher;
use App\Services\Social\ConnectionVerifier;
@@ -65,15 +65,15 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
private const int DEFAULT_RETRY_DELAY_SECONDS = 600;
public function __construct(
- public PostPlatform $postPlatform,
+ public Post $post,
public int $uniqueAttempt = 0,
) {
- $this->onQueue($postPlatform->platform->queue());
+ $this->onQueue($post->platform->queue());
}
public function uniqueId(): string
{
- return "{$this->postPlatform->id}:{$this->uniqueAttempt}";
+ return "{$this->post->id}:{$this->uniqueAttempt}";
}
/**
@@ -82,7 +82,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
public function middleware(): array
{
return [
- (new WithoutOverlapping("social-publish:{$this->postPlatform->id}"))
+ (new WithoutOverlapping("social-publish:{$this->post->id}"))
->releaseAfter(60)
->expireAfter($this->timeout + 60),
];
@@ -90,19 +90,19 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
public function handle(): void
{
- $this->postPlatform->refresh();
+ $this->post->refresh();
- if ($this->postPlatform->status->isClosed() || $this->postPlatform->isWaitingForLimitRetry()) {
+ if ($this->post->publish_status->isClosed() || $this->post->isPublicationWaitingForLimitRetry()) {
return;
}
- if ($this->postPlatform->socialAccount->status === Status::Disconnected) {
+ if ($this->post->socialAccount->status === Status::Disconnected) {
$this->failAndFinalize(__('posts.errors.account_disconnected'));
return;
}
- if ($this->postPlatform->socialAccount->status === Status::TokenExpired) {
+ if ($this->post->socialAccount->status === Status::TokenExpired) {
$this->failAndFinalize(__('posts.errors.account_token_expired'), [
'category' => ErrorCategory::TokenExpired->value,
'failed_at' => now()->toIso8601String(),
@@ -119,7 +119,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
return;
}
- $this->postPlatform->markAsPublishing();
+ $this->post->markPublicationPublishing();
$this->broadcastStatus();
$maxAttempts = 2; // Original attempt + 1 retry after token refresh
@@ -127,7 +127,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
try {
$publisher = $this->getPublisher();
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
$this->recordPublishResult($result);
break;
@@ -198,11 +198,11 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
$threadReplyIds = data_get($result, 'thread_reply_ids');
if (is_array($threadReplyIds) && $threadReplyIds !== []) {
- $this->postPlatform->thread_reply_ids = array_values($threadReplyIds);
+ $this->post->thread_reply_ids = array_values($threadReplyIds);
}
match ($state) {
- LocalPostState::Rejected => $this->postPlatform->markAsRejected(
+ LocalPostState::Rejected => $this->post->markPublicationRejected(
$platformPostId,
$platformUrl,
__('posts.errors.rejected_in_review'),
@@ -210,23 +210,23 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
),
LocalPostState::Processing,
LocalPostState::Scheduled,
- LocalPostState::Unspecified => $this->postPlatform->markAsPendingReview($platformPostId, $platformUrl),
+ LocalPostState::Unspecified => $this->post->markPublicationPendingReview($platformPostId, $platformUrl),
LocalPostState::Live,
LocalPostState::Recurring,
- null => $this->postPlatform->markAsPublished($platformPostId, $platformUrl),
+ null => $this->post->markPublicationPublished($platformPostId, $platformUrl),
};
}
private function refreshAccountToken(): void
{
- app(ConnectionVerifier::class)->verify($this->postPlatform->socialAccount);
+ app(ConnectionVerifier::class)->verify($this->post->socialAccount);
}
private function failForMissingScopes(): bool
{
$missingScopes = array_values(array_diff(
- $this->postPlatform->platform->requiredPublishScopes(),
- $this->postPlatform->socialAccount->scopes ?? [],
+ $this->post->platform->requiredPublishScopes(),
+ $this->post->socialAccount->scopes ?? [],
));
if ($missingScopes === []) {
@@ -256,9 +256,9 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
*/
private function failForInvalidMedia(): bool
{
- $context = $this->postPlatform->error_context;
+ $context = $this->post->error_context;
- if ($this->postPlatform->scheduled_before_media_checks) {
+ if ($this->post->scheduled_before_media_checks) {
return false;
}
@@ -266,15 +266,14 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
return false;
}
- $post = $this->postPlatform->post;
$errors = ContentTypeCompatibleWithMedia::errorsFor(
[[
'key' => 'media',
- 'content_type' => $this->postPlatform->content_type?->value,
+ 'content_type' => $this->post->content_type?->value,
]],
- (array) ($post->media ?? []),
- $post->workspace,
- ) ?: ThreadReplies::mediaErrors($this->postPlatform->platform, $this->postPlatform->meta, $post->workspace);
+ (array) ($this->post->media ?? []),
+ $this->post->workspace,
+ ) ?: ThreadReplies::mediaErrors($this->post->platform, $this->post->meta, $this->post->workspace);
if ($errors === []) {
return false;
@@ -290,7 +289,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
private function rescheduleForRetry(PlatformUnavailableException $e): void
{
- $previousContext = self::withSeparateRetryCounters($this->postPlatform->error_context ?? []);
+ $previousContext = self::withSeparateRetryCounters($this->post->error_context ?? []);
$hasOwnPolicy = $e->maxRetries !== null || $e->retryDelaySeconds !== null;
$counterKey = $hasOwnPolicy ? 'processing_retry_count' : 'retry_count';
$retryCount = (int) data_get($previousContext, $counterKey, 0) + 1;
@@ -323,14 +322,14 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
$nextAttemptAt = now()->addSeconds($retryDelaySeconds);
Log::warning('Publish rescheduled: platform unavailable', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
+ 'post_id' => $this->post->id,
+ 'platform' => $this->post->platform->value,
'next_attempt_at' => $nextAttemptAt->toIso8601String(),
...$context,
]);
- $this->postPlatform->update([
- 'status' => PostPlatformStatus::Retrying,
+ $this->post->writePublication([
+ 'publish_status' => PublishStatus::Retrying,
'error_message' => __('posts.errors.platform_unavailable'),
'error_context' => [
...$context,
@@ -340,7 +339,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
]);
self::dispatch(
- $this->postPlatform,
+ $this->post,
(int) data_get($context, 'retry_count', 0) + (int) data_get($context, 'processing_retry_count', 0),
)->delay($nextAttemptAt);
}
@@ -376,7 +375,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
*/
private function waitForLimitRetry(SocialPublishException $e): bool
{
- $previousContext = $this->postPlatform->error_context ?? [];
+ $previousContext = $this->post->error_context ?? [];
$retries = LimitRetryPolicy::retriesSoFar($previousContext);
$retryAt = LimitRetryPolicy::nextAttemptAt($retries, $e->retryAt);
@@ -384,9 +383,9 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
return false;
}
- match ($this->postPlatform->platform) {
- SocialPlatform::TikTok => app(TikTokPhotoDerivativeCleaner::class)->cleanup($previousContext, $this->postPlatform->id),
- SocialPlatform::GoogleBusiness => app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->postPlatform->id),
+ match ($this->post->platform) {
+ SocialPlatform::TikTok => app(TikTokPhotoDerivativeCleaner::class)->cleanup($previousContext, $this->post->id),
+ SocialPlatform::GoogleBusiness => app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->post),
default => null,
};
@@ -405,14 +404,14 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
];
Log::warning('Publish waiting for a network limit', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
+ 'post_id' => $this->post->id,
+ 'platform' => $this->post->platform->value,
'platform_error_code' => $e->platformErrorCode,
'limit_retries' => $retries + 1,
'retry_at' => $retryAt->toIso8601String(),
]);
- $this->postPlatform->markAsWaitingForLimitRetry($retryAt, $e->userMessage, $context);
+ $this->post->markPublicationWaitingForLimitRetry($retryAt, $e->userMessage, $context);
return true;
}
@@ -429,13 +428,13 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
{
Log::error('Social publish failed', [
...(method_exists($e, 'context') ? $e->context() : []),
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
- 'content_type' => $this->postPlatform->content_type?->value,
+ 'post_id' => $this->post->id,
+ 'platform' => $this->post->platform->value,
+ 'content_type' => $this->post->content_type?->value,
'exception' => $e::class,
'message' => $e->getMessage(),
...$context,
- 'media' => $this->mediaSnapshot($this->postPlatform),
+ 'media' => $this->mediaSnapshot(),
]);
if ($e instanceof TokenExpiredException || ($e instanceof SocialPublishException && $e->isNetworkRejection())) {
@@ -452,9 +451,9 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
*
* @return list<array{url: ?string, mime_type: ?string, size: ?int, type: ?string}>
*/
- private function mediaSnapshot(PostPlatform $postPlatform): array
+ private function mediaSnapshot(): array
{
- $media = $postPlatform->post?->media;
+ $media = $this->post->media;
if (! is_array($media)) {
return [];
@@ -486,7 +485,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
'platform_error_code' => $e->platformErrorCode,
'failed_at' => now()->toIso8601String(),
]);
- $this->postPlatform->socialAccount->markAsTokenExpired($e->getMessage());
+ $this->post->socialAccount->markAsTokenExpired($e->getMessage());
}
/**
@@ -494,21 +493,21 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
*/
private function markPlatformAsFailed(string $message, ?array $context = null): void
{
- $previousContext = $this->postPlatform->error_context ?? [];
+ $previousContext = $this->post->error_context ?? [];
- match ($this->postPlatform->platform) {
+ match ($this->post->platform) {
SocialPlatform::TikTok => app(TikTokPhotoDerivativeCleaner::class)->cleanupUnlessPublishInFlight(
$previousContext,
- $this->postPlatform->id,
+ $this->post->id,
),
- SocialPlatform::GoogleBusiness => app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->postPlatform->id),
+ SocialPlatform::GoogleBusiness => app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->post),
default => null,
};
$failureContext = [...$previousContext, ...($context ?? [])];
- $this->postPlatform->markAsFailed(
- ThreadProgress::failureMessage($this->postPlatform, $message, $failureContext),
+ $this->post->markPublicationFailed(
+ ThreadProgress::failureMessage($this->post, $message, $failureContext),
$failureContext === [] ? null : $failureContext,
);
}
@@ -522,8 +521,8 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
return [
...$extra,
'failed_at' => now()->toIso8601String(),
- 'content_length' => mb_strlen($this->postPlatform->post->content ?? ''),
- 'media_count' => count($this->postPlatform->post->media ?? []),
+ 'content_length' => mb_strlen($this->post->content ?? ''),
+ 'media_count' => count($this->post->media ?? []),
];
}
@@ -539,7 +538,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
private function broadcastStatus(): void
{
- PostPlatformStatusUpdated::dispatch($this->postPlatform->fresh());
+ PostStatusUpdated::dispatch($this->post->fresh());
}
/**
@@ -555,7 +554,7 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
private function getPublisher(): LinkedInPublisher|LinkedInPagePublisher|XPublisher|TikTokPublisher|YouTubePublisher|FacebookPublisher|InstagramPublisher|ThreadsPublisher|PinterestPublisher|BlueskyPublisher|MastodonPublisher|TelegramPublisher|DiscordPublisher|GoogleBusinessPublisher
{
- return match ($this->postPlatform->platform) {
+ return match ($this->post->platform) {
SocialPlatform::LinkedIn => app(LinkedInPublisher::class),
SocialPlatform::LinkedInPage => app(LinkedInPagePublisher::class),
SocialPlatform::X => app(XPublisher::class),
@@ -575,20 +574,20 @@ class PublishToSocialPlatform implements ShouldBeUnique, ShouldQueue
private function updatePostStatus(): void
{
- app(FinalizePostPublication::class)->handle($this->postPlatform->post);
+ app(FinalizePostPublication::class)->handle($this->post);
}
public function failed(?Throwable $exception): void
{
Log::error('PublishToSocialPlatform job failed permanently', [
- 'post_platform_id' => $this->postPlatform->id,
- 'platform' => $this->postPlatform->platform->value,
+ 'post_id' => $this->post->id,
+ 'platform' => $this->post->platform->value,
'error' => $exception?->getMessage(),
]);
- $this->postPlatform->refresh();
+ $this->post->refresh();
- if ($this->postPlatform->status->isClosed() || $this->postPlatform->isWaitingForLimitRetry()) {
+ if ($this->post->publish_status->isClosed() || $this->post->isPublicationWaitingForLimitRetry()) {
return;
}
diff --git a/app/Jobs/ReconcileGoogleBusinessPost.php b/app/Jobs/ReconcileGoogleBusinessPost.php
index 6a57db1ac..ef7a863f4 100644
--- a/app/Jobs/ReconcileGoogleBusinessPost.php
+++ b/app/Jobs/ReconcileGoogleBusinessPost.php
@@ -6,13 +6,13 @@ namespace App\Jobs;
use App\Actions\Post\FinalizePostPublication;
use App\Enums\GoogleBusiness\LocalPostState;
-use App\Enums\PostPlatform\Status;
-use App\Events\PostPlatformStatusUpdated;
+use App\Enums\Post\PublishStatus as Status;
+use App\Events\PostStatusUpdated;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\GoogleBusinessPublishException;
use App\Exceptions\TokenExpiredException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\ConnectionVerifier;
use App\Services\Social\GoogleBusinessPublisher;
@@ -47,25 +47,25 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
*/
public const REVIEW_CEILING_HOURS = 24;
- public function __construct(public PostPlatform $postPlatform)
+ public function __construct(public Post $post)
{
- $this->onQueue($postPlatform->platform->queue());
+ $this->onQueue($post->platform->queue());
}
public function uniqueId(): string
{
- return $this->postPlatform->id;
+ return $this->post->id;
}
public function handle(): void
{
- $this->postPlatform->refresh();
+ $this->post->refresh();
- if ($this->postPlatform->status !== Status::PendingReview || blank($this->postPlatform->platform_post_id)) {
+ if ($this->post->publish_status !== Status::PendingReview || blank($this->post->platform_post_id)) {
return;
}
- $account = $this->postPlatform->socialAccount;
+ $account = $this->post->socialAccount;
if (! $account instanceof SocialAccount) {
$this->giveUp(__('posts.errors.account_disconnected'), [
@@ -94,26 +94,26 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
}
$state = LocalPostState::fromApi(data_get($remote, 'state'));
- $platformUrl = (string) (data_get($remote, 'searchUrl') ?: $this->postPlatform->platform_url);
+ $platformUrl = (string) (data_get($remote, 'searchUrl') ?: $this->post->platform_url);
if ($state->isLive()) {
- $this->postPlatform->markAsPublished((string) $this->postPlatform->platform_post_id, $platformUrl);
+ $this->post->markPublicationPublished((string) $this->post->platform_post_id, $platformUrl);
} elseif ($state->isRejected()) {
- $this->postPlatform->markAsRejected(
- (string) $this->postPlatform->platform_post_id,
+ $this->post->markPublicationRejected(
+ (string) $this->post->platform_post_id,
$platformUrl,
__('posts.errors.rejected_in_review'),
['provider_state' => $state->value],
);
} elseif ($this->reviewExpired()) {
- $this->postPlatform->markAsRejected(
- (string) $this->postPlatform->platform_post_id,
+ $this->post->markPublicationRejected(
+ (string) $this->post->platform_post_id,
$platformUrl,
__('posts.errors.review_unconfirmed'),
['category' => 'review_unconfirmed', 'provider_state' => $state->value],
);
} else {
- $this->postPlatform->update([
+ $this->post->writePublication([
'platform_url' => $platformUrl,
'last_reconciled_at' => now(),
]);
@@ -121,15 +121,15 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
return;
}
- $this->postPlatform->update(['last_reconciled_at' => now()]);
+ $this->post->writePublication(['last_reconciled_at' => now()]);
$this->settle();
}
public function failed(?Throwable $exception): void
{
- $this->postPlatform->refresh();
+ $this->post->refresh();
- if ($this->postPlatform->status !== Status::PendingReview) {
+ if ($this->post->publish_status !== Status::PendingReview) {
return;
}
@@ -151,7 +151,7 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
return app(GoogleBusinessPublisher::class)->fetchLocalPost(
$account,
- (string) $this->postPlatform->platform_post_id,
+ (string) $this->post->platform_post_id,
);
}
@@ -223,7 +223,7 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
return;
}
- $this->postPlatform->update(['last_reconciled_at' => now()]);
+ $this->post->writePublication(['last_reconciled_at' => now()]);
}
/**
@@ -231,19 +231,19 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
*/
private function giveUp(string $errorMessage, array $errorContext = []): void
{
- $this->postPlatform->markAsRejected(
- (string) $this->postPlatform->platform_post_id,
- $this->postPlatform->platform_url,
+ $this->post->markPublicationRejected(
+ (string) $this->post->platform_post_id,
+ $this->post->platform_url,
$errorMessage,
$errorContext,
);
- $this->postPlatform->update(['last_reconciled_at' => now()]);
+ $this->post->writePublication(['last_reconciled_at' => now()]);
$this->settle();
}
private function reviewExpired(): bool
{
- $submittedAt = $this->postPlatform->submitted_at;
+ $submittedAt = $this->post->submitted_at;
return $submittedAt instanceof CarbonInterface
&& $submittedAt->copy()->addHours(self::REVIEW_CEILING_HOURS)->isPast();
@@ -251,8 +251,8 @@ class ReconcileGoogleBusinessPost implements ShouldBeUnique, ShouldQueue
private function settle(): void
{
- app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->postPlatform->id);
- app(FinalizePostPublication::class)->handle($this->postPlatform->post);
- PostPlatformStatusUpdated::dispatch($this->postPlatform->fresh());
+ app(GoogleBusinessDerivativeCleaner::class)->cleanup($this->post);
+ app(FinalizePostPublication::class)->handle($this->post);
+ PostStatusUpdated::dispatch($this->post->fresh());
}
}
diff --git a/app/Jobs/Repurpose/PollRepurposeSource.php b/app/Jobs/Repurpose/PollRepurposeSource.php
index a18239291..7f452da4c 100644
--- a/app/Jobs/Repurpose/PollRepurposeSource.php
+++ b/app/Jobs/Repurpose/PollRepurposeSource.php
@@ -10,7 +10,7 @@ use App\Enums\Repurpose\ItemStatus;
use App\Enums\Repurpose\SourceFormat;
use App\Enums\Repurpose\Status;
use App\Exceptions\Repurpose\SourceFetchException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -20,7 +20,6 @@ use Carbon\CarbonInterface;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
-use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
@@ -223,11 +222,10 @@ class PollRepurposeSource implements ShouldBeUnique, ShouldQueue
return [];
}
- return PostPlatform::query()
+ return Post::query()
->whereIn('platform_post_id', $ids)
- ->whereHas('post', fn (Builder $query) => $query
- ->createdInTryPost()
- ->where('workspace_id', $this->account->workspace_id))
+ ->createdInTryPost()
+ ->where('workspace_id', $this->account->workspace_id)
->pluck('platform_post_id')
->all();
}
diff --git a/app/Jobs/SendNotification.php b/app/Jobs/SendNotification.php
index 7174ab88e..0b912d642 100644
--- a/app/Jobs/SendNotification.php
+++ b/app/Jobs/SendNotification.php
@@ -7,6 +7,8 @@ namespace App\Jobs;
use App\Enums\Notification\Channel;
use App\Enums\Notification\Type;
use App\Mail\PostApprovalRequested;
+use App\Mail\PostApproved;
+use App\Mail\PostRejected;
use App\Models\Post;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
@@ -36,7 +38,7 @@ class SendNotification implements ShouldQueue
public function handle(): void
{
- if (! $this->deliversEmail || ! $this->user->wantsEmailFor($this->type) || ! $this->keepsPendingApprovalPosts()) {
+ if (! $this->deliversEmail || ! $this->user->wantsEmailFor($this->type) || ! $this->stillAboutItsPost()) {
return;
}
@@ -59,19 +61,16 @@ class SendNotification implements ShouldQueue
}
/**
- * An approval request lists only its posts still waiting for approval, and
- * is not sent once every one was approved, rejected or deleted.
+ * An approval request is not sent once its post was approved, rejected or
+ * deleted, and a decision is not sent once its post was deleted.
*/
- private function keepsPendingApprovalPosts(): bool
+ private function stillAboutItsPost(): bool
{
- if (! $this->mailable instanceof PostApprovalRequested) {
- return true;
- }
-
- $pendingIds = Post::query()->whereIn('id', $this->mailable->postIds)->pendingApproval()->pluck('id')->all();
- $this->mailable->postIds = array_values(array_intersect($this->mailable->postIds, $pendingIds));
-
- return $this->mailable->postIds !== [];
+ return match (true) {
+ $this->mailable instanceof PostApprovalRequested => Post::query()->whereKey($this->mailable->postId)->pendingApproval()->exists(),
+ $this->mailable instanceof PostApproved, $this->mailable instanceof PostRejected => Post::query()->whereKey($this->mailable->postId)->exists(),
+ default => true,
+ };
}
public function failed(Throwable $exception): void
diff --git a/app/Jobs/VerifyUpcomingPostConnections.php b/app/Jobs/VerifyUpcomingPostConnections.php
index c64f53e68..4318a3352 100644
--- a/app/Jobs/VerifyUpcomingPostConnections.php
+++ b/app/Jobs/VerifyUpcomingPostConnections.php
@@ -5,12 +5,12 @@ declare(strict_types=1);
namespace App\Jobs;
use App\Enums\Notification\Type;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
+use App\Enums\Post\PublishStatus;
use App\Enums\SocialAccount\Status as SocialAccountStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\TokenExpiredException;
use App\Mail\PostAtRisk;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -76,15 +76,15 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
return;
}
- $postPlatforms = $this->atRiskPostPlatforms();
+ $posts = $this->atRiskPosts();
- if ($postPlatforms->isEmpty()) {
+ if ($posts->isEmpty()) {
return;
}
$atRisk = new Collection;
- foreach ($postPlatforms->groupBy('social_account_id') as $group) {
+ foreach ($posts->groupBy('social_account_id') as $group) {
$account = $group->first()->socialAccount;
if (! $account) {
@@ -94,15 +94,6 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
continue;
}
- $group = $group->filter(fn (PostPlatform $pp) => $pp->post !== null);
-
- if ($group->isEmpty()) {
- // Same race as above, but for the post: every row in this
- // batch was hard-deleted between the main query and its
- // eager-loaded relation resolving.
- continue;
- }
-
$account = SocialAccount::query()->with('workspace')->find($account->id);
if (! $account) {
@@ -116,7 +107,7 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
// Already known broken from an earlier run — don't re-verify,
// just warn about the posts that entered the window since then.
- $atRisk->push(['account' => $account, 'postPlatforms' => $group]);
+ $atRisk->push(['account' => $account, 'posts' => $group]);
continue;
}
@@ -127,7 +118,7 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
continue;
}
- $nearestScheduledAt = $group->min(fn (PostPlatform $pp) => $pp->post->scheduled_at);
+ $nearestScheduledAt = $group->min(fn (Post $post) => $post->scheduled_at);
if ($nearestScheduledAt->isAfter(now()->addMinutes(self::VERIFY_LEAD_MINUTES))) {
// Not close enough to publishing yet — defer the actual API
@@ -192,7 +183,7 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
continue;
}
- $atRisk->push(['account' => $account, 'postPlatforms' => $group]);
+ $atRisk->push(['account' => $account, 'posts' => $group]);
} catch (Exception $e) {
Log::error('Failed to verify social account connection for upcoming-post check', [
'account_id' => $account->id,
@@ -217,7 +208,7 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
return;
}
- // Conditioned on the same "unwarned" window atRiskPostPlatforms() selected
+ // Conditioned on the same "unwarned" window atRiskPosts() selected
// on, so a concurrent run that already claimed some or all of these
// exact rows (the ShouldBeUnique lock's TTL matches the schedule
// cadence, so two instances can briefly overlap if a run takes
@@ -225,9 +216,9 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
// the gap between reading which rows are still claimable and
// stamping them — without it, two overlapping runs could both read
// "unclaimed" for the same row before either writes.
- $warnedIds = $atRisk->flatMap(fn (array $group) => $group['postPlatforms']->pluck('id'));
+ $warnedIds = $atRisk->flatMap(fn (array $group) => $group['posts']->pluck('id'));
$claimedIds = DB::transaction(function () use ($warnedIds) {
- $claimableIds = PostPlatform::whereIn('id', $warnedIds)
+ $claimableIds = Post::whereIn('id', $warnedIds)
->where(function ($query) {
$query->whereNull('connection_warning_sent_at')
->orWhere('connection_warning_sent_at', '<', now()->subDay());
@@ -244,7 +235,7 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
return $claimableIds;
}
- PostPlatform::whereIn('id', $claimableIds)->update(['connection_warning_sent_at' => now()]);
+ Post::whereIn('id', $claimableIds)->toBase()->update(['connection_warning_sent_at' => now()]);
return $claimableIds;
}, attempts: 3);
@@ -255,24 +246,24 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
// (Pre-existing trade-off, not introduced by this transaction: a
// crash between the DB transaction above and notifyOwner() below
- // loses the warning for 24h, until atRiskPostPlatforms()'s re-check window.)
+ // loses the warning for 24h, until atRiskPosts()'s re-check window.)
// A concurrent run may have already claimed some (not all) of these
// rows between when $atRisk was built and the claim above — narrow
// the notification down to what THIS run actually claimed, so the
// email never lists an account/post pair another run is already
// notifying about. $claimedIds is a non-empty subset of $warnedIds,
- // which is exactly the union of every group's post_platform ids, so
+ // which is exactly the union of every group's post ids, so
// at least one group is guaranteed to survive this filter.
$atRisk = $atRisk
->map(function (array $group) use ($claimedIds) {
- $group['postPlatforms'] = $group['postPlatforms']->filter(
- fn (PostPlatform $pp) => $claimedIds->containsStrict($pp->id)
+ $group['posts'] = $group['posts']->filter(
+ fn (Post $post) => $claimedIds->containsStrict($post->id)
);
return $group;
})
- ->filter(fn (array $group) => $group['postPlatforms']->isNotEmpty());
+ ->filter(fn (array $group) => $group['posts']->isNotEmpty());
$this->notifyOwner($owner, $workspace, $atRisk);
}
@@ -280,11 +271,11 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
/**
* Whether we've already sent a PostAtRisk notification covering this
* account within the cooldown window — checked against any of its
- * post_platforms, not just the ones in the current batch.
+ * posts, not just the ones in the current batch.
*/
private function recentlyWarnedAbout(SocialAccount $account): bool
{
- return PostPlatform::query()
+ return Post::query()
->where('social_account_id', $account->id)
->where('connection_warning_sent_at', '>=', now()->subMinutes(self::RENOTIFY_COOLDOWN_MINUTES))
->exists();
@@ -301,45 +292,40 @@ class VerifyUpcomingPostConnections implements ShouldBeUnique, ShouldQueue
}
/**
- * @return Collection<int, PostPlatform>
+ * @return Collection<int, Post>
*/
- private function atRiskPostPlatforms(): Collection
+ private function atRiskPosts(): Collection
{
- return PostPlatform::query()
- ->where('status', PostPlatformStatus::Pending)
- ->enabled() // PublishPost only iterates enabled platforms — an at-risk warning for a disabled one would be a false positive.
+ return Post::query()
+ ->where('workspace_id', $this->workspaceId)
+ ->scheduled()
+ ->whereBetween('scheduled_at', [now(), now()->addHour()])
+ ->where('publish_status', PublishStatus::Pending)
->whereHas('socialAccount')
->where(function ($query) {
$query->whereNull('connection_warning_sent_at')
->orWhere('connection_warning_sent_at', '<', now()->subDay());
})
- ->whereHas('post', function ($query) {
- $query->where('workspace_id', $this->workspaceId)
- ->scheduled()
- ->whereBetween('scheduled_at', [now(), now()->addHour()]);
- })
// socialAccount.workspace is eager-loaded even though this job
// never reads it directly — SocialAccountObserver::syncUsage()
// (fired by the ->update() calls below via markAsTokenExpired())
// reads $account->workspace. Without this eager load every
// account in the batch triggers its own extra query there.
- ->with(['socialAccount.workspace', 'post'])
+ ->with(['socialAccount.workspace'])
->get();
}
/**
- * @param Collection<int, array{account: SocialAccount, postPlatforms: Collection<int, PostPlatform>}> $atRisk
+ * @param Collection<int, array{account: SocialAccount, posts: Collection<int, Post>}> $atRisk
*/
private function notifyOwner(User $owner, Workspace $workspace, Collection $atRisk): void
{
- $postPlatforms = $atRisk->flatMap(fn (array $group) => $group['postPlatforms']);
- $postCount = $postPlatforms->pluck('post_id')->unique()->count();
- $postPlatformIds = $postPlatforms->pluck('id')->all();
+ $postIds = $atRisk->flatMap(fn (array $group) => $group['posts'])->pluck('id')->unique()->values()->all();
SendNotification::dispatch(
user: $owner,
type: Type::PostAtRisk,
- mailable: new PostAtRisk($workspace, $postPlatformIds, $postCount, $owner),
+ mailable: new PostAtRisk($workspace, $postIds, count($postIds), $owner),
);
}
}
diff --git a/app/Mail/PostApprovalRequested.php b/app/Mail/PostApprovalRequested.php
index 72a8d20f6..79b959eaf 100644
--- a/app/Mail/PostApprovalRequested.php
+++ b/app/Mail/PostApprovalRequested.php
@@ -6,7 +6,7 @@ namespace App\Mail;
use App\Enums\Post\ScheduleMode;
use App\Models\User;
-use App\Support\Mail\ApprovalEmailPosts;
+use App\Support\Mail\ApprovalEmailPost;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -18,11 +18,8 @@ class PostApprovalRequested extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
- /**
- * @param list<string> $postIds
- */
public function __construct(
- public array $postIds,
+ public string $postId,
public User $requester,
public User $recipient,
) {}
@@ -36,9 +33,8 @@ class PostApprovalRequested extends Mailable implements ShouldQueue
public function content(): Content
{
- $posts = ApprovalEmailPosts::load($this->postIds);
- $first = $posts->first();
- $workspaceName = (string) $first?->workspace?->name;
+ $post = ApprovalEmailPost::find($this->postId);
+ $workspaceName = (string) $post?->workspace?->name;
return new Content(
view: 'mail.post-approval-requested',
@@ -48,10 +44,10 @@ class PostApprovalRequested extends Mailable implements ShouldQueue
'requesterName' => $this->requester->name,
'requesterEmail' => $this->requester->email,
'workspaceName' => $workspaceName,
- 'postExcerpt' => ApprovalEmailPosts::excerpt($first),
- 'channels' => ApprovalEmailPosts::channels($posts),
- 'queued' => $first?->schedule_mode === ScheduleMode::Queue && $first->scheduled_at === null,
- 'requestedTime' => ApprovalEmailPosts::time($first?->scheduled_at, $this->recipient),
+ 'postExcerpt' => ApprovalEmailPost::excerpt($post),
+ 'channel' => ApprovalEmailPost::channel($post),
+ 'queued' => $post?->schedule_mode === ScheduleMode::Queue && blank($post->scheduled_at),
+ 'requestedTime' => ApprovalEmailPost::time($post?->scheduled_at, $this->recipient),
'url' => route('app.posts.index', ['tab' => 'approvals']),
],
);
diff --git a/app/Mail/PostApproved.php b/app/Mail/PostApproved.php
index 692cfd00e..ff43b6ddc 100644
--- a/app/Mail/PostApproved.php
+++ b/app/Mail/PostApproved.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Mail;
use App\Models\User;
-use App\Support\Mail\ApprovalEmailPosts;
+use App\Support\Mail\ApprovalEmailPost;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -17,11 +17,8 @@ class PostApproved extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
- /**
- * @param list<string> $postIds
- */
public function __construct(
- public array $postIds,
+ public string $postId,
public User $approver,
public User $recipient,
) {}
@@ -35,9 +32,8 @@ class PostApproved extends Mailable implements ShouldQueue
public function content(): Content
{
- $posts = ApprovalEmailPosts::load($this->postIds);
- $workspaceName = (string) $posts->first()?->workspace?->name;
- $goesOut = ApprovalEmailPosts::goesOut($posts, $this->recipient);
+ $post = ApprovalEmailPost::find($this->postId);
+ $workspaceName = (string) $post?->workspace?->name;
return new Content(
view: 'mail.post-approved',
@@ -46,9 +42,8 @@ class PostApproved extends Mailable implements ShouldQueue
'previewText' => __('mail.post_approved.preview', ['name' => $this->approver->name, 'workspace' => $workspaceName]),
'approverName' => $this->approver->name,
'workspaceName' => $workspaceName,
- 'channels' => ApprovalEmailPosts::channels($posts),
- 'goesOutAt' => data_get($goesOut, 'at'),
- 'goesOutPerChannel' => data_get($goesOut, 'perChannel'),
+ 'channel' => ApprovalEmailPost::channel($post),
+ 'goesOutAt' => ApprovalEmailPost::goesOutAt($post, $this->recipient),
'url' => route('app.posts.index', ['tab' => 'queue']),
],
);
diff --git a/app/Mail/PostAtRisk.php b/app/Mail/PostAtRisk.php
index a6e8dc852..c9dde06a1 100644
--- a/app/Mail/PostAtRisk.php
+++ b/app/Mail/PostAtRisk.php
@@ -4,7 +4,7 @@ declare(strict_types=1);
namespace App\Mail;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use App\Support\Mail\RecipientTime;
@@ -30,7 +30,7 @@ class PostAtRisk extends Mailable implements ShouldQueue
/**
* Only the workspace and the recipient (real Eloquent models, reduced to
- * lightweight identifiers by SerializesModels), the post_platform IDs, and the count
+ * lightweight identifiers by SerializesModels), the post IDs, and the count
* observed at dispatch time are carried on the queue payload. The rows
* themselves are rehydrated in atRiskGroups() so the queued job's
* serialized size stays small and the account/post details reflect
@@ -41,11 +41,11 @@ class PostAtRisk extends Mailable implements ShouldQueue
* between dispatch and send, the subject may differ from the number of
* rows actually listed in the body — an acceptable rare edge case.
*
- * @param array<int, string> $postPlatformIds
+ * @param array<int, string> $postIds
*/
public function __construct(
public Workspace $workspace,
- public array $postPlatformIds,
+ public array $postIds,
public int $count,
?User $recipient = null,
) {
@@ -81,7 +81,7 @@ class PostAtRisk extends Mailable implements ShouldQueue
}
/**
- * @return Collection<int, array{account: mixed, postPlatforms: Collection<int, PostPlatform>, postCount: int, times: string}>
+ * @return Collection<int, array{account: mixed, posts: Collection<int, Post>, postCount: int, times: string}>
*/
private function atRiskGroups(): Collection
{
@@ -89,12 +89,12 @@ class PostAtRisk extends Mailable implements ShouldQueue
return $this->atRiskGroups;
}
- $postPlatforms = PostPlatform::query()
- ->with(['socialAccount', 'post'])
- ->whereIn('id', $this->postPlatformIds)
+ $posts = Post::query()
+ ->with('socialAccount')
+ ->whereIn('id', $this->postIds)
->get();
- return $this->atRiskGroups = $postPlatforms->groupBy('social_account_id')
+ return $this->atRiskGroups = $posts->groupBy('social_account_id')
// The account can be null if it was hard-deleted between dispatch
// and send — nothing meaningful to render for it (no platform, no
// handle), so it's dropped rather than crashing the render.
@@ -102,10 +102,10 @@ class PostAtRisk extends Mailable implements ShouldQueue
->map(function (Collection $group) {
return [
'account' => $group->first()->socialAccount,
- 'postPlatforms' => $group,
+ 'posts' => $group,
'postCount' => $group->count(),
- 'times' => $group->sortBy(fn ($pp) => $pp->post->scheduled_at)
- ->map(fn ($pp) => RecipientTime::clock($pp->post->scheduled_at, $this->recipient()))
+ 'times' => $group->sortBy(fn (Post $post) => $post->scheduled_at)
+ ->map(fn (Post $post) => RecipientTime::clock($post->scheduled_at, $this->recipient()))
->implode(', '),
];
})->values();
diff --git a/app/Mail/PostNoteAdded.php b/app/Mail/PostNoteAdded.php
index 3edb2abd6..718bd7140 100644
--- a/app/Mail/PostNoteAdded.php
+++ b/app/Mail/PostNoteAdded.php
@@ -44,11 +44,7 @@ class PostNoteAdded extends Mailable implements ShouldQueue
'workspaceName' => $post->workspace->name,
'noteBody' => (string) $this->note->body,
'postExcerpt' => PostExcerpt::from($post->content, 200),
- 'channels' => $post->postPlatforms()
- ->with('socialAccount')
- ->enabled()
- ->get()
- ->all(),
+ 'channel' => $post->loadMissing('socialAccount')->hasDestination() ? $post : null,
'url' => route('app.posts.edit', ['post' => $post, 'comment' => $this->note->id]),
],
);
diff --git a/app/Mail/PostPublishFailed.php b/app/Mail/PostPublishFailed.php
index a8bb79006..4f9160cdf 100644
--- a/app/Mail/PostPublishFailed.php
+++ b/app/Mail/PostPublishFailed.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
namespace App\Mail;
-use App\Enums\PostPlatform\Status;
use App\Models\Post;
use App\Support\Mail\PostPreview;
use Illuminate\Bus\Queueable;
@@ -31,11 +30,7 @@ class PostPublishFailed extends Mailable implements ShouldQueue
public function content(): Content
{
- $postPlatform = $this->post->postPlatforms()
- ->with('socialAccount')
- ->enabled()
- ->where('status', Status::Failed)
- ->first();
+ $this->post->loadMissing('socialAccount');
return new Content(
view: 'mail.post-publish-failed',
@@ -43,11 +38,11 @@ class PostPublishFailed extends Mailable implements ShouldQueue
'title' => __('mail.post_publish_failed.title'),
'previewText' => __('mail.post_publish_failed.preview'),
'workspaceName' => $this->post->workspace->name,
- 'publication' => $postPlatform ? [
- 'accountName' => $postPlatform->display_name,
- 'platform' => $postPlatform->platform,
- 'error' => $postPlatform->error_message,
- ] : null,
+ 'publication' => [
+ 'accountName' => $this->post->display_name,
+ 'platform' => $this->post->platform,
+ 'error' => $this->post->error_message,
+ ],
'postPreview' => PostPreview::from($this->post),
'url' => route('app.posts.index', ['tab' => 'sent', 'post' => $this->post->id]),
],
diff --git a/app/Mail/PostPublished.php b/app/Mail/PostPublished.php
index 04d43c862..2389f5d54 100644
--- a/app/Mail/PostPublished.php
+++ b/app/Mail/PostPublished.php
@@ -30,11 +30,7 @@ class PostPublished extends Mailable implements ShouldQueue
public function content(): Content
{
- $postPlatform = $this->post->postPlatforms()
- ->with('socialAccount')
- ->enabled()
- ->published()
- ->first();
+ $this->post->loadMissing('socialAccount');
return new Content(
view: 'mail.post-published',
@@ -42,12 +38,12 @@ class PostPublished extends Mailable implements ShouldQueue
'title' => __('mail.post_published.title'),
'previewText' => __('mail.post_published.preview'),
'workspaceName' => $this->post->workspace->name,
- 'publication' => $postPlatform ? [
- 'accountName' => $postPlatform->display_name,
- 'platform' => $postPlatform->platform,
- ] : null,
+ 'publication' => [
+ 'accountName' => $this->post->display_name,
+ 'platform' => $this->post->platform,
+ ],
'postPreview' => PostPreview::from($this->post),
- 'publishedUrl' => $postPlatform?->platform_url,
+ 'publishedUrl' => $this->post->platform_url,
'url' => route('app.posts.edit', $this->post),
],
);
diff --git a/app/Mail/PostRejected.php b/app/Mail/PostRejected.php
index 374224cc6..7fca9c403 100644
--- a/app/Mail/PostRejected.php
+++ b/app/Mail/PostRejected.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Mail;
use App\Models\User;
-use App\Support\Mail\ApprovalEmailPosts;
+use App\Support\Mail\ApprovalEmailPost;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
@@ -17,11 +17,8 @@ class PostRejected extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
- /**
- * @param list<string> $postIds
- */
public function __construct(
- public array $postIds,
+ public string $postId,
public User $approver,
) {}
@@ -34,8 +31,8 @@ class PostRejected extends Mailable implements ShouldQueue
public function content(): Content
{
- $posts = ApprovalEmailPosts::load($this->postIds);
- $workspaceName = (string) $posts->first()?->workspace?->name;
+ $post = ApprovalEmailPost::find($this->postId);
+ $workspaceName = (string) $post?->workspace?->name;
return new Content(
view: 'mail.post-rejected',
@@ -44,7 +41,7 @@ class PostRejected extends Mailable implements ShouldQueue
'previewText' => __('mail.post_rejected.preview', ['name' => $this->approver->name]),
'approverName' => $this->approver->name,
'workspaceName' => $workspaceName,
- 'channels' => ApprovalEmailPosts::channels($posts),
+ 'channel' => ApprovalEmailPost::channel($post),
'url' => route('app.posts.index', ['tab' => 'drafts']),
],
);
diff --git a/app/Mcp/Tools/Post/ApprovePostTool.php b/app/Mcp/Tools/Post/ApprovePostTool.php
index 67b1b55e4..9d01730b2 100644
--- a/app/Mcp/Tools/Post/ApprovePostTool.php
+++ b/app/Mcp/Tools/Post/ApprovePostTool.php
@@ -53,7 +53,7 @@ class ApprovePostTool extends Tool
/** @var Post $approved */
$approved = data_get($result, 'post');
- $approved->load(['postPlatforms.socialAccount', 'labels']);
+ $approved->load(['socialAccount', 'labels']);
return Response::structured((new PostResource($approved))->resolve());
}
diff --git a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php
index a1107d100..30a365b99 100644
--- a/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php
+++ b/app/Mcp/Tools/Post/AttachMediaFromUploadTool.php
@@ -19,7 +19,7 @@ use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
-#[Description('Attach a file uploaded with request-media-upload-tool to a post. The upload_token is the value request-media-upload-tool returned; the file is resolved by that token within the current workspace, then appended after the post media (to reorder or remove media, call update-post-tool with the media ids in the new order). The file type must be one the post channel accepts (allowed_media_types in list-content-types-tool). Posts that are publishing, published, partially_published or failed cannot change; a scheduled post edited by a member who needs approval goes back to pending_approval. Size, video duration, GIF and MOV caps per content_type (see list-content-types-tool) are checked when the post is scheduled or published, not here. Media is added to the post itself; to give a thread reply its own media, pass the upload_token in meta.thread_replies with update-post-tool.')]
+#[Description('Attach a file uploaded with request-media-upload-tool to a post. The upload_token is the value request-media-upload-tool returned; the file is resolved by that token within the current workspace, then appended after the post media (to reorder or remove media, call update-post-tool with the media ids in the new order). The file type must be one the post channel accepts (allowed_media_types in list-content-types-tool). Posts that are publishing, published or failed cannot change; a scheduled post edited by a member who needs approval goes back to pending_approval. Size, video duration, GIF and MOV caps per content_type (see list-content-types-tool) are checked when the post is scheduled or published, not here. Media is added to the post itself; to give a thread reply its own media, pass the upload_token in meta.thread_replies with update-post-tool.')]
class AttachMediaFromUploadTool extends Tool
{
use AuthorizesMcpTool;
@@ -59,7 +59,7 @@ class AttachMediaFromUploadTool extends Tool
return Response::error(__('posts.errors.queue_busy'));
}
- $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
+ $post->refresh()->load(['socialAccount', 'labels']);
return Response::structured([
'post' => (new PostResource($post))->resolve(),
diff --git a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php
index 7ffbf5078..ca8a606eb 100644
--- a/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php
+++ b/app/Mcp/Tools/Post/AttachMediaFromUrlTool.php
@@ -47,7 +47,7 @@ class AttachMediaFromUrlTool extends Tool
return Response::error(__('posts.errors.queue_busy'));
}
- $post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
+ $post->refresh()->load(['socialAccount', 'labels']);
return Response::structured([
'post' => (new PostResource($post))->resolve(),
diff --git a/app/Mcp/Tools/Post/ClearPostRecurrenceTool.php b/app/Mcp/Tools/Post/ClearPostRecurrenceTool.php
index 5f538edbb..20584ee79 100644
--- a/app/Mcp/Tools/Post/ClearPostRecurrenceTool.php
+++ b/app/Mcp/Tools/Post/ClearPostRecurrenceTool.php
@@ -45,7 +45,7 @@ class ClearPostRecurrenceTool extends Tool
UpdatePostRecurrence::execute($post, null);
- $post = Post::query()->with(['postPlatforms.socialAccount', 'labels'])->findOrFail($post->id);
+ $post = Post::query()->with(['socialAccount', 'labels'])->findOrFail($post->id);
return Response::structured((new PostResource($post))->resolve());
}
diff --git a/app/Mcp/Tools/Post/CreatePostTool.php b/app/Mcp/Tools/Post/CreatePostTool.php
index e4574f063..a0df84d9a 100644
--- a/app/Mcp/Tools/Post/CreatePostTool.php
+++ b/app/Mcp/Tools/Post/CreatePostTool.php
@@ -17,10 +17,12 @@ use App\Mcp\Concerns\DescribesPostMedia;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\Workspace;
+use App\Support\PostCompositionValidator;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
use App\Support\Requests\Post\PostRequestRules;
use Illuminate\Contracts\JsonSchema\JsonSchema;
+use Illuminate\Support\Arr;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
@@ -54,7 +56,7 @@ class CreatePostTool extends Tool
$validated = HostInlineMedia::forPost($workspace, Post::allowedMediaTypesFor($platforms), $validated);
try {
- $post = CreatePosts::execute($workspace, $request->user(), [
+ $post = PostCompositionValidator::forSinglePost(fn (): Post => CreatePosts::execute($workspace, $request->user(), [
'status' => $validated['status'] ?? Status::Draft->value,
'content' => $validated['content'] ?? '',
'media' => $validated['media'] ?? [],
@@ -63,13 +65,13 @@ class CreatePostTool extends Tool
'queue_slot' => $validated['queue_slot'] ?? null,
'label_ids' => $validated['label_ids'] ?? [],
'created_via' => CreatedVia::Mcp,
- 'destinations' => [$validated['platforms'][0]],
- ])->sole();
+ 'destinations' => [Arr::only($validated, ['social_account_id', 'content_type', 'meta'])],
+ ])->sole());
} catch (QueueBusyException) {
return Response::error(__('posts.errors.queue_busy'));
}
- $post->load(['postPlatforms.socialAccount', 'labels']);
+ $post->load(['socialAccount', 'labels']);
return Response::structured((new PostResource($post))->resolve());
}
@@ -88,14 +90,9 @@ class CreatePostTool extends Tool
'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()->description('Format for this platform (e.g. linkedin_post, x_post, instagram_feed). Optional. Omitted, it is chosen as the web composer does: on pinterest a video makes pinterest_video_pin, several images pinterest_carousel, else pinterest_pin; on tiktok images only make tiktok_photo, else tiktok_video; every other network takes its default_content_type (list-content-types-tool). A type sent explicitly is validated against the media and refused when they do not match.'),
- 'meta' => $p->object()->description(PostPlatformMetaRules::documentation()),
- ]))
- ->required()
- ->description('Exactly one social account. Use create-posts-tool for multiple accounts.'),
+ 'social_account_id' => $schema->string()->required()->description('UUID of the connected social account (list-social-accounts-tool). Use create-posts-tool for several accounts.'),
+ 'content_type' => $schema->string()->description('Format for this account (e.g. linkedin_post, x_post, instagram_feed). Optional. Omitted, it is chosen as the web composer does: on pinterest a video makes pinterest_video_pin, several images pinterest_carousel, else pinterest_pin; on tiktok images only make tiktok_photo, else tiktok_video; every other network takes its default_content_type (list-content-types-tool). A type sent explicitly is validated against the media and refused when they do not match.'),
+ 'meta' => $schema->object()->description(PostPlatformMetaRules::documentation()),
];
}
}
diff --git a/app/Mcp/Tools/Post/CreatePostsTool.php b/app/Mcp/Tools/Post/CreatePostsTool.php
index 5cc50282e..facb23311 100644
--- a/app/Mcp/Tools/Post/CreatePostsTool.php
+++ b/app/Mcp/Tools/Post/CreatePostsTool.php
@@ -8,6 +8,7 @@ use App\Actions\Post\CreatePosts;
use App\Actions\Post\HostInlineMedia;
use App\Enums\Post\CreatedVia;
use App\Enums\Post\QueuePosition;
+use App\Enums\Post\Status;
use App\Exceptions\Post\QueueBusyException;
use App\Http\Resources\Api\PostResource;
use App\Mcp\Concerns\AuthorizesMcpTool;
@@ -52,7 +53,7 @@ class CreatePostsTool extends Tool
return Response::structured([
'posts' => $posts->map(function (Post $post): array {
- $post->load(['postPlatforms.socialAccount', 'labels']);
+ $post->load(['socialAccount', 'labels']);
return (new PostResource($post))->resolve();
})->all(),
@@ -62,7 +63,7 @@ class CreatePostsTool extends Tool
public function schema(JsonSchema $schema): array
{
return [
- 'status' => $schema->string()->enum(['draft', 'scheduled', 'publishing'])->required()->description('draft keeps the posts editable, scheduled schedules them at scheduled_at or in the queue, publishing publishes them now.'),
+ 'status' => $schema->string()->enum([Status::Draft->value, Status::Scheduled->value, Status::Publishing->value])->required()->description('draft keeps the posts editable, scheduled schedules them at scheduled_at or in the queue, publishing publishes them now.'),
'content' => $schema->string()->description('Shared text; each destination may override it. The post text, in plain text; use \n for line breaks. When link defusing is on, an X post publishes its links non-clickable (example(.)com); preview-post-tool shows the exact text each network gets. The text must fit the account limit (max_content_length in list-social-accounts-tool; on X, 25000 for an account with long_posts, else 280), Instagram takes at most 5 hashtags, and stories publish no text.'),
'media' => $this->mediaSchema($schema, 'Media shared by every destination by default.'),
'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future and before 2038-01-19, e.g. 2026-05-10T15:30:00Z; without an offset it is read as UTC. Times in responses are UTC (Y-m-d H:i:s). Required when status is scheduled without queue.'),
diff --git a/app/Mcp/Tools/Post/DeletePostTool.php b/app/Mcp/Tools/Post/DeletePostTool.php
index 299f516ec..7d7d21043 100644
--- a/app/Mcp/Tools/Post/DeletePostTool.php
+++ b/app/Mcp/Tools/Post/DeletePostTool.php
@@ -16,7 +16,7 @@ use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
#[IsDestructive]
-#[Description('Delete a post from TryPost permanently; this cannot be undone. A post is never removed from the network where it was published. Posts that are publishing, published, partially_published or failed cannot be changed or deleted. A member who needs approval may delete only posts they wrote, or requests they made that are still pending approval.')]
+#[Description('Delete a post from TryPost permanently; this cannot be undone. A post is never removed from the network where it was published. Posts that are publishing, published or failed cannot be changed or deleted. A member who needs approval may delete only posts they wrote, or requests they made that are still pending approval.')]
class DeletePostTool extends Tool
{
use AuthorizesMcpTool;
diff --git a/app/Mcp/Tools/Post/GetPostMetricsTool.php b/app/Mcp/Tools/Post/GetPostMetricsTool.php
index 5571b0002..ce28a5528 100644
--- a/app/Mcp/Tools/Post/GetPostMetricsTool.php
+++ b/app/Mcp/Tools/Post/GetPostMetricsTool.php
@@ -16,7 +16,7 @@ use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
-#[Description('Read all latest saved analytics for a TryPost post across its published platforms, including reactions, comments, saves, reach, views, and watch time where supported. Values may lag the provider until the next analytics job. Returns "unsupported" for excluded or unpublished platforms.')]
+#[Description('Read the latest saved analytics of a published TryPost post, including reactions, comments, saves, reach, views, and watch time where supported. Values may lag the provider until the next analytics job. metrics is "unsupported" for an unpublished post or a network without analytics.')]
class GetPostMetricsTool extends Tool
{
use AuthorizesMcpTool;
@@ -31,7 +31,7 @@ class GetPostMetricsTool extends Tool
$post = $workspace
? Post::where('workspace_id', $workspace->id)
- ->with(['postPlatforms.socialAccount'])
+ ->with(['socialAccount'])
->find(data_get($validated, 'post_id'))
: null;
@@ -43,10 +43,7 @@ class GetPostMetricsTool extends Tool
return $denied;
}
- return Response::structured([
- 'post_id' => $post->id,
- 'platforms' => app(ReadPublicationAnalytics::class)->forPost($post)->all(),
- ]);
+ return Response::structured(app(ReadPublicationAnalytics::class)->forPost($post));
}
public function schema(JsonSchema $schema): array
diff --git a/app/Mcp/Tools/Post/GetPostTool.php b/app/Mcp/Tools/Post/GetPostTool.php
index ba3790941..3c43057e9 100644
--- a/app/Mcp/Tools/Post/GetPostTool.php
+++ b/app/Mcp/Tools/Post/GetPostTool.php
@@ -33,7 +33,7 @@ class GetPostTool extends Tool
}
$post = Post::where('workspace_id', $workspace->id)
- ->with(['postPlatforms.socialAccount', 'labels'])
+ ->with(['socialAccount', 'labels'])
->find(data_get($validated, 'post_id'));
if (! $post) {
diff --git a/app/Mcp/Tools/Post/ListPostsTool.php b/app/Mcp/Tools/Post/ListPostsTool.php
index a06cc7e8f..d6df4d505 100644
--- a/app/Mcp/Tools/Post/ListPostsTool.php
+++ b/app/Mcp/Tools/Post/ListPostsTool.php
@@ -58,7 +58,7 @@ class ListPostsTool extends Tool
RequestIds::uuidList(collect((array) data_get($validated, 'labels'))),
filter_var(data_get($validated, 'untagged'), FILTER_VALIDATE_BOOLEAN),
)
- ->with(['postPlatforms.socialAccount', 'user', 'approvalRequestedBy', 'approver', 'labels']);
+ ->with(['socialAccount', 'user', 'approvalRequestedBy', 'approver', 'labels']);
$query = match (data_get($validated, 'status')) {
Status::Draft->value => $query->draft(),
@@ -89,8 +89,8 @@ class ListPostsTool extends Tool
{
return [
'status' => $schema->string()
- ->enum(['draft', 'scheduled', 'published', 'failed', 'pending_approval'])
- ->description('Filter by status. "published" includes partially-published posts.'),
+ ->enum([Status::Draft->value, Status::Scheduled->value, Status::Published->value, Status::Failed->value, Status::PendingApproval->value])
+ ->description('Filter by status.'),
'search' => $schema->string()->description('Case-insensitive substring match against the post content.'),
'channels' => $schema->array()->items($schema->string())->description('Only posts on one of these social account IDs (list-social-accounts-tool).'),
'labels' => $schema->array()->items($schema->string())->description('Only posts with one of these label IDs.'),
diff --git a/app/Mcp/Tools/Post/PreviewPostTool.php b/app/Mcp/Tools/Post/PreviewPostTool.php
index 92f098745..db4f4fcc2 100644
--- a/app/Mcp/Tools/Post/PreviewPostTool.php
+++ b/app/Mcp/Tools/Post/PreviewPostTool.php
@@ -16,7 +16,7 @@ use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
-#[Description('Preview how a post will be sent to each enabled platform without publishing: the exact text each network gets (X links defused when that is on), next to the original content, with length stats. Use it to check a text before scheduling.')]
+#[Description('Preview how a post will be sent to its channel without publishing: the exact text the network gets (X links defused when that is on), next to the original content, with length stats. Use it to check a text before scheduling.')]
class PreviewPostTool extends Tool
{
use AuthorizesMcpTool;
@@ -31,7 +31,7 @@ class PreviewPostTool extends Tool
$post = $workspace
? Post::where('workspace_id', $workspace->id)
- ->with(['postPlatforms.socialAccount'])
+ ->with(['socialAccount'])
->find(data_get($validated, 'post_id'))
: null;
diff --git a/app/Mcp/Tools/Post/PublishPostTool.php b/app/Mcp/Tools/Post/PublishPostTool.php
index b5261aa70..0b586842d 100644
--- a/app/Mcp/Tools/Post/PublishPostTool.php
+++ b/app/Mcp/Tools/Post/PublishPostTool.php
@@ -23,7 +23,7 @@ use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
#[IsDestructive]
-#[Description('Publish a post now, schedule it at a custom time (scheduled_at) or put it in the channel queue (queue). Works on drafts and on scheduled posts. Use update-post-tool first to change its content, content_type or meta. It is validated like a scheduled post: text limits, required meta, the media rules of its content_type (see list-content-types-tool) and thread replies; a failure names the platform and field, and nothing is published. Posts that are publishing, published, partially_published or failed cannot be changed or deleted. When the acting member needs approval in this workspace, the post is stored with status pending_approval instead and waits for approve-post-tool. Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text); list-content-types-tool lists them per platform as required_meta. A scheduled or published post also needs text or media.')]
+#[Description('Publish a post now, schedule it at a custom time (scheduled_at) or put it in the channel queue (queue). Works on drafts and on scheduled posts. Use update-post-tool first to change its content, content_type or meta. It is validated like a scheduled post: text limits, required meta, the media rules of its content_type (see list-content-types-tool) and thread replies; a failure names the platform and field, and nothing is published. Posts that are publishing, published or failed cannot be changed or deleted. When the acting member needs approval in this workspace, the post is stored with status pending_approval instead and waits for approve-post-tool. Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text); list-content-types-tool lists them per platform as required_meta. A scheduled or published post also needs text or media.')]
class PublishPostTool extends Tool
{
use AuthorizesMcpTool;
@@ -45,7 +45,7 @@ class PublishPostTool extends Tool
return $denied;
}
- if (! $post->postPlatforms()->enabled()->exists()) {
+ if (! $post->hasChannel()) {
return Response::error(__('posts.errors.no_social_account'));
}
@@ -73,7 +73,7 @@ class PublishPostTool extends Tool
/** @var Post $updated */
$updated = data_get($result, 'post');
- $updated->load(['postPlatforms.socialAccount', 'labels']);
+ $updated->load(['socialAccount', 'labels']);
return Response::structured((new PostResource($updated))->resolve());
}
diff --git a/app/Mcp/Tools/Post/RejectPostTool.php b/app/Mcp/Tools/Post/RejectPostTool.php
index edc0bb562..8eb4024dc 100644
--- a/app/Mcp/Tools/Post/RejectPostTool.php
+++ b/app/Mcp/Tools/Post/RejectPostTool.php
@@ -46,7 +46,7 @@ class RejectPostTool extends Tool
return Response::error(__('posts.errors.queue_busy'));
}
- $rejected->load(['postPlatforms.socialAccount', 'labels']);
+ $rejected->load(['socialAccount', 'labels']);
return Response::structured((new PostResource($rejected))->resolve());
}
diff --git a/app/Mcp/Tools/Post/SetPostRecurrenceTool.php b/app/Mcp/Tools/Post/SetPostRecurrenceTool.php
index 3e8e2bd8d..4c9aa25e1 100644
--- a/app/Mcp/Tools/Post/SetPostRecurrenceTool.php
+++ b/app/Mcp/Tools/Post/SetPostRecurrenceTool.php
@@ -10,7 +10,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Http\Resources\Api\PostResource;
use App\Mcp\Concerns\AuthorizesMcpTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Workspace;
use App\Support\PostingSchedule;
use App\Support\Timezone;
@@ -74,11 +73,10 @@ class SetPostRecurrenceTool extends Tool
$frequency = RecurrenceFrequency::from((string) $request->get('frequency'));
$steps = (int) $request->get('interval') * (int) $request->get('times');
$ceiling = CarbonImmutable::parse(PostingSchedule::MAX_INSTANT, 'UTC');
- $tooFar = $post->postPlatforms()->enabled()->with('socialAccount')->get()
- ->contains(fn (PostPlatform $target): bool => $frequency->advance(
- $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($target->socialAccount?->timezone)),
- $steps,
- )->greaterThan($ceiling));
+ $tooFar = $post->hasDestination() && $frequency->advance(
+ $post->scheduled_at->toImmutable()->setTimezone(Timezone::normalize($post->socialAccount?->timezone)),
+ $steps,
+ )->greaterThan($ceiling);
if ($tooFar) {
$validator->errors()->add('times', __('posts.recurrence.errors.too_far'));
@@ -87,7 +85,7 @@ class SetPostRecurrenceTool extends Tool
UpdatePostRecurrence::execute($post, $validated);
- $post = Post::query()->with(['postPlatforms.socialAccount', 'labels'])->findOrFail($post->id);
+ $post = Post::query()->with(['socialAccount', 'labels'])->findOrFail($post->id);
return Response::structured((new PostResource($post))->resolve());
}
diff --git a/app/Mcp/Tools/Post/UpdatePostTool.php b/app/Mcp/Tools/Post/UpdatePostTool.php
index 47c37d108..e75bafadd 100644
--- a/app/Mcp/Tools/Post/UpdatePostTool.php
+++ b/app/Mcp/Tools/Post/UpdatePostTool.php
@@ -27,7 +27,7 @@ use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
-#[Description('Update one post for its existing social account. Caption, media, content_type, meta (platform settings, merged with the stored ones), status, schedule, queue and labels may change; content_type and meta are top-level fields because a post has exactly one social account, which is fixed. When the acting member needs approval in this workspace, a scheduled, queued or publish-now update is stored with status pending_approval instead. meta is merged with the stored settings: send null for a key to clear it; thread_replies replaces the whole list. To place the post in one specific free slot use move-post-to-slot-tool. Posts that are publishing, published, partially_published or failed cannot be changed or deleted. To publish a thread on X, Bluesky or Mastodon, put the follow-up posts in meta.thread_replies: up to 24 replies published under the post, each {text, media} with up to 4 media items given by url, id or upload_token, e.g. [{"text": "2/ ..."}, {"text": "3/ ...", "media": [{"url": "https://..."}]}]. Each reply must fit the text limit of the account and follows the media rules of a post on that network. Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text); list-content-types-tool lists them per platform as required_meta. A scheduled or published post also needs text or media.')]
+#[Description('Update one post for its existing social account. Caption, media, content_type, meta (platform settings, merged with the stored ones), status, schedule, queue and labels may change; content_type and meta are top-level fields because a post has exactly one social account, which is fixed. When the acting member needs approval in this workspace, a scheduled, queued or publish-now update is stored with status pending_approval instead. meta is merged with the stored settings: send null for a key to clear it; thread_replies replaces the whole list. To place the post in one specific free slot use move-post-to-slot-tool. Posts that are publishing, published or failed cannot be changed or deleted. To publish a thread on X, Bluesky or Mastodon, put the follow-up posts in meta.thread_replies: up to 24 replies published under the post, each {text, media} with up to 4 media items given by url, id or upload_token, e.g. [{"text": "2/ ..."}, {"text": "3/ ...", "media": [{"url": "https://..."}]}]. Each reply must fit the text limit of the account and follows the media rules of a post on that network. Before a post can be scheduled or published it needs: TikTok meta.privacy_level (get-tiktok-creator-info-tool), Pinterest meta.board_id (list-pinterest-boards-tool), Discord meta.channel_id (list-discord-channels-tool), Google Business events and offers meta.event (title and dates), YouTube a title (meta.title, or the first line of the text); list-content-types-tool lists them per platform as required_meta. A scheduled or published post also needs text or media.')]
class UpdatePostTool extends Tool
{
use AuthorizesMcpTool;
@@ -50,7 +50,7 @@ class UpdatePostTool extends Tool
return $denied;
}
- $input = PostRequestRules::updateInput($post, $request->all());
+ $input = $request->all();
$validated = Validator::make($input, PostRequestRules::update($workspace, $post, $input), PostRequestRules::messages(), PostRequestRules::attributes())
->after(fn (ValidatorContract $validator) => PostRequestRules::afterUpdate($validator, $post, $input))
@@ -70,7 +70,7 @@ class UpdatePostTool extends Tool
/** @var Post $updated */
$updated = data_get($result, 'post');
- $updated->load(['postPlatforms.socialAccount', 'labels']);
+ $updated->load(['socialAccount', 'labels']);
return Response::structured((new PostResource($updated))->resolve());
}
diff --git a/app/Mcp/Tools/SocialAccount/GetTikTokCreatorInfoTool.php b/app/Mcp/Tools/SocialAccount/GetTikTokCreatorInfoTool.php
index 9e81cc655..78ba279f5 100644
--- a/app/Mcp/Tools/SocialAccount/GetTikTokCreatorInfoTool.php
+++ b/app/Mcp/Tools/SocialAccount/GetTikTokCreatorInfoTool.php
@@ -22,7 +22,7 @@ use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
#[Name('get-tiktok-creator-info-tool')]
-#[Description('Read what TikTok lets a connected TikTok account publish right now: privacy_level_options (the only privacy_level values allowed for this creator), comment_disabled / duet_disabled / stitch_disabled (when true, allow_comments / allow_duet / allow_stitch must stay false), max_video_post_duration_sec (the longest video TikTok accepts from this creator; it is not checked when you schedule, so compare the video duration yourself), and can_post. Call it before creating or scheduling a TikTok post and pick platforms[].meta.privacy_level from privacy_level_options. can_post false means TikTok banned this creator from posting. When TikTok reports a posting limit (daily cap, quota or rate limit) the tool returns an error instead: scheduled posts retry automatically once it lifts. If TikTok does not answer, the tool returns an error: retry in a moment.')]
+#[Description('Read what TikTok lets a connected TikTok account publish right now: privacy_level_options (the only privacy_level values allowed for this creator), comment_disabled / duet_disabled / stitch_disabled (when true, allow_comments / allow_duet / allow_stitch must stay false), max_video_post_duration_sec (the longest video TikTok accepts from this creator; it is not checked when you schedule, so compare the video duration yourself), and can_post. Call it before creating or scheduling a TikTok post and pick meta.privacy_level (destinations[].meta.privacy_level in create-posts-tool) from privacy_level_options. can_post false means TikTok banned this creator from posting. When TikTok reports a posting limit (daily cap, quota or rate limit) the tool returns an error instead: scheduled posts retry automatically once it lifts. If TikTok does not answer, the tool returns an error: retry in a moment.')]
class GetTikTokCreatorInfoTool extends Tool
{
use AuthorizesMcpTool;
diff --git a/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php b/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php
index 4a4bf3363..616f72fca 100644
--- a/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php
+++ b/app/Mcp/Tools/SocialAccount/ListDiscordChannelsTool.php
@@ -17,7 +17,7 @@ use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
-#[Description('List Discord text/announcement channels the bot can post to for a connected Discord server. Use the returned channel id as platforms[].meta.channel_id when creating or updating a Discord post (required to publish).')]
+#[Description('List Discord text/announcement channels the bot can post to for a connected Discord server. Use the returned channel id as meta.channel_id (destinations[].meta.channel_id in create-posts-tool) when creating or updating a Discord post (required to publish).')]
class ListDiscordChannelsTool extends Tool
{
use AuthorizesMcpTool;
diff --git a/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php b/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php
index d51f42d92..a39eb7d0c 100644
--- a/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php
+++ b/app/Mcp/Tools/SocialAccount/ListPinterestBoardsTool.php
@@ -18,7 +18,7 @@ use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
-#[Description('List Pinterest boards for a connected Pinterest account. Use the returned board id as platforms[].meta.board_id when creating or updating a Pinterest post (required to publish).')]
+#[Description('List Pinterest boards for a connected Pinterest account. Use the returned board id as meta.board_id (destinations[].meta.board_id in create-posts-tool) when creating or updating a Pinterest post (required to publish).')]
class ListPinterestBoardsTool extends Tool
{
use AuthorizesMcpTool;
diff --git a/app/Mcp/Tools/SocialAccount/MovePostToSlotTool.php b/app/Mcp/Tools/SocialAccount/MovePostToSlotTool.php
index 9bb6c49ad..ee35eb249 100644
--- a/app/Mcp/Tools/SocialAccount/MovePostToSlotTool.php
+++ b/app/Mcp/Tools/SocialAccount/MovePostToSlotTool.php
@@ -54,7 +54,7 @@ class MovePostToSlotTool extends Tool
return Response::error(__('posts.errors.queue_busy'));
}
- $post = Post::query()->with(['postPlatforms.socialAccount', 'labels'])->findOrFail(data_get($validated, 'post_id'));
+ $post = Post::query()->with(['socialAccount', 'labels'])->findOrFail(data_get($validated, 'post_id'));
return Response::structured((new PostResource($post))->resolve());
}
diff --git a/app/Mcp/Tools/Webhook/CreateWebhookTool.php b/app/Mcp/Tools/Webhook/CreateWebhookTool.php
index 536143407..12d8266f7 100644
--- a/app/Mcp/Tools/Webhook/CreateWebhookTool.php
+++ b/app/Mcp/Tools/Webhook/CreateWebhookTool.php
@@ -58,7 +58,7 @@ class CreateWebhookTool extends Tool
'events' => $schema->array()
->items($schema->string()->enum(array_column(EventType::cases(), 'value')))
->required()
- ->description('At least one event to subscribe to: post.created, post.scheduled, post.unscheduled, post.published, post.partially_published, post.failed, post.deleted.'),
+ ->description('At least one event to subscribe to: post.created, post.scheduled, post.unscheduled, post.published, post.failed, post.deleted.'),
];
}
}
diff --git a/app/Models/AnalyticsPublication.php b/app/Models/AnalyticsPublication.php
index 521a148b2..d0ac3b401 100644
--- a/app/Models/AnalyticsPublication.php
+++ b/app/Models/AnalyticsPublication.php
@@ -25,7 +25,7 @@ class AnalyticsPublication extends Model
'workspace_id',
'social_account_id',
'social_account_key',
- 'post_platform_id',
+ 'post_id',
'post_dismissed_at',
'network',
'platform_user_id',
@@ -77,9 +77,9 @@ class AnalyticsPublication extends Model
return $this->belongsTo(SocialAccount::class);
}
- public function postPlatform(): BelongsTo
+ public function post(): BelongsTo
{
- return $this->belongsTo(PostPlatform::class);
+ return $this->belongsTo(Post::class);
}
public function dailySnapshots(): HasMany
diff --git a/app/Models/Post.php b/app/Models/Post.php
index 4b0d70739..eed0b88cc 100644
--- a/app/Models/Post.php
+++ b/app/Models/Post.php
@@ -9,10 +9,12 @@ use App\Dto\MediaItem;
use App\Enums\Media\Type;
use App\Enums\Post\CreatedVia;
use App\Enums\Post\Origin;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\QueuePosition;
use App\Enums\Post\RecurrenceFrequency;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Observers\PostObserver;
use App\Support\Media\MediaCopyBatch;
@@ -27,8 +29,10 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
+use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
#[ObservedBy([PostObserver::class])]
class Post extends Model
@@ -61,6 +65,33 @@ class Post extends Model
'approved_by',
'approved_at',
'approval_queue_position',
+ 'platform',
+ 'content_type',
+ 'platform_name',
+ 'platform_username',
+ 'platform_avatar',
+ 'meta',
+ 'platform_url',
+ 'error_message',
+ 'error_context',
+ 'thread_reply_ids',
+ 'submitted_at',
+ 'last_reconciled_at',
+ 'connection_warning_sent_at',
+ 'retry_at',
+ 'publication_updated_at',
+ ];
+
+ /**
+ * @var list<string>
+ */
+ protected $hidden = [
+ 'error_context',
+ 'scheduled_before_media_checks',
+ 'last_reconciled_at',
+ 'connection_warning_sent_at',
+ 'publication_updated_at',
+ 'platform_avatar',
];
/**
@@ -68,6 +99,7 @@ class Post extends Model
*/
protected $attributes = [
'origin' => Origin::DEFAULT->value,
+ 'publish_status' => PublishStatus::DEFAULT->value,
];
protected function casts(): array
@@ -88,6 +120,18 @@ class Post extends Model
'approval_requested_at' => 'datetime',
'approved_at' => 'datetime',
'approval_queue_position' => QueuePosition::class,
+ 'publish_status' => PublishStatus::class,
+ 'platform' => Platform::class,
+ 'content_type' => ContentType::class,
+ 'meta' => 'array',
+ 'error_context' => 'array',
+ 'thread_reply_ids' => 'array',
+ 'submitted_at' => 'datetime',
+ 'last_reconciled_at' => 'datetime',
+ 'connection_warning_sent_at' => 'datetime',
+ 'retry_at' => 'datetime',
+ 'publication_updated_at' => 'datetime',
+ 'scheduled_before_media_checks' => 'boolean',
];
}
@@ -137,9 +181,14 @@ class Post extends Model
return $this->hasMany(Media::class, 'post_id')->orderBy('order');
}
- public function postPlatforms(): HasMany
+ public function socialAccount(): BelongsTo
+ {
+ return $this->belongsTo(SocialAccount::class);
+ }
+
+ public function analyticsPublication(): HasOne
{
- return $this->hasMany(PostPlatform::class)->orderBy('id');
+ return $this->hasOne(AnalyticsPublication::class);
}
public function notes(): HasMany
@@ -166,13 +215,13 @@ class Post extends Model
}
/**
- * Scheduled posts with an enabled destination on the given channel, upcoming after `$after`.
+ * Scheduled posts on the given channel, upcoming after `$after`.
*/
public function scopeScheduledOn(Builder $query, string $channelId, CarbonInterface $after): Builder
{
return $query->scheduled()
->where('scheduled_at', '>', $after)
- ->whereHas('postPlatforms', fn (Builder $platforms) => $platforms->enabled()->where('social_account_id', $channelId));
+ ->where('posts.social_account_id', $channelId);
}
/**
@@ -188,7 +237,7 @@ class Post extends Model
{
return $query->holdingSlot()
->where('scheduled_at', '>', $after)
- ->whereHas('postPlatforms', fn (Builder $platforms) => $platforms->enabled()->where('social_account_id', $channelId));
+ ->where('posts.social_account_id', $channelId);
}
public function scopePendingQueueRequestsOn(Builder $query, string $channelId, CarbonInterface $after): Builder
@@ -196,7 +245,7 @@ class Post extends Model
return $query->pendingApproval()
->where('schedule_mode', ScheduleMode::Queue)
->where('scheduled_at', '>', $after)
- ->whereHas('postPlatforms', fn (Builder $platforms) => $platforms->enabled()->where('social_account_id', $channelId));
+ ->where('posts.social_account_id', $channelId);
}
public function scopeQueuedOn(Builder $query, string $channelId, CarbonInterface $after): Builder
@@ -261,7 +310,7 @@ class Post extends Model
public function scopePublished(Builder $query): Builder
{
- return $query->whereIn('status', [PostStatus::Published, PostStatus::PartiallyPublished]);
+ return $query->where('status', PostStatus::Published);
}
public function scopeFailed(Builder $query): Builder
@@ -280,16 +329,36 @@ class Post extends Model
}
/**
- * Posts with an enabled destination on any of the channels; no filter when $channelIds is null.
+ * Posts on any of the channels; no filter when $channelIds is null.
*
* @param list<string>|null $channelIds
*/
public function scopeOnChannels(Builder $query, ?array $channelIds): Builder
{
- return $query->when($channelIds !== null, fn (Builder $filtered): Builder => $filtered->whereHas(
- 'postPlatforms',
- fn (Builder $platforms): Builder => $platforms->enabled()->whereIn('social_account_id', $channelIds),
- ));
+ return $query->when($channelIds !== null, fn (Builder $filtered): Builder => $filtered->whereIn('posts.social_account_id', $channelIds));
+ }
+
+ /**
+ * Posts the network confirmed as published.
+ */
+ public function scopePublicationPublished(Builder $query): Builder
+ {
+ return $query->where('posts.publish_status', PublishStatus::Published);
+ }
+
+ /**
+ * Posts a network refused for a limit whose next attempt is due.
+ */
+ public function scopeDueForLimitRetry(Builder $query): Builder
+ {
+ return $query->where('posts.publish_status', PublishStatus::Retrying)
+ ->whereNotNull('posts.retry_at')
+ ->where('posts.retry_at', '<=', now());
+ }
+
+ public function scopeIncludedInAnalytics(Builder $query): Builder
+ {
+ return $query->whereIn('posts.platform', Platform::analyticsValues());
}
/**
@@ -313,21 +382,195 @@ class Post extends Model
{
$this->update([
'status' => PostStatus::Published,
- 'published_at' => now(),
+ 'published_at' => $this->published_at ?? now(),
]);
}
- public function markAsPartiallyPublished(): void
+ public function markAsFailed(): void
+ {
+ $this->update(['status' => PostStatus::Failed]);
+ }
+
+ /**
+ * The post has a destination: a channel, or the snapshot of one that was deleted.
+ */
+ public function hasDestination(): bool
{
- $this->update([
- 'status' => PostStatus::PartiallyPublished,
- 'published_at' => now(),
+ return filled($this->platform);
+ }
+
+ /**
+ * The post's channel still exists.
+ */
+ public function hasChannel(): bool
+ {
+ return filled($this->social_account_id);
+ }
+
+ /**
+ * Display name, falling back to the snapshot when the account was deleted.
+ */
+ protected function displayName(): Attribute
+ {
+ return Attribute::make(
+ get: fn (): ?string => $this->socialAccount?->accountDisplayName() ?? $this->platform_name ?? $this->platform?->label(),
+ );
+ }
+
+ /**
+ * Username, falling back to the snapshot when the account was deleted.
+ */
+ protected function displayUsername(): Attribute
+ {
+ return Attribute::make(
+ get: fn (): ?string => $this->socialAccount?->username ?? $this->platform_username,
+ );
+ }
+
+ /**
+ * Avatar URL, falling back to the snapshot when the account was deleted.
+ */
+ protected function displayAvatar(): Attribute
+ {
+ return Attribute::make(
+ get: fn (): ?string => $this->socialAccount?->avatar_url
+ ?: ($this->platform_avatar ? Storage::url($this->platform_avatar) : null),
+ );
+ }
+
+ /**
+ * "Facebook Page (@handle)" for emails. Username first, then display name
+ * (live account or the snapshot). When neither is set, just the platform
+ * name, never "(@)". Empty for a draft without a channel.
+ */
+ public function notificationLabel(): string
+ {
+ if (blank($this->platform)) {
+ return '';
+ }
+
+ $identifier = $this->display_username
+ ?: $this->socialAccount?->display_name
+ ?: $this->platform_name;
+
+ if (! filled($identifier) || $identifier === $this->platform->label()) {
+ return $this->platform->label();
+ }
+
+ return "{$this->platform->label()} (@{$identifier})";
+ }
+
+ /**
+ * Whether the publisher attaches the link preview card for the first URL.
+ * False only when the user dropped the card in the composer.
+ */
+ public function attachesLinkPreview(): bool
+ {
+ return data_get($this->meta, 'link_preview') !== false;
+ }
+
+ public function markPublicationPublishing(): void
+ {
+ $this->writePublication(['publish_status' => PublishStatus::Publishing, 'retry_at' => null]);
+ }
+
+ /**
+ * The network refused the publish for a limit: the post waits, not
+ * failed, until the scheduler picks it up at `retry_at`.
+ *
+ * @param array<string, mixed> $errorContext
+ */
+ public function markPublicationWaitingForLimitRetry(CarbonInterface $retryAt, string $errorMessage, array $errorContext): void
+ {
+ $this->writePublication([
+ 'publish_status' => PublishStatus::Retrying,
+ 'retry_at' => $retryAt,
+ 'error_message' => $errorMessage,
+ 'error_context' => $errorContext,
]);
}
- public function markAsFailed(): void
+ public function isPublicationWaitingForLimitRetry(): bool
{
- $this->update(['status' => PostStatus::Failed]);
+ return $this->publish_status === PublishStatus::Retrying && $this->retry_at?->isFuture() === true;
+ }
+
+ public function markPublicationPublished(string $platformPostId, ?string $platformUrl = null): void
+ {
+ $now = now();
+
+ $this->writePublication([
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => $platformPostId,
+ 'platform_url' => $platformUrl,
+ 'published_at' => $now,
+ 'retry_at' => null,
+ 'error_message' => null,
+ 'error_context' => null,
+ ]);
+
+ $this->socialAccount?->update(['last_used_at' => $now]);
+ }
+
+ /**
+ * The provider accepted the post but has not finished reviewing it. It is
+ * neither published nor failed until the review settles.
+ */
+ public function markPublicationPendingReview(string $platformPostId, ?string $platformUrl = null): void
+ {
+ $this->writePublication([
+ 'publish_status' => PublishStatus::PendingReview,
+ 'platform_post_id' => $platformPostId,
+ 'platform_url' => $platformUrl,
+ 'submitted_at' => $this->submitted_at ?? now(),
+ 'retry_at' => null,
+ 'error_message' => null,
+ 'error_context' => null,
+ ]);
+ }
+
+ /**
+ * The provider accepted the post and then refused it in review. Unlike a
+ * failure, the remote row exists, so its id and URL are kept for support.
+ *
+ * @param array<string, mixed>|null $errorContext
+ */
+ public function markPublicationRejected(string $platformPostId, ?string $platformUrl, string $errorMessage, ?array $errorContext = null): void
+ {
+ $this->writePublication([
+ 'publish_status' => PublishStatus::Rejected,
+ 'platform_post_id' => $platformPostId,
+ 'platform_url' => $platformUrl,
+ 'retry_at' => null,
+ 'error_message' => $errorMessage,
+ 'error_context' => $errorContext,
+ ]);
+ }
+
+ /**
+ * @param array<string, mixed>|null $errorContext
+ */
+ public function markPublicationFailed(string $errorMessage, ?array $errorContext = null): void
+ {
+ $this->writePublication([
+ 'publish_status' => PublishStatus::Failed,
+ 'retry_at' => null,
+ 'error_message' => $errorMessage,
+ 'error_context' => $errorContext,
+ 'platform_post_id' => null,
+ 'platform_url' => null,
+ ]);
+ }
+
+ /**
+ * Writes the publication fields with their own clock, so a publish attempt
+ * never moves `updated_at` and a label or note never moves the clock.
+ *
+ * @param array<string, mixed> $attributes
+ */
+ public function writePublication(array $attributes): void
+ {
+ static::withoutTimestamps(fn () => $this->forceFill([...$attributes, 'publication_updated_at' => now()])->save());
}
/**
@@ -374,21 +617,13 @@ class Post extends Model
}
/**
- * MediaTypes accepted by this post — the intersection of what every
- * enabled platform allows. With no platform enabled, accept anything.
+ * MediaTypes accepted by this post's channel. Without a channel, accept anything.
*
* @return array<Type>
*/
public function allowedMediaTypes(): array
{
- $platforms = $this->postPlatforms()
- ->enabled()
- ->with('socialAccount')
- ->get()
- ->pluck('socialAccount.platform')
- ->filter();
-
- return self::allowedMediaTypesFor($platforms);
+ return self::allowedMediaTypesFor(collect([$this->socialAccount?->platform])->filter());
}
/**
diff --git a/app/Models/PostPlatform.php b/app/Models/PostPlatform.php
deleted file mode 100644
index 8180e64c9..000000000
--- a/app/Models/PostPlatform.php
+++ /dev/null
@@ -1,265 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Models;
-
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
-use App\Enums\SocialAccount\Platform as SocialPlatform;
-use App\Observers\PostPlatformObserver;
-use Carbon\CarbonInterface;
-use Database\Factories\PostPlatformFactory;
-use Illuminate\Database\Eloquent\Attributes\ObservedBy;
-use Illuminate\Database\Eloquent\Builder;
-use Illuminate\Database\Eloquent\Concerns\HasUuids;
-use Illuminate\Database\Eloquent\Factories\HasFactory;
-use Illuminate\Database\Eloquent\Model;
-use Illuminate\Database\Eloquent\Relations\BelongsTo;
-use Illuminate\Database\Eloquent\Relations\HasOne;
-use Illuminate\Support\Facades\Storage;
-
-#[ObservedBy(PostPlatformObserver::class)]
-class PostPlatform extends Model
-{
- /** @use HasFactory<PostPlatformFactory> */
- use HasFactory, HasUuids;
-
- protected $fillable = [
- 'post_id',
- 'social_account_id',
- 'enabled',
- 'platform',
- 'platform_name',
- 'platform_username',
- 'platform_avatar',
- 'content_type',
- 'status',
- 'platform_post_id',
- 'platform_url',
- 'error_message',
- 'error_context',
- 'thread_reply_ids',
- 'published_at',
- 'submitted_at',
- 'last_reconciled_at',
- 'meta',
- 'connection_warning_sent_at',
- 'retry_at',
- ];
-
- protected function casts(): array
- {
- return [
- 'enabled' => 'boolean',
- 'scheduled_before_media_checks' => 'boolean',
- 'platform' => SocialPlatform::class,
- 'content_type' => ContentType::class,
- 'status' => Status::class,
- 'published_at' => 'datetime',
- 'submitted_at' => 'datetime',
- 'last_reconciled_at' => 'datetime',
- 'meta' => 'array',
- 'error_context' => 'array',
- 'thread_reply_ids' => 'array',
- 'connection_warning_sent_at' => 'datetime',
- 'retry_at' => 'datetime',
- ];
- }
-
- public function post(): BelongsTo
- {
- return $this->belongsTo(Post::class);
- }
-
- public function socialAccount(): BelongsTo
- {
- return $this->belongsTo(SocialAccount::class);
- }
-
- public function analyticsPublication(): HasOne
- {
- return $this->hasOne(AnalyticsPublication::class);
- }
-
- /**
- * Only platforms still enabled for publishing — disabled ones are
- * excluded from PublishPost, so anything else that mirrors publish
- * eligibility (previews, validation, proactive checks) must too.
- */
- public function scopeEnabled(Builder $query): Builder
- {
- return $query->where('post_platforms.enabled', true);
- }
-
- public function scopeDisabled(Builder $query): Builder
- {
- return $query->where('post_platforms.enabled', false);
- }
-
- public function scopePublished(Builder $query): Builder
- {
- return $query->where('post_platforms.status', Status::Published);
- }
-
- /**
- * Targets a network refused for a limit whose next attempt is due.
- */
- public function scopeDueForLimitRetry(Builder $query): Builder
- {
- return $query->where('post_platforms.status', Status::Retrying)
- ->whereNotNull('post_platforms.retry_at')
- ->where('post_platforms.retry_at', '<=', now());
- }
-
- public function scopeIncludedInAnalytics(Builder $query): Builder
- {
- return $query->whereIn('post_platforms.platform', SocialPlatform::analyticsValues());
- }
-
- /**
- * Get display name, falling back to snapshot if account was deleted.
- */
- public function getDisplayNameAttribute(): string
- {
- return $this->socialAccount?->accountDisplayName() ?? $this->platform_name ?? $this->platform->label();
- }
-
- /**
- * Get username, falling back to snapshot if account was deleted.
- */
- public function getDisplayUsernameAttribute(): ?string
- {
- return $this->socialAccount?->username ?? $this->platform_username;
- }
-
- /**
- * "Facebook Page (@handle)" for emails.
- * Username first, then display name (live account or the snapshot
- * kept on this row). When neither is set — or the account is gone
- * and there is no snapshot — just the platform name, never "(@)".
- */
- public function notificationLabel(): string
- {
- $identifier = $this->display_username
- ?: $this->socialAccount?->display_name
- ?: $this->platform_name;
-
- if (! filled($identifier) || $identifier === $this->platform->label()) {
- return $this->platform->label();
- }
-
- return "{$this->platform->label()} (@{$identifier})";
- }
-
- /**
- * Get avatar URL, falling back to snapshot if account was deleted.
- */
- public function getDisplayAvatarAttribute(): ?string
- {
- if ($this->socialAccount?->avatar_url) {
- return $this->socialAccount->avatar_url;
- }
-
- return $this->platform_avatar ? Storage::url($this->platform_avatar) : null;
- }
-
- /**
- * Whether the publisher attaches the link preview card for the first URL.
- * False only when the user dropped the card in the composer.
- */
- public function attachesLinkPreview(): bool
- {
- return data_get($this->meta, 'link_preview') !== false;
- }
-
- public function markAsPublishing(): void
- {
- $this->update(['status' => Status::Publishing, 'retry_at' => null]);
- }
-
- /**
- * The network refused the publish for a limit: the target waits, not
- * failed, until the scheduler picks it up at `retry_at`.
- *
- * @param array<string, mixed> $errorContext
- */
- public function markAsWaitingForLimitRetry(CarbonInterface $retryAt, string $errorMessage, array $errorContext): void
- {
- $this->update([
- 'status' => Status::Retrying,
- 'retry_at' => $retryAt,
- 'error_message' => $errorMessage,
- 'error_context' => $errorContext,
- ]);
- }
-
- public function isWaitingForLimitRetry(): bool
- {
- return $this->status === Status::Retrying && $this->retry_at?->isFuture() === true;
- }
-
- public function markAsPublished(string $platformPostId, ?string $platformUrl = null): void
- {
- $now = now();
-
- $this->update([
- 'status' => Status::Published,
- 'platform_post_id' => $platformPostId,
- 'platform_url' => $platformUrl,
- 'published_at' => $now,
- 'retry_at' => null,
- 'error_message' => null,
- 'error_context' => null,
- ]);
-
- $this->socialAccount?->update(['last_used_at' => $now]);
- }
-
- /**
- * The provider accepted the post but has not finished reviewing it. It is
- * neither published nor failed until the review settles.
- */
- public function markAsPendingReview(string $platformPostId, ?string $platformUrl = null): void
- {
- $this->update([
- 'status' => Status::PendingReview,
- 'platform_post_id' => $platformPostId,
- 'platform_url' => $platformUrl,
- 'submitted_at' => $this->submitted_at ?? now(),
- 'retry_at' => null,
- 'error_message' => null,
- 'error_context' => null,
- ]);
- }
-
- /**
- * The provider accepted the post and then refused it in review. Unlike a
- * failure, the remote row exists, so its id and URL are kept for support.
- *
- * @param array<string, mixed>|null $errorContext
- */
- public function markAsRejected(string $platformPostId, ?string $platformUrl, string $errorMessage, ?array $errorContext = null): void
- {
- $this->update([
- 'status' => Status::Rejected,
- 'platform_post_id' => $platformPostId,
- 'platform_url' => $platformUrl,
- 'retry_at' => null,
- 'error_message' => $errorMessage,
- 'error_context' => $errorContext,
- ]);
- }
-
- public function markAsFailed(string $errorMessage, ?array $errorContext = null): void
- {
- $this->update([
- 'status' => Status::Failed,
- 'retry_at' => null,
- 'error_message' => $errorMessage,
- 'error_context' => $errorContext,
- 'platform_post_id' => null,
- 'platform_url' => null,
- ]);
- }
-}
diff --git a/app/Models/SocialAccount.php b/app/Models/SocialAccount.php
index e6cd9b5a5..e74c1edfe 100644
--- a/app/Models/SocialAccount.php
+++ b/app/Models/SocialAccount.php
@@ -8,8 +8,8 @@ use App\Actions\Analytics\DispatchAccountAnalytics;
use App\Actions\SocialAccount\ApplyChannelDefaults;
use App\Casts\PostingScheduleCast;
use App\Enums\Notification\Type;
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\SocialAccount\Platform as SocialPlatform;
use App\Enums\SocialAccount\Status;
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
@@ -263,26 +263,28 @@ class SocialAccount extends Model
return;
}
- $awaitingPublish = [PostPlatformStatus::Pending, PostPlatformStatus::Retrying];
+ $awaitingPublish = [PublishStatus::Pending, PublishStatus::Retrying];
$supported = array_values(array_map(
fn (ContentType $contentType): string => $contentType->value,
ContentType::forPlatform($to),
));
- $account->postPlatforms()
- ->whereIn('status', $awaitingPublish)
+ $account->posts()
+ ->whereIn('publish_status', $awaitingPublish)
->whereNotIn('content_type', $supported)
- ->update(['content_type' => ContentType::defaultFor($to)->value]);
+ ->toBase()
+ ->update(['content_type' => ContentType::defaultFor($to)->value, 'publication_updated_at' => now()]);
- $account->postPlatforms()
- ->whereIn('status', $awaitingPublish)
- ->update(['platform' => $to->value]);
+ $account->posts()
+ ->whereIn('publish_status', $awaitingPublish)
+ ->toBase()
+ ->update(['platform' => $to->value, 'publication_updated_at' => now()]);
}
- public function postPlatforms(): HasMany
+ public function posts(): HasMany
{
- return $this->hasMany(PostPlatform::class);
+ return $this->hasMany(Post::class);
}
public function analyticsSyncStates(): HasMany
@@ -371,7 +373,7 @@ class SocialAccount extends Model
}
/**
- * The channel identity a new PostPlatform keeps, so the post still shows
+ * The channel identity a new post keeps, so the post still shows
* who it went to after the account is renamed or disconnected.
*
* @return array{platform_name: string, platform_username: ?string, platform_avatar: ?string}
diff --git a/app/Observers/PostObserver.php b/app/Observers/PostObserver.php
index a2b49b344..484c48ca4 100644
--- a/app/Observers/PostObserver.php
+++ b/app/Observers/PostObserver.php
@@ -4,10 +4,17 @@ declare(strict_types=1);
namespace App\Observers;
+use App\Actions\Analytics\ResolveAnalyticsAccountKey;
+use App\Dto\Analytics\TryPostPublicationIdentity;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Events\PostCreated;
use App\Events\PostStatusChanged;
+use App\Jobs\Analytics\SyncTryPostPublication;
+use App\Jobs\PostHog\SyncAccountPublishingActivity;
use App\Models\Post;
+use App\Services\Analytics\Collectors\Followers\FollowerCollectorFactory;
+use App\Services\PostHogService;
use Illuminate\Support\Facades\DB;
class PostObserver
@@ -26,27 +33,63 @@ class PostObserver
public function saved(Post $post): void
{
- if (! $post->wasChanged('status')) {
+ if ($post->wasChanged('status')) {
+ $previousStatus = $post->getOriginal('status');
+
+ DB::afterCommit(fn () => PostStatusChanged::dispatch($post, $previousStatus));
+ }
+ }
+
+ public function updated(Post $post): void
+ {
+ if (! $this->wasJustPublished($post)) {
return;
}
- $previousStatus = $this->previousStatus($post);
+ $this->syncPublicationAnalytics($post);
+ $this->syncPublishingActivity($post);
+ }
- DB::afterCommit(fn () => PostStatusChanged::dispatch($post, $previousStatus));
+ private function wasJustPublished(Post $post): bool
+ {
+ return $post->wasChanged('publish_status')
+ && $post->publish_status === PublishStatus::Published
+ && filled($post->platform_post_id);
}
- private function previousStatus(Post $post): ?PostStatus
+ /**
+ * Never fails the publication: an error here is only reported.
+ */
+ private function syncPublicationAnalytics(Post $post): void
{
- $previous = $post->getRawOriginal('status');
+ rescue(function () use ($post): void {
+ $account = $post->loadMissing('socialAccount')->socialAccount;
- if ($previous instanceof PostStatus) {
- return $previous;
+ if (blank($account) || ! app(FollowerCollectorFactory::class)->supports($post->platform)) {
+ return;
+ }
+
+ SyncTryPostPublication::dispatch(
+ TryPostPublicationIdentity::fromAccount($account, app(ResolveAnalyticsAccountKey::class)->for($account)),
+ $post->id,
+ )->afterCommit();
+ });
+ }
+
+ private function syncPublishingActivity(Post $post): void
+ {
+ if (! PostHogService::isEnabled()) {
+ return;
}
- if (is_string($previous)) {
- return PostStatus::tryFrom($previous);
+ $accountId = $post->loadMissing('workspace')->workspace?->account_id;
+
+ if (blank($accountId)) {
+ return;
}
- return null;
+ SyncAccountPublishingActivity::dispatch((string) $accountId)
+ ->delay(now()->addSeconds(SyncAccountPublishingActivity::DEBOUNCE_SECONDS))
+ ->afterCommit();
}
}
diff --git a/app/Observers/PostPlatformObserver.php b/app/Observers/PostPlatformObserver.php
deleted file mode 100644
index 49fba2694..000000000
--- a/app/Observers/PostPlatformObserver.php
+++ /dev/null
@@ -1,65 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Observers;
-
-use App\Actions\Analytics\ResolveAnalyticsAccountKey;
-use App\Dto\Analytics\TryPostPublicationIdentity;
-use App\Enums\PostPlatform\Status;
-use App\Jobs\Analytics\SyncTryPostPublication;
-use App\Jobs\PostHog\SyncAccountPublishingActivity;
-use App\Models\PostPlatform;
-use App\Services\Analytics\Collectors\Followers\FollowerCollectorFactory;
-use App\Services\PostHogService;
-use Throwable;
-
-class PostPlatformObserver
-{
- public function updated(PostPlatform $postPlatform): void
- {
- if (! $postPlatform->wasChanged('status')
- || $postPlatform->status !== Status::Published
- || ! filled($postPlatform->platform_post_id)) {
- return;
- }
-
- $this->dispatchAnalyticsSync($postPlatform);
-
- if (! PostHogService::isEnabled()) {
- return;
- }
-
- $accountId = $postPlatform
- ->loadMissing('post.workspace')
- ->post?->workspace?->account_id;
-
- if (! $accountId) {
- return;
- }
-
- SyncAccountPublishingActivity::dispatch((string) $accountId)
- ->delay(now()->addSeconds(SyncAccountPublishingActivity::DEBOUNCE_SECONDS))
- ->afterCommit();
- }
-
- private function dispatchAnalyticsSync(PostPlatform $postPlatform): void
- {
- try {
- $account = $postPlatform->loadMissing('socialAccount')->socialAccount;
-
- if (! $account || ! app(FollowerCollectorFactory::class)->supports($postPlatform->platform)) {
- return;
- }
-
- $identity = TryPostPublicationIdentity::fromAccount(
- $account,
- app(ResolveAnalyticsAccountKey::class)->for($account),
- );
-
- SyncTryPostPublication::dispatch($identity, $postPlatform->id)->afterCommit();
- } catch (Throwable $exception) {
- report($exception);
- }
- }
-}
diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php
index 1cae4e336..67c7db6ec 100644
--- a/app/Providers/AppServiceProvider.php
+++ b/app/Providers/AppServiceProvider.php
@@ -20,7 +20,6 @@ use App\Models\NotificationPreference;
use App\Models\Plan;
use App\Models\Post;
use App\Models\PostNote;
-use App\Models\PostPlatform;
use App\Models\PostTemplate;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
@@ -123,7 +122,6 @@ class AppServiceProvider extends ServiceProvider
'rssFeedCollection' => RssFeedCollection::class,
'rssFeedItem' => RssFeedItem::class,
'postComment' => PostNote::class,
- 'postPlatform' => PostPlatform::class,
'postTemplate' => PostTemplate::class,
'socialAccount' => SocialAccount::class,
'subscription' => Subscription::class,
diff --git a/app/Rules/ContentTypeCompatibleWithMedia.php b/app/Rules/ContentTypeCompatibleWithMedia.php
index 2d9713d01..7ca74c08f 100644
--- a/app/Rules/ContentTypeCompatibleWithMedia.php
+++ b/app/Rules/ContentTypeCompatibleWithMedia.php
@@ -83,35 +83,24 @@ class ContentTypeCompatibleWithMedia implements DataAwareRule, ValidationRule
}
/**
- * The per-platform entries to validate for a post update: each platform's
- * effective content_type (resubmitted in this request, else its stored
- * value), keyed by the error path the caller surfaces. When
- * $requestPlatforms is null, the post's currently-enabled platforms are used,
- * and with $media (media sent without a content type) a network whose type
- * follows its media (ContentType::derivesFromMedia()) takes the type it decides.
+ * The content type an update would publish: the submitted one, else the
+ * one the new media derives (Pinterest, TikTok), else the stored one.
*
- * @param array<int, mixed>|null $requestPlatforms
* @param array<int, mixed>|null $media
* @return array<int, array{key: string, content_type: string|null}>
*/
- public static function entriesForUpdate(Post $post, ?array $requestPlatforms, ?array $media = null): array
+ public static function entriesForUpdate(Post $post, ?string $contentType, ?array $media = null): array
{
- if (is_array($requestPlatforms)) {
- $stored = $post->postPlatforms()->get()->keyBy('id');
-
- return collect($requestPlatforms)->map(fn ($platform, $index): array => [
- 'key' => "platforms.{$index}.content_type",
- 'content_type' => data_get($platform, 'content_type') ?? $stored->get(data_get($platform, 'id'))?->content_type?->value,
- ])->all();
+ if (! $post->hasDestination()) {
+ return [];
}
- return $post->postPlatforms()->enabled()->get()->values()
- ->map(fn ($postPlatform, $index): array => [
- 'key' => "platforms.{$index}.content_type",
- 'content_type' => $media !== null && ContentType::derivesFromMedia($postPlatform->platform)
- ? ContentType::forMedia($postPlatform->platform, $media)->value
- : $postPlatform->content_type?->value,
- ])->all();
+ return [[
+ 'key' => 'content_type',
+ 'content_type' => $contentType ?? ($media !== null && ContentType::derivesFromMedia($post->platform)
+ ? ContentType::forMedia($post->platform, $media)->value
+ : $post->content_type?->value),
+ ]];
}
/**
diff --git a/app/Rules/ContentTypeMatchesPlatform.php b/app/Rules/ContentTypeMatchesPlatform.php
index fd0da853d..331e16fa6 100644
--- a/app/Rules/ContentTypeMatchesPlatform.php
+++ b/app/Rules/ContentTypeMatchesPlatform.php
@@ -12,17 +12,21 @@ use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Str;
/**
- * Cross-validates platforms[].content_type against platforms[].social_account_id
- * — ensures the chosen content_type is supported by the account's platform.
- *
- * Use on `platforms.*.content_type` rules in form requests / tools that accept
- * a `platforms[]` array with `social_account_id` siblings.
+ * Ensures the chosen content_type is supported by the platform of the account
+ * sent next to it: the top-level `social_account_id`, or the sibling of each
+ * `destinations.*.content_type`.
*/
class ContentTypeMatchesPlatform implements DataAwareRule, ValidationRule
{
/** @var array<string, mixed> */
private array $data = [];
+ /**
+ * An account outside `$workspaceId` is left to the `exists` rule, so its
+ * network is never revealed.
+ */
+ public function __construct(private ?string $workspaceId) {}
+
/**
* @param array<string, mixed> $data
*/
@@ -35,17 +39,14 @@ class ContentTypeMatchesPlatform implements DataAwareRule, ValidationRule
public function validate(string $attribute, mixed $value, Closure $fail): void
{
- // attribute is e.g. "platforms.0.content_type" — peel off the leaf
- // and look up the sibling social_account_id under the same parent.
- $parentKey = Str::beforeLast($attribute, '.');
- $accountId = data_get($this->data, $parentKey.'.social_account_id');
+ $accountId = data_get($this->data, self::siblingAccountPath($attribute));
if (! $accountId || ! Str::isUuid((string) $accountId)) {
return;
}
$contentType = ContentType::tryFrom((string) $value);
- $account = SocialAccount::find($accountId);
+ $account = SocialAccount::query()->where('workspace_id', $this->workspaceId)->find($accountId);
if (! $contentType || ! $account) {
return;
@@ -59,4 +60,15 @@ class ContentTypeMatchesPlatform implements DataAwareRule, ValidationRule
));
}
}
+
+ /**
+ * The account sent next to the content type: `social_account_id` at the top,
+ * `destinations.{i}.social_account_id` inside a destination.
+ */
+ private static function siblingAccountPath(string $attribute): string
+ {
+ $parent = Str::beforeLast($attribute, '.');
+
+ return $parent === $attribute ? 'social_account_id' : "{$parent}.social_account_id";
+ }
}
diff --git a/app/Rules/ContentTypeMatchesPostChannel.php b/app/Rules/ContentTypeMatchesPostChannel.php
new file mode 100644
index 000000000..82d723f5b
--- /dev/null
+++ b/app/Rules/ContentTypeMatchesPostChannel.php
@@ -0,0 +1,33 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Rules;
+
+use App\Enums\PostPlatform\ContentType;
+use App\Models\Post;
+use Closure;
+use Illuminate\Contracts\Validation\ValidationRule;
+
+class ContentTypeMatchesPostChannel implements ValidationRule
+{
+ public function __construct(private Post $post) {}
+
+ public function validate(string $attribute, mixed $value, Closure $fail): void
+ {
+ $contentType = ContentType::tryFrom((string) $value);
+ $account = $this->post->socialAccount;
+
+ 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
deleted file mode 100644
index e29bbb6e6..000000000
--- a/app/Rules/ContentTypeMatchesPostPlatform.php
+++ /dev/null
@@ -1,58 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Rules;
-
-use App\Enums\PostPlatform\ContentType;
-use App\Models\PostPlatform;
-use Closure;
-use Illuminate\Contracts\Validation\DataAwareRule;
-use Illuminate\Contracts\Validation\ValidationRule;
-use Illuminate\Support\Str;
-
-/**
- * Cross-validates platforms[].content_type against the platform of the
- * post_platform row identified by platforms[].id — used on UPDATE flows
- * where the social_account is implicit (already attached to the post).
- */
-class ContentTypeMatchesPostPlatform implements DataAwareRule, ValidationRule
-{
- /** @var array<string, mixed> */
- private array $data = [];
-
- /**
- * @param array<string, mixed> $data
- */
- public function setData(array $data): static
- {
- $this->data = $data;
-
- return $this;
- }
-
- public function validate(string $attribute, mixed $value, Closure $fail): void
- {
- $parentKey = Str::beforeLast($attribute, '.');
- $postPlatformId = data_get($this->data, $parentKey.'.id');
-
- if (! $postPlatformId || ! Str::isUuid((string) $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/Media/MediaOptimizer.php b/app/Services/Media/MediaOptimizer.php
index e29c46451..15c899800 100644
--- a/app/Services/Media/MediaOptimizer.php
+++ b/app/Services/Media/MediaOptimizer.php
@@ -114,49 +114,6 @@ class MediaOptimizer
return is_int($maxWidth) ? $maxWidth : null;
}
- /**
- * Center-crop an image to the given aspect ratio (width / height), the
- * crop the Facebook and Instagram publishers made before TryPost 2.0. Only
- * the one-off `posts:bake-aspect-ratio-crops` release step calls it.
- * Returns path to a temp file (caller must clean up).
- */
- public function cropToAspectRatio(string $filePath, float $ratio): string
- {
- $this->assertWithinMemoryBudget($filePath);
-
- $image = $this->manager->decodePath($filePath);
-
- $width = $image->width();
- $height = $image->height();
- $current = $width / $height;
-
- if (abs($current - $ratio) < 0.001) {
- $tempFile = tempnam(sys_get_temp_dir(), 'media_crop_');
- copy($filePath, $tempFile);
-
- return $tempFile;
- }
-
- if ($current > $ratio) {
- $newWidth = (int) round($height * $ratio);
- $newHeight = $height;
- } else {
- $newWidth = $width;
- $newHeight = (int) round($width / $ratio);
- }
-
- $offsetX = (int) round(($width - $newWidth) / 2);
- $offsetY = (int) round(($height - $newHeight) / 2);
-
- $image->crop($newWidth, $newHeight, $offsetX, $offsetY);
-
- $tempFile = tempnam(sys_get_temp_dir(), 'media_crop_');
- $encoded = $image->encodeUsingMediaType('image/jpeg', quality: 100);
- file_put_contents($tempFile, (string) $encoded);
-
- return $tempFile;
- }
-
/**
* Fit an image inside a width×height canvas without cropping: the image is
* scaled to fit and centered, and the empty space is filled with a blurred,
diff --git a/app/Services/Post/PostPreviewer.php b/app/Services/Post/PostPreviewer.php
index 88e091f95..82455a45f 100644
--- a/app/Services/Post/PostPreviewer.php
+++ b/app/Services/Post/PostPreviewer.php
@@ -6,40 +6,38 @@ namespace App\Services\Post;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Services\Social\ContentSanitizer;
use App\Support\ThreadReplies;
use App\Support\YouTubeDescription;
use App\Support\YouTubeMetadata;
-use Illuminate\Support\Collection;
/**
- * Renders per-platform previews of a post — applies the platform-specific
- * `ContentSanitizer` rules without publishing. Used by the REST API
- * preview endpoint and the MCP `PreviewPostTool` so the rendering rules
- * stay in one place.
+ * Renders the preview of a post for its channel — applies the platform-specific
+ * `ContentSanitizer` rules without publishing. Used by the REST API preview
+ * endpoint and the MCP `PreviewPostTool` so the rendering rules stay in one
+ * place.
*/
class PostPreviewer
{
public function __construct(private readonly ContentSanitizer $sanitizer) {}
/**
+ * Without a channel only the original text is returned.
+ *
* @return array{
* post_id: string,
* original_content: string,
* original_length: int,
- * platforms: array<int, array{
- * post_platform_id: string,
- * platform: string,
- * content_type: ?string,
- * sanitized_content: string,
- * sanitized_length: int,
- * max_content_length: int,
- * truncated: bool,
- * description?: string,
- * description_length_bytes?: int,
- * thread_replies?: list<array{text: string, media: list<array<string, mixed>>}>
- * }>
+ * platform?: string,
+ * content_type?: ?string,
+ * sanitized_content?: string,
+ * sanitized_length?: int,
+ * max_content_length?: int,
+ * truncated?: bool,
+ * title?: string,
+ * description?: string,
+ * description_length_bytes?: int,
+ * thread_replies?: list<array{text: string, media: list<array<string, mixed>>}>
* }
*/
public function forPost(Post $post): array
@@ -50,49 +48,48 @@ class PostPreviewer
'post_id' => $post->id,
'original_content' => $original,
'original_length' => mb_strlen($original),
- 'platforms' => $this->platformPreviews($post, $original)->all(),
+ ...$this->channelPreview($post, $original),
];
}
/**
- * @return Collection<int, array<string, mixed>>
+ * @return array<string, mixed>
*/
- private function platformPreviews(Post $post, string $original): Collection
+ private function channelPreview(Post $post, string $original): array
{
- return $post->postPlatforms
- ->where('enabled', true)
- ->values()
- ->map(function (PostPlatform $pp) use ($original) {
- $platform = $pp->socialAccount?->platform ?? $pp->platform;
- $sanitized = $this->sanitizer->sanitize($original, $platform);
+ $platform = $post->socialAccount?->platform ?? $post->platform;
- $preview = [
- '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' => $pp->socialAccount?->maxContentLength() ?? $platform->maxContentLength(),
- 'truncated' => mb_strlen($sanitized) < mb_strlen($original),
- ];
+ if (blank($platform)) {
+ return [];
+ }
- if ($platform === Platform::YouTube) {
- $description = YouTubeDescription::resolve($pp->meta, $sanitized);
- $preview['title'] = YouTubeMetadata::title($pp->meta, $sanitized);
- $preview['description'] = $description;
- $preview['description_length_bytes'] = strlen($description);
- }
+ $sanitized = $this->sanitizer->sanitize($original, $platform);
- $replies = ThreadReplies::supports($platform) ? ThreadReplies::of($pp->meta) : [];
+ $preview = [
+ 'platform' => $platform->value,
+ 'content_type' => $post->content_type?->value,
+ 'sanitized_content' => $sanitized,
+ 'sanitized_length' => mb_strlen($sanitized),
+ 'max_content_length' => $post->socialAccount?->maxContentLength() ?? $platform->maxContentLength(),
+ 'truncated' => mb_strlen($sanitized) < mb_strlen($original),
+ ];
+
+ if ($platform === Platform::YouTube) {
+ $description = YouTubeDescription::resolve($post->meta, $sanitized);
+ $preview['title'] = YouTubeMetadata::title($post->meta, $sanitized);
+ $preview['description'] = $description;
+ $preview['description_length_bytes'] = strlen($description);
+ }
+
+ $replies = ThreadReplies::supports($platform) ? ThreadReplies::of($post->meta) : [];
- if ($replies !== []) {
- $preview['thread_replies'] = array_map(fn (array $reply): array => [
- 'text' => $this->sanitizer->sanitize($reply['text'], $platform),
- 'media' => $reply['media'],
- ], $replies);
- }
+ if ($replies !== []) {
+ $preview['thread_replies'] = array_map(fn (array $reply): array => [
+ 'text' => $this->sanitizer->sanitize($reply['text'], $platform),
+ 'media' => $reply['media'],
+ ], $replies);
+ }
- return $preview;
- });
+ return $preview;
}
}
diff --git a/app/Services/Social/AbstractLinkedInPublisher.php b/app/Services/Social/AbstractLinkedInPublisher.php
index 3832881c2..8d0f16c39 100644
--- a/app/Services/Social/AbstractLinkedInPublisher.php
+++ b/app/Services/Social/AbstractLinkedInPublisher.php
@@ -10,7 +10,7 @@ use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Http\SafeHttpFetcher;
use App\Services\Media\MediaOptimizer;
@@ -73,15 +73,13 @@ abstract class AbstractLinkedInPublisher
return $postId ? "https://www.linkedin.com/feed/update/{$postId}" : null;
}
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
- : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $this->account = $postPlatform->socialAccount;
+ $this->account = $post->socialAccount;
$this->hasRetried = false;
if ($this->account->needsProactiveTokenRefresh()) {
@@ -91,28 +89,28 @@ abstract class AbstractLinkedInPublisher
$this->accessToken = $this->account->access_token;
try {
- return $this->dispatchByMedia($content, $postPlatform);
+ return $this->dispatchByMedia($content, $post);
} catch (TokenExpiredException $e) {
- return $this->retryWithRefresh($postPlatform, $content, $e);
+ return $this->retryWithRefresh($post, $content, $e);
}
}
- private function dispatchByMedia(?string $content, PostPlatform $postPlatform): array
+ private function dispatchByMedia(?string $content, Post $post): array
{
- $media = $postPlatform->post->mediaItems;
+ $media = $post->mediaItems;
if ($media->contains(fn ($item) => $item->isDocument())) {
- return $this->publishDocument($content, $media, $this->resolveDocumentTitle($postPlatform));
+ return $this->publishDocument($content, $media, $this->resolveDocumentTitle($post));
}
if ($media->filter(fn ($item) => $item->isImage())->count() >= 2) {
return $this->publishCarousel($content, $media);
}
- return $this->publishPost($content, $media, $postPlatform->attachesLinkPreview());
+ return $this->publishPost($content, $media, $post->attachesLinkPreview());
}
- private function retryWithRefresh(PostPlatform $postPlatform, ?string $content, TokenExpiredException $originalException): array
+ private function retryWithRefresh(Post $post, ?string $content, TokenExpiredException $originalException): array
{
if ($this->hasRetried) {
throw $originalException;
@@ -124,7 +122,7 @@ abstract class AbstractLinkedInPublisher
app(ConnectionVerifier::class)->refreshToken($this->account);
$this->accessToken = $this->account->access_token;
- return $this->dispatchByMedia($content, $postPlatform);
+ return $this->dispatchByMedia($content, $post);
} catch (Throwable $e) {
Log::error("{$this->label()} refresh failed during retry", [
'account_id' => $this->account->id,
@@ -359,15 +357,15 @@ abstract class AbstractLinkedInPublisher
* The title shown on a LinkedIn document (PDF carousel) post. Falls back to
* the uploaded file name, then a generic label, so it's never empty.
*/
- private function resolveDocumentTitle(PostPlatform $postPlatform): string
+ private function resolveDocumentTitle(Post $post): string
{
- $title = data_get($postPlatform->meta, 'document_title');
+ $title = data_get($post->meta, 'document_title');
if (filled($title)) {
return (string) $title;
}
- return $postPlatform->post->mediaItems->first(fn ($media) => $media->isDocument())?->original_filename ?? 'Document';
+ return $post->mediaItems->first(fn ($media) => $media->isDocument())?->original_filename ?? 'Document';
}
private function uploadMedia($mediaItem): ?string
diff --git a/app/Services/Social/BlueskyPublisher.php b/app/Services/Social/BlueskyPublisher.php
index caa4bef60..e1e045c2a 100644
--- a/app/Services/Social/BlueskyPublisher.php
+++ b/app/Services/Social/BlueskyPublisher.php
@@ -9,7 +9,7 @@ use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\BlueskyPublishException;
use App\Exceptions\Social\ErrorCategory;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Http\SafeHttpFetcher;
use App\Services\Media\MediaOptimizer;
@@ -52,13 +52,13 @@ class BlueskyPublisher
private const JOB_STATE_FAILED = 'JOB_STATE_FAILED';
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$service = $account->meta['service'] ?? config('trypost.platforms.bluesky.default_service');
// Refresh token if needed
@@ -66,12 +66,12 @@ class BlueskyPublisher
app(ConnectionVerifier::class)->refreshToken($account);
}
- $lookForLiveReply = ThreadProgress::rootHash($postPlatform->error_context) !== null;
+ $lookForLiveReply = filled(ThreadProgress::rootHash($post->error_context));
return $this->publishThread(
- $postPlatform,
- ThreadProgress::hash((string) $content, $postPlatform->post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all()),
- fn (): array => $this->publishRoot($postPlatform, $account, $service, $content),
+ $post,
+ ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all()),
+ fn (): array => $this->publishRoot($post, $account, $service, $content),
function (string $text, Collection $media, array $parent, array $root) use ($account, $service, &$lookForLiveReply): array {
$live = $lookForLiveReply ? $this->liveReply($account, $text, $parent) : null;
$lookForLiveReply = false;
@@ -123,16 +123,16 @@ class BlueskyPublisher
/**
* @return array{id: string, url: string, uri: string, cid: string}
*/
- private function publishRoot(PostPlatform $postPlatform, SocialAccount $account, string $service, ?string $content): array
+ private function publishRoot(Post $post, SocialAccount $account, string $service, ?string $content): array
{
- $medias = $postPlatform->post->mediaItems;
+ $medias = $post->mediaItems;
$embed = $this->mediaEmbed($account, $service, $medias);
// No image or video embed, so a bare link can carry a preview card.
// Bluesky does not hydrate cards server-side: the client must attach an
// app.bsky.embed.external built from the page's OpenGraph metadata.
- if ($embed === null && $medias->isEmpty() && $content !== null && $postPlatform->attachesLinkPreview()) {
- $embed = $this->buildExternalEmbed($postPlatform->socialAccount, $service, $content);
+ if ($embed === null && $medias->isEmpty() && $content !== null && $post->attachesLinkPreview()) {
+ $embed = $this->buildExternalEmbed($post->socialAccount, $service, $content);
}
// Parse facets (links, mentions, hashtags) from text
diff --git a/app/Services/Social/Concerns/HasSocialHttpClient.php b/app/Services/Social/Concerns/HasSocialHttpClient.php
index c74daf965..0f079a672 100644
--- a/app/Services/Social/Concerns/HasSocialHttpClient.php
+++ b/app/Services/Social/Concerns/HasSocialHttpClient.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Services\Social\Concerns;
use App\Exceptions\Social\ContentLimitException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\ContentSanitizer;
use App\Services\Social\TokenRedactor;
use App\Support\ThreadReplies;
@@ -24,33 +24,33 @@ trait HasSocialHttpClient
* hashtag cap is a save-time rule only, so a post stored before it still
* publishes.
*/
- protected function validateContentLength(PostPlatform $postPlatform): void
+ protected function validateContentLength(Post $post): void
{
- if ($postPlatform->content_type?->isCaptionless()) {
+ if ($post->content_type?->isCaptionless()) {
return;
}
- $raw = $postPlatform->post->content ?? '';
- $content = app(ContentSanitizer::class)->displayText($raw, $postPlatform->platform);
+ $raw = $post->content ?? '';
+ $content = app(ContentSanitizer::class)->displayText($raw, $post->platform);
- $threadViolation = ThreadReplies::violation($postPlatform->socialAccount ?? $postPlatform->platform, $postPlatform->meta);
+ $threadViolation = ThreadReplies::violation($post->socialAccount ?? $post->platform, $post->meta);
if ($threadViolation !== null) {
- throw new ContentLimitException($postPlatform->platform, $threadViolation[1]);
+ throw new ContentLimitException($post->platform, $threadViolation[1]);
}
- $reserved = $postPlatform->platform->reservedLength($postPlatform->meta);
- $overflow = $postPlatform->socialAccount?->contentOverflow($content, $reserved) ?? $postPlatform->platform->contentOverflow($content, $reserved);
+ $reserved = $post->platform->reservedLength($post->meta);
+ $overflow = $post->socialAccount?->contentOverflow($content, $reserved) ?? $post->platform->contentOverflow($content, $reserved);
if ($overflow === 0) {
return;
}
- $maxLength = $postPlatform->socialAccount?->maxContentLength() ?? $postPlatform->platform->maxContentLength();
+ $maxLength = $post->socialAccount?->maxContentLength() ?? $post->platform->maxContentLength();
$contentLength = mb_strlen($content) + $reserved;
- throw ContentLimitException::exceeds($postPlatform->platform, $maxLength, $contentLength);
+ throw ContentLimitException::exceeds($post->platform, $maxLength, $contentLength);
}
private bool $interactiveHttp = false;
diff --git a/app/Services/Social/Concerns/PublishesThreads.php b/app/Services/Social/Concerns/PublishesThreads.php
index 6427f08eb..f8812cb2e 100644
--- a/app/Services/Social/Concerns/PublishesThreads.php
+++ b/app/Services/Social/Concerns/PublishesThreads.php
@@ -5,7 +5,7 @@ declare(strict_types=1);
namespace App\Services\Social\Concerns;
use App\Dto\MediaItem;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\ContentSanitizer;
use App\Support\Social\ThreadProgress;
use App\Support\ThreadReplies;
@@ -25,26 +25,26 @@ trait PublishesThreads
* @param (callable(array<string, mixed>): void)|null $afterThread
* @return array{id: string, url: ?string, thread_reply_ids?: list<string>}
*/
- protected function publishThread(PostPlatform $postPlatform, string $rootHash, callable $postRoot, callable $postReply, ?callable $afterThread = null): array
+ protected function publishThread(Post $post, string $rootHash, callable $postRoot, callable $postReply, ?callable $afterThread = null): array
{
$replies = array_map(
fn (array $reply): array => [
- 'text' => app(ContentSanitizer::class)->sanitize($reply['text'], $postPlatform->platform),
+ 'text' => app(ContentSanitizer::class)->sanitize($reply['text'], $post->platform),
'media' => ThreadReplies::mediaItems($reply),
],
- ThreadReplies::supports($postPlatform->platform) ? ThreadReplies::of($postPlatform->meta) : [],
+ ThreadReplies::supports($post->platform) ? ThreadReplies::of($post->meta) : [],
);
$hashes = [
- ThreadProgress::rootHash($postPlatform->error_context) ?? $rootHash,
+ ThreadProgress::rootHash($post->error_context) ?? $rootHash,
...array_map(fn (array $reply): string => ThreadProgress::hash($reply['text'], $reply['media']->map(fn (MediaItem $item): string => $item->id)->all()), $replies),
];
- $posted = ThreadProgress::resumable($postPlatform->error_context, $hashes);
+ $posted = ThreadProgress::resumable($post->error_context, $hashes);
if ($posted === []) {
$posted[] = self::threadSegment($hashes[0], $postRoot());
if ($replies !== []) {
- ThreadProgress::remember($postPlatform, $posted);
+ ThreadProgress::remember($post, $posted);
}
}
@@ -57,7 +57,7 @@ trait PublishesThreads
$posted[] = self::threadSegment($hashes[$position], $postReply($reply['text'], $reply['media'], $posted[$position - 1], $posted[0]));
- ThreadProgress::remember($postPlatform, $posted);
+ ThreadProgress::remember($post, $posted);
}
if ($afterThread !== null) {
diff --git a/app/Services/Social/ContentSanitizer.php b/app/Services/Social/ContentSanitizer.php
index 6b1c61f5d..45a755e44 100644
--- a/app/Services/Social/ContentSanitizer.php
+++ b/app/Services/Social/ContentSanitizer.php
@@ -5,6 +5,7 @@ declare(strict_types=1);
namespace App\Services\Social;
use App\Enums\SocialAccount\Platform;
+use App\Models\Post;
use App\Support\LinkTlds;
class ContentSanitizer
@@ -29,6 +30,14 @@ class ContentSanitizer
private const TYPED_BRACKET_PATTERN = '~<(?!'.self::TAG_BODY.')~i';
+ /**
+ * The post's text as its network receives it, or null when it has none.
+ */
+ public function forPost(Post $post): ?string
+ {
+ return filled($post->content) ? $this->sanitize($post->content, $post->platform) : null;
+ }
+
public function sanitize(string $content, Platform $platform): string
{
$content = $this->escapeTypedBrackets($content);
diff --git a/app/Services/Social/Discord/DiscordPublisher.php b/app/Services/Social/Discord/DiscordPublisher.php
index 44b6a0150..2c2dd12be 100644
--- a/app/Services/Social/Discord/DiscordPublisher.php
+++ b/app/Services/Social/Discord/DiscordPublisher.php
@@ -9,7 +9,7 @@ use App\Enums\Media\Type as MediaType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\DiscordPublishException;
use App\Exceptions\Social\ErrorCategory;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\ContentSanitizer;
@@ -31,13 +31,13 @@ class DiscordPublisher
private const MAX_EMBED_COLOR = 0xFFFFFF;
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$guildId = (string) $account->platform_user_id;
- $channelId = (string) data_get($postPlatform->meta, 'channel_id');
+ $channelId = (string) data_get($post->meta, 'channel_id');
if ($channelId === '') {
throw new DiscordPublishException(
@@ -52,11 +52,9 @@ class DiscordPublisher
// bot is in (including another workspace's).
$this->guardChannelBelongsToGuild($guildId, $channelId);
- $content = $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
- : '';
+ $content = app(ContentSanitizer::class)->forPost($post) ?? '';
- $content = $this->appendMentions($content, $postPlatform);
+ $content = $this->appendMentions($content, $post);
if (mb_strlen($content) > self::MAX_MESSAGE_LENGTH) {
throw new DiscordPublishException(
@@ -65,13 +63,13 @@ class DiscordPublisher
);
}
- $embeds = $this->buildEmbeds($postPlatform);
- $media = $postPlatform->post->mediaItems->take($postPlatform->platform->maxImages());
+ $embeds = $this->buildEmbeds($post);
+ $media = $post->mediaItems->take($post->platform->maxImages());
$payload = array_filter([
'content' => $content !== '' ? $content : null,
'embeds' => $embeds !== [] ? $embeds : null,
- 'allowed_mentions' => $this->allowedMentions($postPlatform),
+ 'allowed_mentions' => $this->allowedMentions($post),
], fn ($value) => $value !== null);
$messageId = $media->isEmpty()
@@ -187,9 +185,9 @@ class DiscordPublisher
* meta — not the shared content — so they only ping on Discord and don't leak
* literal `<@id>` markup to other platforms.
*/
- private function appendMentions(string $content, PostPlatform $postPlatform): string
+ private function appendMentions(string $content, Post $post): string
{
- $tokens = $this->mentionTokens($postPlatform)->implode(' ');
+ $tokens = $this->mentionTokens($post)->implode(' ');
if ($tokens === '') {
return $content;
@@ -205,13 +203,13 @@ class DiscordPublisher
*
* @return array<string, mixed>
*/
- private function allowedMentions(PostPlatform $postPlatform): array
+ private function allowedMentions(Post $post): array
{
$parse = [];
$users = [];
$roles = [];
- foreach ($this->mentionTokens($postPlatform) as $token) {
+ foreach ($this->mentionTokens($post) as $token) {
if ($token === '@everyone' || $token === '@here') {
$parse[] = 'everyone';
} elseif (preg_match('/^<@&(\d+)>$/', $token, $matches)) {
@@ -237,9 +235,9 @@ class DiscordPublisher
/**
* @return Collection<int, string>
*/
- private function mentionTokens(PostPlatform $postPlatform): Collection
+ private function mentionTokens(Post $post): Collection
{
- return collect((array) data_get($postPlatform->meta, 'mentions', []))
+ return collect((array) data_get($post->meta, 'mentions', []))
->map(fn ($mention) => trim((string) data_get($mention, 'token')))
->filter()
->values();
@@ -248,9 +246,9 @@ class DiscordPublisher
/**
* @return list<array<string, mixed>>
*/
- private function buildEmbeds(PostPlatform $postPlatform): array
+ private function buildEmbeds(Post $post): array
{
- return collect((array) data_get($postPlatform->meta, 'embeds', []))
+ return collect((array) data_get($post->meta, 'embeds', []))
->map(fn ($embed) => array_filter([
'title' => data_get($embed, 'title'),
'description' => data_get($embed, 'description'),
diff --git a/app/Services/Social/FacebookPublisher.php b/app/Services/Social/FacebookPublisher.php
index cc436ffbb..1a0113bcb 100644
--- a/app/Services/Social/FacebookPublisher.php
+++ b/app/Services/Social/FacebookPublisher.php
@@ -11,7 +11,7 @@ use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\FacebookPublishException;
use App\Exceptions\Social\SocialPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\Concerns\FitsImageToCanvas;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Meta\GraphError;
@@ -45,21 +45,21 @@ class FacebookPublisher
/**
* @return array{id: mixed, url: string}
*/
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$pageId = $account->platform_user_id;
$accessToken = $account->access_token;
- $content = $this->sanitizedContent($postPlatform);
- $media = $postPlatform->post->mediaItems;
- $contentType = $postPlatform->content_type;
+ $content = $this->sanitizedContent($post);
+ $media = $post->mediaItems;
+ $contentType = $post->content_type;
return match ($contentType) {
ContentType::FacebookReel => $this->publishReel($pageId, $accessToken, $content, $this->requireVideo($media->first(), 'Reels')),
ContentType::FacebookStory => $this->publishStory($pageId, $accessToken, $this->requireMedia($media->first(), 'Stories')),
- ContentType::FacebookPost => $this->publishPost($pageId, $accessToken, $content, $media, $postPlatform->attachesLinkPreview()),
+ ContentType::FacebookPost => $this->publishPost($pageId, $accessToken, $content, $media, $post->attachesLinkPreview()),
default => throw new FacebookPublishException(
userMessage: "Unsupported Facebook content type: {$contentType?->value}",
category: ErrorCategory::MediaFormat,
@@ -554,12 +554,12 @@ class FacebookPublisher
return $media;
}
- private function sanitizedContent(PostPlatform $postPlatform): ?string
+ private function sanitizedContent(Post $post): ?string
{
- $content = $postPlatform->post->content;
+ $content = $post->content;
return filled($content)
- ? app(ContentSanitizer::class)->sanitize($content, $postPlatform->platform)
+ ? app(ContentSanitizer::class)->sanitize($content, $post->platform)
: null;
}
diff --git a/app/Services/Social/GoogleBusinessPublisher.php b/app/Services/Social/GoogleBusinessPublisher.php
index b8983f88a..9bc2d3dc1 100644
--- a/app/Services/Social/GoogleBusinessPublisher.php
+++ b/app/Services/Social/GoogleBusinessPublisher.php
@@ -13,7 +13,7 @@ use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\GoogleBusinessPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
@@ -29,14 +29,14 @@ class GoogleBusinessPublisher
{
use HasSocialHttpClient;
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
$state = null;
try {
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
@@ -51,7 +51,7 @@ class GoogleBusinessPublisher
$created = $this->post(
$account->access_token,
$this->url('local_posts_api', "/{$locationId}/localPosts"),
- $this->payload($postPlatform),
+ $this->payload($post),
'Google Business Profile post creation failed',
);
$state = LocalPostState::fromApi(data_get($created, 'state'));
@@ -63,7 +63,7 @@ class GoogleBusinessPublisher
];
} finally {
if (! $state?->isPendingReview()) {
- app(GoogleBusinessDerivativeCleaner::class)->cleanup($postPlatform->id);
+ app(GoogleBusinessDerivativeCleaner::class)->cleanup($post);
}
}
}
@@ -118,22 +118,20 @@ class GoogleBusinessPublisher
/**
* @return array<string, mixed>
*/
- private function payload(PostPlatform $postPlatform): array
+ private function payload(Post $post): array
{
- $topicType = TopicType::fromMeta(data_get($postPlatform->meta, 'topic_type'));
- $locale = $postPlatform->post->user?->locale ?? Locale::DEFAULT;
+ $topicType = TopicType::fromMeta(data_get($post->meta, 'topic_type'));
+ $locale = $post->user?->locale ?? Locale::DEFAULT;
return [
'languageCode' => $locale->bcp47(),
- 'summary' => $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, Platform::GoogleBusiness)
- : '',
+ 'summary' => app(ContentSanitizer::class)->forPost($post) ?? '',
'topicType' => $topicType->value,
...array_filter([
- 'callToAction' => $this->callToAction($postPlatform, $topicType),
- 'media' => $this->photo($postPlatform),
- 'event' => $topicType->requiresEvent() ? $this->event($postPlatform, $topicType) : null,
- 'offer' => $topicType === TopicType::Offer ? $this->offer($postPlatform) : null,
+ 'callToAction' => $this->callToAction($post, $topicType),
+ 'media' => $this->photo($post),
+ 'event' => $topicType->requiresEvent() ? $this->event($post, $topicType) : null,
+ 'offer' => $topicType === TopicType::Offer ? $this->offer($post) : null,
]),
];
}
@@ -141,9 +139,9 @@ class GoogleBusinessPublisher
/**
* @return array{actionType: string, url?: mixed}|null
*/
- private function callToAction(PostPlatform $postPlatform, TopicType $topicType): ?array
+ private function callToAction(Post $post, TopicType $topicType): ?array
{
- $action = CtaAction::fromMeta(data_get($postPlatform->meta, 'call_to_action.action_type'));
+ $action = CtaAction::fromMeta(data_get($post->meta, 'call_to_action.action_type'));
if (! $topicType->allowsCallToAction() || $action === CtaAction::None) {
return null;
@@ -152,7 +150,7 @@ class GoogleBusinessPublisher
return [
'actionType' => $action->value,
...($action->requiresUrl() ? [
- 'url' => data_get($postPlatform->meta, 'call_to_action.url'),
+ 'url' => data_get($post->meta, 'call_to_action.url'),
] : []),
];
}
@@ -160,19 +158,19 @@ class GoogleBusinessPublisher
/**
* @return list<array{mediaFormat: string, sourceUrl: string}>|null
*/
- private function photo(PostPlatform $postPlatform): ?array
+ private function photo(Post $post): ?array
{
- $media = $postPlatform->post->mediaItems->first(
+ $media = $post->mediaItems->first(
fn (MediaItem $item): bool => $item->isImage() && ! MediaType::isGif($item->mime_type),
);
return $media ? [[
'mediaFormat' => 'PHOTO',
- 'sourceUrl' => $this->imageSourceUrl($media, $postPlatform->id),
+ 'sourceUrl' => $this->imageSourceUrl($media, $post),
]] : null;
}
- private function imageSourceUrl(MediaItem $media, string $postPlatformId): string
+ private function imageSourceUrl(MediaItem $media, Post $post): string
{
if (blank($media->path) || ! Storage::exists($media->path)) {
return $media->url;
@@ -188,7 +186,7 @@ class GoogleBusinessPublisher
try {
file_put_contents($input, Storage::get($media->path));
$optimized = app(MediaOptimizer::class)->optimizeImage($input, Platform::GoogleBusiness);
- $path = GoogleBusinessDerivativeCleaner::pathFor($postPlatformId);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, file_get_contents($optimized));
return Storage::url($path);
@@ -211,22 +209,22 @@ class GoogleBusinessPublisher
/**
* @return array{title: string, schedule: array<string, mixed>}
*/
- private function event(PostPlatform $postPlatform, TopicType $topicType): array
+ private function event(Post $post, TopicType $topicType): array
{
$datesRequired = __('posts.errors.google_business.event_dates_required');
return [
'title' => $this->required(
- data_get($postPlatform->meta, 'event.title'),
+ data_get($post->meta, 'event.title'),
$topicType === TopicType::Offer
? __('posts.form.google_business.offer_title_required')
: __('posts.form.google_business.event_title_required'),
),
'schedule' => array_filter([
- 'startDate' => $this->dateParts($this->required(data_get($postPlatform->meta, 'event.start_date'), $datesRequired)),
- 'endDate' => $this->dateParts($this->required(data_get($postPlatform->meta, 'event.end_date'), $datesRequired)),
- 'startTime' => $this->timeParts(data_get($postPlatform->meta, 'event.start_time')),
- 'endTime' => $this->timeParts(data_get($postPlatform->meta, 'event.end_time')),
+ 'startDate' => $this->dateParts($this->required(data_get($post->meta, 'event.start_date'), $datesRequired)),
+ 'endDate' => $this->dateParts($this->required(data_get($post->meta, 'event.end_date'), $datesRequired)),
+ 'startTime' => $this->timeParts(data_get($post->meta, 'event.start_time')),
+ 'endTime' => $this->timeParts(data_get($post->meta, 'event.end_time')),
]),
];
}
@@ -234,12 +232,12 @@ class GoogleBusinessPublisher
/**
* @return array<string, string>
*/
- private function offer(PostPlatform $postPlatform): array
+ private function offer(Post $post): array
{
return array_filter([
- 'couponCode' => data_get($postPlatform->meta, 'offer.coupon_code'),
- 'redeemOnlineUrl' => data_get($postPlatform->meta, 'offer.redeem_online_url'),
- 'termsConditions' => data_get($postPlatform->meta, 'offer.terms_conditions'),
+ 'couponCode' => data_get($post->meta, 'offer.coupon_code'),
+ 'redeemOnlineUrl' => data_get($post->meta, 'offer.redeem_online_url'),
+ 'termsConditions' => data_get($post->meta, 'offer.terms_conditions'),
], filled(...));
}
diff --git a/app/Services/Social/InstagramPublisher.php b/app/Services/Social/InstagramPublisher.php
index 7f31c1b78..319ada9e1 100644
--- a/app/Services/Social/InstagramPublisher.php
+++ b/app/Services/Social/InstagramPublisher.php
@@ -12,7 +12,7 @@ use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\InstagramPublishException;
use App\Exceptions\Social\SocialPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\Concerns\FitsImageToCanvas;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Meta\GraphError;
@@ -29,7 +29,7 @@ class InstagramPublisher
private string $baseUrl;
- private PostPlatform $postPlatform;
+ private Post $post;
private const int STATUS_RETRY_DELAY_SECONDS = 60;
@@ -40,12 +40,12 @@ class InstagramPublisher
private const string WORKFLOW_FINAL_CONTAINER = 'final_container';
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->postPlatform = $postPlatform;
- $this->validateContentLength($postPlatform);
+ $this->post = $post;
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$this->baseUrl = $account->platform->instagramGraphBaseUrl();
if ($account->needsProactiveTokenRefresh()) {
@@ -55,15 +55,15 @@ class InstagramPublisher
$instagramId = $account->platform_user_id;
$accessToken = $account->access_token;
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $pendingWorkflow = PublishCheckpoint::instagramWorkflow($postPlatform->error_context);
+ $pendingWorkflow = PublishCheckpoint::instagramWorkflow($post->error_context);
if ($pendingWorkflow !== null) {
return $this->resumeWorkflow($instagramId, $accessToken, $content, $pendingWorkflow);
}
- $media = $postPlatform->post->mediaItems;
+ $media = $post->mediaItems;
if ($media->isEmpty()) {
throw new InstagramPublishException(
@@ -73,7 +73,7 @@ class InstagramPublisher
}
$firstMedia = $media->first();
- $contentType = $postPlatform->content_type;
+ $contentType = $post->content_type;
return match ($contentType) {
ContentType::InstagramReel => $this->publishReel($instagramId, $accessToken, $content, $firstMedia),
@@ -249,7 +249,7 @@ class InstagramPublisher
private function sharedOptions(): array
{
return array_filter([
- 'is_ai_generated' => data_get($this->postPlatform->meta, 'is_ai_generated') === true ? 'true' : null,
+ 'is_ai_generated' => data_get($this->post->meta, 'is_ai_generated') === true ? 'true' : null,
], fn (?string $value): bool => $value !== null);
}
@@ -261,12 +261,12 @@ class InstagramPublisher
*/
private function reelOptions(): array
{
- if ($this->postPlatform->content_type !== ContentType::InstagramReel) {
+ if ($this->post->content_type !== ContentType::InstagramReel) {
return [];
}
return [
- 'share_to_feed' => data_get($this->postPlatform->meta, 'share_to_feed', true) ? 'true' : 'false',
+ 'share_to_feed' => data_get($this->post->meta, 'share_to_feed', true) ? 'true' : 'false',
];
}
@@ -458,9 +458,9 @@ class InstagramPublisher
*/
private function rememberPublishedMedia(string $containerId, string $mediaId): void
{
- $this->postPlatform->update([
+ $this->post->writePublication([
'error_context' => [
- ...($this->postPlatform->error_context ?? []),
+ ...($this->post->error_context ?? []),
PublishCheckpoint::INSTAGRAM_WORKFLOW => [
'stage' => self::WORKFLOW_FINAL_CONTAINER,
'container_id' => $containerId,
diff --git a/app/Services/Social/MastodonPublisher.php b/app/Services/Social/MastodonPublisher.php
index 5259af4ec..85497a0f7 100644
--- a/app/Services/Social/MastodonPublisher.php
+++ b/app/Services/Social/MastodonPublisher.php
@@ -10,7 +10,7 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\MastodonPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
@@ -29,29 +29,29 @@ class MastodonPublisher
use HasSocialHttpClient;
use PublishesThreads;
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$instance = $account->meta['instance'] ?? config('trypost.platforms.mastodon.default_instance');
- $rootHash = ThreadProgress::hash((string) $content, $postPlatform->post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
+ $rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
return $this->publishThread(
- $postPlatform,
+ $post,
$rootHash,
- fn (): array => $this->publishRoot($postPlatform, $account, $instance, $content, "{$postPlatform->id}:{$rootHash}"),
+ fn (): array => $this->publishRoot($post, $account, $instance, $content, "{$post->id}:{$rootHash}"),
fn (string $text, Collection $media, array $parent): array => $this->createStatus(
$account,
$instance,
[
- ...$this->replyPayload($postPlatform, $text, (string) $parent['id']),
+ ...$this->replyPayload($post, $text, (string) $parent['id']),
...$this->mediaPayload($account, $instance, $media),
],
- "{$postPlatform->id}:{$parent['id']}:".ThreadProgress::hash($text, $media->map(fn (MediaItem $item): string => $item->id)->all()),
+ "{$post->id}:{$parent['id']}:".ThreadProgress::hash($text, $media->map(fn (MediaItem $item): string => $item->id)->all()),
),
);
}
@@ -59,15 +59,15 @@ class MastodonPublisher
/**
* @return array{id: string, url: ?string}
*/
- private function publishRoot(PostPlatform $postPlatform, SocialAccount $account, string $instance, ?string $content, string $idempotencyKey): array
+ private function publishRoot(Post $post, SocialAccount $account, string $instance, ?string $content, string $idempotencyKey): array
{
$payload = [
'status' => $content ?? '',
'visibility' => 'public',
- ...$this->mediaPayload($account, $instance, $postPlatform->post->mediaItems),
+ ...$this->mediaPayload($account, $instance, $post->mediaItems),
];
- return $this->createStatus($account, $instance, [...$payload, ...$this->contentWarning($postPlatform)], $idempotencyKey);
+ return $this->createStatus($account, $instance, [...$payload, ...$this->contentWarning($post)], $idempotencyKey);
}
/**
@@ -93,22 +93,22 @@ class MastodonPublisher
*
* @return array<string, mixed>
*/
- private function replyPayload(PostPlatform $postPlatform, string $text, string $inReplyToId): array
+ private function replyPayload(Post $post, string $text, string $inReplyToId): array
{
return [
'status' => $text,
'visibility' => 'public',
'in_reply_to_id' => $inReplyToId,
- ...$this->contentWarning($postPlatform),
+ ...$this->contentWarning($post),
];
}
/**
* @return array{spoiler_text?: string}
*/
- private function contentWarning(PostPlatform $postPlatform): array
+ private function contentWarning(Post $post): array
{
- $spoilerText = Str::trim((string) data_get($postPlatform->meta, 'spoiler_text'));
+ $spoilerText = Str::trim((string) data_get($post->meta, 'spoiler_text'));
return $spoilerText === '' ? [] : ['spoiler_text' => $spoilerText];
}
diff --git a/app/Services/Social/PinterestPublisher.php b/app/Services/Social/PinterestPublisher.php
index eef5b34a3..e999be95e 100644
--- a/app/Services/Social/PinterestPublisher.php
+++ b/app/Services/Social/PinterestPublisher.php
@@ -11,7 +11,7 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\PinterestPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
@@ -33,26 +33,24 @@ class PinterestPublisher
$this->baseUrl = config('trypost.platforms.pinterest.api');
}
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
}
- $content = $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
- : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- return match ($postPlatform->content_type) {
- ContentType::PinterestPin => $this->publishImagePin($postPlatform, $content),
- ContentType::PinterestVideoPin => $this->publishVideoPin($postPlatform, $content),
- ContentType::PinterestCarousel => $this->publishCarousel($postPlatform, $content),
+ return match ($post->content_type) {
+ ContentType::PinterestPin => $this->publishImagePin($post, $content),
+ ContentType::PinterestVideoPin => $this->publishVideoPin($post, $content),
+ ContentType::PinterestCarousel => $this->publishCarousel($post, $content),
default => throw new PinterestPublishException(
- userMessage: "Unsupported content type: {$postPlatform->content_type->value}",
+ userMessage: "Unsupported content type: {$post->content_type->value}",
category: ErrorCategory::ContentPolicy,
),
};
@@ -64,27 +62,27 @@ class PinterestPublisher
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
- private function applyPinTextFields(array $payload, PostPlatform $postPlatform, ?string $content): array
+ private function applyPinTextFields(array $payload, Post $post, ?string $content): array
{
if (filled($content)) {
$payload['description'] = mb_substr($content, 0, 800);
}
- if (filled(data_get($postPlatform->meta, 'title'))) {
- $payload['title'] = mb_substr((string) data_get($postPlatform->meta, 'title'), 0, 100);
+ if (filled(data_get($post->meta, 'title'))) {
+ $payload['title'] = mb_substr((string) data_get($post->meta, 'title'), 0, 100);
}
- if (filled(data_get($postPlatform->meta, 'link'))) {
- $payload['link'] = data_get($postPlatform->meta, 'link');
+ if (filled(data_get($post->meta, 'link'))) {
+ $payload['link'] = data_get($post->meta, 'link');
}
return $payload;
}
- private function resolveBoardId(PostPlatform $postPlatform): string
+ private function resolveBoardId(Post $post): string
{
- $boardId = data_get($postPlatform->meta, 'board_id')
- ?? data_get($postPlatform->socialAccount->meta, 'default_board_id');
+ $boardId = data_get($post->meta, 'board_id')
+ ?? data_get($post->socialAccount->meta, 'default_board_id');
if (! filled($boardId)) {
throw new PinterestPublishException(
@@ -121,10 +119,10 @@ class PinterestPublisher
];
}
- private function publishImagePin(PostPlatform $postPlatform, ?string $content): array
+ private function publishImagePin(Post $post, ?string $content): array
{
- $account = $postPlatform->socialAccount;
- $media = $postPlatform->post->mediaItems->first();
+ $account = $post->socialAccount;
+ $media = $post->mediaItems->first();
if (! $media) {
throw new PinterestPublishException(
@@ -133,7 +131,7 @@ class PinterestPublisher
);
}
- $boardId = $this->resolveBoardId($postPlatform);
+ $boardId = $this->resolveBoardId($post);
// Download and optimize image
$tempFile = tempnam(sys_get_temp_dir(), 'pin_image_');
@@ -168,9 +166,9 @@ class PinterestPublisher
'content_type' => 'image/jpeg',
'data' => $imageBase64,
],
- ], $postPlatform, $content);
+ ], $post, $content);
- $alt = $postPlatform->post->mediaItems->first(fn ($m) => $m->isImage())?->altTextFor(Platform::Pinterest);
+ $alt = $post->mediaItems->first(fn ($m) => $m->isImage())?->altTextFor(Platform::Pinterest);
if ($alt !== null) {
$payload['alt_text'] = $alt;
@@ -179,10 +177,10 @@ class PinterestPublisher
return $this->createPin($account, $payload, 'Pinterest pin creation failed');
}
- private function publishVideoPin(PostPlatform $postPlatform, ?string $content): array
+ private function publishVideoPin(Post $post, ?string $content): array
{
- $account = $postPlatform->socialAccount;
- $media = $postPlatform->post->mediaItems->first();
+ $account = $post->socialAccount;
+ $media = $post->mediaItems->first();
if (! $media) {
throw new PinterestPublishException(
@@ -191,7 +189,7 @@ class PinterestPublisher
);
}
- $boardId = $this->resolveBoardId($postPlatform);
+ $boardId = $this->resolveBoardId($post);
// Step 1: Register media upload
$registerResponse = $this->socialHttp()->withToken($account->access_token)
@@ -287,17 +285,17 @@ class PinterestPublisher
'source_type' => 'video_id',
'media_id' => $mediaId,
],
- ], $postPlatform, $content);
+ ], $post, $content);
$payload['media_source']['cover_image_key_frame_time'] = (int) round(($media->coverOffsetMs() ?? 0) / 1000);
return $this->createPin($account, $payload, 'Pinterest video pin creation failed');
}
- private function publishCarousel(PostPlatform $postPlatform, ?string $content): array
+ private function publishCarousel(Post $post, ?string $content): array
{
- $account = $postPlatform->socialAccount;
- $medias = $postPlatform->post->mediaItems;
+ $account = $post->socialAccount;
+ $medias = $post->mediaItems;
if ($medias->count() < 2 || $medias->count() > 5) {
throw new PinterestPublishException(
@@ -311,12 +309,12 @@ class PinterestPublisher
])->toArray();
$payload = $this->applyPinTextFields([
- 'board_id' => $this->resolveBoardId($postPlatform),
+ 'board_id' => $this->resolveBoardId($post),
'media_source' => [
'source_type' => 'multiple_image_urls',
'items' => $items,
],
- ], $postPlatform, $content);
+ ], $post, $content);
return $this->createPin($account, $payload, 'Pinterest carousel creation failed');
}
diff --git a/app/Services/Social/Telegram/TelegramPublisher.php b/app/Services/Social/Telegram/TelegramPublisher.php
index 7692f22cd..97eae9895 100644
--- a/app/Services/Social/Telegram/TelegramPublisher.php
+++ b/app/Services/Social/Telegram/TelegramPublisher.php
@@ -6,7 +6,7 @@ namespace App\Services\Social\Telegram;
use App\Dto\MediaItem;
use App\Exceptions\Social\TelegramPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\ContentSanitizer;
@@ -26,18 +26,16 @@ class TelegramPublisher
private const ALBUM_CHUNK = 10;
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
$chatId = (string) data_get($account->meta, 'chat_id');
- $content = $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
- : '';
+ $content = app(ContentSanitizer::class)->forPost($post) ?? '';
- $media = $postPlatform->post->mediaItems->take(self::ALBUM_CHUNK);
+ $media = $post->mediaItems->take(self::ALBUM_CHUNK);
$messageId = $media->isEmpty()
? $this->sendText($chatId, $content)
diff --git a/app/Services/Social/ThreadsPublisher.php b/app/Services/Social/ThreadsPublisher.php
index e2c4eddbf..c650ae398 100644
--- a/app/Services/Social/ThreadsPublisher.php
+++ b/app/Services/Social/ThreadsPublisher.php
@@ -9,7 +9,7 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\ThreadsMediaContainerNotFoundException;
use App\Exceptions\Social\ThreadsPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Support\PostPlatformMetaRules;
use Illuminate\Http\Client\ConnectionException;
@@ -41,13 +41,13 @@ class ThreadsPublisher
$this->baseUrl = config('trypost.platforms.threads.graph_api');
}
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
@@ -56,18 +56,18 @@ class ThreadsPublisher
$userId = $account->platform_user_id;
$accessToken = $account->access_token;
- $media = $postPlatform->post->mediaItems;
+ $media = $post->mediaItems;
- if ($postPlatform->content_type === ContentType::ThreadsGhostPost && $media->isNotEmpty()) {
+ if ($post->content_type === ContentType::ThreadsGhostPost && $media->isNotEmpty()) {
throw new ThreadsPublishException(
userMessage: __('posts.form.warnings.text_only'),
category: ErrorCategory::MediaFormat,
);
}
- $this->containerOptions = $postPlatform->content_type === ContentType::ThreadsGhostPost
+ $this->containerOptions = $post->content_type === ContentType::ThreadsGhostPost
? ['is_ghost_post' => 'true']
- : $this->postOptions($postPlatform);
+ : $this->postOptions($post);
// Text only post
if ($media->isEmpty()) {
@@ -430,9 +430,9 @@ class ThreadsPublisher
/**
* @return array<string, string>
*/
- private function postOptions(PostPlatform $postPlatform): array
+ private function postOptions(Post $post): array
{
- $topicTag = PostPlatformMetaRules::threadsTopicTag((string) data_get($postPlatform->meta, 'topic_tag'));
+ $topicTag = PostPlatformMetaRules::threadsTopicTag((string) data_get($post->meta, 'topic_tag'));
return $topicTag === '' ? [] : ['topic_tag' => $topicTag];
}
diff --git a/app/Services/Social/TikTokAnalytics.php b/app/Services/Social/TikTokAnalytics.php
index 8d6b0a5ef..9ead0bdaa 100644
--- a/app/Services/Social/TikTokAnalytics.php
+++ b/app/Services/Social/TikTokAnalytics.php
@@ -6,7 +6,7 @@ namespace App\Services\Social;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
use Illuminate\Http\Client\PendingRequest;
@@ -65,17 +65,17 @@ class TikTokAnalytics
*
* @return array<int, array{label: string, value: int}>|array{unsupported: true, reason: string}
*/
- public function fetchPostMetrics(PostPlatform $postPlatform): array
+ public function fetchPostMetrics(Post $post): array
{
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
- if (! $account || ! $postPlatform->platform_post_id) {
+ if (! $account || ! $post->platform_post_id) {
return ['unsupported' => true, 'reason' => 'missing_post_id'];
}
$this->prepareAccessToken($account);
- $videoId = $this->videoIdFor($postPlatform);
+ $videoId = $this->videoIdFor($post);
if ($videoId === null) {
return ['unsupported' => true, 'reason' => 'missing_post_id'];
@@ -117,9 +117,9 @@ class TikTokAnalytics
* the show-page link stops pointing at the profile. SELF_ONLY posts never
* appear on the list, so they are not looked up.
*/
- public function findVideoIdByCaption(PostPlatform $postPlatform): ?string
+ public function findVideoIdByCaption(Post $post): ?string
{
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if (! $account) {
return null;
@@ -127,30 +127,30 @@ class TikTokAnalytics
$this->prepareAccessToken($account);
- return $this->matchVideoFromRecentList($postPlatform);
+ return $this->matchVideoFromRecentList($post);
}
- private function videoIdFor(PostPlatform $postPlatform): ?string
+ private function videoIdFor(Post $post): ?string
{
- $stored = (string) $postPlatform->platform_post_id;
+ $stored = (string) $post->platform_post_id;
if (ctype_digit($stored)) {
return $stored;
}
- $videoId = $this->publicVideoIdFromStatus($stored) ?? $this->matchVideoFromRecentList($postPlatform);
+ $videoId = $this->publicVideoIdFromStatus($stored) ?? $this->matchVideoFromRecentList($post);
if ($videoId === null) {
return null;
}
- $username = $postPlatform->socialAccount?->username;
+ $username = $post->socialAccount?->username;
- $postPlatform->update([
+ $post->writePublication([
'platform_post_id' => $videoId,
'platform_url' => filled($username)
? "https://www.tiktok.com/@{$username}/video/{$videoId}"
- : $postPlatform->platform_url,
+ : $post->platform_url,
]);
return $videoId;
@@ -180,21 +180,19 @@ class TikTokAnalytics
* an older repost with the same caption must never be claimed. Allow one
* day because our `published_at` can lag TikTok's `create_time` during review.
*/
- private function matchVideoFromRecentList(PostPlatform $postPlatform): ?string
+ private function matchVideoFromRecentList(Post $post): ?string
{
- if (PrivacyLevel::tryFrom((string) data_get($postPlatform->meta, 'privacy_level')) === PrivacyLevel::SelfOnly) {
+ if (PrivacyLevel::tryFrom((string) data_get($post->meta, 'privacy_level')) === PrivacyLevel::SelfOnly) {
return null;
}
- $postPlatform->loadMissing('post');
-
- $caption = $this->normalizeCaption((string) $postPlatform->post?->content);
+ $caption = $this->normalizeCaption((string) $post->content);
if ($caption === '') {
return null;
}
- $notBefore = ($postPlatform->published_at ?? now())->copy()->utc()->subDay()->getTimestamp();
+ $notBefore = ($post->published_at ?? now())->copy()->utc()->subDay()->getTimestamp();
$cursor = null;
for ($page = 0; $page < self::VIDEO_LIST_MAX_PAGES; $page++) {
diff --git a/app/Services/Social/TikTokPublisher.php b/app/Services/Social/TikTokPublisher.php
index ced328f5e..324c221cc 100644
--- a/app/Services/Social/TikTokPublisher.php
+++ b/app/Services/Social/TikTokPublisher.php
@@ -11,7 +11,7 @@ use App\Enums\TikTok\PublishStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\TikTokPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
@@ -43,13 +43,13 @@ class TikTokPublisher
$this->baseUrl = config('trypost.platforms.tiktok.api');
}
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
@@ -57,17 +57,17 @@ class TikTokPublisher
$this->accessToken = $account->access_token;
- $pendingPublishId = PublishCheckpoint::tiktokPublishId($postPlatform->error_context);
+ $pendingPublishId = PublishCheckpoint::tiktokPublishId($post->error_context);
if ($pendingPublishId !== null) {
return $this->completePublishWithCleanup(
- $postPlatform,
+ $post,
$pendingPublishId,
- PublishCheckpoint::tiktokDerivativePaths($postPlatform->error_context),
+ PublishCheckpoint::tiktokDerivativePaths($post->error_context),
);
}
- $media = $postPlatform->post->mediaItems;
+ $media = $post->mediaItems;
if ($media->isEmpty()) {
throw new TikTokPublishException(
@@ -81,11 +81,11 @@ class TikTokPublisher
$isImage = $firstMedia->isImage();
if ($isVideo) {
- return $this->publishVideo($postPlatform, $firstMedia, $content);
+ return $this->publishVideo($post, $firstMedia, $content);
}
if ($isImage) {
- return $this->publishPhotos($postPlatform, $media, $content);
+ return $this->publishPhotos($post, $media, $content);
}
throw new TikTokPublishException(
@@ -105,9 +105,9 @@ class TikTokPublisher
* FormRequest enforces the same rules upstream; this is the safety net for
* queue/job paths that bypass the request layer.
*/
- private function resolveRequiredPrivacyLevel(PostPlatform $postPlatform): PrivacyLevel
+ private function resolveRequiredPrivacyLevel(Post $post): PrivacyLevel
{
- $violation = PostPlatformMetaRules::requiredMetaViolation(Platform::TikTok, $postPlatform->meta);
+ $violation = PostPlatformMetaRules::requiredMetaViolation(Platform::TikTok, $post->meta);
if ($violation !== null) {
throw new TikTokPublishException(
@@ -116,7 +116,7 @@ class TikTokPublisher
);
}
- return PrivacyLevel::from((string) data_get($postPlatform->meta, 'privacy_level'));
+ return PrivacyLevel::from((string) data_get($post->meta, 'privacy_level'));
}
/**
@@ -126,13 +126,13 @@ class TikTokPublisher
*
* @return array<string, mixed>
*/
- private function buildVideoPostInfo(PostPlatform $postPlatform, ?string $content, ?int $coverOffsetMs = null): array
+ private function buildVideoPostInfo(Post $post, ?string $content, ?int $coverOffsetMs = null): array
{
- $meta = $postPlatform->meta ?? [];
+ $meta = $post->meta ?? [];
$postInfo = [
'title' => $content ?? '',
- 'privacy_level' => $this->resolveRequiredPrivacyLevel($postPlatform)->value,
+ 'privacy_level' => $this->resolveRequiredPrivacyLevel($post)->value,
'disable_duet' => ! data_get($meta, 'allow_duet', false),
'disable_comment' => ! data_get($meta, 'allow_comments', false),
'disable_stitch' => ! data_get($meta, 'allow_stitch', false),
@@ -165,13 +165,13 @@ class TikTokPublisher
*
* @return array<string, mixed>
*/
- private function buildPhotoPostInfo(PostPlatform $postPlatform, ?string $content): array
+ private function buildPhotoPostInfo(Post $post, ?string $content): array
{
- $meta = $postPlatform->meta ?? [];
+ $meta = $post->meta ?? [];
$postInfo = [
'description' => $content ?? '',
- 'privacy_level' => $this->resolveRequiredPrivacyLevel($postPlatform)->value,
+ 'privacy_level' => $this->resolveRequiredPrivacyLevel($post)->value,
'disable_comment' => ! data_get($meta, 'allow_comments', false),
];
@@ -186,11 +186,11 @@ class TikTokPublisher
return $postInfo;
}
- private function publishVideo(PostPlatform $postPlatform, $media, ?string $content): array
+ private function publishVideo(Post $post, $media, ?string $content): array
{
$response = $this->getHttpClient()
->post("{$this->baseUrl}/post/publish/video/init/", [
- 'post_info' => $this->buildVideoPostInfo($postPlatform, $content, $media->coverOffsetMs()),
+ 'post_info' => $this->buildVideoPostInfo($post, $content, $media->coverOffsetMs()),
'source_info' => [
'source' => 'PULL_FROM_URL',
'video_url' => $media->url,
@@ -209,12 +209,12 @@ class TikTokPublisher
$publishId = $this->requirePublishId(data_get($data, 'data.publish_id'));
- $this->rememberPublishId($postPlatform, $publishId);
+ $this->rememberPublishId($post, $publishId);
- return $this->completePublish($postPlatform, $publishId);
+ return $this->completePublish($post, $publishId);
}
- private function publishPhotos(PostPlatform $postPlatform, $mediaCollection, ?string $content): array
+ private function publishPhotos(Post $post, $mediaCollection, ?string $content): array
{
$images = $mediaCollection->filter(fn ($m) => $m->isImage())->values();
@@ -239,10 +239,10 @@ class TikTokPublisher
}
}
- $postInfo = $this->buildPhotoPostInfo($postPlatform, $content);
+ $postInfo = $this->buildPhotoPostInfo($post, $content);
// Auto add music is only for photos.
- $meta = $postPlatform->meta ?? [];
+ $meta = $post->meta ?? [];
if (data_get($meta, 'auto_add_music', false)) {
$postInfo['auto_add_music'] = true;
}
@@ -269,14 +269,14 @@ class TikTokPublisher
$publishId = $this->requirePublishId(data_get($response->json(), 'data.publish_id'));
- $this->rememberPublishId($postPlatform, $publishId, $derivatives);
+ $this->rememberPublishId($post, $publishId, $derivatives);
} catch (Throwable $e) {
app(TikTokPhotoDerivativeCleaner::class)->cleanupPaths($derivatives);
throw $e;
}
- return $this->completePublishWithCleanup($postPlatform, $publishId, $derivatives);
+ return $this->completePublishWithCleanup($post, $publishId, $derivatives);
}
/**
@@ -414,10 +414,10 @@ class TikTokPublisher
*
* @param list<string> $derivatives
*/
- private function rememberPublishId(PostPlatform $postPlatform, string $publishId, array $derivatives = []): void
+ private function rememberPublishId(Post $post, string $publishId, array $derivatives = []): void
{
$context = [
- ...($postPlatform->error_context ?? []),
+ ...($post->error_context ?? []),
PublishCheckpoint::TIKTOK_PUBLISH_ID => $publishId,
];
@@ -425,7 +425,7 @@ class TikTokPublisher
$context[PublishCheckpoint::TIKTOK_DERIVATIVE_PATHS] = $derivatives;
}
- $postPlatform->update([
+ $post->writePublication([
'error_context' => $context,
]);
}
@@ -456,12 +456,12 @@ class TikTokPublisher
* @param array<array-key, mixed> $derivatives
* @return array<string, mixed>
*/
- private function completePublishWithCleanup(PostPlatform $postPlatform, string $publishId, array $derivatives): array
+ private function completePublishWithCleanup(Post $post, string $publishId, array $derivatives): array
{
$retainDerivatives = true;
try {
- $result = $this->completePublish($postPlatform, $publishId);
+ $result = $this->completePublish($post, $publishId);
$retainDerivatives = false;
return $result;
@@ -480,18 +480,18 @@ class TikTokPublisher
}
}
- private function completePublish(PostPlatform $postPlatform, string $publishId): array
+ private function completePublish(Post $post, string $publishId): array
{
$statusData = $this->waitForPublishStatus($publishId);
$postId = (string) data_get($statusData, 'publicaly_available_post_id.0');
if (blank($postId)) {
- $postId = app(TikTokAnalytics::class)->findVideoIdByCaption($postPlatform);
+ $postId = app(TikTokAnalytics::class)->findVideoIdByCaption($post);
}
return [
'id' => $postId ?? $publishId,
- 'url' => $this->buildTikTokUrl($postPlatform->socialAccount, $postId),
+ 'url' => $this->buildTikTokUrl($post->socialAccount, $postId),
];
}
diff --git a/app/Services/Social/XPublisher.php b/app/Services/Social/XPublisher.php
index ade2d3d8f..a2d5d4d60 100644
--- a/app/Services/Social/XPublisher.php
+++ b/app/Services/Social/XPublisher.php
@@ -11,7 +11,7 @@ use App\Enums\X\MediaProcessingState;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\XPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Media\MediaOptimizer;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Services\Social\Concerns\PublishesThreads;
@@ -57,27 +57,27 @@ class XPublisher
$this->baseUrl = config('trypost.platforms.x.api');
}
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $content = $postPlatform->post->content ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform) : null;
+ $content = app(ContentSanitizer::class)->forPost($post);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
}
$this->accessToken = $account->access_token;
- $this->uploadedMedia = PublishCheckpoint::xMedia($postPlatform->error_context);
+ $this->uploadedMedia = PublishCheckpoint::xMedia($post->error_context);
- $rootHash = ThreadProgress::hash((string) $content, $postPlatform->post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
+ $rootHash = ThreadProgress::hash((string) $content, $post->mediaItems->map(fn (MediaItem $item): string => $item->id)->all());
return $this->publishThread(
- $postPlatform,
+ $post,
$rootHash,
- fn (): array => $this->publishRoot($postPlatform, $content),
+ fn (): array => $this->publishRoot($post, $content),
fn (string $text, Collection $media, array $parent): array => $this->createTweet([
...($text !== '' ? ['text' => $text] : []),
...$this->mediaPayload($media),
@@ -89,7 +89,7 @@ class XPublisher
/**
* @return array{id: string, url: ?string}
*/
- private function publishRoot(PostPlatform $postPlatform, ?string $content): array
+ private function publishRoot(Post $post, ?string $content): array
{
$data = [];
@@ -97,9 +97,9 @@ class XPublisher
$data['text'] = $content;
}
- $data = [...$data, ...$this->mediaPayload($postPlatform->post->mediaItems)];
+ $data = [...$data, ...$this->mediaPayload($post->mediaItems)];
- if (data_get($postPlatform->meta, 'is_ai_generated') === true) {
+ if (data_get($post->meta, 'is_ai_generated') === true) {
$data['made_with_ai'] = true;
}
@@ -110,7 +110,7 @@ class XPublisher
);
}
- return $this->createTweet($data, $postPlatform->socialAccount->username);
+ return $this->createTweet($data, $post->socialAccount->username);
}
/**
diff --git a/app/Services/Social/YouTubePublisher.php b/app/Services/Social/YouTubePublisher.php
index 6d643dfb3..0f98c6c5d 100644
--- a/app/Services/Social/YouTubePublisher.php
+++ b/app/Services/Social/YouTubePublisher.php
@@ -10,7 +10,7 @@ use App\Enums\YouTube\PrivacyStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\YouTubePublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Models\SocialAccount;
use App\Services\Social\Concerns\HasSocialHttpClient;
use App\Support\YouTubeDescription;
@@ -31,11 +31,11 @@ class YouTubePublisher
private const CHUNK_SIZE = 10 * 1024 * 1024; // 10MB chunks
- public function publish(PostPlatform $postPlatform): array
+ public function publish(Post $post): array
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
- $metadataViolation = YouTubeMetadata::violation($postPlatform->meta);
+ $metadataViolation = YouTubeMetadata::violation($post->meta);
if ($metadataViolation !== null) {
throw new YouTubePublishException(
@@ -44,18 +44,16 @@ class YouTubePublisher
);
}
- $content = $postPlatform->post->content
- ? app(ContentSanitizer::class)->sanitize($postPlatform->post->content, $postPlatform->platform)
- : null;
- $description = $this->resolveDescription($postPlatform, $content);
+ $content = app(ContentSanitizer::class)->forPost($post);
+ $description = $this->resolveDescription($post, $content);
- $account = $postPlatform->socialAccount;
+ $account = $post->socialAccount;
if ($account->needsProactiveTokenRefresh()) {
app(ConnectionVerifier::class)->refreshToken($account);
}
- $media = $postPlatform->post->mediaItems;
+ $media = $post->mediaItems;
if ($media->isEmpty()) {
throw new YouTubePublishException(
@@ -73,7 +71,7 @@ class YouTubePublisher
);
}
- return $this->publishShort($firstMedia, $account, $content, $description, $postPlatform->meta ?? []);
+ return $this->publishShort($firstMedia, $account, $content, $description, $post->meta ?? []);
}
private function createGoogleClient(SocialAccount $account): GoogleClient
@@ -241,10 +239,10 @@ class YouTubePublisher
);
}
- private function resolveDescription(PostPlatform $postPlatform, ?string $content): string
+ private function resolveDescription(Post $post, ?string $content): string
{
- $description = YouTubeDescription::resolve($postPlatform->meta, $content);
- $violation = YouTubeDescription::violation(data_get($postPlatform->meta, 'description'))
+ $description = YouTubeDescription::resolve($post->meta, $content);
+ $violation = YouTubeDescription::violation(data_get($post->meta, 'description'))
?? YouTubeDescription::violation($description);
if ($violation !== null) {
diff --git a/app/Services/WebhookService.php b/app/Services/WebhookService.php
index 2d8255d9f..13ee2124e 100644
--- a/app/Services/WebhookService.php
+++ b/app/Services/WebhookService.php
@@ -9,7 +9,6 @@ use App\Enums\Media\Type;
use App\Enums\Webhook\EventType as WebhookEvent;
use App\Jobs\DispatchWebhook;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -106,7 +105,7 @@ class WebhookService
*/
public function postPayload(Post $post): array
{
- $post->load(['user', 'workspace', 'labels', 'postPlatforms.socialAccount']);
+ $post->load(['user', 'workspace', 'labels', 'socialAccount']);
return [
'id' => $post->id,
@@ -130,10 +129,18 @@ class WebhookService
->values()
->all(),
'media' => $this->mediaPayload($post),
- 'platforms' => $post->postPlatforms
- ->map(fn (PostPlatform $platform): array => $this->platformPayload($platform))
- ->values()
- ->all(),
+ 'publish_status' => $post->publish_status->value,
+ 'social_account_id' => $post->social_account_id,
+ 'platform' => $post->platform?->value,
+ 'content_type' => $post->content_type?->value,
+ 'platform_post_id' => $post->platform_post_id,
+ 'platform_url' => $post->platform_url,
+ 'error_message' => $post->error_message,
+ 'display_name' => $post->display_name,
+ 'display_username' => $post->display_username,
+ 'display_avatar' => $post->display_avatar,
+ 'meta' => $post->meta ?? [],
+ 'social_account' => $this->socialAccountPayload($post->socialAccount),
];
}
@@ -188,31 +195,6 @@ class WebhookService
->all();
}
- /**
- * @return array<string, mixed>
- */
- private function platformPayload(PostPlatform $platform): array
- {
- return [
- 'id' => $platform->id,
- 'social_account_id' => $platform->social_account_id,
- 'platform' => $platform->platform?->value,
- 'content_type' => $platform->content_type?->value,
- 'enabled' => $platform->enabled,
- 'status' => $platform->status?->value,
- 'platform_post_id' => $platform->platform_post_id,
- 'platform_url' => $platform->platform_url,
- 'published_at' => $platform->published_at?->toIso8601String(),
- 'error_message' => $platform->error_message,
- 'error_context' => $platform->error_context,
- 'display_name' => $platform->display_name,
- 'display_username' => $platform->display_username,
- 'display_avatar' => $platform->display_avatar,
- 'meta' => $platform->meta ?? [],
- 'social_account' => $this->socialAccountPayload($platform->socialAccount),
- ];
- }
-
/**
* @return array{id: string, platform: string|null, display_name: string|null, username: string|null, status: string|null}|null
*/
diff --git a/app/Support/Mail/ApprovalEmailPost.php b/app/Support/Mail/ApprovalEmailPost.php
new file mode 100644
index 000000000..0ddcd3ae0
--- /dev/null
+++ b/app/Support/Mail/ApprovalEmailPost.php
@@ -0,0 +1,55 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Support\Mail;
+
+use App\Enums\Post\Status as PostStatus;
+use App\Models\Post;
+use App\Models\User;
+use Carbon\CarbonInterface;
+
+/**
+ * Shared data for the approval emails, which are sent one per post: the post,
+ * its channel, an excerpt and a time in the recipient's zone.
+ */
+class ApprovalEmailPost
+{
+ public static function find(string $postId): ?Post
+ {
+ return Post::query()->with(['workspace', 'socialAccount'])->find($postId);
+ }
+
+ public static function excerpt(?Post $post): string
+ {
+ return PostExcerpt::from($post?->content, 280);
+ }
+
+ /**
+ * The post itself when it has a channel to show, null for a draft without one.
+ */
+ public static function channel(?Post $post): ?Post
+ {
+ return $post?->hasDestination() ? $post : null;
+ }
+
+ /**
+ * When the approved post goes out; null means it is publishing now.
+ */
+ public static function goesOutAt(?Post $post, User $recipient): ?string
+ {
+ return $post?->status === PostStatus::Scheduled ? self::time($post->scheduled_at, $recipient) : null;
+ }
+
+ public static function time(?CarbonInterface $at, User $recipient): ?string
+ {
+ if (blank($at)) {
+ return null;
+ }
+
+ $dateTime = RecipientTime::dateTime($at, $recipient);
+ $timezone = RecipientTime::timezone($recipient);
+
+ return "{$dateTime} ({$timezone})";
+ }
+}
diff --git a/app/Support/Mail/ApprovalEmailPosts.php b/app/Support/Mail/ApprovalEmailPosts.php
deleted file mode 100644
index cad136fce..000000000
--- a/app/Support/Mail/ApprovalEmailPosts.php
+++ /dev/null
@@ -1,83 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Support\Mail;
-
-use App\Enums\Post\Status as PostStatus;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\User;
-use Carbon\CarbonInterface;
-use Illuminate\Support\Collection;
-
-/**
- * Shared data for the approval emails: the posts of one request (one per
- * channel, same post_group_id), their channels, an excerpt and a local time.
- */
-class ApprovalEmailPosts
-{
- /**
- * @param list<string> $postIds
- * @return Collection<int, Post>
- */
- public static function load(array $postIds): Collection
- {
- return Post::query()
- ->with(['workspace', 'postPlatforms' => fn ($platforms) => $platforms->enabled()->with('socialAccount')])
- ->whereIn('id', $postIds)
- ->orderBy('created_at')
- ->orderBy('id')
- ->get();
- }
-
- public static function excerpt(?Post $post): string
- {
- return PostExcerpt::from($post?->content, 280);
- }
-
- /**
- * @param Collection<int, Post> $posts
- * @return list<PostPlatform>
- */
- public static function channels(Collection $posts): array
- {
- return $posts->flatMap(fn (Post $post) => $post->postPlatforms)
- ->unique(fn (PostPlatform $postPlatform): string => $postPlatform->social_account_id ?? $postPlatform->id)
- ->values()
- ->all();
- }
-
- /**
- * When each channel goes out once approved: a null time means it is
- * publishing now. One shared moment collapses into a single line.
- *
- * @param Collection<int, Post> $posts
- * @return array{at: ?string, perChannel: list<array{channels: list<PostPlatform>, at: ?string}>}
- */
- public static function goesOut(Collection $posts, User $recipient): array
- {
- $perChannel = $posts->map(fn (Post $post): array => [
- 'channels' => self::channels(collect([$post])),
- 'at' => $post->status === PostStatus::Scheduled ? self::time($post->scheduled_at, $recipient) : null,
- ]);
-
- if ($perChannel->pluck('at')->unique()->count() <= 1) {
- return ['at' => data_get($perChannel->first(), 'at'), 'perChannel' => []];
- }
-
- return ['at' => null, 'perChannel' => $perChannel->values()->all()];
- }
-
- public static function time(?CarbonInterface $at, User $recipient): ?string
- {
- if ($at === null) {
- return null;
- }
-
- $dateTime = RecipientTime::dateTime($at, $recipient);
- $timezone = RecipientTime::timezone($recipient);
-
- return "{$dateTime} ({$timezone})";
- }
-}
diff --git a/app/Support/PostCompositionValidator.php b/app/Support/PostCompositionValidator.php
index 1d4ca4562..d032b249c 100644
--- a/app/Support/PostCompositionValidator.php
+++ b/app/Support/PostCompositionValidator.php
@@ -8,6 +8,7 @@ use App\Actions\Media\ResolveWorkspaceMedia;
use App\Actions\Media\SyncOwnedMedia;
use App\Dto\MediaItem;
use App\Enums\Post\QueuePosition;
+use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Models\SocialAccount;
use App\Models\Workspace;
@@ -22,6 +23,28 @@ use Illuminate\Validation\Validator as LaravelValidator;
class PostCompositionValidator
{
+ /**
+ * Runs a single-destination write, reporting its errors under the post's own keys
+ * (`meta.title`, `content_type`) instead of `destinations.0.*`.
+ *
+ * @template TResult
+ *
+ * @param callable(): TResult $write
+ * @return TResult
+ */
+ public static function forSinglePost(callable $write): mixed
+ {
+ try {
+ return $write();
+ } catch (ValidationException $exception) {
+ $errors = collect($exception->errors())
+ ->mapWithKeys(fn (array $messages, string $key): array => [Str::after($key, 'destinations.0.') => $messages])
+ ->all();
+
+ throw ValidationException::withMessages($errors);
+ }
+ }
+
/**
* @param array<string, mixed> $composition
* @return array<string, mixed>
@@ -29,7 +52,7 @@ class PostCompositionValidator
public static function validate(Workspace $workspace, array $composition, array $existingMedia = []): array
{
Validator::make($composition, [
- 'status' => ['required', Rule::in(['draft', 'scheduled', 'publishing'])],
+ 'status' => ['required', Rule::in([Status::Draft->value, Status::Scheduled->value, Status::Publishing->value])],
'content' => ['sometimes', 'nullable', 'string', new PostContentFitsMaxLength],
'media' => ['sometimes', 'array'],
'destinations' => ['required', 'array', 'min:1'],
@@ -63,6 +86,7 @@ class PostCompositionValidator
$destination['media_error_key'] = array_key_exists('media', $destination)
? "destinations.{$index}.media"
: 'media';
+ $destination['meta_error_key'] = "destinations.{$index}.meta";
$destination['content'] = array_key_exists('content', $destination)
? $destination['content']
: ($composition['content'] ?? '');
@@ -120,25 +144,12 @@ class PostCompositionValidator
foreach (PostMediaRules::hostedRules() as $key => $rules) {
$mediaRules[str_replace('media', 'destinations.*.media', $key)] = $rules;
}
- $metaRules = [];
- foreach (PostPlatformMetaRules::rules() as $key => $rules) {
- $metaRules[str_replace('platforms.', 'destinations.', $key)] = array_map(
- fn (mixed $rule): mixed => is_string($rule)
- ? str_replace('platforms.', 'destinations.', $rule)
- : $rule,
- $rules,
- );
- }
- $metaMessages = [];
- foreach (PostPlatformMetaRules::messages() as $key => $message) {
- $metaMessages[str_replace('platforms.', 'destinations.', $key)] = $message;
- }
- $metaAttributes = [];
- foreach (PostPlatformMetaRules::attributes() as $key => $attribute) {
- $metaAttributes[str_replace('platforms.', 'destinations.', $key)] = $attribute;
- }
-
- $validator = Validator::make($composition, [...$mediaRules, ...$metaRules], $metaMessages, $metaAttributes);
+ $validator = Validator::make(
+ $composition,
+ [...$mediaRules, ...PostPlatformMetaRules::rules('destinations.*.meta')],
+ PostPlatformMetaRules::messages('destinations.*.meta'),
+ PostPlatformMetaRules::attributes('destinations.*.meta'),
+ );
$validator->after(function (LaravelValidator $validator) use ($composition, $accounts, $assets, $existingMedia, $workspace): void {
$seen = [];
diff --git a/app/Support/PostPlatformMetaRules.php b/app/Support/PostPlatformMetaRules.php
index bc8cc60c7..cff025377 100644
--- a/app/Support/PostPlatformMetaRules.php
+++ b/app/Support/PostPlatformMetaRules.php
@@ -12,7 +12,6 @@ use App\Enums\YouTube\Category;
use App\Enums\YouTube\License;
use App\Enums\YouTube\PrivacyStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Rules\ValidYouTubeDescription;
use App\Services\Social\ContentSanitizer;
@@ -37,22 +36,23 @@ class PostPlatformMetaRules
public const SYSTEM_KEYS = ['reactions'];
/**
- * Validation rules for `platforms.*.meta` and all its per-platform sub-keys.
+ * Validation rules for the post's meta and all its per-platform sub-keys,
+ * under `$prefix` (`meta`, or `destinations.*.meta` for a list of channels).
* Spread into a FormRequest/MCP tool rule set as the complete meta contract.
*
* @return array<string, mixed>
*/
- public static function rules(): array
+ public static function rules(string $prefix = 'meta'): array
{
return [
- 'platforms.*.meta' => ['sometimes', 'nullable', 'array'],
+ "{$prefix}" => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.share_to_feed' => ['sometimes', 'boolean'],
+ "{$prefix}.share_to_feed" => ['sometimes', 'boolean'],
- 'platforms.*.meta.spoiler_text' => ['sometimes', 'nullable', 'string', 'max:500'],
+ "{$prefix}.spoiler_text" => ['sometimes', 'nullable', 'string', 'max:500'],
- 'platforms.*.meta.thread_replies' => ['sometimes', 'nullable', 'array', 'max:'.ThreadReplies::MAX_REPLIES],
- 'platforms.*.meta.thread_replies.*' => ['nullable', function (string $attribute, mixed $value, Closure $fail): void {
+ "{$prefix}.thread_replies" => ['sometimes', 'nullable', 'array', 'max:'.ThreadReplies::MAX_REPLIES],
+ "{$prefix}.thread_replies.*" => ['nullable', function (string $attribute, mixed $value, Closure $fail): void {
if (! is_string($value) && ! is_array($value)) {
$fail(__('validation.array', ['attribute' => $attribute]));
}
@@ -61,73 +61,73 @@ class PostPlatformMetaRules
$fail(__('validation.max.string', ['attribute' => $attribute, 'max' => Post::CONTENT_MAX_LENGTH]));
}
}],
- 'platforms.*.meta.thread_replies.*.text' => ['sometimes', 'nullable', 'string', 'max:'.Post::CONTENT_MAX_LENGTH],
- 'platforms.*.meta.thread_replies.*.media' => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.thread_replies.*.media.*' => ['array'],
- 'platforms.*.meta.thread_replies.*.media.*.id' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.thread_replies.*.media.*.upload_token' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.thread_replies.*.media.*.url' => ['sometimes', 'nullable', 'string'],
-
- 'platforms.*.meta.document_title' => ['sometimes', 'nullable', 'string', 'max:300'],
-
- 'platforms.*.meta.privacy_level' => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyLevel::class)],
- 'platforms.*.meta.auto_add_music' => ['sometimes', 'boolean'],
- 'platforms.*.meta.allow_comments' => ['sometimes', 'boolean'],
- 'platforms.*.meta.allow_duet' => ['sometimes', 'boolean'],
- 'platforms.*.meta.allow_stitch' => ['sometimes', 'boolean'],
- 'platforms.*.meta.is_aigc' => ['sometimes', 'boolean'],
- 'platforms.*.meta.disclose' => ['sometimes', 'boolean'],
- 'platforms.*.meta.brand_content_toggle' => ['sometimes', 'boolean'],
- 'platforms.*.meta.brand_organic_toggle' => ['sometimes', 'boolean'],
-
- 'platforms.*.meta.board_id' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.title' => ['sometimes', 'nullable', 'string', 'max:100'],
- 'platforms.*.meta.link' => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
-
- 'platforms.*.meta.description' => ['sometimes', 'nullable', 'string', new ValidYouTubeDescription],
- 'platforms.*.meta.category_id' => ['sometimes', 'nullable', Rule::in(array_column(Category::cases(), 'value'))],
- 'platforms.*.meta.privacy_status' => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyStatus::class)],
- 'platforms.*.meta.license' => ['sometimes', 'nullable', 'string', Rule::enum(License::class)],
- 'platforms.*.meta.notify_subscribers' => ['sometimes', 'boolean'],
- 'platforms.*.meta.embeddable' => ['sometimes', 'boolean'],
- 'platforms.*.meta.made_for_kids' => ['sometimes', 'boolean'],
-
- 'platforms.*.meta.is_ai_generated' => ['sometimes', 'boolean'],
-
- 'platforms.*.meta.link_preview' => ['sometimes', 'boolean:strict'],
-
- 'platforms.*.meta.topic_tag' => ['sometimes', 'nullable', 'string', function (string $attribute, mixed $value, Closure $fail): void {
+ "{$prefix}.thread_replies.*.text" => ['sometimes', 'nullable', 'string', 'max:'.Post::CONTENT_MAX_LENGTH],
+ "{$prefix}.thread_replies.*.media" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.thread_replies.*.media.*" => ['array'],
+ "{$prefix}.thread_replies.*.media.*.id" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.thread_replies.*.media.*.upload_token" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.thread_replies.*.media.*.url" => ['sometimes', 'nullable', 'string'],
+
+ "{$prefix}.document_title" => ['sometimes', 'nullable', 'string', 'max:300'],
+
+ "{$prefix}.privacy_level" => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyLevel::class)],
+ "{$prefix}.auto_add_music" => ['sometimes', 'boolean'],
+ "{$prefix}.allow_comments" => ['sometimes', 'boolean'],
+ "{$prefix}.allow_duet" => ['sometimes', 'boolean'],
+ "{$prefix}.allow_stitch" => ['sometimes', 'boolean'],
+ "{$prefix}.is_aigc" => ['sometimes', 'boolean'],
+ "{$prefix}.disclose" => ['sometimes', 'boolean'],
+ "{$prefix}.brand_content_toggle" => ['sometimes', 'boolean'],
+ "{$prefix}.brand_organic_toggle" => ['sometimes', 'boolean'],
+
+ "{$prefix}.board_id" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.title" => ['sometimes', 'nullable', 'string', 'max:100'],
+ "{$prefix}.link" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
+
+ "{$prefix}.description" => ['sometimes', 'nullable', 'string', new ValidYouTubeDescription],
+ "{$prefix}.category_id" => ['sometimes', 'nullable', Rule::in(array_column(Category::cases(), 'value'))],
+ "{$prefix}.privacy_status" => ['sometimes', 'nullable', 'string', Rule::enum(PrivacyStatus::class)],
+ "{$prefix}.license" => ['sometimes', 'nullable', 'string', Rule::enum(License::class)],
+ "{$prefix}.notify_subscribers" => ['sometimes', 'boolean'],
+ "{$prefix}.embeddable" => ['sometimes', 'boolean'],
+ "{$prefix}.made_for_kids" => ['sometimes', 'boolean'],
+
+ "{$prefix}.is_ai_generated" => ['sometimes', 'boolean'],
+
+ "{$prefix}.link_preview" => ['sometimes', 'boolean:strict'],
+
+ "{$prefix}.topic_tag" => ['sometimes', 'nullable', 'string', function (string $attribute, mixed $value, Closure $fail): void {
if (! self::isThreadsTopicTag((string) $value)) {
$fail(__('posts.form.threads.topic_invalid'));
}
}],
- 'platforms.*.meta.channel_id' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.channel_name' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.mentions' => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.mentions.*.token' => ['required', 'string'],
- 'platforms.*.meta.mentions.*.label' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.embeds' => ['sometimes', 'nullable', 'array', 'max:10'],
- 'platforms.*.meta.embeds.*.title' => ['sometimes', 'nullable', 'string', 'max:256'],
- 'platforms.*.meta.embeds.*.description' => ['sometimes', 'nullable', 'string', 'max:4096'],
- 'platforms.*.meta.embeds.*.url' => ['sometimes', 'nullable', 'url'],
- 'platforms.*.meta.embeds.*.image' => ['sometimes', 'nullable', 'url'],
- 'platforms.*.meta.embeds.*.color' => ['sometimes', 'nullable', 'string', 'regex:/^#?[0-9A-Fa-f]{6}$/'],
-
- 'platforms.*.meta.topic_type' => ['sometimes', 'nullable', 'string', Rule::enum(TopicType::class)],
- 'platforms.*.meta.call_to_action' => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.call_to_action.action_type' => ['sometimes', 'nullable', 'string', Rule::enum(CtaAction::class)],
- 'platforms.*.meta.call_to_action.url' => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
- 'platforms.*.meta.event' => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.event.title' => ['sometimes', 'nullable', 'string', 'max:'.TopicType::TITLE_MAX_LENGTH],
- 'platforms.*.meta.event.start_date' => ['sometimes', 'nullable', 'date'],
- 'platforms.*.meta.event.end_date' => ['sometimes', 'nullable', 'date', 'after_or_equal:platforms.*.meta.event.start_date'],
- 'platforms.*.meta.event.start_time' => ['sometimes', 'nullable', 'date_format:H:i'],
- 'platforms.*.meta.event.end_time' => ['sometimes', 'nullable', 'date_format:H:i'],
- 'platforms.*.meta.offer' => ['sometimes', 'nullable', 'array'],
- 'platforms.*.meta.offer.coupon_code' => ['sometimes', 'nullable', 'string'],
- 'platforms.*.meta.offer.redeem_online_url' => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
- 'platforms.*.meta.offer.terms_conditions' => ['sometimes', 'nullable', 'string', 'max:5000'],
+ "{$prefix}.channel_id" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.channel_name" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.mentions" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.mentions.*.token" => ['required', 'string'],
+ "{$prefix}.mentions.*.label" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.embeds" => ['sometimes', 'nullable', 'array', 'max:10'],
+ "{$prefix}.embeds.*.title" => ['sometimes', 'nullable', 'string', 'max:256'],
+ "{$prefix}.embeds.*.description" => ['sometimes', 'nullable', 'string', 'max:4096'],
+ "{$prefix}.embeds.*.url" => ['sometimes', 'nullable', 'url'],
+ "{$prefix}.embeds.*.image" => ['sometimes', 'nullable', 'url'],
+ "{$prefix}.embeds.*.color" => ['sometimes', 'nullable', 'string', 'regex:/^#?[0-9A-Fa-f]{6}$/'],
+
+ "{$prefix}.topic_type" => ['sometimes', 'nullable', 'string', Rule::enum(TopicType::class)],
+ "{$prefix}.call_to_action" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.call_to_action.action_type" => ['sometimes', 'nullable', 'string', Rule::enum(CtaAction::class)],
+ "{$prefix}.call_to_action.url" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
+ "{$prefix}.event" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.event.title" => ['sometimes', 'nullable', 'string', 'max:'.TopicType::TITLE_MAX_LENGTH],
+ "{$prefix}.event.start_date" => ['sometimes', 'nullable', 'date'],
+ "{$prefix}.event.end_date" => ['sometimes', 'nullable', 'date', "after_or_equal:{$prefix}.event.start_date"],
+ "{$prefix}.event.start_time" => ['sometimes', 'nullable', 'date_format:H:i'],
+ "{$prefix}.event.end_time" => ['sometimes', 'nullable', 'date_format:H:i'],
+ "{$prefix}.offer" => ['sometimes', 'nullable', 'array'],
+ "{$prefix}.offer.coupon_code" => ['sometimes', 'nullable', 'string'],
+ "{$prefix}.offer.redeem_online_url" => ['sometimes', 'nullable', 'url:http,https', 'max:2048'],
+ "{$prefix}.offer.terms_conditions" => ['sometimes', 'nullable', 'string', 'max:5000'],
];
}
@@ -140,8 +140,8 @@ class PostPlatformMetaRules
public static function onlyKnown(array $meta): array
{
$known = collect(array_keys(self::rules()))
- ->filter(fn (string $key): bool => str_starts_with($key, 'platforms.*.meta.'))
- ->map(fn (string $key): string => explode('.', substr($key, strlen('platforms.*.meta.')))[0])
+ ->filter(fn (string $key): bool => str_starts_with($key, 'meta.'))
+ ->map(fn (string $key): string => explode('.', substr($key, strlen('meta.')))[0])
->unique()
->all();
@@ -164,67 +164,35 @@ class PostPlatformMetaRules
];
}
- /**
- * The meta of each submitted platform entry, keyed by the given field.
- *
- * @param array<int, mixed> $platforms
- * @return array<string, array<string, mixed>>
- */
- public static function metaByKey(array $platforms, string $keyField): array
- {
- return collect($platforms)
- ->filter(fn (mixed $platform): bool => is_string(data_get($platform, $keyField)))
- ->mapWithKeys(fn (mixed $platform): array => [data_get($platform, $keyField) => (array) data_get($platform, 'meta', [])])
- ->all();
- }
-
- /**
- * The content type of each submitted platform entry, keyed by the given
- * field, falling back to the stored one when the entry omits it.
- *
- * @param array<int, mixed> $platforms
- * @param array<string, string|null> $stored
- * @return array<string, string|null>
- */
- public static function contentTypesByKey(array $platforms, string $keyField, array $stored = []): array
- {
- return collect($platforms)
- ->filter(fn (mixed $platform): bool => is_string(data_get($platform, $keyField)))
- ->mapWithKeys(fn (mixed $platform): array => [
- data_get($platform, $keyField) => data_get($platform, 'content_type', data_get($stored, data_get($platform, $keyField))),
- ])
- ->all();
- }
-
/**
* Custom validation messages for meta fields shown in the UI.
*
* @return array<string, string>
*/
- public static function messages(): array
+ public static function messages(string $prefix = 'meta'): array
{
return [
- 'platforms.*.meta.link.url' => __('posts.form.pinterest.link_invalid'),
- 'platforms.*.meta.link.max' => __('posts.form.pinterest.link_max'),
- 'platforms.*.meta.title.max' => __('posts.form.pinterest.title_max'),
- 'platforms.*.meta.event.end_date.after_or_equal' => __('posts.form.google_business.event_end_date_before_start'),
- 'platforms.*.meta.event.title.max' => __('posts.form.google_business.title_max'),
+ "{$prefix}.link.url" => __('posts.form.pinterest.link_invalid'),
+ "{$prefix}.link.max" => __('posts.form.pinterest.link_max'),
+ "{$prefix}.title.max" => __('posts.form.pinterest.title_max'),
+ "{$prefix}.event.end_date.after_or_equal" => __('posts.form.google_business.event_end_date_before_start'),
+ "{$prefix}.event.title.max" => __('posts.form.google_business.title_max'),
];
}
/**
- * Friendly attribute names so default messages never expose `platforms.0.meta.*`.
+ * Friendly attribute names so default messages never expose raw meta keys.
*
* @return array<string, string>
*/
- public static function attributes(): array
+ public static function attributes(string $prefix = 'meta'): array
{
return [
- 'platforms.*.meta.title' => __('posts.form.pinterest.title'),
- 'platforms.*.meta.description' => __('posts.form.youtube.description'),
- 'platforms.*.meta.link' => __('posts.form.pinterest.link'),
- 'platforms.*.meta.event.title' => __('posts.form.google_business.event_title'),
- 'platforms.*.meta.call_to_action.url' => __('posts.form.google_business.cta_url'),
+ "{$prefix}.title" => __('posts.form.pinterest.title'),
+ "{$prefix}.description" => __('posts.form.youtube.description'),
+ "{$prefix}.link" => __('posts.form.pinterest.link'),
+ "{$prefix}.event.title" => __('posts.form.google_business.event_title'),
+ "{$prefix}.call_to_action.url" => __('posts.form.google_business.cta_url'),
];
}
@@ -253,66 +221,46 @@ class PostPlatformMetaRules
}
/**
- * Adds validation errors for per-platform meta that becomes mandatory once a
- * post is published or scheduled (TikTok privacy, Pinterest board, Discord
- * channel), based on the submitted request platforms. The caller resolves each
- * platform row to its Platform enum, since that lookup differs between create
- * (by social account) and update (by post platform).
- *
- * @param array<int, mixed> $platforms
- * @param callable(mixed, int): (Platform|SocialAccount|null) $resolvePlatform
+ * Adds the validation error for meta that becomes mandatory once a post is
+ * published or scheduled (TikTok privacy, Pinterest board, Discord channel).
*/
- public static function addRequiredOnPublishErrors(Validator $validator, array $platforms, callable $resolvePlatform): void
+ public static function addRequiredOnPublishErrors(Validator $validator, Platform|SocialAccount|null $target, mixed $meta, string $prefix = 'meta'): void
{
- foreach ($platforms as $index => $platform) {
- $violation = self::requiredMetaViolation($resolvePlatform($platform, $index), data_get($platform, 'meta'));
+ $violation = self::requiredMetaViolation($target, $meta);
- if ($violation !== null) {
- [$field, $message] = $violation;
- $key = "platforms.{$index}.meta.{$field}";
+ if (blank($violation)) {
+ return;
+ }
- if (! $validator->errors()->has($key)) {
- $validator->errors()->add($key, $message);
- }
- }
+ [$field, $message] = $violation;
+ $key = "{$prefix}.{$field}";
+
+ if (! $validator->errors()->has($key)) {
+ $validator->errors()->add($key, $message);
}
}
/**
- * Asserts that every ENABLED platform already stored on a post has the meta it
- * needs to publish. Used by entry points that publish a post's stored state
- * without resubmitting platforms (e.g. the MCP publish tool), so a misconfigured
- * post fails fast with a clear message instead of only at publish time.
- *
- * @param array<int, string> $platformIds Submitted order for indexed errors.
+ * Asserts that the post's stored meta is enough to publish. Used by entry
+ * points that publish a post's stored state without resubmitting it (e.g.
+ * the MCP publish tool), so a misconfigured post fails fast with a clear
+ * message instead of only at publish time.
*
* @throws ValidationException
*/
- public static function assertStoredPostPublishable(Post $post, array $platformIds = []): void
+ public static function assertStoredPostPublishable(Post $post): void
{
- $platforms = $post->postPlatforms()->enabled()->with('socialAccount')->get()->values();
-
- if ($platformIds !== []) {
- $platformsById = $platforms->keyBy('id');
- $platforms = collect($platformIds)
- ->map(fn (string $id): ?PostPlatform => $platformsById->get($id))
- ->filter();
+ if (! $post->hasDestination()) {
+ return;
}
- $errors = [];
+ $violation = self::requiredMetaViolation($post->socialAccount ?? $post->platform, $post->meta)
+ ?? self::contentMetaViolation($post->platform, $post->meta, (string) $post->content);
- foreach ($platforms as $index => $postPlatform) {
- $violation = self::requiredMetaViolation($postPlatform->socialAccount ?? $postPlatform->platform, $postPlatform->meta)
- ?? self::contentMetaViolation($postPlatform->platform, $postPlatform->meta, (string) $post->content);
-
- if ($violation !== null) {
- [$field, $message] = $violation;
- $errors["platforms.{$index}.meta.{$field}"] = $message;
- }
- }
+ if (filled($violation)) {
+ [$field, $message] = $violation;
- if ($errors !== []) {
- throw ValidationException::withMessages($errors);
+ throw ValidationException::withMessages(["meta.{$field}" => $message]);
}
}
diff --git a/app/Support/PostStatusRules.php b/app/Support/PostStatusRules.php
index b03b96fb0..dd28c65ed 100644
--- a/app/Support/PostStatusRules.php
+++ b/app/Support/PostStatusRules.php
@@ -30,7 +30,6 @@ class PostStatusRules
*/
private const EDIT_BLOCKED_STATUSES = [
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
PostStatus::Publishing,
];
@@ -43,7 +42,6 @@ class PostStatusRules
private const DELETE_BLOCKED_STATUSES = [
PostStatus::Publishing,
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
];
@@ -123,8 +121,8 @@ class PostStatusRules
*/
public static function assertStoredPostPublishable(Post $post): void
{
- if (! $post->postPlatforms()->enabled()->exists()) {
- throw ValidationException::withMessages(['platforms' => __('validation.required', ['attribute' => 'platforms'])]);
+ if (! $post->hasChannel()) {
+ throw ValidationException::withMessages(['social_account_id' => __('posts.errors.choose_channel')]);
}
PostPlatformMetaRules::assertStoredPostPublishable($post);
diff --git a/app/Support/Repurpose/DestinationMetaRules.php b/app/Support/Repurpose/DestinationMetaRules.php
index 6a72e4d54..57a7121fc 100644
--- a/app/Support/Repurpose/DestinationMetaRules.php
+++ b/app/Support/Repurpose/DestinationMetaRules.php
@@ -9,7 +9,6 @@ use App\Models\Repurpose;
use App\Models\SocialAccount;
use App\Support\PostPlatformMetaRules;
use Illuminate\Support\Facades\Validator as ValidatorFacade;
-use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Illuminate\Validation\Validator;
@@ -21,7 +20,7 @@ class DestinationMetaRules
public static function rules(): array
{
return [
- ...self::reKey(PostPlatformMetaRules::rules()),
+ ...PostPlatformMetaRules::rules('destinations.*.meta'),
'destinations.*.meta.thread_replies.*.media.*.url' => ['prohibited'],
];
}
@@ -31,7 +30,7 @@ class DestinationMetaRules
*/
public static function messages(): array
{
- return self::reKey(PostPlatformMetaRules::messages());
+ return PostPlatformMetaRules::messages('destinations.*.meta');
}
/**
@@ -39,7 +38,7 @@ class DestinationMetaRules
*/
public static function attributes(): array
{
- return self::reKey(PostPlatformMetaRules::attributes());
+ return PostPlatformMetaRules::attributes('destinations.*.meta');
}
public static function enforcedFor(Repurpose $repurpose): bool
@@ -86,23 +85,4 @@ class DestinationMetaRules
throw new ValidationException($validator);
}
}
-
- /**
- * @param array<string, mixed> $entries
- * @return array<string, mixed>
- */
- private static function reKey(array $entries): array
- {
- $destinations = [];
-
- foreach ($entries as $key => $entry) {
- if (! Str::startsWith($key, 'platforms.*.meta')) {
- continue;
- }
-
- $destinations[Str::replaceFirst('platforms.*.', 'destinations.*.', $key)] = $entry;
- }
-
- return $destinations;
- }
}
diff --git a/app/Support/Repurpose/RepurposeRules.php b/app/Support/Repurpose/RepurposeRules.php
index 8f2c6160f..361227243 100644
--- a/app/Support/Repurpose/RepurposeRules.php
+++ b/app/Support/Repurpose/RepurposeRules.php
@@ -66,7 +66,7 @@ class RepurposeRules
'required',
'string',
Rule::enum(ContentType::class),
- new ContentTypeMatchesPlatform,
+ new ContentTypeMatchesPlatform($workspaceId),
fn (string $attribute, mixed $value, callable $fail) => ContentType::tryFrom((string) $value)?->supportsVideo() === false
? $fail(__('repurposes.errors.destination_needs_video'))
: null,
diff --git a/app/Support/Requests/Post/PostRequestRules.php b/app/Support/Requests/Post/PostRequestRules.php
index 8ecb976bc..eba2959eb 100644
--- a/app/Support/Requests/Post/PostRequestRules.php
+++ b/app/Support/Requests/Post/PostRequestRules.php
@@ -8,18 +8,16 @@ use App\Enums\Post\QueuePosition;
use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Rules\ContentFitsPlatformLimits;
use App\Rules\ContentTypeCompatibleWithMedia;
use App\Rules\ContentTypeMatchesPlatform;
-use App\Rules\ContentTypeMatchesPostPlatform;
+use App\Rules\ContentTypeMatchesPostChannel;
use App\Rules\PostContentFitsMaxLength;
use App\Support\PostMediaRules;
use App\Support\PostPlatformMetaRules;
use App\Support\PostStatusRules;
-use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
@@ -40,7 +38,7 @@ class PostRequestRules
*/
public static function store(Workspace $workspace, array $input): array
{
- $platforms = (array) data_get($input, 'platforms', []);
+ $accounts = self::selectedAccounts($workspace, $input);
return [
'content' => [
@@ -50,26 +48,26 @@ class PostRequestRules
Rule::when(
in_array(data_get($input, 'status'), [Status::Scheduled->value, Status::Publishing->value], true),
[new ContentFitsPlatformLimits(
- self::selectedAccounts($workspace, $input),
- PostPlatformMetaRules::metaByKey($platforms, 'social_account_id'),
- PostPlatformMetaRules::contentTypesByKey($platforms, 'social_account_id'),
+ $accounts,
+ $accounts->map(fn (): array => (array) data_get($input, 'meta', []))->all(),
+ $accounts->map(fn (): mixed => data_get($input, 'content_type'))->all(),
)],
),
],
...PostMediaRules::rules(),
- 'platforms' => ['required', 'array', 'size:1'],
+ 'platforms' => ['prohibited'],
'status' => ['sometimes', 'string', Rule::in(self::STATUSES)],
- 'platforms.*.social_account_id' => [
+ 'social_account_id' => [
'required',
'uuid',
Rule::exists('social_accounts', 'id')->where('workspace_id', $workspace->id),
],
- 'platforms.*.content_type' => [
+ 'content_type' => [
'sometimes',
'nullable',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
- new ContentTypeMatchesPlatform,
+ new ContentTypeMatchesPlatform($workspace->id),
],
...PostPlatformMetaRules::rules(),
'scheduled_at' => ['nullable', 'date', 'after:now', 'before:2038-01-19'],
@@ -105,15 +103,13 @@ class PostRequestRules
}
/**
- * Expects the input already passed through updateInput().
- *
* @param array<string, mixed> $input
* @return array<string, mixed>
*/
public static function update(Workspace $workspace, Post $post, array $input): array
{
$status = data_get($input, 'status');
- $platforms = (array) data_get($input, 'platforms', []);
+ $target = $post->socialAccount ?? $post->platform;
return [
'status' => ['sometimes', 'string', Rule::in(self::STATUSES)],
@@ -124,23 +120,20 @@ class PostRequestRules
Rule::when(
in_array($status, [Status::Scheduled->value, Status::Publishing->value], true),
[new ContentFitsPlatformLimits(
- self::submittedTargets($post, $input),
- PostPlatformMetaRules::metaByKey($platforms, 'id'),
- PostPlatformMetaRules::contentTypesByKey($platforms, 'id', self::storedContentTypes($post)),
+ collect(filled($target) ? ['post' => $target] : []),
+ ['post' => self::effectiveMeta($post, $input)],
+ ['post' => data_get($input, 'content_type') ?? $post->content_type?->value],
)],
),
],
...PostMediaRules::rules(),
'social_account_id' => ['prohibited'],
- 'content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],
- 'meta' => ['sometimes', 'array'],
- 'platforms' => ['sometimes', 'array'],
- 'platforms.*.id' => ['required', 'uuid', Rule::exists('post_platforms', 'id')->where('post_id', $post->id)->where('enabled', true)],
- 'platforms.*.content_type' => [
+ 'platforms' => ['prohibited'],
+ 'content_type' => [
'sometimes',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
- new ContentTypeMatchesPostPlatform,
+ new ContentTypeMatchesPostChannel($post),
],
...PostPlatformMetaRules::rules(),
'scheduled_at' => PostStatusRules::scheduledAtRules($post, $status, filled(data_get($input, 'queue'))),
@@ -161,32 +154,6 @@ class PostRequestRules
];
}
- /**
- * The flat `content_type` / `meta` of a single-channel post rewritten as
- * `platforms[0]` for its enabled destination, so both input shapes are
- * validated by the same per-platform rules and report the same keys.
- *
- * @param array<string, mixed> $input
- * @return array<string, mixed>
- */
- public static function updateInput(Post $post, array $input): array
- {
- if (array_key_exists('platforms', $input) || ! Arr::hasAny($input, ['content_type', 'meta'])) {
- return $input;
- }
-
- $targets = $post->postPlatforms()->enabled()->pluck('id');
-
- if ($targets->count() !== 1) {
- return $input;
- }
-
- return [
- ...Arr::except($input, ['content_type', 'meta']),
- 'platforms' => [['id' => $targets->sole(), ...Arr::only($input, ['content_type', 'meta'])]],
- ];
- }
-
/**
* Required-on-publish meta and media compatibility checks of an update
* that schedules or publishes, run after the field rules.
@@ -201,37 +168,25 @@ class PostRequestRules
self::addMediaCompatibilityErrors($validator, $post, $input);
- $targets = self::submittedTargets($post, $input);
-
- PostPlatformMetaRules::addRequiredOnPublishErrors(
- $validator,
- (array) data_get($input, 'platforms', []),
- fn (mixed $platform) => $targets[data_get($platform, 'id')] ?? null,
- );
+ if (array_key_exists('meta', $input)) {
+ PostPlatformMetaRules::addRequiredOnPublishErrors($validator, $post->socialAccount ?? $post->platform, self::effectiveMeta($post, $input));
+ }
}
/**
- * The workspace accounts chosen in `platforms[].social_account_id`, keyed by id.
+ * The workspace account chosen in `social_account_id`, keyed by id. A
+ * malformed id never reaches the query, which PostgreSQL would reject.
*
* @param array<string, mixed> $input
* @return Collection<string, SocialAccount>
*/
public static function selectedAccounts(Workspace $workspace, array $input): Collection
{
- $accountIds = collect((array) data_get($input, 'platforms', []))
- ->pluck('social_account_id')
- ->filter(fn (mixed $id): bool => is_string($id) && Str::isUuid($id))
- ->all();
+ $accountId = data_get($input, 'social_account_id');
- if ($accountIds === []) {
- return collect();
- }
-
- return SocialAccount::query()
- ->where('workspace_id', $workspace->id)
- ->whereIn('id', $accountIds)
- ->get()
- ->keyBy('id');
+ return Str::isUuid($accountId)
+ ? $workspace->socialAccounts()->whereKey($accountId)->get()->keyBy('id')
+ : collect();
}
/**
@@ -273,7 +228,7 @@ class PostRequestRules
*/
private static function addMediaCompatibilityErrors(Validator $validator, Post $post, array $input): void
{
- if (filled(data_get($input, 'content_type')) && ! array_key_exists('platforms', $input)) {
+ if (filled(data_get($input, 'content_type'))) {
return;
}
@@ -281,7 +236,7 @@ class PostRequestRules
$entries = ContentTypeCompatibleWithMedia::entriesForUpdate(
$post,
- array_key_exists('platforms', $input) ? (array) data_get($input, 'platforms', []) : null,
+ null,
array_key_exists('media', $input) ? $media : null,
);
@@ -291,39 +246,13 @@ class PostRequestRules
}
/**
- * The post's destinations named in `platforms[].id`, each resolved to its
- * account (or its platform when the account is gone), keyed by id.
+ * The meta the update would store: the submitted keys over the stored ones.
*
* @param array<string, mixed> $input
- * @return Collection<string, mixed>
- */
- private static function submittedTargets(Post $post, array $input): Collection
- {
- $ids = collect((array) data_get($input, 'platforms', []))
- ->pluck('id')
- ->filter(fn (mixed $id): bool => is_string($id) && Str::isUuid($id))
- ->all();
-
- if ($ids === []) {
- return collect();
- }
-
- return $post->postPlatforms()
- ->whereIn('id', $ids)
- ->with('socialAccount')
- ->get()
- ->mapWithKeys(fn (PostPlatform $postPlatform): array => [
- $postPlatform->id => $postPlatform->socialAccount ?? $postPlatform->platform,
- ]);
- }
-
- /**
- * @return array<string, string|null>
+ * @return array<string, mixed>
*/
- private static function storedContentTypes(Post $post): array
+ private static function effectiveMeta(Post $post, array $input): array
{
- return $post->postPlatforms()->pluck('content_type', 'id')
- ->map(fn (?ContentType $contentType): ?string => $contentType?->value)
- ->all();
+ return [...($post->meta ?? []), ...(array) data_get($input, 'meta', [])];
}
}
diff --git a/app/Support/Social/AbandonGoogleBusinessReview.php b/app/Support/Social/AbandonGoogleBusinessReview.php
deleted file mode 100644
index 948f91c33..000000000
--- a/app/Support/Social/AbandonGoogleBusinessReview.php
+++ /dev/null
@@ -1,37 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace App\Support\Social;
-
-use App\Actions\Post\FinalizePostPublication;
-use App\Enums\PostPlatform\Status;
-use App\Events\PostPlatformStatusUpdated;
-use App\Models\PostPlatform;
-
-/**
- * Stops waiting on a Google Business review we can no longer settle remotely
- * (disconnected account, switched-off target, recover sweep). Rejects the
- * row, prunes the JPEG, and lets FinalizePostPublication close the parent.
- */
-class AbandonGoogleBusinessReview
-{
- /**
- * @param array<string, mixed> $errorContext
- */
- public static function execute(PostPlatform $postPlatform, string $errorMessage, array $errorContext = []): void
- {
- if ($postPlatform->status === Status::PendingReview) {
- $postPlatform->markAsRejected(
- (string) $postPlatform->platform_post_id,
- $postPlatform->platform_url,
- $errorMessage,
- $errorContext,
- );
- }
-
- app(GoogleBusinessDerivativeCleaner::class)->cleanup($postPlatform->id);
- app(FinalizePostPublication::class)->handle($postPlatform->post);
- PostPlatformStatusUpdated::dispatch($postPlatform->fresh());
- }
-}
diff --git a/app/Support/Social/GoogleBusinessDerivativeCleaner.php b/app/Support/Social/GoogleBusinessDerivativeCleaner.php
index 0148d8599..6ba9c6210 100644
--- a/app/Support/Social/GoogleBusinessDerivativeCleaner.php
+++ b/app/Support/Social/GoogleBusinessDerivativeCleaner.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
namespace App\Support\Social;
+use App\Models\Post;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Throwable;
@@ -12,20 +13,23 @@ class GoogleBusinessDerivativeCleaner
{
public const string DIRECTORY = 'google-business-derivatives';
- public static function pathFor(string $postPlatformId): string
+ /**
+ * The JPEG is named after the post.
+ */
+ public static function pathFor(Post $post): string
{
- return self::DIRECTORY."/{$postPlatformId}.jpg";
+ return self::DIRECTORY."/{$post->id}.jpg";
}
- public function cleanup(string $postPlatformId): void
+ public function cleanup(Post $post): void
{
- $path = self::pathFor($postPlatformId);
+ $path = self::pathFor($post);
try {
Storage::delete($path);
} catch (Throwable $e) {
Log::warning('Failed to prune Google Business Profile image derivative', [
- 'post_platform_id' => $postPlatformId,
+ 'post_id' => $post->id,
'path' => $path,
'error' => $e->getMessage(),
]);
diff --git a/app/Support/Social/PublishCheckpoint.php b/app/Support/Social/PublishCheckpoint.php
index fa11a4954..773bf7cb4 100644
--- a/app/Support/Social/PublishCheckpoint.php
+++ b/app/Support/Social/PublishCheckpoint.php
@@ -6,7 +6,7 @@ namespace App\Support\Social;
/**
* Shared keys and readers for in-flight publish checkpoints on
- * PostPlatform.error_context. Used by the publishers, the TikTok
+ * posts.error_context. Used by the publishers, the TikTok
* derivative cleaner, and posts:retry.
*/
final class PublishCheckpoint
diff --git a/app/Support/Social/ThreadProgress.php b/app/Support/Social/ThreadProgress.php
index 302878a49..012dbba6f 100644
--- a/app/Support/Social/ThreadProgress.php
+++ b/app/Support/Social/ThreadProgress.php
@@ -4,12 +4,12 @@ declare(strict_types=1);
namespace App\Support\Social;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Support\ThreadReplies;
/**
* Segments of a thread already live on the network, kept in
- * PostPlatform.error_context so any retry resumes instead of re-posting.
+ * posts.error_context so any retry resumes instead of re-posting.
*/
final class ThreadProgress
{
@@ -42,10 +42,10 @@ final class ThreadProgress
*
* @param array<string, mixed>|null $context
*/
- public static function failureMessage(PostPlatform $postPlatform, string $message, ?array $context): string
+ public static function failureMessage(Post $post, string $message, ?array $context): string
{
$published = count((array) data_get($context, self::KEY, []));
- $total = 1 + (ThreadReplies::supports($postPlatform->platform) ? count(ThreadReplies::of($postPlatform->meta)) : 0);
+ $total = 1 + (ThreadReplies::supports($post->platform) ? count(ThreadReplies::of($post->meta)) : 0);
return $published > 0 && $published < $total
? __('posts.errors.thread_incomplete', ['published' => $published, 'total' => $total, 'error' => $message])
@@ -78,10 +78,10 @@ final class ThreadProgress
/**
* @param list<array<string, mixed>> $posted
*/
- public static function remember(PostPlatform $postPlatform, array $posted): void
+ public static function remember(Post $post, array $posted): void
{
- $postPlatform->forceFill([
- 'error_context' => [...($postPlatform->error_context ?? []), self::KEY => $posted],
- ])->save();
+ $post->writePublication([
+ 'error_context' => [...($post->error_context ?? []), self::KEY => $posted],
+ ]);
}
}
diff --git a/app/Support/Social/TikTokPhotoDerivativeCleaner.php b/app/Support/Social/TikTokPhotoDerivativeCleaner.php
index 1ff2e4af3..37ed7663b 100644
--- a/app/Support/Social/TikTokPhotoDerivativeCleaner.php
+++ b/app/Support/Social/TikTokPhotoDerivativeCleaner.php
@@ -16,9 +16,9 @@ class TikTokPhotoDerivativeCleaner
/**
* @param array<string, mixed>|null $context
*/
- public function cleanup(?array $context, ?string $postPlatformId = null): void
+ public function cleanup(?array $context, ?string $postId = null): void
{
- $this->cleanupPaths(PublishCheckpoint::tiktokDerivativePaths($context), $postPlatformId);
+ $this->cleanupPaths(PublishCheckpoint::tiktokDerivativePaths($context), $postId);
}
/**
@@ -26,19 +26,19 @@ class TikTokPhotoDerivativeCleaner
*
* @param array<string, mixed>|null $context
*/
- public function cleanupUnlessPublishInFlight(?array $context, ?string $postPlatformId = null): void
+ public function cleanupUnlessPublishInFlight(?array $context, ?string $postId = null): void
{
if (PublishCheckpoint::tiktokPublishId($context) !== null) {
return;
}
- $this->cleanup($context, $postPlatformId);
+ $this->cleanup($context, $postId);
}
/**
* @param array<array-key, mixed> $paths
*/
- public function cleanupPaths(array $paths, ?string $postPlatformId = null): void
+ public function cleanupPaths(array $paths, ?string $postId = null): void
{
$derivativePaths = array_values(array_filter(
$paths,
@@ -53,7 +53,7 @@ class TikTokPhotoDerivativeCleaner
Storage::delete($derivativePaths);
} catch (Throwable $e) {
Log::warning('Failed to prune TikTok photo derivatives', [
- 'post_platform_id' => $postPlatformId,
+ 'post_id' => $postId,
'error' => $e->getMessage(),
]);
}
diff --git a/config/trypost.php b/config/trypost.php
index 8c8d0f80b..a682d06aa 100644
--- a/config/trypost.php
+++ b/config/trypost.php
@@ -176,7 +176,7 @@ return [
| Post history retention
|--------------------------------------------------------------------------
|
- | Published and partially published posts older than this many days are
+ | Published posts older than this many days are
| deleted with their media by posts:prune-history. Must be 1 or more.
|
*/
diff --git a/database/factories/AnalyticsPublicationFactory.php b/database/factories/AnalyticsPublicationFactory.php
index afd31c296..bb9536075 100644
--- a/database/factories/AnalyticsPublicationFactory.php
+++ b/database/factories/AnalyticsPublicationFactory.php
@@ -28,7 +28,7 @@ class AnalyticsPublicationFactory extends Factory
'workspace_id' => Workspace::factory(),
'social_account_id' => null,
'social_account_key' => fake()->uuid(),
- 'post_platform_id' => null,
+ 'post_id' => null,
'network' => Platform::Instagram->network(),
'platform_user_id' => fake()->uuid(),
'platform' => Platform::Instagram,
diff --git a/database/factories/PostFactory.php b/database/factories/PostFactory.php
index 911e146f6..61e6ed4e1 100644
--- a/database/factories/PostFactory.php
+++ b/database/factories/PostFactory.php
@@ -5,14 +5,23 @@ declare(strict_types=1);
namespace Database\Factories;
use App\Enums\Post\Origin;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
+use App\Enums\PostPlatform\ContentType;
+use App\Enums\SocialAccount\Platform;
+use App\Enums\TikTok\PrivacyLevel;
use App\Models\Post;
+use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
+ * A post without a channel is a draft that was never sent anywhere. Use
+ * forAccount() or a network state (linkedin(), x(), ...) for a post with a
+ * channel; a network state creates the channel in the post's workspace.
+ *
* @extends Factory<Post>
*/
class PostFactory extends Factory
@@ -33,6 +42,17 @@ class PostFactory extends Factory
];
}
+ public function forAccount(SocialAccount $account, ?ContentType $contentType = null): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'workspace_id' => $account->workspace_id,
+ 'social_account_id' => $account->id,
+ 'platform' => $account->platform,
+ 'content_type' => $contentType ?? ContentType::defaultFor($account->platform),
+ 'meta' => $attributes['meta'] ?? [],
+ ]);
+ }
+
public function draft(): static
{
return $this->state(fn (array $attributes) => [
@@ -59,10 +79,21 @@ class PostFactory extends Factory
]);
}
+ public function publishing(): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => PublishStatus::Publishing,
+ ]);
+ }
+
public function published(): static
{
return $this->state(fn (array $attributes) => [
'status' => PostStatus::Published,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => $this->faker->uuid(),
+ 'platform_url' => $this->faker->url(),
'published_at' => now(),
]);
}
@@ -73,6 +104,8 @@ class PostFactory extends Factory
'origin' => Origin::Network,
'user_id' => null,
'status' => PostStatus::Published,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => $this->faker->uuid(),
'published_at' => now(),
]);
}
@@ -81,6 +114,117 @@ class PostFactory extends Factory
{
return $this->state(fn (array $attributes) => [
'status' => PostStatus::Failed,
+ 'publish_status' => PublishStatus::Failed,
+ 'error_message' => 'Failed to publish',
+ ]);
+ }
+
+ public function pendingReview(): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => PublishStatus::PendingReview,
+ 'submitted_at' => now(),
+ ]);
+ }
+
+ public function linkedin(): static
+ {
+ return $this->onNetwork(Platform::LinkedIn, ContentType::LinkedInPost, 'linkedin');
+ }
+
+ public function x(): static
+ {
+ return $this->onNetwork(Platform::X, ContentType::XPost, 'x');
+ }
+
+ public function instagram(): static
+ {
+ return $this->onNetwork(Platform::Instagram, ContentType::InstagramFeed, 'instagram');
+ }
+
+ public function bluesky(): static
+ {
+ return $this->onNetwork(Platform::Bluesky, ContentType::BlueskyPost, 'bluesky');
+ }
+
+ public function mastodon(): static
+ {
+ return $this->onNetwork(Platform::Mastodon, ContentType::MastodonPost, 'mastodon');
+ }
+
+ public function threads(): static
+ {
+ return $this->onNetwork(Platform::Threads, ContentType::ThreadsPost, 'threads');
+ }
+
+ public function tiktok(): static
+ {
+ return $this->onNetwork(Platform::TikTok, ContentType::TikTokVideo, 'tiktok', ['privacy_level' => PrivacyLevel::SelfOnly->value]);
+ }
+
+ public function youtube(): static
+ {
+ return $this->onNetwork(Platform::YouTube, ContentType::YouTubeShort, 'youtube');
+ }
+
+ public function pinterest(): static
+ {
+ return $this->onNetwork(Platform::Pinterest, ContentType::PinterestPin, 'pinterest');
+ }
+
+ public function pinterestVideoPin(): static
+ {
+ return $this->onNetwork(Platform::Pinterest, ContentType::PinterestVideoPin, 'pinterest');
+ }
+
+ public function pinterestCarousel(): static
+ {
+ return $this->onNetwork(Platform::Pinterest, ContentType::PinterestCarousel, 'pinterest');
+ }
+
+ public function googleBusiness(): static
+ {
+ return $this->onNetwork(Platform::GoogleBusiness, ContentType::GoogleBusinessPost, 'googleBusiness');
+ }
+
+ public function facebook(): static
+ {
+ return $this->onNetwork(Platform::Facebook, ContentType::FacebookPost, 'facebook');
+ }
+
+ public function facebookReel(): static
+ {
+ return $this->onNetwork(Platform::Facebook, ContentType::FacebookReel, 'facebook');
+ }
+
+ public function facebookStory(): static
+ {
+ return $this->onNetwork(Platform::Facebook, ContentType::FacebookStory, 'facebook');
+ }
+
+ public function discord(): static
+ {
+ return $this->onNetwork(Platform::Discord, ContentType::DiscordMessage, 'discord');
+ }
+
+ public function telegram(): static
+ {
+ return $this->onNetwork(Platform::Telegram, ContentType::defaultFor(Platform::Telegram), 'telegram');
+ }
+
+ /**
+ * @param array<string, mixed> $meta
+ */
+ private function onNetwork(Platform $platform, ContentType $contentType, string $accountState, array $meta = []): static
+ {
+ return $this->state(fn (array $attributes) => [
+ 'platform' => $platform,
+ 'content_type' => $contentType,
+ 'meta' => [...$meta, ...($attributes['meta'] ?? [])],
+ 'social_account_id' => isset($attributes['social_account_id'])
+ ? $attributes['social_account_id']
+ : fn (array $resolved) => SocialAccount::factory()->{$accountState}()->state(['workspace_id' => $resolved['workspace_id']]),
]);
}
}
diff --git a/database/factories/PostPlatformFactory.php b/database/factories/PostPlatformFactory.php
deleted file mode 100644
index 72da643ee..000000000
--- a/database/factories/PostPlatformFactory.php
+++ /dev/null
@@ -1,198 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-namespace Database\Factories;
-
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
-use App\Enums\SocialAccount\Platform;
-use App\Enums\TikTok\PrivacyLevel;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use Illuminate\Database\Eloquent\Factories\Factory;
-
-/**
- * @extends Factory<PostPlatform>
- */
-class PostPlatformFactory extends Factory
-{
- /**
- * Define the model's default state.
- *
- * @return array<string, mixed>
- */
- public function definition(): array
- {
- return [
- 'post_id' => Post::factory(),
- 'social_account_id' => SocialAccount::factory(),
- 'enabled' => true,
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'status' => Status::Pending,
- 'meta' => [],
- ];
- }
-
- public function disabled(): static
- {
- return $this->state(fn (array $attributes) => [
- 'enabled' => false,
- ]);
- }
-
- public function published(): static
- {
- return $this->state(fn (array $attributes) => [
- 'status' => Status::Published,
- 'platform_post_id' => $this->faker->uuid(),
- 'platform_url' => $this->faker->url(),
- 'published_at' => now(),
- ]);
- }
-
- public function failed(): static
- {
- return $this->state(fn (array $attributes) => [
- 'status' => Status::Failed,
- 'error_message' => 'Failed to publish',
- ]);
- }
-
- public function pendingReview(): static
- {
- return $this->state(fn (array $attributes) => [
- 'status' => Status::PendingReview,
- 'submitted_at' => now(),
- ]);
- }
-
- public function linkedin(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::LinkedIn,
- ]);
- }
-
- public function x(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- ]);
- }
-
- public function instagram(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Instagram,
- ]);
- }
-
- public function bluesky(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Bluesky,
- 'content_type' => ContentType::BlueskyPost,
- ]);
- }
-
- public function mastodon(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Mastodon,
- 'content_type' => ContentType::MastodonPost,
- ]);
- }
-
- public function threads(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Threads,
- 'content_type' => ContentType::ThreadsPost,
- ]);
- }
-
- public function tiktok(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
- 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
- ]);
- }
-
- public function youtube(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::YouTube,
- 'content_type' => ContentType::YouTubeShort,
- ]);
- }
-
- public function pinterest(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Pinterest,
- 'content_type' => ContentType::PinterestPin,
- ]);
- }
-
- public function googleBusiness(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::GoogleBusiness,
- 'content_type' => ContentType::GoogleBusinessPost,
- ]);
- }
-
- public function pinterestVideoPin(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Pinterest,
- 'content_type' => ContentType::PinterestVideoPin,
- ]);
- }
-
- public function pinterestCarousel(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Pinterest,
- 'content_type' => ContentType::PinterestCarousel,
- ]);
- }
-
- public function facebook(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Facebook,
- 'content_type' => ContentType::FacebookPost,
- ]);
- }
-
- public function discord(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Discord,
- 'content_type' => ContentType::DiscordMessage,
- ]);
- }
-
- public function facebookReel(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Facebook,
- 'content_type' => ContentType::FacebookReel,
- ]);
- }
-
- public function facebookStory(): static
- {
- return $this->state(fn (array $attributes) => [
- 'platform' => Platform::Facebook,
- 'content_type' => ContentType::FacebookStory,
- ]);
- }
-}
diff --git a/database/migrations/2026_10_08_222940_prepare_post_platforms_for_merge_into_posts.php b/database/migrations/2026_10_08_222940_prepare_post_platforms_for_merge_into_posts.php
new file mode 100644
index 000000000..f4d1368ad
--- /dev/null
+++ b/database/migrations/2026_10_08_222940_prepare_post_platforms_for_merge_into_posts.php
@@ -0,0 +1,162 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Storage;
+
+return new class extends Migration
+{
+ /**
+ * Every post gets exactly one destination before `post_platforms` is
+ * folded into `posts`. The legacy rows TryPost 2.0's split left behind
+ * are resolved here; anything that still needs a person stops the
+ * upgrade before a single column is added.
+ *
+ * - A destination whose account is gone is dropped: its channel no longer
+ * exists, and disconnecting a channel deletes its posts.
+ * - A disabled destination that never published is dropped: the column
+ * goes away and a backfill must never promote it to the post's channel.
+ * - A post left without any destination becomes a draft (its content is
+ * kept and can be recovered from the composer). A published one is a
+ * history whose channel no longer exists: it is deleted with its media,
+ * quietly, as disconnecting a channel deletes its posts.
+ * - A partially published post with one destination left takes that
+ * destination's outcome, as the split settles it.
+ */
+ public function up(): void
+ {
+ DB::transaction(function (): void {
+ DB::table('post_platforms')->whereNull('social_account_id')->delete();
+
+ DB::table('post_platforms')
+ ->where('enabled', false)
+ ->where('status', '!=', 'published')
+ ->delete();
+
+ $this->settlePartiallyPublishedPosts();
+ $this->turnPostsWithoutDestinationIntoDrafts();
+ $this->deletePublishedPostsWithoutDestination();
+ $this->assertEveryPostHasOneDestination();
+ });
+ }
+
+ private function settlePartiallyPublishedPosts(): void
+ {
+ DB::table('posts')
+ ->where('status', 'partially_published')
+ ->whereIn('id', $this->postsWithTargets(exactly: 1))
+ ->select('id')
+ ->chunkById(500, function (Collection $posts): void {
+ foreach ($posts as $post) {
+ $target = DB::table('post_platforms')->where('post_id', $post->id)->first(['status', 'published_at']);
+
+ $status = match ($target?->status) {
+ 'published' => 'published',
+ 'failed', 'rejected' => 'failed',
+ default => null,
+ };
+
+ if ($status === null) {
+ continue;
+ }
+
+ DB::table('posts')->where('id', $post->id)->update([
+ 'status' => $status,
+ 'published_at' => $target->published_at,
+ ]);
+ }
+ });
+ }
+
+ private function turnPostsWithoutDestinationIntoDrafts(): void
+ {
+ DB::table('posts')
+ ->whereIn('status', ['scheduled', 'pending_approval', 'publishing', 'failed'])
+ ->whereNotIn('id', DB::table('post_platforms')->select('post_id'))
+ ->update([
+ 'status' => 'draft',
+ 'schedule_mode' => null,
+ 'published_at' => null,
+ 'approval_requested_at' => null,
+ 'approval_requested_by' => null,
+ 'approval_queue_position' => null,
+ 'recurrence_interval' => null,
+ 'recurrence_frequency' => null,
+ 'recurrence_remaining' => null,
+ 'recurrence_anchor_at' => null,
+ 'recurrence_origin_at' => null,
+ ]);
+ }
+
+ private function deletePublishedPostsWithoutDestination(): void
+ {
+ $postIds = DB::table('posts')
+ ->whereIn('status', ['published', 'partially_published'])
+ ->whereNotIn('id', DB::table('post_platforms')->select('post_id'))
+ ->orderBy('id')
+ ->pluck('id')
+ ->all();
+
+ $paths = [];
+
+ foreach (array_chunk($postIds, 500) as $chunk) {
+ array_push($paths, ...DB::table('medias')->whereIn('post_id', $chunk)->pluck('path')->all());
+ DB::table('medias')->whereIn('post_id', $chunk)->delete();
+ DB::table('posts')->whereIn('id', $chunk)->delete();
+ }
+
+ DB::afterCommit(fn () => $this->deleteUnreferencedFiles(array_values(array_unique(array_filter($paths)))));
+ }
+
+ /**
+ * Files are removed only after the deletion commits, and only when no
+ * other media row still points at them.
+ *
+ * @param list<string> $paths
+ */
+ private function deleteUnreferencedFiles(array $paths): void
+ {
+ foreach (array_chunk($paths, 500) as $chunk) {
+ $referenced = DB::table('medias')->whereIn('path', $chunk)->distinct()->pluck('path')->all();
+
+ foreach (array_diff($chunk, $referenced) as $path) {
+ rescue(fn (): bool => Storage::delete($path), report: false);
+ }
+ }
+ }
+
+ private function assertEveryPostHasOneDestination(): void
+ {
+ $blockers = array_filter([
+ 'posts with more than one destination' => DB::table('posts')->whereIn('id', $this->postsWithTargets(moreThan: 1))->count(),
+ 'disabled destinations that published' => DB::table('post_platforms')->where('enabled', false)->count(),
+ 'partially published posts with a destination still in flight' => DB::table('posts')->where('status', 'partially_published')->count(),
+ 'destinations whose account belongs to another workspace' => DB::table('post_platforms')
+ ->join('posts', 'posts.id', '=', 'post_platforms.post_id')
+ ->join('social_accounts', 'social_accounts.id', '=', 'post_platforms.social_account_id')
+ ->whereColumn('social_accounts.workspace_id', '!=', 'posts.workspace_id')
+ ->count(),
+ ]);
+
+ if ($blockers === []) {
+ return;
+ }
+
+ $found = collect($blockers)->map(fn (int $count, string $what): string => "{$count} {$what}")->implode(', ');
+
+ throw new RuntimeException("Posts cannot be merged with their destinations yet ({$found}). Upgrade to TryPost v2.0.0 and run `php artisan release:trypost-2` first; fix any row it leaves by hand (in flight destinations settle on their own), then run the migrations again.");
+ }
+
+ private function postsWithTargets(?int $exactly = null, ?int $moreThan = null): Builder
+ {
+ return DB::table('post_platforms')
+ ->select('post_id')
+ ->groupBy('post_id')
+ ->when($exactly !== null, fn (Builder $query) => $query->havingRaw('count(*) = ?', [$exactly]))
+ ->when($moreThan !== null, fn (Builder $query) => $query->havingRaw('count(*) > ?', [$moreThan]));
+ }
+};
diff --git a/database/migrations/2026_10_08_222942_add_target_columns_to_posts_table.php b/database/migrations/2026_10_08_222942_add_target_columns_to_posts_table.php
new file mode 100644
index 000000000..e6ba9af1e
--- /dev/null
+++ b/database/migrations/2026_10_08_222942_add_target_columns_to_posts_table.php
@@ -0,0 +1,96 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\PublishStatus;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ Schema::table('posts', function (Blueprint $table): void {
+ $table->uuid('social_account_id')->nullable();
+ $table->string('publish_status')->default(PublishStatus::DEFAULT->value);
+ $table->string('platform')->nullable();
+ $table->string('content_type')->nullable();
+ $table->string('platform_name')->nullable();
+ $table->string('platform_username')->nullable();
+ $table->text('platform_avatar')->nullable();
+ $table->json('meta')->nullable();
+ $table->string('platform_post_id')->nullable();
+ $table->text('platform_url')->nullable();
+ $table->text('error_message')->nullable();
+ $table->json('error_context')->nullable();
+ $table->json('thread_reply_ids')->nullable();
+ $table->timestamp('submitted_at')->nullable();
+ $table->timestamp('last_reconciled_at')->nullable();
+ $table->timestamp('connection_warning_sent_at')->nullable();
+ $table->timestamp('retry_at')->nullable();
+ $table->timestamp('publication_updated_at')->nullable();
+ $table->boolean('scheduled_before_media_checks')->default(false);
+
+ $table->index(['social_account_id', 'status', 'scheduled_at']);
+ $table->index(['social_account_id', 'publish_status', 'published_at']);
+ $table->index(['social_account_id', 'platform_post_id']);
+ $table->index('platform_post_id');
+ $table->index(['publish_status', 'last_reconciled_at']);
+ $table->index(['publish_status', 'retry_at']);
+ $table->index(['workspace_id', 'publish_status', 'published_at']);
+ });
+
+ Schema::table('posts', function (Blueprint $table): void {
+ $table->foreign('social_account_id')->references('id')->on('social_accounts')->nullOnDelete();
+ });
+
+ Schema::table('analytics_publications', function (Blueprint $table): void {
+ $table->foreignUuid('post_id')->nullable()->unique()->constrained()->nullOnDelete();
+ });
+ }
+
+ public function down(): void
+ {
+ Schema::table('analytics_publications', function (Blueprint $table): void {
+ $table->dropForeign(['post_id']);
+ $table->dropUnique(['post_id']);
+ $table->dropColumn('post_id');
+ });
+
+ Schema::table('posts', function (Blueprint $table): void {
+ $table->dropForeign(['social_account_id']);
+ });
+
+ Schema::table('posts', function (Blueprint $table): void {
+ $table->dropIndex(['social_account_id', 'status', 'scheduled_at']);
+ $table->dropIndex(['social_account_id', 'publish_status', 'published_at']);
+ $table->dropIndex(['social_account_id', 'platform_post_id']);
+ $table->dropIndex(['platform_post_id']);
+ $table->dropIndex(['publish_status', 'last_reconciled_at']);
+ $table->dropIndex(['publish_status', 'retry_at']);
+ $table->dropIndex(['workspace_id', 'publish_status', 'published_at']);
+ $table->dropColumn([
+ 'social_account_id',
+ 'publish_status',
+ 'platform',
+ 'content_type',
+ 'platform_name',
+ 'platform_username',
+ 'platform_avatar',
+ 'meta',
+ 'platform_post_id',
+ 'platform_url',
+ 'error_message',
+ 'error_context',
+ 'thread_reply_ids',
+ 'submitted_at',
+ 'last_reconciled_at',
+ 'connection_warning_sent_at',
+ 'retry_at',
+ 'publication_updated_at',
+ 'scheduled_before_media_checks',
+ ]);
+ });
+ }
+};
diff --git a/database/migrations/2026_10_08_222943_backfill_posts_from_post_platforms.php b/database/migrations/2026_10_08_222943_backfill_posts_from_post_platforms.php
new file mode 100644
index 000000000..1c72f6b22
--- /dev/null
+++ b/database/migrations/2026_10_08_222943_backfill_posts_from_post_platforms.php
@@ -0,0 +1,215 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\DB;
+
+return new class extends Migration
+{
+ public $withinTransaction = false;
+
+ private const array TARGET_COLUMNS = [
+ 'social_account_id',
+ 'platform',
+ 'content_type',
+ 'platform_name',
+ 'platform_username',
+ 'platform_avatar',
+ 'meta',
+ 'platform_post_id',
+ 'platform_url',
+ 'error_message',
+ 'error_context',
+ 'thread_reply_ids',
+ 'submitted_at',
+ 'last_reconciled_at',
+ 'connection_warning_sent_at',
+ 'retry_at',
+ 'scheduled_before_media_checks',
+ ];
+
+ private const array JSON_COLUMNS = ['meta', 'error_context', 'thread_reply_ids'];
+
+ /**
+ * Copies each post's single destination onto the post. Each chunk commits
+ * on its own and every row is overwritten, so the migration can run again
+ * after a failure. `posts.updated_at` is left as it was.
+ */
+ public function up(): void
+ {
+ $unresolved = DB::table('post_platforms')->where(fn (Builder $query) => $query->where('enabled', false)->orWhereNull('social_account_id'))->count();
+
+ if ($unresolved > 0) {
+ throw new RuntimeException("{$unresolved} destinations are switched off or lost their channel; roll back and run the migrations again from 2026_10_08_222940.");
+ }
+
+ $this->clearCopiesOfVanishedTargets();
+ $this->copyTargets();
+ $this->linkAnalyticsPublications();
+ $this->assertParity();
+ $this->replacePartiallyPublishedWebhookEvent();
+ }
+
+ private function clearCopiesOfVanishedTargets(): void
+ {
+ DB::table('posts')
+ ->whereNotNull('platform')
+ ->whereNotIn('id', DB::table('post_platforms')->select('post_id'))
+ ->update([
+ ...array_fill_keys(self::TARGET_COLUMNS, null),
+ 'scheduled_before_media_checks' => false,
+ 'publish_status' => 'pending',
+ 'publication_updated_at' => null,
+ ]);
+ }
+
+ private function copyTargets(): void
+ {
+ DB::table('post_platforms')
+ ->join('posts', 'posts.id', '=', 'post_platforms.post_id')
+ ->select([
+ 'post_platforms.id as pp_id',
+ 'post_platforms.post_id as pp_post_id',
+ 'post_platforms.status as pp_status',
+ 'post_platforms.published_at as pp_published_at',
+ 'post_platforms.updated_at as pp_updated_at',
+ 'posts.published_at as p_published_at',
+ ...array_map(fn (string $column): string => "post_platforms.{$column} as pp_{$column}", self::TARGET_COLUMNS),
+ ])
+ ->chunkById(500, function (Collection $targets): void {
+ DB::transaction(function () use ($targets): void {
+ foreach ($targets as $target) {
+ DB::table('posts')->where('id', $target->pp_post_id)->update([
+ ...collect(self::TARGET_COLUMNS)->mapWithKeys(fn (string $column): array => [$column => $target->{"pp_{$column}"}])->all(),
+ 'publish_status' => $target->pp_status,
+ 'published_at' => $target->pp_status === 'published' ? ($target->p_published_at ?? $target->pp_published_at) : $target->pp_published_at,
+ 'publication_updated_at' => $target->pp_updated_at,
+ ]);
+ }
+ });
+ }, 'post_platforms.id', 'pp_id');
+ }
+
+ private function linkAnalyticsPublications(): void
+ {
+ DB::table('analytics_publications')
+ ->whereNotNull('post_platform_id')
+ ->select(['id', 'post_platform_id'])
+ ->chunkById(500, function (Collection $publications): void {
+ DB::transaction(function () use ($publications): void {
+ $postIds = DB::table('post_platforms')
+ ->whereIn('id', $publications->pluck('post_platform_id'))
+ ->pluck('post_id', 'id');
+
+ foreach ($publications as $publication) {
+ DB::table('analytics_publications')
+ ->where('id', $publication->id)
+ ->update(['post_id' => $postIds[$publication->post_platform_id] ?? null]);
+ }
+ });
+ });
+ }
+
+ private function assertParity(): void
+ {
+ $targets = DB::table('post_platforms')->count();
+ $posts = DB::table('post_platforms')->distinct()->count('post_id');
+ $copies = DB::table('posts')->whereNotNull('platform')->count();
+
+ if ($targets !== $posts || $targets !== $copies) {
+ throw new RuntimeException("Backfill parity failed: {$targets} destinations on {$posts} posts, {$copies} posts carry one.");
+ }
+
+ $scalarColumns = array_values(array_diff(self::TARGET_COLUMNS, self::JSON_COLUMNS));
+
+ DB::table('post_platforms')
+ ->join('posts', 'posts.id', '=', 'post_platforms.post_id')
+ ->select([
+ 'post_platforms.id as pp_id',
+ 'post_platforms.status as pp_status',
+ 'posts.publish_status as p_publish_status',
+ ...array_map(fn (string $column): string => "post_platforms.{$column} as pp_{$column}", self::TARGET_COLUMNS),
+ ...array_map(fn (string $column): string => "posts.{$column} as p_{$column}", self::TARGET_COLUMNS),
+ ])
+ ->chunkById(500, function (Collection $rows) use ($scalarColumns): void {
+ foreach ($rows as $row) {
+ $mismatch = $row->pp_status !== $row->p_publish_status
+ || collect($scalarColumns)->contains(fn (string $column): bool => ! $this->sameScalar($row->{"pp_{$column}"}, $row->{"p_{$column}"}))
+ || collect(self::JSON_COLUMNS)->contains(fn (string $column): bool => ! $this->sameJson($row->{"pp_{$column}"}, $row->{"p_{$column}"}));
+
+ if ($mismatch) {
+ throw new RuntimeException("Backfill parity failed for destination {$row->pp_id}.");
+ }
+ }
+ }, 'post_platforms.id', 'pp_id');
+
+ $crossWorkspace = DB::table('posts')
+ ->join('social_accounts', 'social_accounts.id', '=', 'posts.social_account_id')
+ ->whereColumn('social_accounts.workspace_id', '!=', 'posts.workspace_id')
+ ->count();
+
+ $crossWorkspaceAnalytics = DB::table('analytics_publications')
+ ->join('posts', 'posts.id', '=', 'analytics_publications.post_id')
+ ->whereColumn('analytics_publications.workspace_id', '!=', 'posts.workspace_id')
+ ->count();
+
+ if ($crossWorkspace > 0 || $crossWorkspaceAnalytics > 0) {
+ throw new RuntimeException("Backfill parity failed: {$crossWorkspace} posts and {$crossWorkspaceAnalytics} publications point outside their workspace.");
+ }
+ }
+
+ private function sameScalar(mixed $left, mixed $right): bool
+ {
+ if ($left === null || $right === null) {
+ return $left === $right;
+ }
+
+ return (string) $left === (string) $right;
+ }
+
+ private function sameJson(mixed $left, mixed $right): bool
+ {
+ $decode = fn (mixed $value): mixed => is_string($value) ? json_decode($value, true) : $value;
+
+ return $this->normalize($decode($left)) == $this->normalize($decode($right));
+ }
+
+ private function normalize(mixed $value): mixed
+ {
+ if (! is_array($value)) {
+ return $value;
+ }
+
+ if (! array_is_list($value)) {
+ ksort($value);
+ }
+
+ return array_map($this->normalize(...), $value);
+ }
+
+ private function replacePartiallyPublishedWebhookEvent(): void
+ {
+ DB::table('webhooks')
+ ->select(['id', 'events'])
+ ->chunkById(500, function (Collection $webhooks): void {
+ foreach ($webhooks as $webhook) {
+ $events = json_decode((string) $webhook->events, true);
+
+ if (! is_array($events) || ! in_array('post.partially_published', $events, true)) {
+ continue;
+ }
+
+ $replaced = array_values(array_unique([
+ ...array_filter($events, fn (mixed $event): bool => $event !== 'post.partially_published'),
+ 'post.published',
+ 'post.failed',
+ ]));
+
+ DB::table('webhooks')->where('id', $webhook->id)->update(['events' => json_encode($replaced)]);
+ }
+ });
+ }
+};
diff --git a/database/migrations/2026_10_08_222944_drop_post_platforms_table.php b/database/migrations/2026_10_08_222944_drop_post_platforms_table.php
new file mode 100644
index 000000000..887d8acff
--- /dev/null
+++ b/database/migrations/2026_10_08_222944_drop_post_platforms_table.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Query\Builder;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ public function up(): void
+ {
+ $unmirrored = DB::table('post_platforms')
+ ->whereNotExists(fn (Builder $query) => $query->select(DB::raw(1))
+ ->from('posts')
+ ->whereColumn('posts.id', 'post_platforms.post_id')
+ ->whereColumn('posts.platform', 'post_platforms.platform')
+ ->whereColumn('posts.social_account_id', 'post_platforms.social_account_id'))
+ ->count();
+
+ if ($unmirrored > 0) {
+ throw new RuntimeException("{$unmirrored} destinations were not copied to their posts; post_platforms was kept.");
+ }
+
+ $unlinked = DB::table('analytics_publications')->whereNotNull('post_platform_id')->whereNull('post_id')->count();
+
+ if ($unlinked > 0) {
+ throw new RuntimeException("{$unlinked} analytics publications were not linked to their posts; post_platforms was kept.");
+ }
+
+ Schema::table('analytics_publications', function (Blueprint $table): void {
+ $table->dropForeign(['post_platform_id']);
+ $table->dropUnique(['post_platform_id']);
+ $table->dropColumn('post_platform_id');
+ });
+
+ Schema::dropIfExists('post_platforms');
+ }
+};
diff --git a/lang/ar/mail.php b/lang/ar/mail.php
index b50bf71fc..dc6de63ea 100644
--- a/lang/ar/mail.php
+++ b/lang/ar/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name طلب الموافقة في :workspace.',
'heading' => 'منشور يحتاج إلى موافقتك',
'body' => ':name (:email) طلب الموافقة في مساحة العمل :workspace.',
- 'channels' => 'القنوات',
+ 'channel' => 'القناة',
'requested_time' => 'الوقت المطلوب',
'next_queue_slot' => 'الموعد التالي في قائمة الانتظار',
'as_soon_as_approved' => 'فور الموافقة عليه',
@@ -82,7 +82,7 @@ return [
'preview' => ':name وافق على منشورك في :workspace.',
'heading' => 'تمت الموافقة على منشورك',
'body' => ':name وافق على منشورك في مساحة العمل :workspace.',
- 'channels' => 'القنوات',
+ 'channel' => 'القناة',
'goes_out' => 'موعد النشر',
'channel_time' => ':channel: :time',
'publishing_now' => 'يُنشر الآن',
@@ -95,7 +95,7 @@ return [
'preview' => ':name أعاد منشورك إلى المسودات.',
'heading' => 'لم تتم الموافقة على منشورك',
'body' => ':name أعاد منشورك في مساحة العمل :workspace إلى المسودات.',
- 'channels' => 'القنوات',
+ 'channel' => 'القناة',
'button' => 'عرض في المسودات',
],
diff --git a/lang/ar/posts.php b/lang/ar/posts.php
index aa40ee33d..359071350 100644
--- a/lang/ar/posts.php
+++ b/lang/ar/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'قيد النشر',
'retrying' => 'إعادة المحاولة',
'published' => 'منشور',
- 'partially_published' => 'منشور جزئيًا',
'failed' => 'فشل',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'الأعلام',
],
- 'status' => [
- 'pending' => 'قيد الانتظار',
- 'scheduled' => 'مجدول',
- 'published' => 'منشور',
- 'publishing' => 'جارٍ النشر...',
- 'retrying' => 'جارٍ إعادة المحاولة...',
- 'failed' => 'فشل',
- 'pending_review' => 'قيد مراجعة Google',
- 'rejected' => 'مرفوض',
- ],
-
'delete_modal' => [
'title' => 'حذف المنشور',
'description' => 'هل أنت متأكد من رغبتك في حذف هذا المنشور؟ لا يمكن التراجع عن هذا الإجراء.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'حجم هذا الملف يتجاوز :size ميغابايت المسموح بها لنوعه.',
'queue_requires_schedule' => 'ليس لهذه القناة أوقات نشر بعد. أضف أوقات النشر من إعدادات القناة لاستخدام قائمة الانتظار.',
'queue_with_scheduled_at' => 'اختر موضعًا في قائمة الانتظار أو تاريخًا ووقتًا، وليس كليهما.',
- 'queue_legacy_post' => 'أُنشئ هذا المنشور لعدة قنوات دفعة واحدة ولا يمكن إضافته إلى قائمة الانتظار. حدّد تاريخًا ووقتًا بدلًا من ذلك.',
'queue_busy' => 'يجري تحديث قائمة الانتظار. يرجى المحاولة مرة أخرى.',
'no_social_account' => 'لا يحتوي هذا المنشور على حساب اجتماعي، لذا لا يمكن نشره.',
+ 'choose_channel' => 'اختر قناة قبل جدولة هذا المنشور أو نشره.',
'queue_order_stale' => 'تغيّرت قائمة الانتظار منذ فتحتها. حدّث الصفحة وحاول مرة أخرى.',
'account_disconnected' => 'الحساب الاجتماعي مفصول',
- 'target_disabled' => 'تم إيقاف وجهة النشر هذه',
'account_token_expired' => 'انتهت جلسة الحساب الاجتماعي — يرجى إعادة الربط',
'platform_unavailable' => 'المنصة غير متاحة مؤقتًا. سنعيد المحاولة قريبًا.',
'platform_unavailable_exhausted' => 'ظلت المنصة غير متاحة بعد عدة محاولات. يرجى المحاولة لاحقًا.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'يُنشر الآن',
'publishing_badge' => 'جارٍ النشر…',
'publishing_on' => 'جارٍ النشر على :network…',
+ 'in_google_review' => 'قيد مراجعة Google',
'retrying_at' => 'إعادة المحاولة في :time',
'published_via' => 'نُشر عبر',
'published_directly_from' => 'نُشر مباشرةً من :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'القنوات (:count)',
- 'collapse' => 'إخفاء القنوات',
- 'expand' => 'إظهار القنوات',
],
'approvals' => [
'badge' => 'موافقة',
diff --git a/lang/ar/webhooks.php b/lang/ar/webhooks.php
index caa17aba7..8695382bd 100644
--- a/lang/ar/webhooks.php
+++ b/lang/ar/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'عند جدولة منشور للنشر.',
'post_unscheduled' => 'عند إعادة منشور مجدول إلى المسودات.',
'post_published' => 'عند نشر منشور على قناة.',
- 'post_partially_published' => 'عند نجاح النشر في بعض القنوات وفشله في أخرى.',
'post_failed' => 'عند فشل نشر منشور.',
'post_deleted' => 'عند حذف منشور.',
],
diff --git a/lang/de/mail.php b/lang/de/mail.php
index 58199ef60..ce0533421 100644
--- a/lang/de/mail.php
+++ b/lang/de/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name bittet in :workspace um Freigabe.',
'heading' => 'Ein Beitrag braucht deine Freigabe',
'body' => ':name (:email) bittet im Workspace :workspace um Freigabe.',
- 'channels' => 'Kanäle',
+ 'channel' => 'Kanal',
'requested_time' => 'Gewünschter Zeitpunkt',
'next_queue_slot' => 'Nächster Platz in der Warteschlange',
'as_soon_as_approved' => 'Sobald er freigegeben ist',
@@ -82,7 +82,7 @@ return [
'preview' => ':name hat deinen Beitrag in :workspace freigegeben.',
'heading' => 'Dein Beitrag wurde freigegeben',
'body' => ':name hat deinen Beitrag im Workspace :workspace freigegeben.',
- 'channels' => 'Kanäle',
+ 'channel' => 'Kanal',
'goes_out' => 'Wird veröffentlicht',
'channel_time' => ':channel: :time',
'publishing_now' => 'Wird jetzt veröffentlicht',
@@ -95,7 +95,7 @@ return [
'preview' => ':name hat deinen Beitrag zurück in die Entwürfe verschoben.',
'heading' => 'Dein Beitrag wurde nicht freigegeben',
'body' => ':name hat deinen Beitrag im Workspace :workspace zurück in die Entwürfe verschoben.',
- 'channels' => 'Kanäle',
+ 'channel' => 'Kanal',
'button' => 'In den Entwürfen ansehen',
],
diff --git a/lang/de/posts.php b/lang/de/posts.php
index 83d920fd8..34fdd6f91 100644
--- a/lang/de/posts.php
+++ b/lang/de/posts.php
@@ -535,7 +535,6 @@ return [
'publishing' => 'Wird veröffentlicht',
'retrying' => 'Erneuter Versuch',
'published' => 'Veröffentlicht',
- 'partially_published' => 'Teilweise veröffentlicht',
'failed' => 'Fehlgeschlagen',
],
@@ -641,17 +640,6 @@ return [
'flags' => 'Flaggen',
],
- 'status' => [
- 'pending' => 'Ausstehend',
- 'scheduled' => 'Geplant',
- 'published' => 'Veröffentlicht',
- 'publishing' => 'Wird veröffentlicht...',
- 'retrying' => 'Erneuter Versuch...',
- 'failed' => 'Fehlgeschlagen',
- 'pending_review' => 'Google-Prüfung läuft',
- 'rejected' => 'Abgelehnt',
- ],
-
'delete_modal' => [
'title' => 'Beitrag löschen',
'description' => 'Möchtest du diesen Beitrag wirklich löschen? Diese Aktion kann nicht rückgängig gemacht werden.',
@@ -821,12 +809,11 @@ return [
'media_file_too_large' => 'Diese Datei ist größer als die für ihren Typ erlaubten :size MB.',
'queue_requires_schedule' => 'Dieser Kanal hat noch keine Veröffentlichungszeiten. Füge in den Kanaleinstellungen Zeiten hinzu, um die Warteschlange zu nutzen.',
'queue_with_scheduled_at' => 'Wähle entweder eine Position in der Warteschlange oder Datum und Uhrzeit, nicht beides.',
- 'queue_legacy_post' => 'Dieser Beitrag wurde für mehrere Kanäle gleichzeitig erstellt und kann keiner Warteschlange hinzugefügt werden. Lege stattdessen Datum und Uhrzeit fest.',
'queue_busy' => 'Die Warteschlange wird gerade aktualisiert. Bitte versuche es erneut.',
'no_social_account' => 'Dieser Beitrag hat kein Social-Media-Konto und kann daher nicht veröffentlicht werden.',
+ 'choose_channel' => 'Wähle einen Kanal, bevor du diesen Beitrag planst oder veröffentlichst.',
'queue_order_stale' => 'Die Warteschlange hat sich geändert, seit du sie geöffnet hast. Aktualisiere die Seite und versuche es erneut.',
'account_disconnected' => 'Social-Media-Konto ist getrennt',
- 'target_disabled' => 'Dieses Ziel wurde deaktiviert',
'account_token_expired' => 'Sitzung des Social-Media-Kontos abgelaufen – bitte erneut verbinden',
'platform_unavailable' => 'Die Plattform ist vorübergehend nicht verfügbar. Wir versuchen es in Kürze erneut.',
'platform_unavailable_exhausted' => 'Die Plattform blieb nach mehreren Versuchen nicht verfügbar. Bitte später erneut versuchen.',
@@ -908,6 +895,7 @@ return [
'publishing_now' => 'Wird jetzt veröffentlicht',
'publishing_badge' => 'Veröffentlichen…',
'publishing_on' => 'Wird auf :network veröffentlicht…',
+ 'in_google_review' => 'Google-Prüfung läuft',
'retrying_at' => 'Neuer Versuch um :time',
'published_via' => 'Veröffentlicht über',
'published_directly_from' => 'Direkt über :network veröffentlicht',
@@ -994,8 +982,6 @@ return [
],
'group' => [
'channels' => 'Kanäle (:count)',
- 'collapse' => 'Kanäle ausblenden',
- 'expand' => 'Kanäle anzeigen',
],
'approvals' => [
'badge' => 'Freigabe',
diff --git a/lang/de/webhooks.php b/lang/de/webhooks.php
index 3afbc1e28..e28f490f7 100644
--- a/lang/de/webhooks.php
+++ b/lang/de/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Wenn ein Beitrag zur Veröffentlichung geplant wird.',
'post_unscheduled' => 'Wenn ein geplanter Beitrag zurück zu Entwürfen geht.',
'post_published' => 'Wenn ein Beitrag auf einem Kanal live geht.',
- 'post_partially_published' => 'Wenn einige Kanäle veröffentlichen, andere scheitern.',
'post_failed' => 'Wenn ein Beitrag nicht veröffentlicht werden kann.',
'post_deleted' => 'Wenn ein Beitrag gelöscht wird.',
],
diff --git a/lang/el/mail.php b/lang/el/mail.php
index b43326ccd..edc9fc7d3 100644
--- a/lang/el/mail.php
+++ b/lang/el/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => 'Ο/Η :name ζήτησε έγκριση στο :workspace.',
'heading' => 'Μια ανάρτηση χρειάζεται την έγκρισή σας',
'body' => 'Ο/Η :name (:email) ζήτησε έγκριση στο workspace :workspace.',
- 'channels' => 'Κανάλια',
+ 'channel' => 'Κανάλι',
'requested_time' => 'Ζητούμενη ώρα',
'next_queue_slot' => 'Επόμενη θέση στην ουρά',
'as_soon_as_approved' => 'Μόλις εγκριθεί',
@@ -82,7 +82,7 @@ return [
'preview' => 'Ο/Η :name ενέκρινε την ανάρτησή σας στο :workspace.',
'heading' => 'Η ανάρτησή σας εγκρίθηκε',
'body' => 'Ο/Η :name ενέκρινε την ανάρτησή σας στο workspace :workspace.',
- 'channels' => 'Κανάλια',
+ 'channel' => 'Κανάλι',
'goes_out' => 'Θα δημοσιευτεί',
'channel_time' => ':channel: :time',
'publishing_now' => 'Δημοσιεύεται τώρα',
@@ -95,7 +95,7 @@ return [
'preview' => 'Ο/Η :name μετέφερε την ανάρτησή σας πίσω στα πρόχειρα.',
'heading' => 'Η ανάρτησή σας δεν εγκρίθηκε',
'body' => 'Ο/Η :name μετέφερε την ανάρτησή σας στο workspace :workspace πίσω στα πρόχειρα.',
- 'channels' => 'Κανάλια',
+ 'channel' => 'Κανάλι',
'button' => 'Προβολή στα πρόχειρα',
],
diff --git a/lang/el/posts.php b/lang/el/posts.php
index 2903149aa..40a5fd543 100644
--- a/lang/el/posts.php
+++ b/lang/el/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Δημοσιεύεται',
'retrying' => 'Επανάληψη',
'published' => 'Δημοσιεύτηκε',
- 'partially_published' => 'Δημοσιεύτηκε εν μέρει',
'failed' => 'Απέτυχε',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Σημαίες',
],
- 'status' => [
- 'pending' => 'Σε εκκρεμότητα',
- 'scheduled' => 'Προγραμματισμένη',
- 'published' => 'Δημοσιεύτηκε',
- 'publishing' => 'Δημοσίευση...',
- 'retrying' => 'Επανάληψη...',
- 'failed' => 'Απέτυχε',
- 'pending_review' => 'Σε έλεγχο από την Google',
- 'rejected' => 'Απορρίφθηκε',
- ],
-
'delete_modal' => [
'title' => 'Διαγραφή δημοσίευσης',
'description' => 'Είστε βέβαιοι ότι θέλετε να διαγράψετε αυτή τη δημοσίευση; Αυτή η ενέργεια δεν μπορεί να αναιρεθεί.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Αυτό το αρχείο υπερβαίνει τα :size MB που επιτρέπονται για τον τύπο του.',
'queue_requires_schedule' => 'Αυτό το κανάλι δεν έχει ακόμη ώρες δημοσίευσης. Προσθέστε ώρες στις ρυθμίσεις του καναλιού για να χρησιμοποιήσετε την ουρά.',
'queue_with_scheduled_at' => 'Επιλέξτε είτε θέση στην ουρά είτε ημερομηνία και ώρα, όχι και τα δύο.',
- 'queue_legacy_post' => 'Αυτή η ανάρτηση δημιουργήθηκε για πολλά κανάλια ταυτόχρονα και δεν μπορεί να προστεθεί σε ουρά. Ορίστε ημερομηνία και ώρα.',
'queue_busy' => 'Η ουρά ενημερώνεται. Δοκιμάστε ξανά.',
'no_social_account' => 'Αυτή η ανάρτηση δεν έχει λογαριασμό κοινωνικού δικτύου, οπότε δεν μπορεί να δημοσιευτεί.',
+ 'choose_channel' => 'Επιλέξτε ένα κανάλι πριν προγραμματίσετε ή δημοσιεύσετε αυτή την ανάρτηση.',
'queue_order_stale' => 'Η ουρά άλλαξε από τότε που την ανοίξατε. Ανανεώστε και δοκιμάστε ξανά.',
'account_disconnected' => 'Ο λογαριασμός κοινωνικού δικτύου έχει αποσυνδεθεί',
- 'target_disabled' => 'Αυτός ο προορισμός απενεργοποιήθηκε',
'account_token_expired' => 'Η συνεδρία του λογαριασμού κοινωνικού δικτύου έληξε — επανασυνδεθείτε',
'platform_unavailable' => 'Η πλατφόρμα είναι προσωρινά μη διαθέσιμη. Θα δοκιμάσουμε ξανά σύντομα.',
'platform_unavailable_exhausted' => 'Η πλατφόρμα παρέμεινε μη διαθέσιμη μετά από αρκετές προσπάθειες. Δοκιμάστε ξανά αργότερα.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Δημοσιεύεται τώρα',
'publishing_badge' => 'Δημοσίευση…',
'publishing_on' => 'Δημοσίευση στο :network…',
+ 'in_google_review' => 'Σε έλεγχο από την Google',
'retrying_at' => 'Νέα προσπάθεια στις :time',
'published_via' => 'Δημοσιεύτηκε μέσω',
'published_directly_from' => 'Δημοσιεύτηκε απευθείας από το :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Κανάλια (:count)',
- 'collapse' => 'Απόκρυψη καναλιών',
- 'expand' => 'Εμφάνιση καναλιών',
],
'approvals' => [
'badge' => 'Προς έγκριση',
diff --git a/lang/el/webhooks.php b/lang/el/webhooks.php
index 8161a611d..7587498aa 100644
--- a/lang/el/webhooks.php
+++ b/lang/el/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Όταν μια ανάρτηση προγραμματίζεται.',
'post_unscheduled' => 'Όταν μια προγραμματισμένη ανάρτηση γίνεται πρόχειρο.',
'post_published' => 'Όταν μια ανάρτηση δημοσιεύεται σε ένα κανάλι.',
- 'post_partially_published' => 'Όταν μόνο ορισμένα κανάλια δημοσιεύουν.',
'post_failed' => 'Όταν μια ανάρτηση αποτυγχάνει να δημοσιευτεί.',
'post_deleted' => 'Όταν διαγράφεται μια ανάρτηση.',
],
diff --git a/lang/en/mail.php b/lang/en/mail.php
index f621d2f2c..d865ae819 100644
--- a/lang/en/mail.php
+++ b/lang/en/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name asked for approval in :workspace.',
'heading' => 'A post needs your approval',
'body' => ':name (:email) asked for approval in the :workspace workspace.',
- 'channels' => 'Channels',
+ 'channel' => 'Channel',
'requested_time' => 'Requested time',
'next_queue_slot' => 'Next queue slot',
'as_soon_as_approved' => 'As soon as it\'s approved',
@@ -82,7 +82,7 @@ return [
'preview' => ':name approved your post in :workspace.',
'heading' => 'Your post was approved',
'body' => ':name approved your post in the :workspace workspace.',
- 'channels' => 'Channels',
+ 'channel' => 'Channel',
'goes_out' => 'It will go out',
'channel_time' => ':channel: :time',
'publishing_now' => 'Publishing now',
@@ -95,7 +95,7 @@ return [
'preview' => ':name moved your post back to drafts.',
'heading' => 'Your post was not approved',
'body' => ':name moved your post in the :workspace workspace back to drafts.',
- 'channels' => 'Channels',
+ 'channel' => 'Channel',
'button' => 'View in drafts',
],
diff --git a/lang/en/posts.php b/lang/en/posts.php
index 198fa3fa6..d469dee19 100644
--- a/lang/en/posts.php
+++ b/lang/en/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publishing',
'retrying' => 'Retrying',
'published' => 'Published',
- 'partially_published' => 'Partially Published',
'failed' => 'Failed',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Flags',
],
- 'status' => [
- 'pending' => 'Pending',
- 'scheduled' => 'Scheduled',
- 'published' => 'Published',
- 'publishing' => 'Publishing...',
- 'retrying' => 'Retrying...',
- 'failed' => 'Failed',
- 'pending_review' => 'In review by Google',
- 'rejected' => 'Rejected',
- ],
-
'delete_modal' => [
'title' => 'Delete Post',
'description' => 'Are you sure you want to delete this post? This action cannot be undone.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'This file is larger than the :size MB allowed for its type.',
'queue_requires_schedule' => 'This channel has no posting times yet. Add posting times in the channel settings to use the queue.',
'queue_with_scheduled_at' => 'Choose either a queue position or a date and time, not both.',
- 'queue_legacy_post' => 'This post was created for several channels at once and cannot be added to a queue. Set a date and time instead.',
'queue_busy' => 'The queue is being updated. Please try again.',
'no_social_account' => 'This post has no social account, so it cannot be published.',
+ 'choose_channel' => 'Choose a channel before scheduling or publishing this post.',
'queue_order_stale' => 'The queue changed since you opened it. Refresh and try again.',
'account_disconnected' => 'Social account is disconnected',
- 'target_disabled' => 'This destination was switched off',
'account_token_expired' => 'Social account session expired — please reconnect',
'platform_unavailable' => 'The platform is temporarily unavailable. We\'ll retry shortly.',
'platform_unavailable_exhausted' => 'The platform stayed unavailable after several retries. Please try again later.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Publishing now',
'publishing_badge' => 'Publishing…',
'publishing_on' => 'Publishing on :network…',
+ 'in_google_review' => 'In review by Google',
'retrying_at' => 'Retrying at :time',
'published_via' => 'Published via',
'published_directly_from' => 'This was published directly from :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Channels (:count)',
- 'collapse' => 'Hide channels',
- 'expand' => 'Show channels',
],
'approvals' => [
'badge' => 'Approval',
diff --git a/lang/en/webhooks.php b/lang/en/webhooks.php
index 30a2cf155..1cd83d8d8 100644
--- a/lang/en/webhooks.php
+++ b/lang/en/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'When a post is scheduled to publish.',
'post_unscheduled' => 'When a scheduled post goes back to drafts.',
'post_published' => 'When a post goes live on a channel.',
- 'post_partially_published' => 'When some channels publish and others fail.',
'post_failed' => 'When a post fails to publish.',
'post_deleted' => 'When a post is deleted.',
],
diff --git a/lang/es/mail.php b/lang/es/mail.php
index e73cfb045..062c79c1a 100644
--- a/lang/es/mail.php
+++ b/lang/es/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name pidió aprobación en :workspace.',
'heading' => 'Una publicación necesita tu aprobación',
'body' => ':name (:email) pidió aprobación en el workspace :workspace.',
- 'channels' => 'Canales',
+ 'channel' => 'Canal',
'requested_time' => 'Hora solicitada',
'next_queue_slot' => 'Próximo hueco de la cola',
'as_soon_as_approved' => 'En cuanto se apruebe',
@@ -82,7 +82,7 @@ return [
'preview' => ':name aprobó tu publicación en :workspace.',
'heading' => 'Tu publicación fue aprobada',
'body' => ':name aprobó tu publicación en el workspace :workspace.',
- 'channels' => 'Canales',
+ 'channel' => 'Canal',
'goes_out' => 'Se publicará',
'channel_time' => ':channel: :time',
'publishing_now' => 'Publicando ahora',
@@ -95,7 +95,7 @@ return [
'preview' => ':name devolvió tu publicación a borradores.',
'heading' => 'Tu publicación no fue aprobada',
'body' => ':name devolvió tu publicación del workspace :workspace a borradores.',
- 'channels' => 'Canales',
+ 'channel' => 'Canal',
'button' => 'Ver en borradores',
],
diff --git a/lang/es/posts.php b/lang/es/posts.php
index 5f5339afb..a699ac95f 100644
--- a/lang/es/posts.php
+++ b/lang/es/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publicando',
'retrying' => 'Reintentando',
'published' => 'Publicado',
- 'partially_published' => 'Parcialmente publicado',
'failed' => 'Fallido',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Banderas',
],
- 'status' => [
- 'pending' => 'Pendiente',
- 'scheduled' => 'Programado',
- 'published' => 'Publicado',
- 'publishing' => 'Publicando...',
- 'retrying' => 'Reintentando...',
- 'failed' => 'Fallido',
- 'pending_review' => 'En revisión por Google',
- 'rejected' => 'Rechazado',
- ],
-
'delete_modal' => [
'title' => 'Eliminar post',
'description' => '¿Estás seguro de que deseas eliminar este post? Esta acción no se puede deshacer.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Este archivo supera los :size MB permitidos para su tipo.',
'queue_requires_schedule' => 'Este canal aún no tiene horarios de publicación. Añade horarios en los ajustes del canal para usar la cola.',
'queue_with_scheduled_at' => 'Elige una posición en la cola o una fecha y hora, no ambas.',
- 'queue_legacy_post' => 'Esta publicación se creó para varios canales a la vez y no se puede añadir a una cola. Define una fecha y hora.',
'queue_busy' => 'La cola se está actualizando. Inténtalo de nuevo.',
'no_social_account' => 'Esta publicación no tiene una cuenta social, así que no se puede publicar.',
+ 'choose_channel' => 'Elige un canal antes de programar o publicar esta publicación.',
'queue_order_stale' => 'La cola ha cambiado desde que la abriste. Actualiza e inténtalo de nuevo.',
'account_disconnected' => 'Cuenta social desconectada',
- 'target_disabled' => 'Este destino se desactivó',
'account_token_expired' => 'Sesión de la cuenta social expirada — reconecta la cuenta',
'platform_unavailable' => 'La plataforma no está disponible temporalmente. Reintentaremos en breve.',
'platform_unavailable_exhausted' => 'La plataforma siguió sin estar disponible tras varios reintentos. Inténtalo de nuevo más tarde.',
@@ -907,6 +894,7 @@ return [
'publishing_now' => 'Publicando ahora',
'publishing_badge' => 'Publicando…',
'publishing_on' => 'Publicando en :network…',
+ 'in_google_review' => 'En revisión por Google',
'retrying_at' => 'Reintento a las :time',
'published_via' => 'Publicado en',
'published_directly_from' => 'Publicado directamente desde :network',
@@ -993,8 +981,6 @@ return [
],
'group' => [
'channels' => 'Canales (:count)',
- 'collapse' => 'Ocultar canales',
- 'expand' => 'Mostrar canales',
],
'approvals' => [
'badge' => 'Aprobación',
diff --git a/lang/es/webhooks.php b/lang/es/webhooks.php
index 1c6763141..0a49be334 100644
--- a/lang/es/webhooks.php
+++ b/lang/es/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Cuando se programa un post para publicarse.',
'post_unscheduled' => 'Cuando un post programado vuelve a borradores.',
'post_published' => 'Cuando un post se publica en un canal.',
- 'post_partially_published' => 'Cuando algunos canales publican y otros fallan.',
'post_failed' => 'Cuando un post no se puede publicar.',
'post_deleted' => 'Cuando se elimina un post.',
],
diff --git a/lang/fr/mail.php b/lang/fr/mail.php
index d2dffb09e..8292e8c6b 100644
--- a/lang/fr/mail.php
+++ b/lang/fr/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name demande une approbation dans :workspace.',
'heading' => 'Une publication attend votre approbation',
'body' => ':name (:email) demande une approbation dans l\'espace de travail :workspace.',
- 'channels' => 'Canaux',
+ 'channel' => 'Canal',
'requested_time' => 'Heure demandée',
'next_queue_slot' => 'Prochain créneau de la file d\'attente',
'as_soon_as_approved' => 'Dès son approbation',
@@ -82,7 +82,7 @@ return [
'preview' => ':name a approuvé votre publication dans :workspace.',
'heading' => 'Votre publication a été approuvée',
'body' => ':name a approuvé votre publication dans l\'espace de travail :workspace.',
- 'channels' => 'Canaux',
+ 'channel' => 'Canal',
'goes_out' => 'Publication prévue',
'channel_time' => ':channel : :time',
'publishing_now' => 'Publication en cours',
@@ -95,7 +95,7 @@ return [
'preview' => ':name a remis votre publication dans les brouillons.',
'heading' => 'Votre publication n\'a pas été approuvée',
'body' => ':name a remis votre publication de l\'espace de travail :workspace dans les brouillons.',
- 'channels' => 'Canaux',
+ 'channel' => 'Canal',
'button' => 'Voir dans les brouillons',
],
diff --git a/lang/fr/posts.php b/lang/fr/posts.php
index f79e4c018..721c6040c 100644
--- a/lang/fr/posts.php
+++ b/lang/fr/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publication en cours',
'retrying' => 'Nouvelle tentative',
'published' => 'Publiée',
- 'partially_published' => 'Partiellement publiée',
'failed' => 'Échec',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Drapeaux',
],
- 'status' => [
- 'pending' => 'En attente',
- 'scheduled' => 'Programmée',
- 'published' => 'Publiée',
- 'publishing' => 'Publication en cours...',
- 'retrying' => 'Nouvelle tentative...',
- 'failed' => 'Échec',
- 'pending_review' => 'En cours d\'examen par Google',
- 'rejected' => 'Refusé',
- ],
-
'delete_modal' => [
'title' => 'Supprimer la publication',
'description' => 'Voulez-vous vraiment supprimer cette publication ? Cette action est irréversible.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Ce fichier dépasse les :size Mo autorisés pour son type.',
'queue_requires_schedule' => 'Ce canal n\'a pas encore d\'horaires de publication. Ajoutez-en dans les paramètres du canal pour utiliser la file d\'attente.',
'queue_with_scheduled_at' => 'Choisissez une position dans la file d\'attente ou une date et une heure, pas les deux.',
- 'queue_legacy_post' => 'Ce post a été créé pour plusieurs canaux à la fois et ne peut pas être ajouté à une file d\'attente. Définissez plutôt une date et une heure.',
'queue_busy' => 'La file d\'attente est en cours de mise à jour. Veuillez réessayer.',
'no_social_account' => 'Cette publication n\'a pas de compte social, elle ne peut donc pas être publiée.',
+ 'choose_channel' => 'Choisissez un canal avant de programmer ou de publier ce post.',
'queue_order_stale' => 'La file d\'attente a changé depuis votre ouverture. Actualisez et réessayez.',
'account_disconnected' => 'Le compte social est déconnecté',
- 'target_disabled' => 'Cette destination a été désactivée',
'account_token_expired' => 'La session du compte social a expiré — veuillez reconnecter',
'platform_unavailable' => 'La plateforme est temporairement indisponible. Nouvelle tentative sous peu.',
'platform_unavailable_exhausted' => 'La plateforme est restée indisponible après plusieurs tentatives. Réessayez plus tard.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Publication en cours',
'publishing_badge' => 'Publication…',
'publishing_on' => 'Publication sur :network…',
+ 'in_google_review' => 'En cours d\'examen par Google',
'retrying_at' => 'Nouvel essai à :time',
'published_via' => 'Publié via',
'published_directly_from' => 'Publié directement depuis :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Canaux (:count)',
- 'collapse' => 'Masquer les canaux',
- 'expand' => 'Afficher les canaux',
],
'approvals' => [
'badge' => 'Approbation',
diff --git a/lang/fr/webhooks.php b/lang/fr/webhooks.php
index d1b2b54a3..7d5c9aad8 100644
--- a/lang/fr/webhooks.php
+++ b/lang/fr/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Quand une publication est programmée.',
'post_unscheduled' => 'Quand une publication programmée repasse en brouillon.',
'post_published' => 'Quand une publication est en ligne sur un canal.',
- 'post_partially_published' => 'Quand certains canaux publient et d’autres échouent.',
'post_failed' => 'Quand une publication échoue.',
'post_deleted' => 'Quand une publication est supprimée.',
],
diff --git a/lang/it/mail.php b/lang/it/mail.php
index 83cd8bbdc..bd6bb95a4 100644
--- a/lang/it/mail.php
+++ b/lang/it/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name ha chiesto un\'approvazione in :workspace.',
'heading' => 'Un post richiede la tua approvazione',
'body' => ':name (:email) ha chiesto un\'approvazione nel workspace :workspace.',
- 'channels' => 'Canali',
+ 'channel' => 'Canale',
'requested_time' => 'Orario richiesto',
'next_queue_slot' => 'Prossimo slot della coda',
'as_soon_as_approved' => 'Appena viene approvato',
@@ -82,7 +82,7 @@ return [
'preview' => ':name ha approvato il tuo post in :workspace.',
'heading' => 'Il tuo post è stato approvato',
'body' => ':name ha approvato il tuo post nel workspace :workspace.',
- 'channels' => 'Canali',
+ 'channel' => 'Canale',
'goes_out' => 'Verrà pubblicato',
'channel_time' => ':channel: :time',
'publishing_now' => 'Pubblicazione in corso',
@@ -95,7 +95,7 @@ return [
'preview' => ':name ha riportato il tuo post nelle bozze.',
'heading' => 'Il tuo post non è stato approvato',
'body' => ':name ha riportato il tuo post del workspace :workspace nelle bozze.',
- 'channels' => 'Canali',
+ 'channel' => 'Canale',
'button' => 'Vedi nelle bozze',
],
diff --git a/lang/it/posts.php b/lang/it/posts.php
index d31767631..4a48423f9 100644
--- a/lang/it/posts.php
+++ b/lang/it/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'In pubblicazione',
'retrying' => 'Nuovo tentativo',
'published' => 'Pubblicato',
- 'partially_published' => 'Pubblicato parzialmente',
'failed' => 'Non riuscito',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Bandiere',
],
- 'status' => [
- 'pending' => 'In attesa',
- 'scheduled' => 'Programmato',
- 'published' => 'Pubblicato',
- 'publishing' => 'Pubblicazione in corso...',
- 'retrying' => 'Nuovo tentativo...',
- 'failed' => 'Non riuscito',
- 'pending_review' => 'In revisione da Google',
- 'rejected' => 'Rifiutato',
- ],
-
'delete_modal' => [
'title' => 'Elimina post',
'description' => 'Vuoi davvero eliminare questo post? Questa azione non può essere annullata.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Questo file supera i :size MB consentiti per il suo tipo.',
'queue_requires_schedule' => 'Questo canale non ha ancora orari di pubblicazione. Aggiungili nelle impostazioni del canale per usare la coda.',
'queue_with_scheduled_at' => 'Scegli una posizione nella coda oppure una data e un\'ora, non entrambe.',
- 'queue_legacy_post' => 'Questo post è stato creato per più canali insieme e non può essere aggiunto a una coda. Imposta invece una data e un\'ora.',
'queue_busy' => 'La coda è in fase di aggiornamento. Riprova.',
'no_social_account' => 'Questo post non ha un account social, quindi non può essere pubblicato.',
+ 'choose_channel' => 'Scegli un canale prima di programmare o pubblicare questo post.',
'queue_order_stale' => 'La coda è cambiata da quando l\'hai aperta. Aggiorna e riprova.',
'account_disconnected' => 'L\'account social è scollegato',
- 'target_disabled' => 'Questa destinazione è stata disattivata',
'account_token_expired' => 'Sessione dell\'account social scaduta — ricollegalo',
'platform_unavailable' => 'La piattaforma è temporaneamente non disponibile. Riproveremo a breve.',
'platform_unavailable_exhausted' => 'La piattaforma è rimasta non disponibile dopo diversi tentativi. Riprova più tardi.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'In pubblicazione',
'publishing_badge' => 'Pubblicazione…',
'publishing_on' => 'Pubblicazione su :network…',
+ 'in_google_review' => 'In revisione da Google',
'retrying_at' => 'Nuovo tentativo alle :time',
'published_via' => 'Pubblicato tramite',
'published_directly_from' => 'Pubblicato direttamente da :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Canali (:count)',
- 'collapse' => 'Nascondi canali',
- 'expand' => 'Mostra canali',
],
'approvals' => [
'badge' => 'Approvazione',
diff --git a/lang/it/webhooks.php b/lang/it/webhooks.php
index 2a0a08625..456a3ec30 100644
--- a/lang/it/webhooks.php
+++ b/lang/it/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Quando un post viene programmato.',
'post_unscheduled' => 'Quando un post programmato torna tra le bozze.',
'post_published' => 'Quando un post va online su un canale.',
- 'post_partially_published' => 'Quando alcuni canali pubblicano e altri falliscono.',
'post_failed' => 'Quando la pubblicazione di un post non riesce.',
'post_deleted' => 'Quando un post viene eliminato.',
],
diff --git a/lang/ja/mail.php b/lang/ja/mail.php
index 3fbd1b6de..75db61425 100644
--- a/lang/ja/mail.php
+++ b/lang/ja/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':nameさんが:workspaceで承認を依頼しました。',
'heading' => '承認が必要な投稿があります',
'body' => ':nameさん(:email)がワークスペース「:workspace」で承認を依頼しました。',
- 'channels' => 'チャンネル',
+ 'channel' => 'チャンネル',
'requested_time' => '希望時刻',
'next_queue_slot' => 'キューの次の枠',
'as_soon_as_approved' => '承認されしだい',
@@ -82,7 +82,7 @@ return [
'preview' => ':nameさんが:workspaceであなたの投稿を承認しました。',
'heading' => '投稿が承認されました',
'body' => ':nameさんがワークスペース「:workspace」であなたの投稿を承認しました。',
- 'channels' => 'チャンネル',
+ 'channel' => 'チャンネル',
'goes_out' => '公開予定',
'channel_time' => ':channel::time',
'publishing_now' => '今すぐ公開中',
@@ -95,7 +95,7 @@ return [
'preview' => ':nameさんがあなたの投稿を下書きに戻しました。',
'heading' => '投稿は承認されませんでした',
'body' => ':nameさんがワークスペース「:workspace」のあなたの投稿を下書きに戻しました。',
- 'channels' => 'チャンネル',
+ 'channel' => 'チャンネル',
'button' => '下書きで見る',
],
diff --git a/lang/ja/posts.php b/lang/ja/posts.php
index 6f9540492..5b76c7947 100644
--- a/lang/ja/posts.php
+++ b/lang/ja/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => '公開中',
'retrying' => '再試行中',
'published' => '公開済み',
- 'partially_published' => '一部公開済み',
'failed' => '失敗',
],
@@ -639,17 +638,6 @@ return [
'flags' => '旗',
],
- 'status' => [
- 'pending' => '保留中',
- 'scheduled' => '予約済み',
- 'published' => '公開済み',
- 'publishing' => '公開中...',
- 'retrying' => '再試行中...',
- 'failed' => '失敗',
- 'pending_review' => 'Google が審査中',
- 'rejected' => '拒否されました',
- ],
-
'delete_modal' => [
'title' => '投稿を削除',
'description' => 'この投稿を削除してもよろしいですか?この操作は取り消せません。',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'このファイルは、その形式で許可されている :size MB を超えています。',
'queue_requires_schedule' => 'このチャンネルにはまだ投稿時間がありません。キューを使うには、チャンネル設定で投稿時間を追加してください。',
'queue_with_scheduled_at' => 'キューの位置か日時のどちらか一方を選んでください。',
- 'queue_legacy_post' => 'この投稿は複数のチャンネル向けに一度に作成されたため、キューに追加できません。代わりに日時を設定してください。',
'queue_busy' => 'キューを更新中です。もう一度お試しください。',
'no_social_account' => 'この投稿にはソーシャルアカウントがないため、公開できません。',
+ 'choose_channel' => 'この投稿を予約または公開する前にチャンネルを選択してください。',
'queue_order_stale' => 'キューを開いてから変更されました。更新してもう一度お試しください。',
'account_disconnected' => 'ソーシャルアカウントの接続が解除されています',
- 'target_disabled' => 'この投稿先はオフになりました',
'account_token_expired' => 'ソーシャルアカウントのセッションの有効期限が切れました — 再接続してください',
'platform_unavailable' => 'プラットフォームが一時的に利用できません。まもなく再試行します。',
'platform_unavailable_exhausted' => '何度か再試行しましたがプラットフォームが利用できませんでした。後でもう一度お試しください。',
@@ -906,6 +893,7 @@ return [
'publishing_now' => '公開中',
'publishing_badge' => '公開中…',
'publishing_on' => ':network に投稿中…',
+ 'in_google_review' => 'Google が審査中',
'retrying_at' => ':time に再試行',
'published_via' => '公開先:',
'published_directly_from' => ':network から直接公開されました',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'チャンネル (:count)',
- 'collapse' => 'チャンネルを隠す',
- 'expand' => 'チャンネルを表示',
],
'approvals' => [
'badge' => '承認',
diff --git a/lang/ja/webhooks.php b/lang/ja/webhooks.php
index 4e36e94c9..7ff7d14f2 100644
--- a/lang/ja/webhooks.php
+++ b/lang/ja/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => '投稿の公開が予約されたとき。',
'post_unscheduled' => '予約済みの投稿が下書きに戻ったとき。',
'post_published' => '投稿がチャンネルで公開されたとき。',
- 'post_partially_published' => '一部のチャンネルで公開され、他が失敗したとき。',
'post_failed' => '投稿の公開に失敗したとき。',
'post_deleted' => '投稿が削除されたとき。',
],
diff --git a/lang/ko/mail.php b/lang/ko/mail.php
index 031796d74..f81f08f32 100644
--- a/lang/ko/mail.php
+++ b/lang/ko/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name님이 :workspace에서 승인을 요청했습니다.',
'heading' => '승인이 필요한 게시물이 있습니다',
'body' => ':name님(:email)이 :workspace 워크스페이스에서 승인을 요청했습니다.',
- 'channels' => '채널',
+ 'channel' => '채널',
'requested_time' => '요청한 시간',
'next_queue_slot' => '대기열의 다음 시간',
'as_soon_as_approved' => '승인되는 즉시',
@@ -82,7 +82,7 @@ return [
'preview' => ':name님이 :workspace에서 게시물을 승인했습니다.',
'heading' => '게시물이 승인되었습니다',
'body' => ':name님이 :workspace 워크스페이스에서 게시물을 승인했습니다.',
- 'channels' => '채널',
+ 'channel' => '채널',
'goes_out' => '게시 예정',
'channel_time' => ':channel: :time',
'publishing_now' => '지금 게시 중',
@@ -95,7 +95,7 @@ return [
'preview' => ':name님이 게시물을 초안으로 되돌렸습니다.',
'heading' => '게시물이 승인되지 않았습니다',
'body' => ':name님이 :workspace 워크스페이스의 게시물을 초안으로 되돌렸습니다.',
- 'channels' => '채널',
+ 'channel' => '채널',
'button' => '초안에서 보기',
],
diff --git a/lang/ko/posts.php b/lang/ko/posts.php
index 0df056530..bc3b61238 100644
--- a/lang/ko/posts.php
+++ b/lang/ko/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => '게시 중',
'retrying' => '재시도 중',
'published' => '게시됨',
- 'partially_published' => '부분 게시됨',
'failed' => '실패',
],
@@ -639,17 +638,6 @@ return [
'flags' => '깃발',
],
- 'status' => [
- 'pending' => '대기 중',
- 'scheduled' => '예약됨',
- 'published' => '게시됨',
- 'publishing' => '게시 중...',
- 'retrying' => '재시도 중...',
- 'failed' => '실패',
- 'pending_review' => 'Google 검토 중',
- 'rejected' => '거부됨',
- ],
-
'delete_modal' => [
'title' => '게시물 삭제',
'description' => '이 게시물을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => '이 파일은 해당 형식에 허용된 :size MB를 초과합니다.',
'queue_requires_schedule' => '이 채널에는 아직 게시 시간이 없습니다. 대기열을 사용하려면 채널 설정에서 게시 시간을 추가하세요.',
'queue_with_scheduled_at' => '대기열 위치나 날짜와 시간 중 하나만 선택하세요.',
- 'queue_legacy_post' => '이 게시물은 여러 채널용으로 한 번에 만들어져 대기열에 추가할 수 없습니다. 대신 날짜와 시간을 설정하세요.',
'queue_busy' => '대기열을 업데이트하는 중입니다. 다시 시도해 주세요.',
'no_social_account' => '이 게시물에는 소셜 계정이 없어 게시할 수 없습니다.',
+ 'choose_channel' => '이 게시물을 예약하거나 게시하기 전에 채널을 선택하세요.',
'queue_order_stale' => '대기열을 연 이후 변경되었습니다. 새로 고침한 후 다시 시도해 주세요.',
'account_disconnected' => '소셜 계정 연결이 해제되었습니다',
- 'target_disabled' => '이 게시 대상이 꺼졌습니다',
'account_token_expired' => '소셜 계정 세션이 만료되었습니다 — 재연결하세요',
'platform_unavailable' => '플랫폼을 일시적으로 사용할 수 없습니다. 곧 다시 시도합니다.',
'platform_unavailable_exhausted' => '여러 번 재시도했지만 플랫폼을 사용할 수 없었습니다. 나중에 다시 시도하세요.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => '지금 게시 중',
'publishing_badge' => '게시 중…',
'publishing_on' => ':network에 게시 중…',
+ 'in_google_review' => 'Google 검토 중',
'retrying_at' => ':time에 재시도',
'published_via' => '게시 채널:',
'published_directly_from' => ':network에서 직접 게시됨',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => '채널 (:count)',
- 'collapse' => '채널 숨기기',
- 'expand' => '채널 보기',
],
'approvals' => [
'badge' => '승인',
diff --git a/lang/ko/webhooks.php b/lang/ko/webhooks.php
index f9a042906..67cd2cd23 100644
--- a/lang/ko/webhooks.php
+++ b/lang/ko/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => '게시물 게시가 예약될 때.',
'post_unscheduled' => '예약된 게시물이 초안으로 돌아갈 때.',
'post_published' => '게시물이 채널에 게시될 때.',
- 'post_partially_published' => '일부 채널은 게시되고 나머지는 실패할 때.',
'post_failed' => '게시물 게시에 실패할 때.',
'post_deleted' => '게시물이 삭제될 때.',
],
diff --git a/lang/nl/mail.php b/lang/nl/mail.php
index 86438f826..9504da053 100644
--- a/lang/nl/mail.php
+++ b/lang/nl/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name vraagt om goedkeuring in :workspace.',
'heading' => 'Een bericht wacht op je goedkeuring',
'body' => ':name (:email) vraagt om goedkeuring in de workspace :workspace.',
- 'channels' => 'Kanalen',
+ 'channel' => 'Kanaal',
'requested_time' => 'Gevraagd tijdstip',
'next_queue_slot' => 'Volgende plek in de wachtrij',
'as_soon_as_approved' => 'Zodra het is goedgekeurd',
@@ -82,7 +82,7 @@ return [
'preview' => ':name heeft je bericht in :workspace goedgekeurd.',
'heading' => 'Je bericht is goedgekeurd',
'body' => ':name heeft je bericht in de workspace :workspace goedgekeurd.',
- 'channels' => 'Kanalen',
+ 'channel' => 'Kanaal',
'goes_out' => 'Wordt gepubliceerd',
'channel_time' => ':channel: :time',
'publishing_now' => 'Wordt nu gepubliceerd',
@@ -95,7 +95,7 @@ return [
'preview' => ':name heeft je bericht teruggezet naar concepten.',
'heading' => 'Je bericht is niet goedgekeurd',
'body' => ':name heeft je bericht in de workspace :workspace teruggezet naar concepten.',
- 'channels' => 'Kanalen',
+ 'channel' => 'Kanaal',
'button' => 'Bekijken in concepten',
],
diff --git a/lang/nl/posts.php b/lang/nl/posts.php
index 14a26c8a9..6616a1edd 100644
--- a/lang/nl/posts.php
+++ b/lang/nl/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publiceren',
'retrying' => 'Opnieuw proberen',
'published' => 'Gepubliceerd',
- 'partially_published' => 'Gedeeltelijk gepubliceerd',
'failed' => 'Mislukt',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Vlaggen',
],
- 'status' => [
- 'pending' => 'In afwachting',
- 'scheduled' => 'Gepland',
- 'published' => 'Gepubliceerd',
- 'publishing' => 'Publiceren...',
- 'retrying' => 'Opnieuw proberen...',
- 'failed' => 'Mislukt',
- 'pending_review' => 'In beoordeling bij Google',
- 'rejected' => 'Afgewezen',
- ],
-
'delete_modal' => [
'title' => 'Post verwijderen',
'description' => 'Weet je zeker dat je deze post wilt verwijderen? Deze actie kan niet ongedaan worden gemaakt.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Dit bestand is groter dan de :size MB die voor dit type is toegestaan.',
'queue_requires_schedule' => 'Dit kanaal heeft nog geen publicatietijden. Voeg tijden toe in de kanaalinstellingen om de wachtrij te gebruiken.',
'queue_with_scheduled_at' => 'Kies een positie in de wachtrij of een datum en tijd, niet allebei.',
- 'queue_legacy_post' => 'Dit bericht is voor meerdere kanalen tegelijk gemaakt en kan niet aan een wachtrij worden toegevoegd. Stel in plaats daarvan een datum en tijd in.',
'queue_busy' => 'De wachtrij wordt bijgewerkt. Probeer het opnieuw.',
'no_social_account' => 'Dit bericht heeft geen social account en kan daarom niet worden gepubliceerd.',
+ 'choose_channel' => 'Kies een kanaal voordat je dit bericht inplant of publiceert.',
'queue_order_stale' => 'De wachtrij is gewijzigd sinds je hem opende. Vernieuw en probeer het opnieuw.',
'account_disconnected' => 'Social account is losgekoppeld',
- 'target_disabled' => 'Deze bestemming is uitgeschakeld',
'account_token_expired' => 'Sessie van social account verlopen — koppel opnieuw',
'platform_unavailable' => 'Het platform is tijdelijk niet beschikbaar. We proberen het zo opnieuw.',
'platform_unavailable_exhausted' => 'Het platform bleef na meerdere pogingen niet beschikbaar. Probeer het later opnieuw.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Nu aan het publiceren',
'publishing_badge' => 'Publiceren…',
'publishing_on' => 'Publiceren op :network…',
+ 'in_google_review' => 'In beoordeling bij Google',
'retrying_at' => 'Nieuwe poging om :time',
'published_via' => 'Gepubliceerd via',
'published_directly_from' => 'Rechtstreeks gepubliceerd vanuit :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Kanalen (:count)',
- 'collapse' => 'Kanalen verbergen',
- 'expand' => 'Kanalen tonen',
],
'approvals' => [
'badge' => 'Goedkeuring',
diff --git a/lang/nl/webhooks.php b/lang/nl/webhooks.php
index 9d72b78c6..b7a48786f 100644
--- a/lang/nl/webhooks.php
+++ b/lang/nl/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Wanneer een post wordt ingepland.',
'post_unscheduled' => 'Wanneer een geplande post terug naar concepten gaat.',
'post_published' => 'Wanneer een post live gaat op een kanaal.',
- 'post_partially_published' => 'Wanneer sommige kanalen publiceren en andere falen.',
'post_failed' => 'Wanneer het publiceren van een post mislukt.',
'post_deleted' => 'Wanneer een post wordt verwijderd.',
],
diff --git a/lang/pl/mail.php b/lang/pl/mail.php
index a79d36e8a..8b9f963e9 100644
--- a/lang/pl/mail.php
+++ b/lang/pl/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name prosi o zatwierdzenie w :workspace.',
'heading' => 'Post czeka na Twoje zatwierdzenie',
'body' => ':name (:email) prosi o zatwierdzenie w przestrzeni roboczej :workspace.',
- 'channels' => 'Kanały',
+ 'channel' => 'Kanał',
'requested_time' => 'Wybrany czas',
'next_queue_slot' => 'Następne miejsce w kolejce',
'as_soon_as_approved' => 'Gdy tylko zostanie zatwierdzony',
@@ -82,7 +82,7 @@ return [
'preview' => ':name zatwierdził(a) Twój post w :workspace.',
'heading' => 'Twój post został zatwierdzony',
'body' => ':name zatwierdził(a) Twój post w przestrzeni roboczej :workspace.',
- 'channels' => 'Kanały',
+ 'channel' => 'Kanał',
'goes_out' => 'Zostanie opublikowany',
'channel_time' => ':channel: :time',
'publishing_now' => 'Publikowanie teraz',
@@ -95,7 +95,7 @@ return [
'preview' => ':name przeniósł(a) Twój post z powrotem do wersji roboczych.',
'heading' => 'Twój post nie został zatwierdzony',
'body' => ':name przeniósł(a) Twój post w przestrzeni roboczej :workspace z powrotem do wersji roboczych.',
- 'channels' => 'Kanały',
+ 'channel' => 'Kanał',
'button' => 'Zobacz w wersjach roboczych',
],
diff --git a/lang/pl/posts.php b/lang/pl/posts.php
index 4e97a465a..24374ca05 100644
--- a/lang/pl/posts.php
+++ b/lang/pl/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publikowanie',
'retrying' => 'Ponawianie',
'published' => 'Opublikowany',
- 'partially_published' => 'Częściowo opublikowany',
'failed' => 'Nieudany',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Flagi',
],
- 'status' => [
- 'pending' => 'Oczekuje',
- 'scheduled' => 'Zaplanowany',
- 'published' => 'Opublikowany',
- 'publishing' => 'Publikowanie...',
- 'retrying' => 'Ponawianie...',
- 'failed' => 'Nieudany',
- 'pending_review' => 'W weryfikacji przez Google',
- 'rejected' => 'Odrzucony',
- ],
-
'delete_modal' => [
'title' => 'Usuń post',
'description' => 'Czy na pewno chcesz usunąć ten post? Tej operacji nie można cofnąć.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Ten plik jest większy niż dozwolone dla jego typu :size MB.',
'queue_requires_schedule' => 'Ten kanał nie ma jeszcze godzin publikacji. Dodaj je w ustawieniach kanału, aby korzystać z kolejki.',
'queue_with_scheduled_at' => 'Wybierz albo pozycję w kolejce, albo datę i godzinę, ale nie oba naraz.',
- 'queue_legacy_post' => 'Ten post został utworzony jednocześnie dla kilku kanałów i nie można go dodać do kolejki. Ustaw zamiast tego datę i godzinę.',
'queue_busy' => 'Kolejka jest aktualizowana. Spróbuj ponownie.',
'no_social_account' => 'Ten post nie ma konta społecznościowego, więc nie można go opublikować.',
+ 'choose_channel' => 'Wybierz kanał przed zaplanowaniem lub opublikowaniem tego posta.',
'queue_order_stale' => 'Kolejka zmieniła się od momentu jej otwarcia. Odśwież stronę i spróbuj ponownie.',
'account_disconnected' => 'Konto społecznościowe jest rozłączone',
- 'target_disabled' => 'Ten cel publikacji został wyłączony',
'account_token_expired' => 'Sesja konta społecznościowego wygasła — połącz ponownie',
'platform_unavailable' => 'Platforma jest tymczasowo niedostępna. Spróbujemy ponownie wkrótce.',
'platform_unavailable_exhausted' => 'Platforma pozostała niedostępna po kilku próbach. Spróbuj ponownie później.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Trwa publikacja',
'publishing_badge' => 'Publikowanie…',
'publishing_on' => 'Publikowanie w :network…',
+ 'in_google_review' => 'W weryfikacji przez Google',
'retrying_at' => 'Ponowna próba o :time',
'published_via' => 'Opublikowano przez',
'published_directly_from' => 'Opublikowano bezpośrednio w :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Kanały (:count)',
- 'collapse' => 'Ukryj kanały',
- 'expand' => 'Pokaż kanały',
],
'approvals' => [
'badge' => 'Zatwierdzenie',
diff --git a/lang/pl/webhooks.php b/lang/pl/webhooks.php
index f139643fb..d32f9f7ab 100644
--- a/lang/pl/webhooks.php
+++ b/lang/pl/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Gdy post zostanie zaplanowany do publikacji.',
'post_unscheduled' => 'Gdy zaplanowany post wraca do wersji roboczych.',
'post_published' => 'Gdy post zostanie opublikowany na kanale.',
- 'post_partially_published' => 'Gdy część kanałów publikuje, a część zawodzi.',
'post_failed' => 'Gdy publikacja posta się nie powiedzie.',
'post_deleted' => 'Gdy post zostanie usunięty.',
],
diff --git a/lang/pt-BR/mail.php b/lang/pt-BR/mail.php
index f436b5e1f..b02f9b783 100644
--- a/lang/pt-BR/mail.php
+++ b/lang/pt-BR/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name pediu aprovação em :workspace.',
'heading' => 'Um post precisa da sua aprovação',
'body' => ':name (:email) pediu aprovação no workspace :workspace.',
- 'channels' => 'Canais',
+ 'channel' => 'Canal',
'requested_time' => 'Horário pedido',
'next_queue_slot' => 'Próximo horário da fila',
'as_soon_as_approved' => 'Assim que for aprovado',
@@ -82,7 +82,7 @@ return [
'preview' => ':name aprovou seu post em :workspace.',
'heading' => 'Seu post foi aprovado',
'body' => ':name aprovou seu post no workspace :workspace.',
- 'channels' => 'Canais',
+ 'channel' => 'Canal',
'goes_out' => 'Vai ser publicado',
'channel_time' => ':channel: :time',
'publishing_now' => 'Publicando agora',
@@ -95,7 +95,7 @@ return [
'preview' => ':name devolveu seu post para os rascunhos.',
'heading' => 'Seu post não foi aprovado',
'body' => ':name devolveu seu post do workspace :workspace para os rascunhos.',
- 'channels' => 'Canais',
+ 'channel' => 'Canal',
'button' => 'Ver nos rascunhos',
],
diff --git a/lang/pt-BR/posts.php b/lang/pt-BR/posts.php
index 7e33d6867..7d6856cab 100644
--- a/lang/pt-BR/posts.php
+++ b/lang/pt-BR/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Publicando',
'retrying' => 'Tentando novamente',
'published' => 'Publicado',
- 'partially_published' => 'Parcialmente Publicado',
'failed' => 'Falhou',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Bandeiras',
],
- 'status' => [
- 'pending' => 'Pendente',
- 'scheduled' => 'Agendado',
- 'published' => 'Publicado',
- 'publishing' => 'Publicando...',
- 'retrying' => 'Tentando novamente...',
- 'failed' => 'Falhou',
- 'pending_review' => 'Em revisão pelo Google',
- 'rejected' => 'Recusado',
- ],
-
'delete_modal' => [
'title' => 'Excluir Post',
'description' => 'Tem certeza que deseja excluir este post? Esta ação não pode ser desfeita.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Este arquivo é maior que os :size MB permitidos para o tipo dele.',
'queue_requires_schedule' => 'Este canal ainda não tem horários de postagem. Adicione horários nas configurações do canal para usar a fila.',
'queue_with_scheduled_at' => 'Escolha uma posição na fila ou uma data e hora, não os dois.',
- 'queue_legacy_post' => 'Este post foi criado para vários canais de uma vez e não pode entrar em uma fila. Defina uma data e hora.',
'queue_busy' => 'A fila está sendo atualizada. Tente novamente.',
'no_social_account' => 'Este post não tem uma conta social, então não pode ser publicado.',
+ 'choose_channel' => 'Escolha um canal antes de agendar ou publicar este post.',
'queue_order_stale' => 'A fila mudou desde que você abriu. Atualize e tente de novo.',
'account_disconnected' => 'Conta social está desconectada',
- 'target_disabled' => 'Este destino foi desligado',
'account_token_expired' => 'Sessão da conta social expirou — reconecte a conta',
'platform_unavailable' => 'A plataforma está temporariamente indisponível. Vamos tentar de novo em breve.',
'platform_unavailable_exhausted' => 'A plataforma continuou indisponível após várias tentativas. Tente de novo mais tarde.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Publicando agora',
'publishing_badge' => 'Publicando…',
'publishing_on' => 'Publicando no :network…',
+ 'in_google_review' => 'Em revisão pelo Google',
'retrying_at' => 'Nova tentativa às :time',
'published_via' => 'Publicado via',
'published_directly_from' => 'Publicado diretamente pelo :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Canais (:count)',
- 'collapse' => 'Ocultar canais',
- 'expand' => 'Mostrar canais',
],
'approvals' => [
'badge' => 'Aprovação',
diff --git a/lang/pt-BR/webhooks.php b/lang/pt-BR/webhooks.php
index 516405a11..e8a67001f 100644
--- a/lang/pt-BR/webhooks.php
+++ b/lang/pt-BR/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Quando um post é agendado para publicação.',
'post_unscheduled' => 'Quando um post agendado volta para rascunhos.',
'post_published' => 'Quando um post é publicado em um canal.',
- 'post_partially_published' => 'Quando alguns canais publicam e outros falham.',
'post_failed' => 'Quando um post falha ao publicar.',
'post_deleted' => 'Quando um post é excluído.',
],
diff --git a/lang/ru/mail.php b/lang/ru/mail.php
index 460ff9651..7b7f5714a 100644
--- a/lang/ru/mail.php
+++ b/lang/ru/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name запросил(а) одобрение в :workspace.',
'heading' => 'Публикация ждёт вашего одобрения',
'body' => ':name (:email) запросил(а) одобрение в рабочем пространстве :workspace.',
- 'channels' => 'Каналы',
+ 'channel' => 'Канал',
'requested_time' => 'Запрошенное время',
'next_queue_slot' => 'Следующее место в очереди',
'as_soon_as_approved' => 'Сразу после одобрения',
@@ -82,7 +82,7 @@ return [
'preview' => ':name одобрил(а) вашу публикацию в :workspace.',
'heading' => 'Ваша публикация одобрена',
'body' => ':name одобрил(а) вашу публикацию в рабочем пространстве :workspace.',
- 'channels' => 'Каналы',
+ 'channel' => 'Канал',
'goes_out' => 'Будет опубликована',
'channel_time' => ':channel: :time',
'publishing_now' => 'Публикуется сейчас',
@@ -95,7 +95,7 @@ return [
'preview' => ':name вернул(а) вашу публикацию в черновики.',
'heading' => 'Ваша публикация не одобрена',
'body' => ':name вернул(а) вашу публикацию в рабочем пространстве :workspace в черновики.',
- 'channels' => 'Каналы',
+ 'channel' => 'Канал',
'button' => 'Посмотреть в черновиках',
],
diff --git a/lang/ru/posts.php b/lang/ru/posts.php
index 694b1245b..7c0d0b927 100644
--- a/lang/ru/posts.php
+++ b/lang/ru/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Публикуется',
'retrying' => 'Повторная попытка',
'published' => 'Опубликован',
- 'partially_published' => 'Частично опубликован',
'failed' => 'Ошибка',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Флаги',
],
- 'status' => [
- 'pending' => 'В ожидании',
- 'scheduled' => 'Запланирован',
- 'published' => 'Опубликован',
- 'publishing' => 'Публикация...',
- 'retrying' => 'Повторная попытка...',
- 'failed' => 'Ошибка',
- 'pending_review' => 'На проверке в Google',
- 'rejected' => 'Отклонено',
- ],
-
'delete_modal' => [
'title' => 'Удалить пост',
'description' => 'Вы уверены, что хотите удалить этот пост? Это действие нельзя отменить.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Этот файл больше допустимых для его типа :size МБ.',
'queue_requires_schedule' => 'У этого канала пока нет времени публикации. Добавьте время в настройках канала, чтобы использовать очередь.',
'queue_with_scheduled_at' => 'Выберите либо позицию в очереди, либо дату и время, но не оба варианта.',
- 'queue_legacy_post' => 'Этот пост создан сразу для нескольких каналов и не может быть добавлен в очередь. Укажите дату и время.',
'queue_busy' => 'Очередь обновляется. Повторите попытку.',
'no_social_account' => 'У этой публикации нет аккаунта соцсети, поэтому её нельзя опубликовать.',
+ 'choose_channel' => 'Выберите канал, прежде чем планировать или публиковать этот пост.',
'queue_order_stale' => 'Очередь изменилась с момента открытия. Обновите страницу и повторите попытку.',
'account_disconnected' => 'Социальный аккаунт отключён',
- 'target_disabled' => 'Этот канал публикации отключён',
'account_token_expired' => 'Сессия социального аккаунта истекла — переподключите',
'platform_unavailable' => 'Платформа временно недоступна. Мы повторим попытку вскоре.',
'platform_unavailable_exhausted' => 'Платформа оставалась недоступной после нескольких попыток. Попробуйте позже.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Публикуется сейчас',
'publishing_badge' => 'Публикация…',
'publishing_on' => 'Публикация в :network…',
+ 'in_google_review' => 'На проверке в Google',
'retrying_at' => 'Повтор в :time',
'published_via' => 'Опубликовано через',
'published_directly_from' => 'Опубликовано напрямую из :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Каналы (:count)',
- 'collapse' => 'Скрыть каналы',
- 'expand' => 'Показать каналы',
],
'approvals' => [
'badge' => 'Одобрение',
diff --git a/lang/ru/webhooks.php b/lang/ru/webhooks.php
index 26e55594b..9520180e5 100644
--- a/lang/ru/webhooks.php
+++ b/lang/ru/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Когда пост запланирован к публикации.',
'post_unscheduled' => 'Когда пост снят с расписания.',
'post_published' => 'Когда пост публикуется в канале.',
- 'post_partially_published' => 'Когда одни каналы публикуют, а другие нет.',
'post_failed' => 'Когда пост не удаётся опубликовать.',
'post_deleted' => 'Когда пост удалён.',
],
diff --git a/lang/tr/mail.php b/lang/tr/mail.php
index 7132aa7b0..840cf93a9 100644
--- a/lang/tr/mail.php
+++ b/lang/tr/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name, :workspace içinde onay istedi.',
'heading' => 'Bir gönderi onayınızı bekliyor',
'body' => ':name (:email), :workspace çalışma alanında onay istedi.',
- 'channels' => 'Kanallar',
+ 'channel' => 'Kanal',
'requested_time' => 'İstenen saat',
'next_queue_slot' => 'Kuyruktaki bir sonraki zaman',
'as_soon_as_approved' => 'Onaylanır onaylanmaz',
@@ -82,7 +82,7 @@ return [
'preview' => ':name, :workspace içindeki gönderinizi onayladı.',
'heading' => 'Gönderiniz onaylandı',
'body' => ':name, :workspace çalışma alanındaki gönderinizi onayladı.',
- 'channels' => 'Kanallar',
+ 'channel' => 'Kanal',
'goes_out' => 'Yayınlanacağı zaman',
'channel_time' => ':channel: :time',
'publishing_now' => 'Şimdi yayınlanıyor',
@@ -95,7 +95,7 @@ return [
'preview' => ':name gönderinizi taslaklara geri taşıdı.',
'heading' => 'Gönderiniz onaylanmadı',
'body' => ':name, :workspace çalışma alanındaki gönderinizi taslaklara geri taşıdı.',
- 'channels' => 'Kanallar',
+ 'channel' => 'Kanal',
'button' => 'Taslaklarda görüntüle',
],
diff --git a/lang/tr/posts.php b/lang/tr/posts.php
index fd34b50c6..d45bd2a3a 100644
--- a/lang/tr/posts.php
+++ b/lang/tr/posts.php
@@ -535,7 +535,6 @@ return [
'publishing' => 'Yayınlanıyor',
'retrying' => 'Yeniden deneniyor',
'published' => 'Yayınlandı',
- 'partially_published' => 'Kısmen Yayınlandı',
'failed' => 'Başarısız',
],
@@ -641,17 +640,6 @@ return [
'flags' => 'Bayraklar',
],
- 'status' => [
- 'pending' => 'Beklemede',
- 'scheduled' => 'Zamanlandı',
- 'published' => 'Yayınlandı',
- 'publishing' => 'Yayınlanıyor...',
- 'retrying' => 'Yeniden deneniyor...',
- 'failed' => 'Başarısız',
- 'pending_review' => 'Google incelemesinde',
- 'rejected' => 'Reddedildi',
- ],
-
'delete_modal' => [
'title' => 'Gönderiyi Sil',
'description' => 'Bu gönderiyi silmek istediğinizden emin misiniz? Bu işlem geri alınamaz.',
@@ -821,12 +809,11 @@ return [
'media_file_too_large' => 'Bu dosya, türü için izin verilen :size MB sınırını aşıyor.',
'queue_requires_schedule' => 'Bu kanalın henüz paylaşım saati yok. Kuyruğu kullanmak için kanal ayarlarından paylaşım saatleri ekleyin.',
'queue_with_scheduled_at' => 'Kuyruk konumu ya da tarih ve saat seçin, ikisini birden değil.',
- 'queue_legacy_post' => 'Bu gönderi aynı anda birden fazla kanal için oluşturuldu ve kuyruğa eklenemez. Bunun yerine tarih ve saat belirleyin.',
'queue_busy' => 'Kuyruk güncelleniyor. Lütfen tekrar deneyin.',
'no_social_account' => 'Bu gönderinin bir sosyal hesabı yok, bu yüzden yayınlanamaz.',
+ 'choose_channel' => 'Bu gönderiyi planlamadan veya yayınlamadan önce bir kanal seçin.',
'queue_order_stale' => 'Kuyruk siz açtıktan sonra değişti. Yenileyip tekrar deneyin.',
'account_disconnected' => 'Sosyal hesabın bağlantısı kesildi',
- 'target_disabled' => 'Bu hedef kapatıldı',
'account_token_expired' => 'Sosyal hesap oturumunun süresi doldu — lütfen yeniden bağlanın',
'platform_unavailable' => 'Platform geçici olarak kullanılamıyor. Kısa süre içinde yeniden deneyeceğiz.',
'platform_unavailable_exhausted' => 'Platform birkaç denemeden sonra kullanılamaz kaldı. Lütfen daha sonra tekrar deneyin.',
@@ -908,6 +895,7 @@ return [
'publishing_now' => 'Şimdi yayınlanıyor',
'publishing_badge' => 'Yayınlanıyor…',
'publishing_on' => ':network üzerinde paylaşılıyor…',
+ 'in_google_review' => 'Google incelemesinde',
'retrying_at' => ':time itibarıyla yeniden denenecek',
'published_via' => 'Yayınlandığı yer:',
'published_directly_from' => 'Doğrudan :network üzerinden yayınlandı',
@@ -994,8 +982,6 @@ return [
],
'group' => [
'channels' => 'Kanallar (:count)',
- 'collapse' => 'Kanalları gizle',
- 'expand' => 'Kanalları göster',
],
'approvals' => [
'badge' => 'Onay',
diff --git a/lang/tr/webhooks.php b/lang/tr/webhooks.php
index 93b31db4e..1ee9a6719 100644
--- a/lang/tr/webhooks.php
+++ b/lang/tr/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Bir gönderi yayın için zamanlandığında.',
'post_unscheduled' => 'Zamanlanmış bir gönderi taslaklara döndüğünde.',
'post_published' => 'Bir gönderi bir kanalda yayınlandığında.',
- 'post_partially_published' => 'Bazı kanallar yayınlayıp diğerleri başarısız olduğunda.',
'post_failed' => 'Bir gönderi yayınlanamadığında.',
'post_deleted' => 'Bir gönderi silindiğinde.',
],
diff --git a/lang/uk/mail.php b/lang/uk/mail.php
index 31d55e206..bea618b5e 100644
--- a/lang/uk/mail.php
+++ b/lang/uk/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name запросив(-ла) схвалення в :workspace.',
'heading' => 'Публікація чекає на ваше схвалення',
'body' => ':name (:email) запросив(-ла) схвалення в робочому просторі :workspace.',
- 'channels' => 'Канали',
+ 'channel' => 'Канал',
'requested_time' => 'Запитаний час',
'next_queue_slot' => 'Наступне місце в черзі',
'as_soon_as_approved' => 'Щойно його схвалять',
@@ -82,7 +82,7 @@ return [
'preview' => ':name схвалив(-ла) вашу публікацію в :workspace.',
'heading' => 'Вашу публікацію схвалено',
'body' => ':name схвалив(-ла) вашу публікацію в робочому просторі :workspace.',
- 'channels' => 'Канали',
+ 'channel' => 'Канал',
'goes_out' => 'Буде опубліковано',
'channel_time' => ':channel: :time',
'publishing_now' => 'Публікується зараз',
@@ -95,7 +95,7 @@ return [
'preview' => ':name повернув(-ла) вашу публікацію до чернеток.',
'heading' => 'Вашу публікацію не схвалено',
'body' => ':name повернув(-ла) вашу публікацію в робочому просторі :workspace до чернеток.',
- 'channels' => 'Канали',
+ 'channel' => 'Канал',
'button' => 'Переглянути в чернетках',
],
diff --git a/lang/uk/posts.php b/lang/uk/posts.php
index bad7442df..4783f3423 100644
--- a/lang/uk/posts.php
+++ b/lang/uk/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => 'Публікується',
'retrying' => 'Повторна спроба',
'published' => 'Опубліковано',
- 'partially_published' => 'Частково опубліковано',
'failed' => 'Помилка',
],
@@ -639,17 +638,6 @@ return [
'flags' => 'Прапори',
],
- 'status' => [
- 'pending' => 'Очікує',
- 'scheduled' => 'Заплановано',
- 'published' => 'Опубліковано',
- 'publishing' => 'Публікується...',
- 'retrying' => 'Повторна спроба...',
- 'failed' => 'Помилка',
- 'pending_review' => 'На перевірці в Google',
- 'rejected' => 'Відхилено',
- ],
-
'delete_modal' => [
'title' => 'Видалити пост',
'description' => 'Ви впевнені, що хочете видалити цей пост? Цю дію не можна скасувати.',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => 'Цей файл більший за дозволені для його типу :size МБ.',
'queue_requires_schedule' => 'Цей канал ще не має часу публікації. Додайте час у налаштуваннях каналу, щоб користуватися чергою.',
'queue_with_scheduled_at' => 'Виберіть або позицію в черзі, або дату й час, але не обидва варіанти.',
- 'queue_legacy_post' => 'Цей допис створено одразу для кількох каналів, тому його не можна додати до черги. Натомість вкажіть дату й час.',
'queue_busy' => 'Черга оновлюється. Спробуйте ще раз.',
'no_social_account' => 'Ця публікація не має акаунта соцмережі, тому її не можна опублікувати.',
+ 'choose_channel' => 'Виберіть канал, перш ніж планувати або публікувати цей допис.',
'queue_order_stale' => 'Черга змінилася з моменту відкриття. Оновіть сторінку та спробуйте ще раз.',
'account_disconnected' => 'Соціальний акаунт відключено',
- 'target_disabled' => 'Цей канал публікації вимкнено',
'account_token_expired' => 'Сесія соціального акаунта закінчилася — перепідключіть',
'platform_unavailable' => 'Платформа тимчасово недоступна. Ми спробуємо знову незабаром.',
'platform_unavailable_exhausted' => 'Платформа залишалася недоступною після кількох спроб. Спробуйте пізніше.',
@@ -906,6 +893,7 @@ return [
'publishing_now' => 'Публікується зараз',
'publishing_badge' => 'Публікація…',
'publishing_on' => 'Публікація в :network…',
+ 'in_google_review' => 'На перевірці в Google',
'retrying_at' => 'Повтор о :time',
'published_via' => 'Опубліковано через',
'published_directly_from' => 'Опубліковано напряму з :network',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => 'Канали (:count)',
- 'collapse' => 'Сховати канали',
- 'expand' => 'Показати канали',
],
'approvals' => [
'badge' => 'Схвалення',
diff --git a/lang/uk/webhooks.php b/lang/uk/webhooks.php
index 7fe440849..5538af5a4 100644
--- a/lang/uk/webhooks.php
+++ b/lang/uk/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => 'Коли пост заплановано до публікації.',
'post_unscheduled' => 'Коли запланований пост повертається до чернеток.',
'post_published' => 'Коли пост опубліковано в каналі.',
- 'post_partially_published' => 'Коли одні канали публікують, а інші ні.',
'post_failed' => 'Коли пост не вдалося опублікувати.',
'post_deleted' => 'Коли пост видалено.',
],
diff --git a/lang/zh/mail.php b/lang/zh/mail.php
index 40b514692..53162b6de 100644
--- a/lang/zh/mail.php
+++ b/lang/zh/mail.php
@@ -68,7 +68,7 @@ return [
'preview' => ':name 在 :workspace 中请求审批。',
'heading' => '有帖子需要你的审批',
'body' => ':name(:email)在工作区 :workspace 中请求审批。',
- 'channels' => '频道',
+ 'channel' => '频道',
'requested_time' => '请求的时间',
'next_queue_slot' => '队列中的下一个时段',
'as_soon_as_approved' => '获批后立即发布',
@@ -82,7 +82,7 @@ return [
'preview' => ':name 在 :workspace 中批准了你的帖子。',
'heading' => '你的帖子已获批准',
'body' => ':name 在工作区 :workspace 中批准了你的帖子。',
- 'channels' => '频道',
+ 'channel' => '频道',
'goes_out' => '发布时间',
'channel_time' => ':channel::time',
'publishing_now' => '正在发布',
@@ -95,7 +95,7 @@ return [
'preview' => ':name 已将你的帖子退回草稿。',
'heading' => '你的帖子未获批准',
'body' => ':name 已将你在工作区 :workspace 中的帖子退回草稿。',
- 'channels' => '频道',
+ 'channel' => '频道',
'button' => '在草稿中查看',
],
diff --git a/lang/zh/posts.php b/lang/zh/posts.php
index 3f037c285..4de091b98 100644
--- a/lang/zh/posts.php
+++ b/lang/zh/posts.php
@@ -533,7 +533,6 @@ return [
'publishing' => '发布中',
'retrying' => '重试中',
'published' => '已发布',
- 'partially_published' => '部分发布',
'failed' => '已失败',
],
@@ -639,17 +638,6 @@ return [
'flags' => '旗帜',
],
- 'status' => [
- 'pending' => '等待中',
- 'scheduled' => '已排期',
- 'published' => '已发布',
- 'publishing' => '发布中…',
- 'retrying' => '重试中…',
- 'failed' => '已失败',
- 'pending_review' => 'Google 审核中',
- 'rejected' => '已拒绝',
- ],
-
'delete_modal' => [
'title' => '删除帖子',
'description' => '确定要删除此帖子吗?此操作无法撤销。',
@@ -819,12 +807,11 @@ return [
'media_file_too_large' => '此文件超过其类型允许的 :size MB。',
'queue_requires_schedule' => '此频道尚未设置发布时间。请在频道设置中添加发布时间以使用队列。',
'queue_with_scheduled_at' => '请选择队列位置或日期时间,不能同时选择。',
- 'queue_legacy_post' => '此帖子是同时为多个频道创建的,无法加入队列。请改为设置日期和时间。',
'queue_busy' => '队列正在更新,请重试。',
'no_social_account' => '此帖子没有社交账号,因此无法发布。',
+ 'choose_channel' => '请先选择一个频道,再安排或发布此帖子。',
'queue_order_stale' => '自你打开以来队列已发生变化。请刷新后重试。',
'account_disconnected' => '社交账号已断开连接',
- 'target_disabled' => '已关闭此发布目标',
'account_token_expired' => '社交账号会话已过期——请重新连接',
'platform_unavailable' => '平台暂时不可用。我们稍后会重试。',
'platform_unavailable_exhausted' => '多次重试后平台仍不可用。请稍后再试。',
@@ -906,6 +893,7 @@ return [
'publishing_now' => '正在发布',
'publishing_badge' => '发布中…',
'publishing_on' => '正在发布到 :network…',
+ 'in_google_review' => 'Google 审核中',
'retrying_at' => '将于 :time 重试',
'published_via' => '发布于',
'published_directly_from' => '直接从 :network 发布',
@@ -992,8 +980,6 @@ return [
],
'group' => [
'channels' => '频道 (:count)',
- 'collapse' => '隐藏频道',
- 'expand' => '显示频道',
],
'approvals' => [
'badge' => '审批',
diff --git a/lang/zh/webhooks.php b/lang/zh/webhooks.php
index 796ca6141..176f305c8 100644
--- a/lang/zh/webhooks.php
+++ b/lang/zh/webhooks.php
@@ -96,7 +96,6 @@ return [
'post_scheduled' => '帖子被排期发布时。',
'post_unscheduled' => '已排期的帖子退回草稿时。',
'post_published' => '帖子在频道上发布时。',
- 'post_partially_published' => '部分频道发布成功、其他失败时。',
'post_failed' => '帖子发布失败时。',
'post_deleted' => '帖子被删除时。',
],
diff --git a/maizzle/components/channel-card.html b/maizzle/components/channel-card.html
new file mode 100644
index 000000000..c31a0f3b4
--- /dev/null
+++ b/maizzle/components/channel-card.html
@@ -0,0 +1,7 @@
+<table role="presentation" class="w-full mt-3">
+ <tr>
+ <td class="rounded-xl border border-solid border-border bg-surface p-4">
+ <x-channel-identity platform="$channel->platform" account-name="$channel->display_name" />
+ </td>
+ </tr>
+</table>
diff --git a/maizzle/components/channel-list.html b/maizzle/components/channel-list.html
deleted file mode 100644
index f8e017c46..000000000
--- a/maizzle/components/channel-list.html
+++ /dev/null
@@ -1,15 +0,0 @@
-<script props>
- module.exports = {
- channelsExpression: props.channels || '$channels',
- }
-</script>
-
-@foreach({!! channelsExpression !!} as $emailChannel)
- <table role="presentation" class="w-full mt-3">
- <tr>
- <td class="rounded-xl border border-solid border-border bg-surface p-4">
- <x-channel-identity platform="$emailChannel->platform" account-name="$emailChannel->display_name" />
- </td>
- </tr>
- </table>
-@endforeach
diff --git a/maizzle/templates/post-approval-requested.html b/maizzle/templates/post-approval-requested.html
index 53c68618a..8359b1bac 100644
--- a/maizzle/templates/post-approval-requested.html
+++ b/maizzle/templates/post-approval-requested.html
@@ -12,10 +12,12 @@
<p class="m-0 leading-6 text-sm text-foreground" style="white-space: pre-line;">@{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_approval_requested.post_without_text') }}</p>
</div>
- <p class="m-0 mt-4 text-sm font-semibold text-foreground">
- @{{ __('mail.post_approval_requested.channels') }}
- </p>
- <x-channel-list />
+ @if($channel)
+ <p class="m-0 mt-4 text-sm font-semibold text-foreground">
+ @{{ __('mail.post_approval_requested.channel') }}
+ </p>
+ <x-channel-card />
+ @endif
<p class="m-0 mt-4 text-sm font-semibold text-foreground">
@{{ __('mail.post_approval_requested.requested_time') }}
diff --git a/maizzle/templates/post-approved.html b/maizzle/templates/post-approved.html
index c61af75cc..bf32b1063 100644
--- a/maizzle/templates/post-approved.html
+++ b/maizzle/templates/post-approved.html
@@ -8,28 +8,18 @@
@{{ __('mail.post_approved.body', ['name' => $approverName, 'workspace' => $workspaceName]) }}
</p>
- @if(count($goesOutPerChannel) > 0)
+ @if($channel)
<p class="m-0 mt-4 text-sm font-semibold text-foreground">
- @{{ __('mail.post_approved.goes_out') }}
- </p>
- @foreach($goesOutPerChannel as $goesOut)
- <x-channel-list channels="$goesOut['channels']" />
- <p class="m-0 mt-2 text-sm leading-6">
- @{{ $goesOut['at'] ?? __('mail.post_approved.publishing_now') }}
- </p>
- @endforeach
- @else
- <p class="m-0 mt-4 text-sm font-semibold text-foreground">
- @{{ __('mail.post_approved.channels') }}
- </p>
- <x-channel-list />
- <p class="m-0 mt-4 text-sm font-semibold text-foreground">
- @{{ __('mail.post_approved.goes_out') }}
- </p>
- <p class="m-0 mt-2 leading-6 text-sm">
- @{{ $goesOutAt ?? __('mail.post_approved.publishing_now') }}
+ @{{ __('mail.post_approved.channel') }}
</p>
+ <x-channel-card />
@endif
+ <p class="m-0 mt-4 text-sm font-semibold text-foreground">
+ @{{ __('mail.post_approved.goes_out') }}
+ </p>
+ <p class="m-0 mt-2 leading-6 text-sm">
+ @{{ $goesOutAt ?? __('mail.post_approved.publishing_now') }}
+ </p>
<x-spacer height="24px" />
diff --git a/maizzle/templates/post-note-added.html b/maizzle/templates/post-note-added.html
index bca2762fc..1dff3aa8e 100644
--- a/maizzle/templates/post-note-added.html
+++ b/maizzle/templates/post-note-added.html
@@ -17,8 +17,8 @@
@{{ __('mail.post_note_added.post_title') }}
</p>
<p class="m-0 mt-2 leading-6 text-sm" style="white-space: pre-line;">@{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_note_added.post_without_text') }}</p>
- @if(count($channels) > 0)
- <x-channel-list />
+ @if($channel)
+ <x-channel-card />
@endif
</div>
diff --git a/maizzle/templates/post-publish-failed.html b/maizzle/templates/post-publish-failed.html
index 341120b4d..736f22f40 100644
--- a/maizzle/templates/post-publish-failed.html
+++ b/maizzle/templates/post-publish-failed.html
@@ -8,13 +8,11 @@
@{{ __('mail.post_publish_failed.body', ['workspace' => $workspaceName]) }}
</p>
- @if($publication)
- <x-post-preview />
- @if($publication['error'])
- <x-alert title-key="mail.post_preview.error">
- @{{ $publication['error'] }}
- </x-alert>
- @endif
+ <x-post-preview />
+ @if($publication['error'])
+ <x-alert title-key="mail.post_preview.error">
+ @{{ $publication['error'] }}
+ </x-alert>
@endif
<x-spacer height="24px" />
diff --git a/maizzle/templates/post-published.html b/maizzle/templates/post-published.html
index 62b5e7a5b..fd2bdedd0 100644
--- a/maizzle/templates/post-published.html
+++ b/maizzle/templates/post-published.html
@@ -8,9 +8,7 @@
@{{ __('mail.post_published.body', ['workspace' => $workspaceName]) }}
</p>
- @if($publication)
- <x-post-preview />
- @endif
+ <x-post-preview />
<x-spacer height="24px" />
diff --git a/maizzle/templates/post-rejected.html b/maizzle/templates/post-rejected.html
index 63a42965d..3c7f40476 100644
--- a/maizzle/templates/post-rejected.html
+++ b/maizzle/templates/post-rejected.html
@@ -8,10 +8,12 @@
@{{ __('mail.post_rejected.body', ['name' => $approverName, 'workspace' => $workspaceName]) }}
</p>
- <p class="m-0 mt-4 text-sm font-semibold text-foreground">
- @{{ __('mail.post_rejected.channels') }}
- </p>
- <x-channel-list />
+ @if($channel)
+ <p class="m-0 mt-4 text-sm font-semibold text-foreground">
+ @{{ __('mail.post_rejected.channel') }}
+ </p>
+ <x-channel-card />
+ @endif
<x-spacer height="24px" />
diff --git a/resources/js/components/ChannelConfigurator.vue b/resources/js/components/ChannelConfigurator.vue
index 615a46436..3f4750a5a 100644
--- a/resources/js/components/ChannelConfigurator.vue
+++ b/resources/js/components/ChannelConfigurator.vue
@@ -45,9 +45,6 @@ const emit = defineEmits<{
const isSelected = (id: string): boolean => props.selectedIds.includes(id);
-// Order matches the `platforms` array the editor submits (both filter the same
-// post_platforms list by the same selection), so a settings panel's position
-// here is the `platforms.{index}.*` index its backend errors are keyed by.
const selectedChannels = computed(() =>
props.channels.filter((channel) => isSelected(channel.id)),
);
@@ -179,6 +176,7 @@ const settingsIndex = (channel: Channel): number =>
:video-duration-sec="videoDurationSec"
:content-type="channel.contentType"
:meta="channel.meta"
+ :platform-index="settingsIndex(channel)"
:disabled="disabled"
@update:meta="updateMeta(channel, $event)"
/>
@@ -191,6 +189,7 @@ const settingsIndex = (channel: Channel): number =>
:boards="channel.boards ?? []"
:boards-truncated="channel.boardsTruncated ?? false"
:meta="channel.meta"
+ :platform-index="settingsIndex(channel)"
:disabled="disabled"
@update:meta="updateMeta(channel, $event)"
/>
@@ -217,6 +216,7 @@ const settingsIndex = (channel: Channel): number =>
v-else-if="channel.platform === Platform.Discord"
:social-account="channel.socialAccount"
:meta="channel.meta"
+ :platform-index="settingsIndex(channel)"
:disabled="disabled"
@update:meta="updateMeta(channel, $event)"
/>
diff --git a/resources/js/components/ConfirmDeleteModal.vue b/resources/js/components/ConfirmDeleteModal.vue
index 5f36f9cc0..09650a5b7 100644
--- a/resources/js/components/ConfirmDeleteModal.vue
+++ b/resources/js/components/ConfirmDeleteModal.vue
@@ -183,7 +183,11 @@ defineExpose({
<template>
<Dialog :open="isOpen" @update:open="onOpenChange">
- <DialogContent class="sm:max-w-md" data-testid="confirm-delete-modal">
+ <DialogContent
+ class="sm:max-w-md"
+ :fullscreen-on-mobile="false"
+ data-testid="confirm-delete-modal"
+ >
<DialogHeader>
<DialogTitle>{{ title }}</DialogTitle>
<DialogDescription data-testid="confirm-delete-description">{{
diff --git a/resources/js/components/posts/composer/ComposerNetworkSettings.vue b/resources/js/components/posts/composer/ComposerNetworkSettings.vue
index d994311dc..078999d53 100644
--- a/resources/js/components/posts/composer/ComposerNetworkSettings.vue
+++ b/resources/js/components/posts/composer/ComposerNetworkSettings.vue
@@ -132,6 +132,7 @@ const aiGenerated = computed({
:video-duration-sec="videoDurationSec"
:content-type="destination.content_type"
:meta="destination.meta"
+ :platform-index="platformIndex"
:disabled="disabled"
@update:meta="update"
/>
@@ -150,6 +151,7 @@ const aiGenerated = computed({
:boards="pinterestBoards?.boards ?? []"
:boards-truncated="pinterestBoards?.truncated ?? false"
:meta="destination.meta"
+ :platform-index="platformIndex"
:disabled="disabled"
@update:meta="update"
/>
@@ -175,6 +177,7 @@ const aiGenerated = computed({
v-else-if="account.platform === Platform.Discord"
:social-account="account"
:meta="destination.meta"
+ :platform-index="platformIndex"
:disabled="disabled"
@update:meta="update"
/>
diff --git a/resources/js/components/posts/composer/PostComposerDialog.vue b/resources/js/components/posts/composer/PostComposerDialog.vue
index 0e0aeaa8b..5a4cfa53d 100644
--- a/resources/js/components/posts/composer/PostComposerDialog.vue
+++ b/resources/js/components/posts/composer/PostComposerDialog.vue
@@ -814,11 +814,13 @@ const mediaErrorKeys = computed(() => {
};
for (const [key, message] of Object.entries(errors.value)) {
const shared = /^media\.(\d+)(\.|$)/.exec(key);
- if (shared) {
+ if (shared && !props.initialPost) {
record('', submitted.shared, Number(shared[1]), message);
continue;
}
- const match = /^destinations\.(\d+)\.media\.(\d+)(\.|$)/.exec(key);
+ const match = shared
+ ? ['', '0', shared[1]]
+ : /^destinations\.(\d+)\.media\.(\d+)(\.|$)/.exec(key);
const destination = match
? submitted.destinations[Number(match[1])]
: undefined;
@@ -1187,7 +1189,9 @@ const activeRemaining = (group: NetworkGroup): number | null => {
const threadReplyErrors = (group: NetworkGroup): Record<number, string> => {
const found: Record<number, string> = {};
for (const account of group.accounts) {
- const prefix = `destinations.${selectedAccounts.value.indexOf(account)}.meta.thread_replies`;
+ const prefix = props.initialPost
+ ? 'meta.thread_replies'
+ : `destinations.${selectedAccounts.value.indexOf(account)}.meta.thread_replies`;
for (const [key, message] of Object.entries(errors.value)) {
const match = key.startsWith(`${prefix}.`)
? Number(key.slice(prefix.length + 1).split('.')[0])
@@ -1809,17 +1813,17 @@ const onMediaEdited = async (changes: MediaEditChange[]): Promise<void> => {
const submit = (status: PostComposition['status']): void => {
if (
!canSubmit.value ||
- (status !== 'draft' && hasBlockingIssues.value)
+ (status !== PostStatus.Draft && hasBlockingIssues.value)
)
return;
submittedMedia.value = snapshotMedia();
const queue =
- status === 'scheduled' &&
+ status === PostStatus.Scheduled &&
(scheduleMode.value === 'next' || scheduleMode.value === 'top')
? scheduleMode.value
: null;
const payload = composition.materialize(status, queue);
- if (status === 'scheduled' && !queue) {
+ if (status === PostStatus.Scheduled && !queue) {
if (!scheduledInstant) return;
payload.scheduled_at = scheduledInstant;
if (isInitialQueueSlot()) payload.queue_slot = scheduledInstant;
@@ -1836,8 +1840,16 @@ const submit = (status: PostComposition['status']): void => {
emit('submit', payload, createAnother.value && !props.postId);
};
+const submitDraft = (): void => {
+ submit(PostStatus.Draft);
+};
+
const submitSelectedSchedule = (): void => {
- submit(scheduleMode.value === 'now' ? 'publishing' : 'scheduled');
+ submit(
+ scheduleMode.value === 'now'
+ ? PostStatus.Publishing
+ : PostStatus.Scheduled,
+ );
};
const isScheduleModeDisabled = (mode: ComposerScheduleMode): boolean =>
@@ -3326,7 +3338,7 @@ const close = (): void => emit('update:open', false);
class="max-sm:h-8 max-sm:px-3"
data-testid="composer-save-draft"
:disabled="!canSubmit"
- @click="submit('draft')"
+ @click="submitDraft"
>{{ $t(draftActionLabel) }}</Button
>
<p
diff --git a/resources/js/components/posts/editor/DiscordSettings.vue b/resources/js/components/posts/editor/DiscordSettings.vue
index b9680ba08..c05841e90 100644
--- a/resources/js/components/posts/editor/DiscordSettings.vue
+++ b/resources/js/components/posts/editor/DiscordSettings.vue
@@ -14,7 +14,7 @@ import SettingsSection from '@/components/posts/editor/SettingsSection.vue';
import SearchableSelect from '@/components/SearchableSelect.vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
-import { usePageErrors } from '@/composables/usePageErrors';
+import { useMetaErrors } from '@/composables/useMetaErrors';
interface SocialAccount {
id: string;
@@ -55,6 +55,7 @@ const props = withDefaults(
defineProps<{
socialAccount: SocialAccount | null;
meta: Record<string, any>;
+ platformIndex: number;
disabled?: boolean;
}>(),
{ disabled: false },
@@ -133,16 +134,10 @@ watch(
{ immediate: true },
);
-const errors = usePageErrors();
-const channelError = computed<string | undefined>(() => {
- if (props.meta?.channel_id) {
- return undefined;
- }
-
- return Object.entries(errors.value).find(([key]) =>
- key.endsWith('.meta.channel_id'),
- )?.[1];
-});
+const storedChannelError = useMetaErrors(() => props.platformIndex)('channel_id');
+const channelError = computed(() =>
+ props.meta?.channel_id ? undefined : storedChannelError.value,
+);
const mentionQuery = ref('');
const mentionResults = ref<MentionTarget[]>([]);
diff --git a/resources/js/components/posts/editor/GoogleBusinessSettings.vue b/resources/js/components/posts/editor/GoogleBusinessSettings.vue
index 5d11ef391..6ead692f1 100644
--- a/resources/js/components/posts/editor/GoogleBusinessSettings.vue
+++ b/resources/js/components/posts/editor/GoogleBusinessSettings.vue
@@ -15,7 +15,7 @@ import {
SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
-import { usePageErrors } from '@/composables/usePageErrors';
+import { useMetaErrors } from '@/composables/useMetaErrors';
import {
GOOGLE_BUSINESS_CTA_OPTIONS,
GoogleBusinessCtaAction,
@@ -27,7 +27,7 @@ import {
} from '@/lib/googleBusiness';
interface Props {
- /** This panel's position in the submitted `destinations` (composer) or `platforms` array — see findError. */
+ /** This panel's position in the submitted `destinations` (composer); an edit has one and reports `meta.*` — see useMetaErrors. */
platformIndex: number;
meta: Record<string, any>;
disabled?: boolean;
@@ -192,23 +192,17 @@ const offerCouponCode = offerField('coupon_code');
const offerRedeemUrl = offerField('redeem_online_url');
const offerTerms = offerField('terms_conditions');
-const errors = usePageErrors();
-const findError = (field: string) =>
- computed<string | undefined>(
- () =>
- errors.value[`destinations.${props.platformIndex}.meta.${field}`] ??
- errors.value[`platforms.${props.platformIndex}.meta.${field}`],
- );
-const eventTitleError = findError('event.title');
-const eventStartDateError = findError('event.start_date');
-const eventEndDateError = findError('event.end_date');
-const eventStartTimeError = findError('event.start_time');
-const eventEndTimeError = findError('event.end_time');
-const offerCouponCodeError = findError('offer.coupon_code');
-const offerRedeemUrlError = findError('offer.redeem_online_url');
-const offerTermsError = findError('offer.terms_conditions');
-const ctaActionTypeError = findError('call_to_action.action_type');
-const ctaUrlError = findError('call_to_action.url');
+const metaError = useMetaErrors(() => props.platformIndex);
+const eventTitleError = metaError('event.title');
+const eventStartDateError = metaError('event.start_date');
+const eventEndDateError = metaError('event.end_date');
+const eventStartTimeError = metaError('event.start_time');
+const eventEndTimeError = metaError('event.end_time');
+const offerCouponCodeError = metaError('offer.coupon_code');
+const offerRedeemUrlError = metaError('offer.redeem_online_url');
+const offerTermsError = metaError('offer.terms_conditions');
+const ctaActionTypeError = metaError('call_to_action.action_type');
+const ctaUrlError = metaError('call_to_action.url');
</script>
<template>
diff --git a/resources/js/components/posts/editor/PinterestSettings.vue b/resources/js/components/posts/editor/PinterestSettings.vue
index 59ebc8109..86b44b057 100644
--- a/resources/js/components/posts/editor/PinterestSettings.vue
+++ b/resources/js/components/posts/editor/PinterestSettings.vue
@@ -6,7 +6,7 @@ import PinterestBoardPicker from '@/components/posts/editor/PinterestBoardPicker
import SettingsRow from '@/components/posts/editor/SettingsRow.vue';
import SettingsSection from '@/components/posts/editor/SettingsSection.vue';
import { Input } from '@/components/ui/input';
-import { usePageErrors } from '@/composables/usePageErrors';
+import { useMetaErrors } from '@/composables/useMetaErrors';
import type { PinterestBoard } from '@/types';
interface SocialAccount {
@@ -19,6 +19,7 @@ interface Props {
boards: PinterestBoard[];
boardsTruncated?: boolean;
meta: Record<string, any>;
+ platformIndex: number;
disabled?: boolean;
}
@@ -61,17 +62,10 @@ const pinLink = computed({
},
});
-const errors = usePageErrors();
-const fieldError = (field: string) =>
- computed<string | undefined>(
- () =>
- Object.entries(errors.value).find(([key]) =>
- key.endsWith(`.meta.${field}`),
- )?.[1],
- );
-const titleError = fieldError('title');
-const linkError = fieldError('link');
-const storedBoardError = fieldError('board_id');
+const metaError = useMetaErrors(() => props.platformIndex);
+const titleError = metaError('title');
+const linkError = metaError('link');
+const storedBoardError = metaError('board_id');
const boardError = computed(() =>
props.meta?.board_id ? undefined : storedBoardError.value,
);
diff --git a/resources/js/components/posts/editor/TikTokSettings.vue b/resources/js/components/posts/editor/TikTokSettings.vue
index 761c0f560..5c7ee44d7 100644
--- a/resources/js/components/posts/editor/TikTokSettings.vue
+++ b/resources/js/components/posts/editor/TikTokSettings.vue
@@ -16,7 +16,7 @@ import {
SelectValue,
} from '@/components/ui/select';
import { Switch } from '@/components/ui/switch';
-import { usePageErrors } from '@/composables/usePageErrors';
+import { useMetaErrors } from '@/composables/useMetaErrors';
import { ContentType } from '@/types/content-type';
import {
isTikTokPrivacyLevel,
@@ -52,6 +52,7 @@ interface Props {
videoDurationSec?: number | null;
contentType: string;
meta: Record<string, any>;
+ platformIndex: number;
disabled?: boolean;
}
@@ -65,16 +66,13 @@ const emit = defineEmits<{
'update:meta': [value: Record<string, any>];
}>();
-const errors = usePageErrors();
-const privacyError = computed<string | undefined>(() => {
- if (isTikTokPrivacyLevel(props.meta?.privacy_level)) {
- return undefined;
- }
-
- return Object.entries(errors.value).find(([key]) =>
- key.endsWith('.meta.privacy_level'),
- )?.[1];
-});
+const metaError = useMetaErrors(() => props.platformIndex);
+const storedPrivacyError = metaError('privacy_level');
+const privacyError = computed(() =>
+ isTikTokPrivacyLevel(props.meta?.privacy_level)
+ ? undefined
+ : storedPrivacyError.value,
+);
const updateMeta = (patch: Record<string, any>) => {
emit('update:meta', { ...props.meta, ...patch });
diff --git a/resources/js/components/posts/editor/YouTubeSettings.vue b/resources/js/components/posts/editor/YouTubeSettings.vue
index 4feff471f..749799a0c 100644
--- a/resources/js/components/posts/editor/YouTubeSettings.vue
+++ b/resources/js/components/posts/editor/YouTubeSettings.vue
@@ -15,7 +15,7 @@ import {
SelectValue,
} from '@/components/ui/select';
import { Textarea } from '@/components/ui/textarea';
-import { usePageErrors } from '@/composables/usePageErrors';
+import { useMetaErrors } from '@/composables/useMetaErrors';
import { htmlToPlainText, toNullableText } from '@/lib/utils';
import {
getYouTubeDescriptionIssue,
@@ -52,7 +52,7 @@ const emit = defineEmits<{
'update:meta': [value: Record<string, unknown>];
}>();
-const errors = usePageErrors();
+const metaError = useMetaErrors(() => props.platformIndex);
const descriptionId = computed(
() => `youtube-description-${props.platformIndex}`,
);
@@ -153,11 +153,7 @@ const labelFor = (
options: readonly { value: string; labelKey: string }[],
value: string,
): string => options.find((option) => option.value === value)?.labelKey ?? '';
-const titleError = computed(
- () =>
- errors.value[`destinations.${props.platformIndex}.meta.title`] ??
- errors.value[`platforms.${props.platformIndex}.meta.title`],
-);
+const titleError = metaError('title');
const description = computed({
get: () => toNullableText(props.meta.description) ?? '',
@@ -167,11 +163,7 @@ const usedBytes = computed(() => youtubeDescriptionBytes(description.value));
const descriptionIssueKey = computed(() =>
getYouTubeDescriptionIssue(props.meta.description),
);
-const descriptionServerError = computed(
- () =>
- errors.value[`destinations.${props.platformIndex}.meta.description`] ??
- errors.value[`platforms.${props.platformIndex}.meta.description`],
-);
+const descriptionServerError = metaError('description');
const hasDescriptionError = computed(
() => !!descriptionIssueKey.value || !!descriptionServerError.value,
);
diff --git a/resources/js/components/publish/ApprovePostButton.vue b/resources/js/components/publish/ApprovePostButton.vue
index 95d3d5bf2..f7925ed71 100644
--- a/resources/js/components/publish/ApprovePostButton.vue
+++ b/resources/js/components/publish/ApprovePostButton.vue
@@ -11,10 +11,10 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
-import { useComposerTimezone } from '@/composables/useComposerTimezone';
import { toastFirstError } from '@/composables/usePostCardActions';
import date from '@/date';
import dayjs from '@/dayjs';
+import { userTimezone } from '@/preferences';
import { ScheduleMode } from '@/types/post';
import type { PostCard } from '@/types/publish';
@@ -33,10 +33,8 @@ const isQueued = computed(
() => props.post.schedule_mode === ScheduleMode.Queue,
);
-const postTimezone = useComposerTimezone(() =>
- props.post.post_platforms
- .filter((platform) => platform.enabled)
- .map((platform) => platform.social_account ?? {}),
+const postTimezone = computed(
+ () => props.post.social_account?.timezone ?? userTimezone.value,
);
const needsTime = computed(
diff --git a/resources/js/components/publish/CalendarPeriodPicker.vue b/resources/js/components/publish/CalendarPeriodPicker.vue
index ff2e9d38b..49f969c0f 100644
--- a/resources/js/components/publish/CalendarPeriodPicker.vue
+++ b/resources/js/components/publish/CalendarPeriodPicker.vue
@@ -7,7 +7,7 @@ import {
IconChevronLeft,
IconChevronRight,
} from '@tabler/icons-vue';
-import { computed, ref } from 'vue';
+import { computed, ref, useTemplateRef } from 'vue';
import ResponsivePopover from '@/components/ResponsivePopover.vue';
import { Button } from '@/components/ui/button';
@@ -67,6 +67,15 @@ const pickDay = (value: DateValue | undefined): void => {
close();
emit('pickDay', value.toString());
};
+
+const titleElement = useTemplateRef<HTMLHeadingElement>('titleElement');
+
+const missingTitleWidth = (): number =>
+ titleElement.value
+ ? titleElement.value.scrollWidth - titleElement.value.clientWidth
+ : 0;
+
+defineExpose({ missingTitleWidth });
</script>
<template>
@@ -147,12 +156,12 @@ const pickDay = (value: DateValue | undefined): void => {
</div>
</ResponsivePopover>
- <div v-else class="flex h-12 min-w-0 items-center gap-4">
+ <div v-else class="flex h-12 min-w-0 items-center gap-2">
<div class="flex min-w-0 items-center">
<Button
variant="ghost"
size="icon"
- class="-ms-3 shrink-0"
+ class="shrink-0"
:aria-label="$t('calendar.previous')"
data-testid="calendar-previous"
@click="emit('navigate', -1)"
@@ -170,6 +179,7 @@ const pickDay = (value: DateValue | undefined): void => {
<IconChevronRight class="size-4" />
</Button>
<h2
+ ref="titleElement"
class="ms-1 truncate font-heading text-base leading-5 font-medium text-foreground capitalize"
data-testid="calendar-title"
>
diff --git a/resources/js/components/publish/CalendarPostChip.vue b/resources/js/components/publish/CalendarPostChip.vue
index 8db80b003..a99734a93 100644
--- a/resources/js/components/publish/CalendarPostChip.vue
+++ b/resources/js/components/publish/CalendarPostChip.vue
@@ -31,7 +31,6 @@ const props = withDefaults(
{ layout: 'month' },
);
-const MAX_ICONS = 4;
const open = ref(false);
const detailsOpen = ref(false);
@@ -65,13 +64,11 @@ const onDetails = (value: boolean): void => {
const SENT_STATUSES: readonly string[] = [
PostStatus.Published,
- PostStatus.PartiallyPublished,
PostStatus.Failed,
];
const STATUS_CLASSES: Record<string, string> = {
draft: 'border-dashed',
- partially_published: 'border-warning/40 bg-warning/5',
failed: 'border-destructive/40 bg-destructive/5',
};
@@ -89,27 +86,11 @@ const tab = computed((): PublishTab => {
: 'queue';
});
-const visibleTargets = computed(() =>
- props.post.post_platforms.slice(
- 0,
- props.post.post_platforms.length > MAX_ICONS
- ? MAX_ICONS - 1
- : MAX_ICONS,
- ),
-);
-
-const hiddenTargets = computed(
- () => props.post.post_platforms.length - visibleTargets.value.length,
-);
-
const channels = computed(() =>
- props.post.post_platforms
- .map(
- (target) =>
- target.social_account?.display_label ??
- getPlatformLabel(target.platform),
- )
- .join(', '),
+ props.post.platform
+ ? (props.post.social_account?.display_label ??
+ getPlatformLabel(props.post.platform))
+ : '',
);
const time = computed(() =>
@@ -166,16 +147,10 @@ const scheduleMode = computed(() =>
<span class="flex min-w-0 flex-1 flex-col gap-1">
<span class="flex min-w-0 items-center gap-1">
<PlatformBrandIcon
- v-for="target in visibleTargets"
- :key="target.id"
- :platform="target.platform"
+ v-if="post.platform"
+ :platform="post.platform"
class="size-4 shrink-0"
/>
- <span
- v-if="hiddenTargets > 0"
- class="text-xs text-muted-foreground"
- >+{{ hiddenTargets }}</span
- >
<span
class="truncate text-xs font-medium text-muted-foreground"
>{{ time }}</span
diff --git a/resources/js/components/publish/CalendarTimeGrid.vue b/resources/js/components/publish/CalendarTimeGrid.vue
index d2f9a1e8e..33968882d 100644
--- a/resources/js/components/publish/CalendarTimeGrid.vue
+++ b/resources/js/components/publish/CalendarTimeGrid.vue
@@ -66,6 +66,11 @@ const expandHour = (key: string, hour: number): void => {
expandedHours.value = [...expandedHours.value, `${key}-${hour}`];
};
+const isStacked = (
+ column: { byHour: Map<number, CalendarItem[]> },
+ hour: number,
+): boolean => (column.byHour.get(hour)?.length ?? 0) > 1;
+
const visibleItems = (
key: string,
hour: number,
@@ -167,10 +172,15 @@ watch(
</div>
<div
- class="flex min-w-0 flex-1 gap-1"
+ class="flex min-w-0 flex-1"
:class="
- isExpanded(column.key, hour)
- ? 'max-h-full flex-col overflow-y-auto overscroll-contain'
+ isStacked(column, hour)
+ ? [
+ 'flex-col gap-0.5',
+ isExpanded(column.key, hour)
+ ? 'max-h-full overflow-y-auto overscroll-contain'
+ : '',
+ ]
: 'flex-nowrap'
"
>
@@ -186,14 +196,16 @@ watch(
v-if="item.post"
:post="item.post"
:timezone="timezone"
- layout="week"
- class="flex-1"
- :class="{
- 'min-h-7 grow-0': isExpanded(
- column.key,
- hour,
- ),
- }"
+ :layout="
+ isStacked(column, hour)
+ ? 'month'
+ : 'week'
+ "
+ :class="
+ isStacked(column, hour)
+ ? 'w-full shrink-0'
+ : 'flex-1'
+ "
/>
<CalendarSlotChip
v-else-if="item.slot"
@@ -201,13 +213,11 @@ watch(
:channel="channels[item.slot.channel_id] ?? null"
:timezone="timezone"
:can-create-post="canCreatePost"
- class="flex-1"
- :class="{
- 'min-h-7 grow-0': isExpanded(
- column.key,
- hour,
- ),
- }"
+ :class="
+ isStacked(column, hour)
+ ? 'w-full shrink-0'
+ : 'flex-1'
+ "
/>
</template>
<button
@@ -217,7 +227,7 @@ watch(
MAX_CHIPS
"
type="button"
- class="flex h-7 shrink-0 items-center rounded-lg px-1.5 text-xs font-medium text-muted-foreground transition-control hover:bg-secondary hover:text-foreground"
+ class="flex h-7 w-full shrink-0 items-center rounded-lg px-1.5 text-xs font-medium text-muted-foreground transition-control hover:bg-secondary hover:text-foreground"
:data-testid="`calendar-more-${column.key}-${hourLabel(hour)}`"
@click="expandHour(column.key, hour)"
>
@@ -233,7 +243,7 @@ watch(
v-if="canCreatePost && !isPastSlot(column.key, hour)"
type="button"
:aria-label="$t('calendar.new_post')"
- class="flex size-6 shrink-0 items-center justify-center rounded-md border border-border-strong bg-card text-muted-foreground opacity-0 transition-opacity duration-100 ease-in-out group-hover:opacity-100 hover:text-foreground focus-visible:opacity-100 max-md:hidden [@media(hover:none)]:opacity-100"
+ class="flex size-7 shrink-0 items-center justify-center rounded-lg border border-dashed border-border-strong text-muted-foreground opacity-0 transition-opacity duration-100 ease-in-out group-hover:opacity-100 hover:bg-accent hover:text-accent-foreground focus-visible:opacity-100 max-md:hidden [@media(hover:none)]:opacity-100"
:data-testid="`calendar-add-${column.key}-${hourLabel(hour)}`"
@click="compose(column.key, hour)"
>
diff --git a/resources/js/components/publish/CalendarUndatedPanel.vue b/resources/js/components/publish/CalendarUndatedPanel.vue
index a9ad8cf40..d95c28121 100644
--- a/resources/js/components/publish/CalendarUndatedPanel.vue
+++ b/resources/js/components/publish/CalendarUndatedPanel.vue
@@ -26,8 +26,6 @@ const thumbnail = (draft: UndatedDraft): string | null =>
const plainText = (draft: UndatedDraft): string =>
htmlToPlainText(draft.content ?? '').trim();
-
-const target = (draft: UndatedDraft) => draft.post_platforms[0] ?? null;
</script>
<template>
@@ -95,17 +93,16 @@ const target = (draft: UndatedDraft) => draft.post_platforms[0] ?? null;
>
<div class="flex min-w-0 items-center gap-2">
<img
- v-if="target(draft)"
- :src="getPlatformLogo(target(draft)!.platform)"
- :alt="getPlatformLabel(target(draft)!.platform)"
+ v-if="draft.platform"
+ :src="getPlatformLogo(draft.platform)"
+ :alt="getPlatformLabel(draft.platform)"
class="size-4 shrink-0 rounded-sm"
/>
<span
class="min-w-0 flex-1 truncate text-sm leading-[17.5px] font-emphasis text-foreground"
>
{{
- target(draft)?.social_account
- ?.display_label ??
+ draft.social_account?.display_label ??
$t('calendar.undated.no_channel')
}}
</span>
diff --git a/resources/js/components/publish/PostDetailsDialog.vue b/resources/js/components/publish/PostDetailsDialog.vue
index 7a8f86ec9..9e0059a0e 100644
--- a/resources/js/components/publish/PostDetailsDialog.vue
+++ b/resources/js/components/publish/PostDetailsDialog.vue
@@ -2,8 +2,6 @@
import { useHttp } from '@inertiajs/vue3';
import {
IconExternalLink,
- IconLayoutSidebarLeftCollapse,
- IconLayoutSidebarLeftExpand,
IconPencil,
IconRepeat,
IconSend,
@@ -36,10 +34,7 @@ import {
getPlatformLabel,
} from '@/composables/usePlatformLogo';
import { schedulePostCard } from '@/composables/usePostCardActions';
-import {
- getPlatformStatusConfig,
- getPostStatusConfig,
-} from '@/composables/usePostStatus';
+import { getPostStatusConfig } from '@/composables/usePostStatus';
import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';
import date from '@/date';
import dayjs from '@/dayjs';
@@ -49,7 +44,7 @@ import { type ThreadReply, threadRepliesOf } from '@/lib/threadReplies';
import type { MediaItem } from '@/types/media';
import { THREAD_PLATFORMS } from '@/types/network-options';
import { Platform } from '@/types/platform';
-import { PostOrigin, PostStatus } from '@/types/post';
+import { PostOrigin, PostStatus, PublishStatus } from '@/types/post';
import type { PostCard, PostCardMenuAction } from '@/types/publish';
const props = defineProps<{
@@ -75,16 +70,6 @@ const selectSibling = (id: typeof selectedId.value): void => {
selectedId.value = id;
};
-const railCollapsed = ref(false);
-
-const collapseRail = (): void => {
- railCollapsed.value = true;
-};
-
-const expandRail = (): void => {
- railCollapsed.value = false;
-};
-
const loadGroup = async (): Promise<void> => {
try {
const response = await http.get(showPostGroup.url(props.post.id));
@@ -132,20 +117,37 @@ const current = computed<PostCard>(() =>
props.post),
);
+const isInGoogleReview = computed(
+ () =>
+ current.value.status === PostStatus.Publishing &&
+ current.value.publish_status === PublishStatus.PendingReview,
+);
+
+const currentStatusConfig = computed(() =>
+ getPostStatusConfig(
+ isInGoogleReview.value
+ ? PublishStatus.PendingReview
+ : current.value.status,
+ ),
+);
+
const currentKey = computed(() =>
current.value.id === props.post.id ? props.testKey : current.value.id,
);
-const targets = computed(() =>
- current.value.post_platforms.filter((target) => target.enabled),
+const channel = computed(() =>
+ current.value.platform
+ ? {
+ platform: current.value.platform,
+ social_account: current.value.social_account,
+ }
+ : null,
);
-const permalink = computed(() => targets.value[0]?.platform_url ?? null);
+const permalink = computed(() => current.value.platform_url ?? null);
const metricsDetail = computed(() => {
- const detail = targets.value[0]
- ? current.value.metrics?.[targets.value[0].id]
- : null;
+ const detail = current.value.metrics ?? null;
return detail &&
detail.available &&
@@ -201,10 +203,8 @@ watch(
);
const threadReplies = computed((): ThreadReply[] => {
- const target = targets.value[0];
-
- return target && THREAD_PLATFORMS.includes(target.platform)
- ? threadRepliesOf(target.meta).filter(
+ return channel.value && THREAD_PLATFORMS.includes(channel.value.platform)
+ ? threadRepliesOf(current.value.meta ?? {}).filter(
(reply) => reply.text.trim() !== '' || reply.media.length > 0,
)
: [];
@@ -213,7 +213,7 @@ const threadReplies = computed((): ThreadReply[] => {
const showsThread = computed(
() =>
threadReplies.value.length > 0 &&
- Boolean(targets.value[0]?.social_account),
+ Boolean(channel.value?.social_account),
);
const lightboxOpen = ref(false);
@@ -233,11 +233,9 @@ const isEditable = computed(
current.value.status === PostStatus.PendingApproval,
);
-const siblingAccount = (sibling: PostCard) =>
- sibling.post_platforms[0]?.social_account ?? null;
+const siblingAccount = (sibling: PostCard) => sibling.social_account ?? null;
-const siblingPlatform = (sibling: PostCard): string =>
- sibling.post_platforms[0]?.platform ?? '';
+const siblingPlatform = (sibling: PostCard): string => sibling.platform ?? '';
const siblingMoment = (sibling: PostCard): string | null => {
const at = sibling.published_at ?? sibling.scheduled_at;
@@ -254,36 +252,25 @@ const siblingMoment = (sibling: PostCard): string | null => {
<template>
<Dialog v-model:open="open">
<DialogContent
- class="gap-0 p-0"
+ class="gap-0 p-0 sm:overflow-hidden"
:class="
- isGrouped && !railCollapsed ? 'sm:max-w-4xl' : 'sm:max-w-xl'
+ isGrouped ? 'sm:max-w-4xl' : 'sm:max-w-xl'
"
:data-testid="`post-details-${testKey}`"
>
- <div class="flex min-h-0 min-w-0 flex-col sm:flex-row">
+ <div class="flex min-h-0 min-w-0 flex-col sm:max-h-[85dvh] sm:flex-row">
<aside
- v-if="showRail && !railCollapsed"
- class="flex shrink-0 flex-col gap-2 border-b border-border p-4 sm:w-64 sm:border-e sm:border-b-0"
+ v-if="showRail"
+ class="flex shrink-0 flex-col gap-2 border-b border-border p-4 sm:w-64 sm:overflow-y-auto sm:border-e sm:border-b-0"
:data-testid="`post-details-rail-${testKey}`"
>
- <div class="flex items-center justify-between gap-2">
- <p class="text-sm text-muted-foreground">
- {{
- $t('posts.group.channels', {
- count: String(siblings.length),
- })
- }}
- </p>
- <Button
- variant="ghost"
- size="icon"
- :aria-label="$t('posts.group.collapse')"
- :data-testid="`post-details-rail-collapse-${testKey}`"
- @click="collapseRail"
- >
- <IconLayoutSidebarLeftCollapse class="size-4" />
- </Button>
- </div>
+ <p class="text-sm text-muted-foreground">
+ {{
+ $t('posts.group.channels', {
+ count: String(siblings.length),
+ })
+ }}
+ </p>
<button
v-for="sibling in siblings"
:key="sibling.id"
@@ -342,35 +329,30 @@ const siblingMoment = (sibling: PostCard): string | null => {
<Skeleton class="h-10 w-full" />
</div>
- <div class="flex min-w-0 flex-1 flex-col gap-4 px-6 pt-6 pb-4">
+ <div
+ class="flex min-w-0 flex-1 flex-col gap-4 px-6 pt-6 pb-4 sm:overflow-y-auto"
+ :data-testid="`post-details-body-${testKey}`"
+ >
<DialogHeader class="pe-8">
- <div class="flex items-center gap-2">
- <Button
- v-if="showRail && railCollapsed"
- variant="ghost"
- size="icon"
- :aria-label="$t('posts.group.expand')"
- :data-testid="`post-details-rail-expand-${testKey}`"
- @click="expandRail"
- >
- <IconLayoutSidebarLeftExpand class="size-4" />
- </Button>
- <DialogTitle>{{ $t('posts.show.title') }}</DialogTitle>
- </div>
+ <DialogTitle>{{ $t('posts.show.title') }}</DialogTitle>
<DialogDescription
class="flex flex-wrap items-center gap-2"
as="div"
>
<Badge
- :variant="getPostStatusConfig(current.status).variant"
+ :variant="currentStatusConfig.variant"
class="h-6 gap-1 px-2 [&>svg]:size-4"
:data-testid="`post-details-status-${testKey}`"
>
<component
- :is="getPostStatusConfig(current.status).icon"
- :class="getPostStatusConfig(current.status).iconClass"
+ :is="currentStatusConfig.icon"
+ :class="currentStatusConfig.iconClass"
/>
- {{ $t(`posts.status.${current.status}`) }}
+ {{
+ isInGoogleReview
+ ? $t('posts.publish.in_google_review')
+ : $t(`posts.status.${current.status}`)
+ }}
</Badge>
<span
class="text-sm text-muted-foreground"
@@ -400,20 +382,19 @@ const siblingMoment = (sibling: PostCard): string | null => {
</DialogHeader>
<section
- v-for="target in showsThread ? [] : targets"
- :key="target.id"
+ v-if="!showsThread && channel"
class="flex items-center gap-3"
- :data-testid="`post-details-target-${target.id}`"
+ :data-testid="`post-details-target-${current.id}`"
>
<ChannelAvatar
- :status="target.social_account?.status"
- :account-id="target.social_account?.id"
- :platform="target.platform"
- :src="target.social_account?.avatar_url"
- :verified="target.social_account?.verified_badge"
+ :status="channel.social_account?.status"
+ :account-id="channel.social_account?.id"
+ :platform="channel.platform"
+ :src="channel.social_account?.avatar_url"
+ :verified="channel.social_account?.verified_badge"
:name="
- target.social_account?.display_label ??
- getPlatformLabel(target.platform)
+ channel.social_account?.display_label ??
+ getPlatformLabel(channel.platform)
"
:size="40"
/>
@@ -421,31 +402,21 @@ const siblingMoment = (sibling: PostCard): string | null => {
<span
class="truncate text-sm font-emphasis text-foreground"
>{{
- target.social_account?.display_label ??
- getPlatformLabel(target.platform)
+ channel.social_account?.display_label ??
+ getPlatformLabel(channel.platform)
}}</span
>
<span
- v-if="target.social_account?.handle_label"
+ v-if="channel.social_account?.handle_label"
class="truncate text-xs text-muted-foreground"
- >{{ target.social_account.handle_label }}</span
+ >{{ channel.social_account.handle_label }}</span
>
</span>
- <Badge
- v-if="targets.length > 1"
- :variant="
- getPlatformStatusConfig(target.status).variant
- "
- class="h-6 px-2"
- :data-testid="`post-details-target-status-${target.id}`"
- >
- {{ $t(`posts.edit.status.${target.status}`) }}
- </Badge>
</section>
<ThreadView
- v-if="showsThread && targets[0]?.social_account"
- :account="targets[0].social_account"
+ v-if="showsThread && channel?.social_account"
+ :account="channel.social_account"
:posts="[{ text: content, media }, ...threadReplies]"
:test-key="currentKey"
@open-media="openMediaPreview"
@@ -493,7 +464,7 @@ const siblingMoment = (sibling: PostCard): string | null => {
<PostMetricsBand
v-if="metricsDetail"
:detail="metricsDetail"
- :channel-id="targets[0]?.social_account?.id ?? null"
+ :channel-id="channel?.social_account?.id ?? null"
class="-mx-6 px-6"
:metrics-test-id="`post-details-metrics-${currentKey}`"
:insights-test-id="`post-details-insights-${currentKey}`"
@@ -513,7 +484,7 @@ const siblingMoment = (sibling: PostCard): string | null => {
<TooltipProvider
v-if="
current.origin === PostOrigin.Network &&
- targets[0]
+ channel
"
:delay-duration="200"
>
@@ -525,18 +496,18 @@ const siblingMoment = (sibling: PostCard): string | null => {
>
{{ $t('posts.publish.published_via') }}
<PlatformBrandIcon
- :platform="targets[0].platform"
+ :platform="channel.platform"
:data-testid="`post-details-published-via-icon-${currentKey}`"
/>
- <template v-if="targets[0].platform !== Platform.X">
- {{ getPlatformLabel(targets[0].platform) }}
+ <template v-if="channel.platform !== Platform.X">
+ {{ getPlatformLabel(channel.platform) }}
</template>
</span>
</TooltipTrigger>
<TooltipContent :data-testid="`post-details-published-via-tooltip-${currentKey}`">
{{
$t('posts.publish.published_directly_from', {
- network: getPlatformLabel(targets[0].platform),
+ network: getPlatformLabel(channel.platform),
})
}}
</TooltipContent>
diff --git a/resources/js/components/publish/PostFailurePopover.vue b/resources/js/components/publish/PostFailurePopover.vue
index 483e20db5..efee4118b 100644
--- a/resources/js/components/publish/PostFailurePopover.vue
+++ b/resources/js/components/publish/PostFailurePopover.vue
@@ -11,7 +11,7 @@ import {
import { getPlatformLabel } from '@/composables/usePlatformLogo';
import { getPostStatusConfig } from '@/composables/usePostStatus';
import date from '@/date';
-import { PostPlatformStatus } from '@/types/post';
+import { PublishStatus } from '@/types/post';
import type { PostCard } from '@/types/publish';
const props = defineProps<{
@@ -35,30 +35,30 @@ const CATEGORIES = [
const status = computed(() => getPostStatusConfig(props.post.status));
-const failures = computed(() =>
- props.post.post_platforms
- .filter(
- (target) =>
- target.enabled &&
- (target.status === PostPlatformStatus.Failed ||
- target.status === PostPlatformStatus.Rejected),
- )
- .map((target) => {
- const category = target.error_context?.category ?? '';
- const at = target.error_context?.failed_at ?? props.attemptedAt;
+const failure = computed(() => {
+ const post = props.post;
- return {
- id: target.id,
- platform: target.platform,
- account: target.social_account?.display_label ?? null,
- reasonKey: CATEGORIES.includes(category)
- ? `posts.publish.failure.categories.${category}`
- : 'posts.publish.failure.generic',
- details: target.error_message?.trim() || null,
- at: at ? date.formatDateTimeInTimezone(at, props.timezone) : null,
- };
- }),
-);
+ if (
+ !post.platform ||
+ (post.publish_status !== PublishStatus.Failed &&
+ post.publish_status !== PublishStatus.Rejected)
+ ) {
+ return null;
+ }
+
+ const category = post.failure?.category ?? '';
+ const at = post.failure?.failed_at ?? props.attemptedAt;
+
+ return {
+ platform: post.platform,
+ account: post.social_account?.display_label ?? null,
+ reasonKey: CATEGORIES.includes(category)
+ ? `posts.publish.failure.categories.${category}`
+ : 'posts.publish.failure.generic',
+ details: post.error_message?.trim() || null,
+ at: at ? date.formatDateTimeInTimezone(at, props.timezone) : null,
+ };
+});
</script>
<template>
@@ -88,17 +88,13 @@ const failures = computed(() =>
{{ $t('posts.publish.failure.title') }}
</p>
<p
- v-if="failures.length === 0"
+ v-if="!failure"
class="text-sm text-foreground"
:data-testid="`post-failure-reason-${testKey}`"
>
{{ $t('posts.publish.failure.generic') }}
</p>
- <div
- v-for="failure in failures"
- :key="failure.id"
- class="flex flex-col gap-2"
- >
+ <div v-else class="flex flex-col gap-2">
<p
class="flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground"
>
diff --git a/resources/js/components/publish/PostTimelineCard.vue b/resources/js/components/publish/PostTimelineCard.vue
index 4c7f01bba..57362bf16 100644
--- a/resources/js/components/publish/PostTimelineCard.vue
+++ b/resources/js/components/publish/PostTimelineCard.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { Link, router, usePage } from '@inertiajs/vue3';
+import { router, usePage } from '@inertiajs/vue3';
import {
IconArrowsMaximize,
IconCircleDashedPlus,
@@ -7,8 +7,8 @@ import {
IconExternalLink,
IconGripVertical,
IconListNumbers,
- IconCheck,
IconClockPause,
+ IconHourglass,
IconLoader2,
IconPencil,
IconPlayerPlayFilled,
@@ -66,7 +66,7 @@ import { videoFrameUrl } from '@/lib/videoFrame';
import { Platform } from '@/types/platform';
import {
PostOrigin,
- PostPlatformStatus,
+ PublishStatus,
PostStatus,
ScheduleMode,
} from '@/types/post';
@@ -122,8 +122,6 @@ watch(
},
);
-const testKey = computed(() => props.post.card_key ?? props.post.id);
-
const authUserId = computed(() => String(page.props.authUserId ?? ''));
const openPostNotesId = computed(
() => (page.props.openPostNotesId as string | null | undefined) ?? null,
@@ -132,11 +130,8 @@ const highlightNoteId = computed(
() => (page.props.highlightNoteId as string | null | undefined) ?? null,
);
-const targets = computed(() =>
- props.post.post_platforms.filter((target) => target.enabled),
-);
-const primaryTarget = computed(() => targets.value[0] ?? null);
-const account = computed(() => primaryTarget.value?.social_account ?? null);
+const platform = computed(() => props.post.platform ?? null);
+const account = computed(() => props.post.social_account ?? null);
const recurrenceTimezone = computed(
() => account.value?.timezone ?? timezone.value,
);
@@ -145,6 +140,12 @@ const isPublishing = computed(
() => props.post.status === PostStatus.Publishing,
);
+const isInGoogleReview = computed(
+ () =>
+ isPublishing.value &&
+ props.post.publish_status === PublishStatus.PendingReview,
+);
+
const scheduleMode = computed(() => {
if (props.post.origin === PostOrigin.Network) {
return props.tab === 'sent' ? ScheduleMode.Custom : null;
@@ -174,25 +175,12 @@ const time = computed(() => {
: props.post.scheduled_at;
});
-const limitRetryAt = computed(
- () =>
- targets.value.find(
- (target) =>
- target.status === PostPlatformStatus.Retrying &&
- Boolean(target.retry_at),
- )?.retry_at ?? null,
+const limitRetryAt = computed(() =>
+ props.post.publish_status === PublishStatus.Retrying
+ ? (props.post.retry_at ?? null)
+ : null,
);
-const PUBLISHED_TARGET_STATUSES = ['published', 'pending_review'];
-const FAILED_TARGET_STATUSES = ['failed', 'rejected'];
-
-const targetProgress = (status: string): 'done' | 'failed' | 'running' =>
- PUBLISHED_TARGET_STATUSES.includes(status)
- ? 'done'
- : FAILED_TARGET_STATUSES.includes(status)
- ? 'failed'
- : 'running';
-
const isPending = computed(
() => props.post.status === PostStatus.PendingApproval,
);
@@ -244,15 +232,12 @@ const CONTENT_TYPE_ICONS: Record<string, Component> = {
};
const contentTypeIcon = computed(() =>
- CONTENT_TYPE_ICONS[primaryTarget.value?.content_type ?? ''] ?? null,
+ CONTENT_TYPE_ICONS[props.post.content_type ?? ''] ?? null,
);
const contentTypeKey = computed(() =>
- primaryTarget.value
- ? getContentTypeBadgeKey(
- primaryTarget.value.platform,
- primaryTarget.value.content_type ?? null,
- )
+ platform.value
+ ? getContentTypeBadgeKey(platform.value, props.post.content_type ?? null)
: null,
);
@@ -260,12 +245,10 @@ const canQueue = computed(
() => account.value?.has_posting_schedule === true,
);
-const permalink = computed(() => primaryTarget.value?.platform_url ?? null);
+const permalink = computed(() => props.post.platform_url ?? null);
const metricsDetail = computed(() => {
- const detail = primaryTarget.value
- ? props.post.metrics?.[primaryTarget.value.id]
- : null;
+ const detail = props.post.metrics ?? null;
return detail && detail.available ? detail : null;
});
@@ -284,16 +267,7 @@ const showStatus = computed(
!isPending.value,
);
-const hasFailure = computed(
- () =>
- props.post.status === PostStatus.Failed ||
- (props.post.status === PostStatus.PartiallyPublished &&
- targets.value.some(
- (target) =>
- target.status === PostPlatformStatus.Failed ||
- target.status === PostPlatformStatus.Rejected,
- )),
-);
+const hasFailure = computed(() => props.post.status === PostStatus.Failed);
const APPROVAL_RELOAD = {
only: ['posts', 'counts', 'queue', 'hasData'],
@@ -339,6 +313,16 @@ const edit = (post: PostCard = props.post): void => {
router.visit(editUrl(post));
};
+const open = (): void => {
+ if (isEditable.value) {
+ edit();
+
+ return;
+ }
+
+ openDetails();
+};
+
const runPostAction = (action: PostCardMenuAction, post: PostCard): void => {
switch (action) {
case 'publish_now':
@@ -384,7 +368,7 @@ defineExpose({ openDetails });
<template>
<div
- :data-testid="`post-card-${testKey}`"
+ :data-testid="`post-card-${post.id}`"
:data-post-id="post.id"
class="group/post relative"
:class="
@@ -410,7 +394,7 @@ defineExpose({ openDetails });
? 'shrink-0 transition-opacity active:cursor-grabbing md:absolute md:top-0.5 md:left-[79px] md:opacity-0 md:group-focus-within/post:opacity-100 md:group-hover/post:opacity-100 md:in-data-dragging:opacity-100'
: 'md:-ms-5'
"
- :data-testid="`post-drag-handle-${testKey}`"
+ :data-testid="`post-drag-handle-${post.id}`"
aria-hidden="true"
/>
<time
@@ -418,7 +402,7 @@ defineExpose({ openDetails });
class="text-sm text-foreground"
:class="popover ? 'font-emphasis' : 'font-medium'"
:datetime="time"
- :data-testid="`post-time-${testKey}`"
+ :data-testid="`post-time-${post.id}`"
>
{{
popover
@@ -434,7 +418,7 @@ defineExpose({ openDetails });
v-if="isPending"
variant="warning"
class="h-6 gap-1 px-2 [&>svg]:size-4"
- :data-testid="`post-approval-badge-${testKey}`"
+ :data-testid="`post-approval-badge-${post.id}`"
>
<IconEdit />
{{ $t('posts.approvals.badge') }}
@@ -442,14 +426,14 @@ defineExpose({ openDetails });
<span
v-if="timePassed"
class="text-xs text-destructive-text"
- :data-testid="`post-time-passed-${testKey}`"
+ :data-testid="`post-time-passed-${post.id}`"
>
{{ $t('posts.approvals.time_passed') }}
</span>
<span
v-if="recurrence"
class="inline-flex items-center gap-0.5 text-xs text-muted-foreground"
- :data-testid="`post-recurring-${testKey}`"
+ :data-testid="`post-recurring-${post.id}`"
>
<IconRepeat class="size-3" />
{{ $t('posts.recurrence.marker') }}
@@ -463,7 +447,7 @@ defineExpose({ openDetails });
<PostFailurePopover
v-if="showStatus && hasFailure"
:post="post"
- :test-key="testKey"
+ :test-key="post.id"
:attempted-at="time"
:timezone="timezone"
/>
@@ -471,7 +455,7 @@ defineExpose({ openDetails });
v-else-if="showStatus && !isPublishing"
:variant="getPostStatusConfig(post.status).variant"
class="h-6 gap-1 px-2 [&>svg]:size-4"
- :data-testid="`post-status-${testKey}`"
+ :data-testid="`post-status-${post.id}`"
>
<component
:is="getPostStatusConfig(post.status).icon"
@@ -485,7 +469,7 @@ defineExpose({ openDetails });
size="icon"
class="-my-1 ms-auto -me-2"
:aria-label="$t('posts.show.title')"
- :data-testid="`post-details-expand-${testKey}`"
+ :data-testid="`post-details-expand-${post.id}`"
@click="openDetails"
>
<IconArrowsMaximize class="size-4" />
@@ -502,7 +486,7 @@ defineExpose({ openDetails });
<p
v-if="recurrence && post.scheduled_at"
class="flex items-start gap-2 border-b border-border-strong bg-secondary px-4 py-2.5 text-sm text-foreground"
- :data-testid="`post-recurrence-banner-${testKey}`"
+ :data-testid="`post-recurrence-banner-${post.id}`"
>
<IconRepeat class="mt-0.5 size-4 shrink-0" />
<PostRecurrenceSummary
@@ -517,12 +501,13 @@ defineExpose({ openDetails });
v-if="isPublishing && !popover"
class="relative flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-border-strong bg-secondary px-4 py-2.5 text-sm text-foreground"
role="status"
- :data-testid="`post-publishing-${testKey}`"
+ :data-testid="`post-publishing-${post.id}`"
>
<span
+ v-if="!isInGoogleReview"
class="absolute inset-x-0 -bottom-px h-0.5 overflow-hidden"
aria-hidden="true"
- :data-testid="`post-publishing-progress-${testKey}`"
+ :data-testid="`post-publishing-progress-${post.id}`"
>
<span
class="motion-progress-sweep block h-full w-2/5 rounded-full bg-primary-strong"
@@ -531,7 +516,7 @@ defineExpose({ openDetails });
<span
v-if="limitRetryAt"
class="inline-flex items-center gap-2"
- :data-testid="`post-limit-retry-${testKey}`"
+ :data-testid="`post-limit-retry-${post.id}`"
>
<IconClockPause
class="size-4 text-primary-strong"
@@ -543,66 +528,52 @@ defineExpose({ openDetails });
})
}}
</span>
+ <span
+ v-else-if="isInGoogleReview"
+ class="inline-flex items-center gap-2"
+ :data-testid="`post-google-review-${post.id}`"
+ >
+ <IconHourglass
+ class="size-4 text-primary-strong"
+ aria-hidden="true"
+ />
+ {{ $t('posts.publish.in_google_review') }}
+ </span>
<span v-else class="inline-flex items-center gap-2">
<IconLoader2
class="size-4 animate-spin text-primary-strong"
aria-hidden="true"
/>
{{
- targets.length === 1 && primaryTarget
+ platform
? $t('posts.publish.publishing_on', {
- network: getPlatformLabel(primaryTarget.platform),
+ network: getPlatformLabel(platform),
})
: $t('posts.publish.publishing_badge')
}}
</span>
- <ul
- v-if="targets.length > 1"
- class="flex flex-wrap items-center gap-1.5"
- >
- <li
- v-for="target in targets"
- :key="target.id"
- class="inline-flex h-6 items-center gap-1 rounded-full bg-card px-1.5 text-xs"
- :title="getPlatformLabel(target.platform)"
- :data-testid="`post-publishing-target-${target.id}`"
- :data-progress="targetProgress(target.status)"
- >
- <PlatformBrandIcon :platform="target.platform" />
- <IconLoader2
- v-if="targetProgress(target.status) === 'running'"
- class="size-3.5 animate-spin text-muted-foreground"
- />
- <IconCheck
- v-else-if="targetProgress(target.status) === 'done'"
- class="size-3.5 text-success"
- />
- <IconX v-else class="size-3.5 text-destructive-text" />
- </li>
- </ul>
</div>
<div
class="relative flex gap-4 p-4 md:gap-6"
:class="{ 'opacity-70': isPublishing && !popover }"
>
- <component
- :is="isEditable ? Link : 'div'"
- :href="isEditable ? editUrl(post) : undefined"
+ <div
:draggable="draggable ? 'false' : undefined"
- class="flex min-w-0 flex-1 flex-col gap-4 outline-none after:absolute after:inset-0 focus-visible:after:outline-2 focus-visible:after:outline-offset-[-2px] focus-visible:after:outline-ring"
- :data-testid="`post-open-${testKey}`"
+ class="flex min-w-0 flex-1 cursor-pointer flex-col gap-4 outline-none after:absolute after:inset-0 focus-visible:after:outline-2 focus-visible:after:outline-offset-[-2px] focus-visible:after:outline-ring"
+ :data-testid="`post-open-${post.id}`"
+ @click="open"
>
<div class="flex items-center gap-3">
<ChannelAvatar
:status="account?.status"
:account-id="account?.id"
- v-if="primaryTarget"
- :platform="primaryTarget.platform"
+ v-if="platform"
+ :platform="platform"
:src="account?.avatar_url"
:verified="account?.verified_badge"
:name="
account?.display_label ??
- getPlatformLabel(primaryTarget.platform)
+ getPlatformLabel(platform)
"
ring="card"
@dragstart="draggable ? $event.preventDefault() : undefined"
@@ -613,7 +584,7 @@ defineExpose({ openDetails });
>
{{
account?.display_label ??
- getPlatformLabel(primaryTarget?.platform ?? '')
+ getPlatformLabel(platform ?? '')
}}
</p>
<p
@@ -623,16 +594,11 @@ defineExpose({ openDetails });
{{ account.handle_label }}
</p>
</div>
- <span
- v-if="targets.length > 1"
- class="text-xs font-medium text-muted-foreground"
- >+{{ targets.length - 1 }}</span
- >
<Badge
v-if="contentTypeKey"
variant="secondary"
class="ms-auto h-6 gap-1 px-2"
- :data-testid="`post-content-type-${testKey}`"
+ :data-testid="`post-content-type-${post.id}`"
>
<component
:is="contentTypeIcon"
@@ -652,7 +618,7 @@ defineExpose({ openDetails });
>
{{ preview || $t('calendar.no_content') }}
</p>
- </component>
+ </div>
<div
v-if="thumbnails.length"
class="relative z-10 grid w-24 shrink-0 content-start gap-2"
@@ -668,7 +634,7 @@ defineExpose({ openDetails });
:aria-label="$t('common.media_lightbox.open')"
:draggable="draggable ? 'false' : undefined"
class="group/thumbnail relative block aspect-square cursor-zoom-in overflow-hidden rounded-md border border-border-strong bg-secondary focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
- :data-testid="`post-thumbnail-${testKey}-${index}`"
+ :data-testid="`post-thumbnail-${post.id}-${index}`"
@click="openLightbox(index)"
>
<img
@@ -686,7 +652,7 @@ defineExpose({ openDetails });
muted
playsinline
preload="metadata"
- :data-testid="`post-thumbnail-video-${testKey}-${index}`"
+ :data-testid="`post-thumbnail-video-${post.id}-${index}`"
/>
<IconPlayerPlayFilled
aria-hidden="true"
@@ -699,7 +665,7 @@ defineExpose({ openDetails });
>
<IconArrowsMaximize
class="size-6 text-white opacity-0 drop-shadow transition-opacity group-hover/thumbnail:opacity-100"
- :data-testid="`post-thumbnail-expand-${testKey}-${index}`"
+ :data-testid="`post-thumbnail-expand-${post.id}-${index}`"
/>
</span>
</button>
@@ -708,7 +674,7 @@ defineExpose({ openDetails });
type="button"
:aria-label="$t('common.media_lightbox.open')"
class="absolute right-1.5 bottom-1.5 inline-flex size-6 cursor-zoom-in items-center justify-center rounded-full bg-foreground/60 text-xs font-medium text-background transition-colors hover:bg-foreground/80 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
- :data-testid="`post-thumbnail-more-${testKey}`"
+ :data-testid="`post-thumbnail-more-${post.id}`"
@click="openLightbox(MAX_THUMBNAILS)"
>
+{{ hiddenVisuals }}
@@ -738,21 +704,21 @@ defineExpose({ openDetails });
class="-mt-1 px-4 pb-4"
:post-id="post.id"
:labels="post.labels ?? []"
- :test-key="testKey"
+ :test-key="post.id"
/>
<PostMetricsBand
v-if="tab === 'sent' && metricsDetail && hasMetrics"
:detail="metricsDetail"
:channel-id="account?.id ?? null"
- :metrics-test-id="`post-metrics-${testKey}`"
- :insights-test-id="`post-insights-${testKey}`"
+ :metrics-test-id="`post-metrics-${post.id}`"
+ :insights-test-id="`post-insights-${post.id}`"
/>
<div
class="m-2 flex min-h-14 flex-wrap items-center gap-x-4 gap-y-2 rounded-xl bg-muted p-3 [&_[data-variant=ghost]:hover]:bg-secondary"
:class="popover ? 'justify-end' : 'justify-between'"
- :data-testid="`post-footer-${testKey}`"
+ :data-testid="`post-footer-${post.id}`"
>
<p
v-if="!popover"
@@ -760,29 +726,29 @@ defineExpose({ openDetails });
:class="{ 'max-sm:hidden': post.origin === PostOrigin.Network }"
>
<TooltipProvider
- v-if="post.origin === PostOrigin.Network && primaryTarget"
+ v-if="post.origin === PostOrigin.Network && platform"
:delay-duration="200"
>
<Tooltip>
<TooltipTrigger as-child>
<span
class="inline-flex cursor-default items-center gap-1"
- :data-testid="`post-published-via-${testKey}`"
+ :data-testid="`post-published-via-${post.id}`"
>
{{ $t('posts.publish.published_via') }}
<PlatformBrandIcon
- :platform="primaryTarget.platform"
- :data-testid="`post-published-via-icon-${testKey}`"
+ :platform="platform"
+ :data-testid="`post-published-via-icon-${post.id}`"
/>
- <template v-if="primaryTarget.platform !== Platform.X">
- {{ getPlatformLabel(primaryTarget.platform) }}
+ <template v-if="platform !== Platform.X">
+ {{ getPlatformLabel(platform) }}
</template>
</span>
</TooltipTrigger>
- <TooltipContent :data-testid="`post-published-via-tooltip-${testKey}`">
+ <TooltipContent :data-testid="`post-published-via-tooltip-${post.id}`">
{{
$t('posts.publish.published_directly_from', {
- network: getPlatformLabel(primaryTarget.platform),
+ network: getPlatformLabel(platform),
})
}}
</TooltipContent>
@@ -790,7 +756,7 @@ defineExpose({ openDetails });
</TooltipProvider>
<span
v-else-if="post.user?.name"
- :data-testid="`post-created-by-${testKey}`"
+ :data-testid="`post-created-by-${post.id}`"
>{{
$t('posts.publish.created_by', {
name: post.user.name,
@@ -800,14 +766,14 @@ defineExpose({ openDetails });
</p>
<div
class="flex max-w-full shrink-0 flex-wrap items-center gap-1 max-sm:ms-auto"
- :data-testid="`post-actions-${testKey}`"
+ :data-testid="`post-actions-${post.id}`"
>
<template v-if="isPending && canApprove">
- <ApprovePostButton :post="post" :test-key="testKey" />
+ <ApprovePostButton :post="post" :test-key="post.id" />
<Button
variant="outline"
class="text-destructive-text"
- :data-testid="`post-reject-${testKey}`"
+ :data-testid="`post-reject-${post.id}`"
@click="rejectPost"
>
<IconX class="size-4" />
@@ -817,7 +783,7 @@ defineExpose({ openDetails });
<Button
v-else-if="isPending"
variant="outline"
- :data-testid="`post-revert-${testKey}`"
+ :data-testid="`post-revert-${post.id}`"
@click="revertRequest"
>
<IconX class="size-4" />
@@ -827,7 +793,7 @@ defineExpose({ openDetails });
<Button
v-if="canQueue"
variant="outline"
- :data-testid="`post-add-to-queue-${testKey}`"
+ :data-testid="`post-add-to-queue-${post.id}`"
@click="addToQueue"
>
<IconListNumbers class="size-4" />
@@ -840,7 +806,7 @@ defineExpose({ openDetails });
<Button
variant="outline"
disabled
- :data-testid="`post-add-to-queue-${testKey}`"
+ :data-testid="`post-add-to-queue-${post.id}`"
>
<IconListNumbers class="size-4" />
{{
@@ -861,7 +827,7 @@ defineExpose({ openDetails });
</Tooltip>
</TooltipProvider>
</template>
- <Tooltip v-if="permalink && primaryTarget">
+ <Tooltip v-if="permalink && platform">
<TooltipTrigger as-child>
<Button
as="a"
@@ -869,19 +835,19 @@ defineExpose({ openDetails });
target="_blank"
rel="noopener noreferrer"
variant="outline"
- :data-testid="`post-view-${testKey}`"
+ :data-testid="`post-view-${post.id}`"
>
<IconExternalLink class="size-4" />
{{ $t('posts.publish.actions.view_post') }}
</Button>
</TooltipTrigger>
<TooltipContent
- :data-testid="`post-view-tooltip-${testKey}`"
+ :data-testid="`post-view-tooltip-${post.id}`"
>
{{
$t('posts.publish.actions.open_on_network', {
network: getPlatformLabel(
- primaryTarget.platform,
+ platform,
),
})
}}
@@ -890,7 +856,7 @@ defineExpose({ openDetails });
<Button
v-if="canPublishDirectly && post.status === PostStatus.Scheduled"
variant="outline"
- :data-testid="`post-publish-now-${testKey}`"
+ :data-testid="`post-publish-now-${post.id}`"
@click="schedulePostCard(post.id, 'publish_now')"
>
<IconSend class="size-4" />
@@ -902,7 +868,7 @@ defineExpose({ openDetails });
variant="outline"
size="icon"
:aria-label="$t('posts.publish.actions.edit')"
- :data-testid="`post-edit-${testKey}`"
+ :data-testid="`post-edit-${post.id}`"
@click="edit()"
>
<IconPencil class="size-4" />
@@ -915,7 +881,7 @@ defineExpose({ openDetails });
<PostCardMenu
v-if="canCreatePost && !isPublishing"
:post="post"
- :test-key="testKey"
+ :test-key="post.id"
:can-move-up="canMoveUp"
:can-move-down="canMoveDown"
:movable="movable"
@@ -925,7 +891,7 @@ defineExpose({ openDetails });
v-if="canCreatePost"
v-model:open="detailsOpen"
:post="post"
- :test-key="testKey"
+ :test-key="post.id"
:timezone="timezone"
@select="runPostAction"
@edit="edit"
@@ -936,7 +902,7 @@ defineExpose({ openDetails });
:post="
recurrencePost.id === post.id ? post : recurrencePost
"
- :test-key="testKey"
+ :test-key="post.id"
:timezone="recurrenceTimezone"
/>
</div>
diff --git a/resources/js/components/publish/PublishFilterMenu.vue b/resources/js/components/publish/PublishFilterMenu.vue
index 0ed9cf15b..4ceabc893 100644
--- a/resources/js/components/publish/PublishFilterMenu.vue
+++ b/resources/js/components/publish/PublishFilterMenu.vue
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { Link } from '@inertiajs/vue3';
import { IconCheck, IconDotsVertical, IconFilter2 } from '@tabler/icons-vue';
+import { computed } from 'vue';
import CalendarStatusFilter from '@/components/publish/CalendarStatusFilter.vue';
import ResponsivePopover from '@/components/ResponsivePopover.vue';
@@ -23,8 +24,9 @@ const props = withDefaults(
timezones: TimezoneOption[];
showSlots?: boolean | null;
manageSlotsHref?: string | null;
+ compact?: boolean | null;
}>(),
- { showSlots: null, manageSlotsHref: null },
+ { showSlots: null, manageSlotsHref: null, compact: null },
);
const timezone = defineModel<string>('timezone', { required: true });
@@ -34,7 +36,8 @@ const emit = defineEmits<{
'update:showSlots': [value: boolean];
}>();
-const compact = useBelowBreakpoint('md');
+const belowMd = useBelowBreakpoint('md');
+const isCompact = computed(() => props.compact ?? belowMd.value);
const hasSlotOptions = (): boolean =>
props.showSlots !== null || props.manageSlotsHref !== null;
@@ -53,7 +56,7 @@ const rowClass =
<template>
<ResponsivePopover
- v-if="compact"
+ v-if="isCompact"
:title="$t('posts.table.actions')"
:test-id="`${testId}-menu-content`"
content-class="w-72 p-2"
diff --git a/resources/js/components/repurpose/RepurposeItemList.vue b/resources/js/components/repurpose/RepurposeItemList.vue
index 096790fd5..2fff3ce48 100644
--- a/resources/js/components/repurpose/RepurposeItemList.vue
+++ b/resources/js/components/repurpose/RepurposeItemList.vue
@@ -14,7 +14,7 @@ import type { Component } from 'vue';
import { getPlatformLabel, getPlatformLogo } from '@/composables/usePlatformLogo';
import date from '@/date';
import { edit } from '@/routes/app/posts';
-import { PostPlatformStatus, type PostPlatformStatusValue } from '@/types/post';
+import { PublishStatus, type PublishStatusValue } from '@/types/post';
import type { RepurposeItem, RepurposeItemPost } from '@/types/repurpose';
import { RepurposeItemStatus, type RepurposeItemStatusValue } from '@/types/repurpose-status';
@@ -33,21 +33,12 @@ const marks: Record<RepurposeItemStatusValue, { icon: Component; class: string }
const detail = (item: RepurposeItem): string | null => item.error ?? null;
-const postState = (post: RepurposeItemPost): PostPlatformStatusValue | null => {
- const states = post.platforms
- .map((entry) => entry.status)
- .filter((status): status is PostPlatformStatusValue => status !== null);
-
- if (states.length === 0) {
- return null;
- }
-
- if (states.includes(PostPlatformStatus.Failed)) {
- return PostPlatformStatus.Failed;
- }
-
- return states.every((status) => status === states[0]) ? states[0] : null;
-};
+const postState = (post: RepurposeItemPost): PublishStatusValue | null =>
+ post.platform
+ ? post.publish_status === PublishStatus.Rejected
+ ? PublishStatus.Failed
+ : post.publish_status
+ : null;
</script>
<template>
@@ -114,26 +105,29 @@ const postState = (post: RepurposeItemPost): PostPlatformStatusValue | null => {
class="group/post inline-flex h-6 items-center gap-1.5 rounded-md bg-secondary pr-1.5 pl-2 text-xs font-medium text-foreground transition-control hover:bg-border-strong"
>
<img
- v-for="entry in post.platforms"
- :key="entry.platform"
- :src="getPlatformLogo(entry.platform)"
- :alt="getPlatformLabel(entry.platform)"
+ v-if="post.platform"
+ :src="getPlatformLogo(post.platform)"
+ :alt="getPlatformLabel(post.platform)"
class="size-4 rounded-sm"
- :class="{ 'opacity-40': entry.status === PostPlatformStatus.Failed }"
+ :class="{ 'opacity-40': postState(post) === PublishStatus.Failed }"
/>
- {{ post.platforms.map((entry) => getPlatformLabel(entry.platform)).join(', ') }}
+ {{ post.platform ? getPlatformLabel(post.platform) : '' }}
<span
v-if="postState(post)"
:class="[
'rounded px-1 py-px text-[10px] font-semibold uppercase tracking-wide',
- postState(post) === PostPlatformStatus.Failed
+ postState(post) === PublishStatus.Failed
? 'bg-critical-subtle text-destructive-text'
: 'bg-foreground/10 text-foreground/60',
]"
>
- {{ $t(`posts.status.${postState(post)}`) }}
+ {{
+ postState(post) === PublishStatus.PendingReview
+ ? $t('posts.publish.in_google_review')
+ : $t(`posts.status.${postState(post)}`)
+ }}
</span>
<IconChevronRight class="size-3.5 text-muted-foreground transition-colors group-hover/post:text-foreground" />
diff --git a/resources/js/components/ui/dialog/DialogContent.vue b/resources/js/components/ui/dialog/DialogContent.vue
index 656d46e07..3b37850e2 100644
--- a/resources/js/components/ui/dialog/DialogContent.vue
+++ b/resources/js/components/ui/dialog/DialogContent.vue
@@ -17,12 +17,13 @@ defineOptions({
inheritAttrs: false,
})
-const props = withDefaults(defineProps<DialogContentProps & { class?: HTMLAttributes["class"], showCloseButton?: boolean }>(), {
+const props = withDefaults(defineProps<DialogContentProps & { class?: HTMLAttributes["class"], showCloseButton?: boolean, fullscreenOnMobile?: boolean }>(), {
showCloseButton: true,
+ fullscreenOnMobile: true,
})
const emits = defineEmits<DialogContentEmits>()
-const delegatedProps = reactiveOmit(props, "class")
+const delegatedProps = reactiveOmit(props, "class", "fullscreenOnMobile")
const forwarded = useForwardPropsEmits(delegatedProps, emits)
</script>
@@ -35,7 +36,8 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
v-bind="{ ...$attrs, ...forwarded }"
:class="
cn(
- 'motion-dialog bg-background fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 max-h-[85dvh] overflow-y-auto rounded-2xl px-6 pt-6 pb-4 shadow-lg duration-200 sm:max-w-lg dark:border max-sm:inset-0 max-sm:flex max-sm:h-dvh max-sm:max-h-none max-sm:w-full max-sm:max-w-none max-sm:translate-none max-sm:flex-col max-sm:rounded-none max-sm:shadow-none max-sm:[&>:has([data-slot$=dialog-footer])]:flex max-sm:[&>:has([data-slot$=dialog-footer])]:grow max-sm:[&>:has([data-slot$=dialog-footer])]:flex-col max-sm:[&>[data-slot$=dialog-header]]:sticky max-sm:[&>[data-slot$=dialog-header]]:top-0 max-sm:[&>[data-slot$=dialog-header]]:z-10 max-sm:[&>[data-slot$=dialog-header]]:bg-background max-sm:[&>[data-slot$=dialog-header]]:shadow-[0_-1.5rem_0_1.5rem_var(--background)]',
+ 'motion-dialog bg-background fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 max-h-[85dvh] overflow-y-auto rounded-2xl px-6 pt-6 pb-4 shadow-lg duration-200 sm:max-w-lg dark:border',
+ fullscreenOnMobile && 'max-sm:inset-0 max-sm:flex max-sm:h-dvh max-sm:max-h-none max-sm:w-full max-sm:max-w-none max-sm:translate-none max-sm:flex-col max-sm:rounded-none max-sm:shadow-none max-sm:[&>:has([data-slot$=dialog-footer])]:flex max-sm:[&>:has([data-slot$=dialog-footer])]:grow max-sm:[&>:has([data-slot$=dialog-footer])]:flex-col max-sm:[&>[data-slot$=dialog-header]]:sticky max-sm:[&>[data-slot$=dialog-header]]:top-0 max-sm:[&>[data-slot$=dialog-header]]:z-10 max-sm:[&>[data-slot$=dialog-header]]:bg-background max-sm:[&>[data-slot$=dialog-header]]:shadow-[0_-1.5rem_0_1.5rem_var(--background)]',
props.class,
)"
>
@@ -46,7 +48,7 @@ const forwarded = useForwardPropsEmits(delegatedProps, emits)
data-slot="dialog-close"
data-testid="dialog-close"
:aria-label="$t('common.close')"
- :class="cn(buttonVariants({ variant: 'ghost', size: 'icon' }), 'absolute top-4 end-4 max-sm:fixed max-sm:top-[calc(1rem+env(safe-area-inset-top))] max-sm:end-[calc(1rem+env(safe-area-inset-right))] max-sm:z-20')"
+ :class="cn(buttonVariants({ variant: 'ghost', size: 'icon' }), 'absolute top-4 end-4', fullscreenOnMobile && 'max-sm:fixed max-sm:top-[calc(1rem+env(safe-area-inset-top))] max-sm:end-[calc(1rem+env(safe-area-inset-right))] max-sm:z-20')"
>
<IconX class="size-4" />
<span class="sr-only">{{ $t('common.close') }}</span>
diff --git a/resources/js/components/webhook/webhook-events.ts b/resources/js/components/webhook/webhook-events.ts
index f65c5a108..cfe796333 100644
--- a/resources/js/components/webhook/webhook-events.ts
+++ b/resources/js/components/webhook/webhook-events.ts
@@ -8,7 +8,6 @@ export const webhookEventGroups = [
'post.scheduled',
'post.unscheduled',
'post.published',
- 'post.partially_published',
'post.failed',
'post.deleted',
],
diff --git a/resources/js/composables/useCollapseWhenTruncated.ts b/resources/js/composables/useCollapseWhenTruncated.ts
new file mode 100644
index 000000000..e8fb8ca0a
--- /dev/null
+++ b/resources/js/composables/useCollapseWhenTruncated.ts
@@ -0,0 +1,47 @@
+import { useResizeObserver } from '@vueuse/core';
+import { nextTick, readonly, ref, type Ref } from 'vue';
+
+/**
+ * Collapses a toolbar while its content no longer fits. `missingWidth`
+ * returns how many pixels the content lacks; the toolbar remembers the
+ * width it needed and expands again once it is that wide.
+ */
+export const useCollapseWhenTruncated = (
+ container: Readonly<Ref<HTMLElement | null>>,
+ missingWidth: () => number,
+): { collapsed: Readonly<Ref<boolean>>; expand: () => void } => {
+ const collapsed = ref(false);
+ let widthToExpand: number | null = null;
+
+ const fit = (): void => {
+ const element = container.value;
+
+ if (!element) {
+ return;
+ }
+
+ if (collapsed.value) {
+ if (widthToExpand !== null && element.clientWidth >= widthToExpand) {
+ expand();
+ }
+
+ return;
+ }
+
+ const missing = missingWidth();
+
+ if (missing > 0) {
+ widthToExpand = element.clientWidth + missing;
+ collapsed.value = true;
+ }
+ };
+
+ const expand = (): void => {
+ collapsed.value = false;
+ nextTick(fit);
+ };
+
+ useResizeObserver(container, fit);
+
+ return { collapsed: readonly(collapsed), expand };
+};
diff --git a/resources/js/composables/useMetaErrors.ts b/resources/js/composables/useMetaErrors.ts
new file mode 100644
index 000000000..6560f61c0
--- /dev/null
+++ b/resources/js/composables/useMetaErrors.ts
@@ -0,0 +1,22 @@
+import { computed, type ComputedRef } from 'vue';
+
+import { usePageErrors } from '@/composables/usePageErrors';
+
+/**
+ * The validation error of one meta field of a settings panel. A panel in a
+ * batch (composer create, repurpose destinations) is reported under
+ * `destinations.{platformIndex}.meta.*`; an edit has one post and reports
+ * `meta.*`.
+ */
+export const useMetaErrors = (
+ platformIndex: () => number,
+): ((field: string) => ComputedRef<string | undefined>) => {
+ const errors = usePageErrors();
+
+ return (field) =>
+ computed(
+ () =>
+ errors.value[`destinations.${platformIndex()}.meta.${field}`] ??
+ errors.value[`meta.${field}`],
+ );
+};
diff --git a/resources/js/composables/usePageErrors.ts b/resources/js/composables/usePageErrors.ts
index 79eb61701..e327ac371 100644
--- a/resources/js/composables/usePageErrors.ts
+++ b/resources/js/composables/usePageErrors.ts
@@ -3,7 +3,7 @@ import { computed, type ComputedRef } from 'vue';
/**
* Reactive access to Inertia's page-level validation errors, keyed by field
- * path (e.g. `scheduled_at`, `platforms.0.content_type`). Returns an empty
+ * path (e.g. `scheduled_at`, `meta.title`). Returns an empty
* object when no errors are present so consumers can index without null
* checks. Cast to `Record<string, string>` because the app only ever flashes
* single string messages (no nested error bags).
diff --git a/resources/js/composables/usePostCardActions.ts b/resources/js/composables/usePostCardActions.ts
index caa1fdbdc..0d674e8de 100644
--- a/resources/js/composables/usePostCardActions.ts
+++ b/resources/js/composables/usePostCardActions.ts
@@ -72,9 +72,7 @@ export const schedulePostCard = (
};
export const duplicatePostCard = (post: PostCard): void => {
- router.post(duplicatePost.url(post.id), {
- post_platform_id: post.post_platforms[0]?.id,
- });
+ router.post(duplicatePost.url(post.id));
};
export const syncPostCardLabels = (
diff --git a/resources/js/composables/usePostComposition.ts b/resources/js/composables/usePostComposition.ts
index a8bd17e35..50b3b0e65 100644
--- a/resources/js/composables/usePostComposition.ts
+++ b/resources/js/composables/usePostComposition.ts
@@ -4,7 +4,11 @@ import { getContentTypeOptions } from '@/composables/usePlatformLogo';
import { derivedContentTypeFor } from '@/lib/derivedContentType';
import type { MediaItem } from '@/types/media';
import { Platform } from '@/types/platform';
-import type { QueuePositionValue, ScheduleModeValue } from '@/types/post';
+import {
+ PostStatus,
+ type QueuePositionValue,
+ type ScheduleModeValue,
+} from '@/types/post';
import type { PostingSchedule } from '@/types/posting-schedule';
import type { VerifiedBadge } from '@/types/social-account';
import type { SocialAccountStatusValue } from '@/types/social-account-status';
@@ -38,7 +42,10 @@ export interface PostComposition {
scheduled_at: string | null;
queue?: QueuePositionValue | null;
queue_slot?: string;
- status: 'draft' | 'scheduled' | 'publishing';
+ status:
+ | typeof PostStatus.Draft
+ | typeof PostStatus.Scheduled
+ | typeof PostStatus.Publishing;
label_ids: string[];
destinations: DestinationDraft[];
}
@@ -353,8 +360,8 @@ export const usePostComposition = (
content: content.value,
media: [...media.value],
scheduled_at:
- status === 'scheduled' && !queue ? scheduledAt.value || null : null,
- queue: status === 'scheduled' ? queue : null,
+ status === PostStatus.Scheduled && !queue ? scheduledAt.value || null : null,
+ queue: status === PostStatus.Scheduled ? queue : null,
status,
label_ids: [...labelIds.value],
destinations: selectedAccounts.value.map((account) =>
diff --git a/resources/js/composables/usePostStatus.ts b/resources/js/composables/usePostStatus.ts
index 171985d9c..07fcfa7e6 100644
--- a/resources/js/composables/usePostStatus.ts
+++ b/resources/js/composables/usePostStatus.ts
@@ -27,7 +27,6 @@ const CONFIGS: Record<string, Pick<StatusConfig, 'variant' | 'icon' | 'iconClass
publishing: { variant: 'warning', icon: IconLoader2, iconClass: 'animate-spin' },
retrying: { variant: 'warning', icon: IconLoader2, iconClass: 'animate-spin' },
published: { variant: 'success', icon: IconCircleCheck },
- partially_published: { variant: 'warning', icon: IconAlertCircle },
failed: { variant: 'destructive-subtle', icon: IconAlertCircle },
rejected: { variant: 'destructive-subtle', icon: IconBan },
pending_review: { variant: 'warning', icon: IconHourglass },
@@ -37,18 +36,3 @@ export const getPostStatusConfig = (status: string): StatusConfig => {
const config = CONFIGS[status] ?? CONFIGS.draft;
return { ...config, label: trans(`posts.status.${status}`) };
};
-
-export const getPlatformStatusConfig = (status: string): StatusConfig => {
- const map: Record<string, string> = {
- pending: 'draft',
- publishing: 'publishing',
- retrying: 'retrying',
- published: 'published',
- failed: 'failed',
- rejected: 'rejected',
- pending_review: 'pending_review',
- };
- const key = map[status] ?? 'draft';
- const config = CONFIGS[key];
- return { ...config, label: trans(`posts.edit.status.${status}`) };
-};
diff --git a/resources/js/pages/posts/Calendar.vue b/resources/js/pages/posts/Calendar.vue
index 729daaa18..e1d4c7c51 100644
--- a/resources/js/pages/posts/Calendar.vue
+++ b/resources/js/pages/posts/Calendar.vue
@@ -7,7 +7,15 @@ import {
IconPlus,
} from '@tabler/icons-vue';
import { useSwipe, type UseSwipeDirection } from '@vueuse/core';
-import { computed, onMounted, onUnmounted, provide, ref, watch } from 'vue';
+import {
+ computed,
+ onMounted,
+ onUnmounted,
+ provide,
+ ref,
+ useTemplateRef,
+ watch,
+} from 'vue';
import { destroy as destroyPost } from '@/actions/App/Http/Controllers/App/PostController';
import AppHeaderActions from '@/components/AppHeaderActions.vue';
@@ -24,6 +32,7 @@ import PublishFilterMenu from '@/components/publish/PublishFilterMenu.vue';
import PublishHeader from '@/components/publish/PublishHeader.vue';
import { Button } from '@/components/ui/button';
import { useAtLeastBreakpoint } from '@/composables/useBreakpoint';
+import { useCollapseWhenTruncated } from '@/composables/useCollapseWhenTruncated';
import { useDisplayTimezone } from '@/composables/useDisplayTimezone';
import { openPostComposer } from '@/composables/useGlobalPostComposer';
import {
@@ -265,6 +274,18 @@ const todayKey = computed(() =>
const isDesktop = useAtLeastBreakpoint('md');
+const toolbar = useTemplateRef<HTMLElement>('toolbar');
+const periodPicker =
+ useTemplateRef<InstanceType<typeof CalendarPeriodPicker>>('periodPicker');
+const { collapsed: filtersCollapsed, expand: showAllFilters } =
+ useCollapseWhenTruncated(
+ toolbar,
+ () => periodPicker.value?.missingTitleWidth() ?? 0,
+ );
+const compactFilters = computed(
+ () => !isDesktop.value || filtersCollapsed.value,
+);
+
const weekdayNames = computed(() => {
const start = localized().startOf('week');
@@ -325,6 +346,8 @@ const headerTitle = computed(() =>
: weekHeaderTitle.value,
);
+watch(headerTitle, showAllFilters);
+
const currentDateQuery = (
view: CalendarView = props.view,
): Record<string, string> =>
@@ -563,10 +586,12 @@ const goToDay = (key: string): void => {
<div class="flex min-h-0 flex-1 flex-col">
<div
- class="mx-4 mt-2 flex h-12 shrink-0 items-center justify-between gap-2 md:mx-8 md:gap-4"
+ class="mx-4 mt-2 flex h-12 shrink-0 items-center justify-between gap-2 md:mx-8"
+ ref="toolbar"
data-testid="calendar-toolbar"
>
<CalendarPeriodPicker
+ ref="periodPicker"
:view="view"
:views="VIEWS"
:title="isDesktop ? headerTitle : mobileTitle"
@@ -578,7 +603,7 @@ const goToDay = (key: string): void => {
/>
<div
- class="flex shrink-0 items-center gap-1 md:ms-auto md:gap-2"
+ class="flex shrink-0 items-center gap-1 md:ms-auto md:gap-0"
data-testid="calendar-filters"
>
<PostChannelFilter
@@ -586,10 +611,18 @@ const goToDay = (key: string): void => {
v-model="selectedChannelIds"
:channels="filterAccounts"
/>
+ <div class="shrink-0 max-md:hidden">
+ <LabelFilter
+ v-model="selectedLabelIds"
+ v-model:untagged="selectedUntagged"
+ :labels="labels"
+ />
+ </div>
<PublishFilterMenu
v-model:status="selectedStatus"
:timezone="timezone"
test-id="calendar"
+ :compact="compactFilters"
:timezones="timezones"
:show-slots="showSlots"
:manage-slots-href="
@@ -599,15 +632,7 @@ const goToDay = (key: string): void => {
"
@update:timezone="setTimezone"
@update:show-slots="toggleSlots"
- >
- <template #desktop-filters>
- <LabelFilter
- v-model="selectedLabelIds"
- v-model:untagged="selectedUntagged"
- :labels="labels"
- />
- </template>
- </PublishFilterMenu>
+ />
<AppHeaderActions>
<ScheduleViewSwitch
active-view="calendar"
@@ -686,13 +711,13 @@ const goToDay = (key: string): void => {
<div
v-for="(week, weekIndex) in calendarWeeks"
:key="weekIndex"
- class="grid min-h-24 flex-1 grid-cols-7 border-border-strong md:min-h-[208px]"
+ class="grid min-h-24 flex-1 auto-rows-[minmax(0,1fr)] grid-cols-7 border-border-strong md:min-h-[208px]"
:class="{ 'border-t': weekIndex > 0 }"
>
<div
v-for="(day, index) in week"
:key="dayKey(day)"
- class="group flex min-w-0 flex-col gap-1 border-border-strong p-1 md:p-2"
+ class="group flex min-h-0 min-w-0 flex-col gap-1 border-border-strong p-1 md:p-2"
:class="{
'border-l': index > 0,
'bg-accent': isPast(day),
@@ -727,7 +752,15 @@ const goToDay = (key: string): void => {
</button>
</div>
- <div class="flex flex-col gap-1">
+ <div class="relative min-h-0 flex-1">
+ <div
+ class="flex flex-col gap-1"
+ :class="{
+ 'absolute inset-0 overflow-y-auto overscroll-contain':
+ expandedDays.includes(dayKey(day)),
+ }"
+ :data-testid="`calendar-items-${dayKey(day)}`"
+ >
<template
v-for="item in visibleMonthItems(day)"
:key="item.key"
@@ -749,12 +782,14 @@ const goToDay = (key: string): void => {
:can-create-post="canCreatePost"
/>
</template>
- <button
+ </div>
+ </div>
+ <button
v-if="
itemsFor(day).length > MONTH_CHIPS
"
type="button"
- class="inline-flex h-6 items-center gap-1 self-end rounded-md px-2 text-xs font-medium text-foreground transition-control hover:bg-accent"
+ class="inline-flex h-6 shrink-0 items-center gap-1 self-end rounded-md px-2 text-xs font-medium text-foreground transition-control hover:bg-accent"
:aria-expanded="
expandedDays.includes(dayKey(day))
"
@@ -784,7 +819,6 @@ const goToDay = (key: string): void => {
})
}}
</button>
- </div>
</div>
</div>
</div>
diff --git a/resources/js/pages/publish/Index.vue b/resources/js/pages/publish/Index.vue
index 72f488419..8784cbbcb 100644
--- a/resources/js/pages/publish/Index.vue
+++ b/resources/js/pages/publish/Index.vue
@@ -122,11 +122,6 @@ interface CardGroup {
}
const NO_TIME = 'no-time';
-const SENT_STATUSES: readonly string[] = [
- PostStatus.Published,
- PostStatus.PartiallyPublished,
- PostStatus.Failed,
-];
const props = defineProps<Props>();
const page = usePage();
@@ -233,24 +228,10 @@ const newPost = (): void => {
);
};
-const splitSettledTargets = (post: PostCard): PostCard[] => {
- const targets = post.post_platforms.filter((target) => target.enabled);
-
- if (!SENT_STATUSES.includes(post.status) || targets.length <= 1) {
- return [post];
- }
-
- return targets.map((target) => ({
- ...post,
- card_key: `${post.id}:${target.id}`,
- post_platforms: [target],
- }));
-};
-
const listGroups = computed<CardGroup[]>(() => {
const groups = new Map<string, PostCard[]>();
- for (const post of (props.posts?.data ?? []).flatMap(splitSettledTargets)) {
+ for (const post of props.posts?.data ?? []) {
const at =
props.tab === 'drafts' || props.tab === 'approvals'
? post.scheduled_at
@@ -263,10 +244,6 @@ const listGroups = computed<CardGroup[]>(() => {
return [...groups].map(([key, posts]) => ({ key, posts }));
});
-const queueTarget = (post: PostCard): string | null =>
- post.post_platforms.find((target) => target.enabled)?.social_account_id ??
- null;
-
const itemTime = (item: QueueItem): number => dayjs.utc(item.at).valueOf();
const groupQueueItems = (items: QueueItem[]): QueueDay[] => {
@@ -351,7 +328,7 @@ const queueSource = computed<QueueView>(() => {
const postItems: QueueItem[] = [];
for (const post of scheduled) {
- const channelId = queueTarget(post);
+ const channelId = post.social_account_id;
if (!post.scheduled_at || !channelId) {
continue;
@@ -376,7 +353,7 @@ const queueSource = computed<QueueView>(() => {
? (props.queue?.days ?? []).flatMap((day) => day.items)
: channelSlots.value.filter(loaded);
const pendingItems = pending.flatMap((post): QueueItem[] => {
- const channelId = queueTarget(post);
+ const channelId = post.social_account_id;
return post.scheduled_at && channelId
? [
@@ -721,8 +698,7 @@ const composerSubmitting = ref(false);
const initialPost = computed<ComposerInitialPost | null>(() => {
const post = props.editPost;
- const target = post?.post_platforms.find((platform) => platform.enabled);
- if (!post || !target?.social_account_id) return null;
+ if (!post?.social_account_id) return null;
return {
content: post.content ?? '',
media: post.media ?? [],
@@ -730,17 +706,16 @@ const initialPost = computed<ComposerInitialPost | null>(() => {
status: post.status,
schedule_mode: post.schedule_mode ?? null,
queue_position: post.approval_queue_position ?? null,
- social_account_id: target.social_account_id,
- content_type: target.content_type ?? '',
- meta: target.meta ?? {},
+ social_account_id: post.social_account_id,
+ content_type: post.content_type ?? '',
+ meta: post.meta ?? {},
label_ids: post.labels?.map((label) => label.id) ?? [],
};
});
const recoveryDraft = computed<ComposerInitialDraft | null>(() => {
const post = props.editPost;
- if (!post || post.post_platforms.some((target) => target.enabled))
- return null;
+ if (!post || post.social_account_id) return null;
return {
content: post.content ?? '',
@@ -1066,7 +1041,7 @@ const submitComposition = (composition: PostComposition): void => {
/>
<PostTimelineCard
v-for="post in group.posts"
- :key="post.card_key ?? post.id"
+ :key="post.id"
:post="post"
:tab="tab"
:display-timezone="timezone"
diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.ts
index aa0d18eca..888847061 100644
--- a/resources/js/types/analytics.ts
+++ b/resources/js/types/analytics.ts
@@ -37,7 +37,6 @@ export interface PostBucket {
export interface TopPost {
id: string;
- post_platform_id: string | null;
post_id: string | null;
social_account_key: string;
platform: string;
@@ -256,7 +255,7 @@ export interface PublicationAnalyticsDetail {
reason: null;
publication: {
id: string;
- post_platform_id: string | null;
+ post_id: string | null;
social_account_key: string;
platform: string;
origin: string;
diff --git a/resources/js/types/google-business.ts b/resources/js/types/google-business.ts
index 79be2ea89..ffda23447 100644
--- a/resources/js/types/google-business.ts
+++ b/resources/js/types/google-business.ts
@@ -1,6 +1,6 @@
/**
* Google Business Profile Local Post topic types and call-to-action buttons.
- * Mirrors the v4 enums we persist on `platforms.*.meta` (STANDARD/EVENT/OFFER,
+ * Mirrors the v4 enums we persist on the post `meta` (STANDARD/EVENT/OFFER,
* NONE/BOOK/…). Same shape as `tiktok-privacy.ts`.
*/
diff --git a/resources/js/types/post.ts b/resources/js/types/post.ts
index 2ba8b3b05..b63bf0e49 100644
--- a/resources/js/types/post.ts
+++ b/resources/js/types/post.ts
@@ -4,13 +4,12 @@ export const PostStatus = {
Scheduled: 'scheduled',
Publishing: 'publishing',
Published: 'published',
- PartiallyPublished: 'partially_published',
Failed: 'failed',
} as const;
export type PostStatusValue = (typeof PostStatus)[keyof typeof PostStatus];
-export const PostPlatformStatus = {
+export const PublishStatus = {
Pending: 'pending',
Publishing: 'publishing',
Published: 'published',
@@ -20,7 +19,7 @@ export const PostPlatformStatus = {
PendingReview: 'pending_review',
} as const;
-export type PostPlatformStatusValue = (typeof PostPlatformStatus)[keyof typeof PostPlatformStatus];
+export type PublishStatusValue = (typeof PublishStatus)[keyof typeof PublishStatus];
export const ScheduleMode = {
Queue: 'queue',
diff --git a/resources/js/types/publish.ts b/resources/js/types/publish.ts
index fd5fd5d55..7282b5d4d 100644
--- a/resources/js/types/publish.ts
+++ b/resources/js/types/publish.ts
@@ -4,6 +4,7 @@ import type { MediaItem } from '@/types/media';
import type {
PostOriginValue,
PostStatusValue,
+ PublishStatusValue,
QueuePositionValue,
ScheduleModeValue,
} from '@/types/post';
@@ -38,21 +39,6 @@ export interface PublishChannel extends PublishSocialAccount {
has_grid: boolean;
}
-export interface PostCardPlatform {
- id: string;
- social_account_id: string;
- enabled: boolean;
- platform: string;
- status: string;
- platform_url?: string | null;
- error_message?: string | null;
- error_context?: { category?: string | null; failed_at?: string | null } | null;
- retry_at?: string | null;
- social_account: PublishSocialAccount | null;
- content_type?: string;
- meta?: Record<string, any>;
-}
-
export interface PostCardLabel {
id: string;
name: string;
@@ -66,11 +52,25 @@ export interface UnavailablePostMetrics {
export type PostCardMetrics = PublicationAnalyticsDetail | UnavailablePostMetrics;
+export interface PostCardFailure {
+ category?: string | null;
+ failed_at?: string | null;
+}
+
export interface PostCard {
id: string;
- card_key?: string;
content: string | null;
status: PostStatusValue;
+ publish_status: PublishStatusValue;
+ social_account_id: string | null;
+ social_account: PublishSocialAccount | null;
+ platform: string | null;
+ content_type?: string | null;
+ meta?: Record<string, any> | null;
+ platform_url?: string | null;
+ error_message?: string | null;
+ failure?: PostCardFailure | null;
+ retry_at?: string | null;
origin: PostOriginValue;
created_at: string;
updated_at: string;
@@ -87,12 +87,11 @@ export interface PostCard {
recurrence_origin_at?: string | null;
published_at: string | null;
user: { name: string } | null;
- post_platforms: PostCardPlatform[];
labels: PostCardLabel[];
notes_count: number;
media?: MediaItem[];
can_delete: boolean;
- metrics?: Record<string, PostCardMetrics | null>;
+ metrics?: PostCardMetrics | null;
}
export interface QueueItem {
diff --git a/resources/js/types/repurpose.ts b/resources/js/types/repurpose.ts
index b0981282b..857ac8435 100644
--- a/resources/js/types/repurpose.ts
+++ b/resources/js/types/repurpose.ts
@@ -1,5 +1,5 @@
import type { ChannelAccount } from '@/types/channel';
-import type { PostPlatformStatusValue } from '@/types/post';
+import type { PublishStatusValue } from '@/types/post';
import type { PauseReasonValue, RepurposeItemStatusValue, RepurposeStatusValue } from '@/types/repurpose-status';
export type RepurposeSourceFormat = 'reel' | 'video' | 'story';
@@ -41,14 +41,10 @@ export interface Repurpose {
updated_at: string;
}
-export interface RepurposeItemPlatform {
- platform: string;
- status: PostPlatformStatusValue | null;
-}
-
export interface RepurposeItemPost {
id: string;
- platforms: RepurposeItemPlatform[];
+ platform: string | null;
+ publish_status: PublishStatusValue;
}
export interface RepurposeItem {
diff --git a/resources/views/mail/post-approval-requested.blade.php b/resources/views/mail/post-approval-requested.blade.php
index 94bb02fe8..d215cffd4 100644
--- a/resources/views/mail/post-approval-requested.blade.php
+++ b/resources/views/mail/post-approval-requested.blade.php
@@ -70,14 +70,15 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
<div style="margin-top: 16px; border-radius: 8px; background-color: #f7f6f3; padding: 16px">
<p style="white-space: pre-line; margin: 0; font-size: 14px; line-height: 24px; color: #292928">{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_approval_requested.post_without_text') }}</p>
</div>
+ @if($channel)
<p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
- {{ __('mail.post_approval_requested.channels') }}
- </p>@foreach($channels as $emailChannel)
+ {{ __('mail.post_approval_requested.channel') }}
+ </p>
<table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
- $emailChannelPlatform = $emailChannel->platform;
- $emailChannelName = $emailChannel->display_name;
+ $emailChannelPlatform = $channel->platform;
+ $emailChannelName = $channel->display_name;
@endphp
<table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
<tr>
@@ -95,7 +96,8 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endforeach <p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
+ @endif
+ <p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
{{ __('mail.post_approval_requested.requested_time') }}
</p>
<p style="margin: 8px 0 0; font-size: 14px; line-height: 24px">
diff --git a/resources/views/mail/post-approved.blade.php b/resources/views/mail/post-approved.blade.php
index 9a008d6f1..f08ec77f9 100644
--- a/resources/views/mail/post-approved.blade.php
+++ b/resources/views/mail/post-approved.blade.php
@@ -67,47 +67,15 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
<p style="margin: 0; line-height: 24px">
{{ __('mail.post_approved.body', ['name' => $approverName, 'workspace' => $workspaceName]) }}
</p>
- @if(count($goesOutPerChannel) > 0)
+ @if($channel)
<p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
- {{ __('mail.post_approved.goes_out') }}
- </p>
- @foreach($goesOutPerChannel as $goesOut)@foreach($goesOut['channels'] as $emailChannel)
- <table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
- <tr>
- <td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
- $emailChannelPlatform = $emailChannel->platform;
- $emailChannelName = $emailChannel->display_name;
- @endphp
- <table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
- <tr>
- <td style="width: 44px; vertical-align: middle">
- <img src="{{ asset('images/accounts/'.$emailChannelPlatform->network().'.png') }}" width="32" height="32" alt style="max-width: 100%; vertical-align: middle; display: block; border-radius: 8px">
- </td>
- <td style="vertical-align: middle">
- <p style="margin: 0; font-size: 16px; font-weight: 600; line-height: 20px; color: #292928">{{ $emailChannelName }}</p>
- @if($emailChannelName !== $emailChannelPlatform->label())
- <p style="margin: 2px 0 0; font-size: 13px; line-height: 18px; color: #5a5a59">{{ $emailChannelPlatform->label() }}</p>
- @endif
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
- @endforeach
- <p style="margin: 8px 0 0; font-size: 14px; line-height: 24px">
- {{ $goesOut['at'] ?? __('mail.post_approved.publishing_now') }}
+ {{ __('mail.post_approved.channel') }}
</p>
- @endforeach
- @else
- <p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
- {{ __('mail.post_approved.channels') }}
- </p>@foreach($channels as $emailChannel)
<table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
- $emailChannelPlatform = $emailChannel->platform;
- $emailChannelName = $emailChannel->display_name;
+ $emailChannelPlatform = $channel->platform;
+ $emailChannelName = $channel->display_name;
@endphp
<table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
<tr>
@@ -125,14 +93,14 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endforeach
+ @endif
<p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
{{ __('mail.post_approved.goes_out') }}
</p>
<p style="margin: 8px 0 0; font-size: 14px; line-height: 24px">
{{ $goesOutAt ?? __('mail.post_approved.publishing_now') }}
</p>
- @endif <div role="separator" style="line-height: 24px">&zwj;</div>
+ <div role="separator" style="line-height: 24px">&zwj;</div>
<div style="text-align: center">
<a href="{{ $url }}" style="display: inline-block; text-decoration: none; font-weight: 600; border-radius: 8px; border: 1px solid #ddd6fe; background-color: #ddd6fe; padding: 12px 24px; text-align: center; font-size: 16px; line-height: 24px; color: #292928">
<!--[if mso]><i style="mso-font-width: 150%; mso-text-raise: 31px" hidden>&emsp;</i><![endif]-->
diff --git a/resources/views/mail/post-note-added.blade.php b/resources/views/mail/post-note-added.blade.php
index 814f26fcf..ae64e38f5 100644
--- a/resources/views/mail/post-note-added.blade.php
+++ b/resources/views/mail/post-note-added.blade.php
@@ -75,12 +75,12 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
{{ __('mail.post_note_added.post_title') }}
</p>
<p style="white-space: pre-line; margin: 8px 0 0; font-size: 14px; line-height: 24px">{{ $postExcerpt !== '' ? $postExcerpt : __('mail.post_note_added.post_without_text') }}</p>
- @if(count($channels) > 0)@foreach($channels as $emailChannel)
+ @if($channel)
<table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
- $emailChannelPlatform = $emailChannel->platform;
- $emailChannelName = $emailChannel->display_name;
+ $emailChannelPlatform = $channel->platform;
+ $emailChannelName = $channel->display_name;
@endphp
<table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
<tr>
@@ -98,7 +98,6 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endforeach
@endif
</div>
<div role="separator" style="line-height: 24px">&zwj;</div>
diff --git a/resources/views/mail/post-publish-failed.blade.php b/resources/views/mail/post-publish-failed.blade.php
index 3040f145f..380775cf3 100644
--- a/resources/views/mail/post-publish-failed.blade.php
+++ b/resources/views/mail/post-publish-failed.blade.php
@@ -70,7 +70,6 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
<p style="margin: 0; line-height: 24px">
{{ __('mail.post_publish_failed.body', ['workspace' => $workspaceName]) }}
</p>
- @if($publication)
<table role="presentation" style="margin-top: 24px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td class="sm-p-4" style="border-radius: 12px; border: 1px solid #eae8e5; padding: 20px">@php
@@ -110,7 +109,6 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endif
@endif <div role="separator" style="line-height: 24px">&zwj;</div>
<div style="text-align: center">
<a href="{{ $url }}" style="display: inline-block; text-decoration: none; font-weight: 600; border-radius: 8px; border: 1px solid #ddd6fe; background-color: #ddd6fe; padding: 12px 24px; text-align: center; font-size: 16px; line-height: 24px; color: #292928">
diff --git a/resources/views/mail/post-published.blade.php b/resources/views/mail/post-published.blade.php
index 902eb97d7..79a20dc89 100644
--- a/resources/views/mail/post-published.blade.php
+++ b/resources/views/mail/post-published.blade.php
@@ -80,7 +80,6 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
<p style="margin: 0; line-height: 24px">
{{ __('mail.post_published.body', ['workspace' => $workspaceName]) }}
</p>
- @if($publication)
<table role="presentation" style="margin-top: 24px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td class="sm-p-4" style="border-radius: 12px; border: 1px solid #eae8e5; padding: 20px">@php
@@ -110,7 +109,7 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endif <div role="separator" style="line-height: 24px">&zwj;</div> @if($publishedUrl)
+ <div role="separator" style="line-height: 24px">&zwj;</div> @if($publishedUrl)
<table role="presentation" align="center" style="margin-left: auto; margin-right: auto" cellpadding="0" cellspacing="0">
<tr>
<td style="vertical-align: middle">
diff --git a/resources/views/mail/post-rejected.blade.php b/resources/views/mail/post-rejected.blade.php
index 8a83b0057..96b35f0cf 100644
--- a/resources/views/mail/post-rejected.blade.php
+++ b/resources/views/mail/post-rejected.blade.php
@@ -67,14 +67,15 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
<p style="margin: 0; line-height: 24px">
{{ __('mail.post_rejected.body', ['name' => $approverName, 'workspace' => $workspaceName]) }}
</p>
+ @if($channel)
<p style="margin: 16px 0 0; font-size: 14px; font-weight: 600; color: #292928">
- {{ __('mail.post_rejected.channels') }}
- </p>@foreach($channels as $emailChannel)
+ {{ __('mail.post_rejected.channel') }}
+ </p>
<table role="presentation" style="margin-top: 12px; width: 100%" cellpadding="0" cellspacing="0">
<tr>
<td style="border-radius: 12px; border: 1px solid #eae8e5; background-color: #ffffff; padding: 16px">@php
- $emailChannelPlatform = $emailChannel->platform;
- $emailChannelName = $emailChannel->display_name;
+ $emailChannelPlatform = $channel->platform;
+ $emailChannelName = $channel->display_name;
@endphp
<table role="presentation" style="width: 100%" cellpadding="0" cellspacing="0">
<tr>
@@ -92,7 +93,7 @@ $direction = Locale::tryFrom(app()->getLocale())?->direction() ?? 'ltr';
</td>
</tr>
</table>
- @endforeach <div role="separator" style="line-height: 24px">&zwj;</div>
+ @endif <div role="separator" style="line-height: 24px">&zwj;</div>
<div style="text-align: center">
<a href="{{ $url }}" style="display: inline-block; text-decoration: none; font-weight: 600; border-radius: 8px; border: 1px solid #ddd6fe; background-color: #ddd6fe; padding: 12px 24px; text-align: center; font-size: 16px; line-height: 24px; color: #292928">
<!--[if mso]><i style="mso-font-width: 150%; mso-text-raise: 31px" hidden>&emsp;</i><![endif]-->
diff --git a/routes/app.php b/routes/app.php
index 4a1a02dfa..d9083f955 100644
--- a/routes/app.php
+++ b/routes/app.php
@@ -224,7 +224,6 @@ Route::middleware(['auth', EnsureAccountReady::class, EnsureHasWorkspace::class]
Route::get('posts/create', [PostController::class, 'create'])->name('app.posts.create');
Route::post('posts', [PostController::class, 'store'])->name('app.posts.store');
Route::get('posts/{post}/edit', [PostController::class, 'edit'])->name('app.posts.edit');
- Route::get('posts/{post}/platforms/{postPlatform}/metrics', [PostController::class, 'platformMetrics'])->name('app.posts.platforms.metrics');
Route::put('posts/{post}', [PostController::class, 'update'])->name('app.posts.update');
Route::put('posts/{post}/schedule', [PostScheduleController::class, 'update'])->name('app.posts.schedule.update');
Route::put('posts/{post}/approve', [PostApprovalController::class, 'approve'])->name('app.posts.approve');
diff --git a/tests/Browser/CalendarPageTest.php b/tests/Browser/CalendarPageTest.php
index e2683690a..49c346e3e 100644
--- a/tests/Browser/CalendarPageTest.php
+++ b/tests/Browser/CalendarPageTest.php
@@ -11,7 +11,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -66,19 +65,11 @@ function waitForCalendarCondition(mixed $page, string $condition): void
function calendarPagePost(SocialAccount $account, ?CarbonInterface $at, PostStatus $status = PostStatus::Scheduled): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
+ return Post::factory()->forAccount($account)->create([
'user_id' => $account->workspace->user_id,
'status' => $status,
'scheduled_at' => $at,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- return $post;
}
function calendarChipSlot(mixed $page, Post $post): ?string
@@ -86,7 +77,7 @@ function calendarChipSlot(mixed $page, Post $post): ?string
return $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]')?.closest('[data-testid^=\"calendar-slot-\"]')?.dataset.testid ?? null");
}
-test('the week grid places posts in their hour row, side by side when they share it', function () {
+test('the week grid places posts in their hour row, stacked as compact rows when they share it', function () {
[$user, $linkedin, $x] = calendarPageSetup();
$weekStart = now('UTC')->startOfWeek()->addWeek();
$day = $weekStart->copy()->addDays(2);
@@ -114,17 +105,17 @@ test('the week grid places posts in their hour row, side by side when they share
const second = box('{$second->id}');
return {
- sameRow: Math.abs(first.top - second.top) < 1,
- sideBySide: second.left >= first.right,
+ stacked: second.top >= first.bottom && Math.abs(first.left - second.left) < 1,
+ sameWidth: Math.abs(first.width - second.width) < 1,
hourOffset: Math.round(slot.top - midnight.top),
- inSlot: first.top >= slot.top && first.bottom <= slot.bottom,
+ inSlot: first.top >= slot.top && second.bottom <= slot.bottom,
};
})()
JS);
expect($layout)->toBe([
- 'sameRow' => true,
- 'sideBySide' => true,
+ 'stacked' => true,
+ 'sameWidth' => true,
'hourOffset' => 14 * 106,
'inSlot' => true,
]);
@@ -162,7 +153,7 @@ test('the calendar honours the channels filter and the display time zone', funct
'week' => $weekStart->format('Y-m-d'),
'channels' => [$x->id],
'tz' => 'Asia/Tokyo',
- ]));
+ ]))->resize(1600, 900);
waitForCalendarTestId($page, "calendar-post-{$xPost->id}");
$page->assertMissing("@calendar-post-{$linkedinPost->id}")
@@ -213,7 +204,7 @@ test('the status filter narrows the calendar to one kind of post', function () {
$this->actingAs($user);
- $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));
+ $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]))->resize(1600, 900);
waitForCalendarTestId($page, "calendar-post-{$scheduled->id}");
$page->assertSeeIn('@calendar-status-filter', 'All posts')
->click('@calendar-status-filter');
@@ -322,6 +313,8 @@ test('show posting times renders empty slots in the week and month views', funct
$page->hover("@calendar-posting-slot-{$slotKey}");
$page->assertSeeIn("@calendar-posting-slot-{$slotKey}", __('posts.publish.add_post_in_slot'));
+ expect($page->script("document.querySelector('[data-testid=\"calendar-add-{$day->format('Y-m-d')}-15\"]').getBoundingClientRect().height"))
+ ->toBe($page->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').getBoundingClientRect().height"));
expect($page->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').closest('[data-testid^=\"calendar-slot-\"]').dataset.testid"))
->toBe("calendar-slot-{$day->format('Y-m-d')}-15");
@@ -424,16 +417,9 @@ test('a published post popover shows its metrics, go to post and the sent menu',
[$user] = calendarPageSetup();
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $user->current_workspace_id, 'timezone' => 'UTC']);
- $post = Post::factory()->published()->create([
- 'workspace_id' => $instagram->workspace_id,
+ $post = Post::factory()->forAccount($instagram)->published()->create([
'user_id' => $user->id,
'content' => 'Already live',
- 'published_at' => now()->subHour(),
- ]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram,
'platform_url' => 'https://www.instagram.com/p/abc/',
'published_at' => now()->subHour(),
]);
@@ -441,10 +427,10 @@ test('a published post popover shows its metrics, go to post and the sent menu',
'workspace_id' => $instagram->workspace_id,
'social_account_id' => $instagram->id,
'social_account_key' => $instagram->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'network' => Platform::Instagram->network(),
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $post->platform_post_id,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
@@ -482,29 +468,48 @@ test('a published post popover shows its metrics, go to post and the sent menu',
->assertNoJavaScriptErrors();
});
-test('an overflowing month day expands and collapses back', function () {
+test('an overflowing month day expands and collapses back, scrolling inside its cell', function () {
[$user, $linkedin] = calendarPageSetup();
$day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(12);
$dayKey = $day->format('Y-m-d');
- $posts = collect(range(0, 3))->map(fn (int $index) => calendarPagePost($linkedin, $day->copy()->setTime(9 + $index, 0)));
+ $posts = collect(range(0, 9))->map(fn (int $index) => calendarPagePost($linkedin, $day->copy()->setTime(9 + $index, 0)));
+ $last = $posts->last();
$this->actingAs($user);
- $page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]));
+ $page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]))->resize(1440, 900);
waitForCalendarTestId($page, "calendar-more-{$dayKey}");
- $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 1]))
- ->assertMissing("@calendar-post-{$posts[3]->id}")
+ $cellHeight = "document.querySelector('[data-testid=\"calendar-day-{$dayKey}\"]').getBoundingClientRect().height";
+ $heightBefore = $page->script($cellHeight);
+
+ $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 7]))
+ ->assertMissing("@calendar-post-{$last->id}")
->click("@calendar-more-{$dayKey}");
- waitForCalendarTestId($page, "calendar-post-{$posts[3]->id}");
+ waitForCalendarTestId($page, "calendar-post-{$last->id}");
- $page->assertVisible("@calendar-post-{$posts[3]->id}")
- ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.less'))
+ $layout = $page->script(<<<JS
+ (() => {
+ const cell = document.querySelector('[data-testid="calendar-day-{$dayKey}"]').getBoundingClientRect();
+ const items = document.querySelector('[data-testid="calendar-items-{$dayKey}"]');
+ const more = document.querySelector('[data-testid="calendar-more-{$dayKey}"]').getBoundingClientRect();
+
+ return {
+ scrolls: items.scrollHeight > items.clientHeight,
+ moreInCell: more.bottom <= cell.bottom + 0.5,
+ };
+ })()
+ JS);
+
+ expect($layout)->toBe(['scrolls' => true, 'moreInCell' => true])
+ ->and(abs($page->script($cellHeight) - $heightBefore))->toBeLessThan(1);
+
+ $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.less'))
->click("@calendar-more-{$dayKey}");
- waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-{$posts[3]->id}\"]')");
+ waitForCalendarCondition($page, "!document.querySelector('[data-testid=\"calendar-post-{$last->id}\"]')");
- $page->assertMissing("@calendar-post-{$posts[3]->id}")
- ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 1]))
+ $page->assertMissing("@calendar-post-{$last->id}")
+ ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 7]))
->assertNoJavaScriptErrors();
});
@@ -671,3 +676,15 @@ test('on a phone the period picker opens from the bottom, switches the view in p
waitForCalendarTestId($page, 'calendar-previous');
$page->assertVisible('@calendar-next')->assertVisible('@calendar-view-trigger');
});
+
+test('the previous period arrow starts on the same line as the calendar', function () {
+ [$user] = calendarPageSetup();
+ $this->actingAs($user);
+
+ $page = visit(route('app.calendar', ['view' => 'week']))->resize(1440, 900);
+ waitForCalendarTestId($page, 'calendar-time-grid');
+
+ expect($page->script("Math.round(document.querySelector('[data-testid=\"calendar-previous\"]').getBoundingClientRect().left)"))
+ ->toBe($page->script("Math.round(document.querySelector('[data-testid=\"calendar-grid\"]').getBoundingClientRect().left)"));
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/ChannelGridTest.php b/tests/Browser/ChannelGridTest.php
index 5cd4eb610..b776f5e91 100644
--- a/tests/Browser/ChannelGridTest.php
+++ b/tests/Browser/ChannelGridTest.php
@@ -2,12 +2,10 @@
declare(strict_types=1);
-use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -42,22 +40,12 @@ function channelGridBrowserUser(): User
/**
* @param list<array<string, mixed>> $media
*/
-function channelGridBrowserPost(SocialAccount $account, string $publishedAt, ContentType $contentType, array $media): PostPlatform
+function channelGridBrowserPost(SocialAccount $account, string $publishedAt, ContentType $contentType, array $media): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
- 'status' => PostStatus::Published,
+ return Post::factory()->forAccount($account, $contentType)->published()->create([
'published_at' => $publishedAt,
'media' => $media,
]);
-
- return PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'published_at' => $publishedAt,
- ]);
}
/**
@@ -95,14 +83,14 @@ test('an instagram channel offers the grid view and the grid lays posts out in t
waitForChannelGridTestId($page, 'channel-grid');
$page->assertPathIs(route('app.channels.grid', $this->instagram, false))
- ->assertVisible("@grid-tile-{$reel->post_id}")
- ->assertVisible("@grid-tile-{$carousel->post_id}")
- ->assertVisible("@grid-tile-{$single->post_id}")
- ->assertMissing("@grid-tile-{$story->post_id}")
- ->assertVisible("@grid-tile-reel-{$reel->post_id}")
- ->assertVisible("@grid-tile-carousel-{$carousel->post_id}")
- ->assertMissing("@grid-tile-reel-{$single->post_id}")
- ->assertMissing("@grid-tile-carousel-{$single->post_id}");
+ ->assertVisible("@grid-tile-{$reel->id}")
+ ->assertVisible("@grid-tile-{$carousel->id}")
+ ->assertVisible("@grid-tile-{$single->id}")
+ ->assertMissing("@grid-tile-{$story->id}")
+ ->assertVisible("@grid-tile-reel-{$reel->id}")
+ ->assertVisible("@grid-tile-carousel-{$carousel->id}")
+ ->assertMissing("@grid-tile-reel-{$single->id}")
+ ->assertMissing("@grid-tile-carousel-{$single->id}");
$columns = $page->script(<<<'JS'
getComputedStyle(document.querySelector('[data-testid="channel-grid"]')).gridTemplateColumns.split(' ').length
@@ -110,15 +98,15 @@ test('an instagram channel offers the grid view and the grid lays posts out in t
expect($columns)->toBe(3);
$tops = $page->script(<<<JS
- ['{$reel->post_id}', '{$carousel->post_id}', '{$single->post_id}']
+ ['{$reel->id}', '{$carousel->id}', '{$single->id}']
.map((id) => Math.round(document.querySelector(`[data-testid="grid-tile-\${id}"]`).getBoundingClientRect().top))
JS);
expect(array_unique($tops))->toHaveCount(1);
- $page->hover("@grid-tile-{$reel->post_id}");
- waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->post_id}");
+ $page->hover("@grid-tile-{$reel->id}");
+ waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->id}");
- expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->post_id}\"] [role=\"tooltip\"]').textContent")))
+ expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->id}\"] [role=\"tooltip\"]').textContent")))
->toBe('This post was sent September 20, 2026 at 10:00 AM');
$page->assertNoJavaScriptErrors();
@@ -197,9 +185,9 @@ test('clicking a carousel tile opens its media in the lightbox', function () {
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, "grid-tile-{$carousel->post_id}");
+ waitForChannelGridTestId($page, "grid-tile-{$carousel->id}");
- $page->click("@grid-tile-{$carousel->post_id}");
+ $page->click("@grid-tile-{$carousel->id}");
waitForChannelGridTestId($page, 'media-lightbox-counter');
$page->assertVisible('@media-lightbox')
@@ -218,11 +206,11 @@ test('the grid tooltip shows the sent time in the user zone, not the browser zon
$this->actingAs($this->user);
$page = visit(route('app.channels.grid', $this->instagram));
- waitForChannelGridTestId($page, "grid-tile-{$reel->post_id}");
- $page->hover("@grid-tile-{$reel->post_id}");
- waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->post_id}");
+ waitForChannelGridTestId($page, "grid-tile-{$reel->id}");
+ $page->hover("@grid-tile-{$reel->id}");
+ waitForChannelGridTestId($page, "grid-tile-tooltip-{$reel->id}");
- expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->post_id}\"] [role=\"tooltip\"]').textContent")))
+ expect(trim((string) $page->script("document.querySelector('[data-testid=\"grid-tile-tooltip-{$reel->id}\"] [role=\"tooltip\"]').textContent")))
->toBe('This post was sent September 20, 2026 at 7:00 PM');
$page->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/ChannelInsightsFiltersTest.php b/tests/Browser/ChannelInsightsFiltersTest.php
index adbe88b0a..46abd5252 100644
--- a/tests/Browser/ChannelInsightsFiltersTest.php
+++ b/tests/Browser/ChannelInsightsFiltersTest.php
@@ -10,7 +10,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -46,20 +45,14 @@ function waitForInsightsFilterScript(mixed $page, string $condition): void
function insightsFilterPublication(SocialAccount $account, User $user, CarbonImmutable $publishedAt, int $reactions, ?ContentType $contentType, ?WorkspaceLabel $label = null, PublicationContentType $publicationType = PublicationContentType::Image): AnalyticsPublication
{
- $destination = null;
+ $post = null;
if ($contentType !== null) {
- $post = Post::factory()->published()->create(['workspace_id' => $account->workspace_id, 'user_id' => $user->id]);
+ $post = Post::factory()->forAccount($account, $contentType)->published()->create(['user_id' => $user->id]);
if ($label !== null) {
$post->labels()->attach($label);
}
-
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'content_type' => $contentType,
- ]);
}
$publication = AnalyticsPublication::factory()->create([
@@ -69,7 +62,7 @@ function insightsFilterPublication(SocialAccount $account, User $user, CarbonImm
'platform' => $account->platform,
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
- 'post_platform_id' => $destination?->id,
+ 'post_id' => $post?->id,
'content_type' => $publicationType,
'provider_published_at' => $publishedAt,
]);
diff --git a/tests/Browser/ChannelInsightsTest.php b/tests/Browser/ChannelInsightsTest.php
index 352c394dc..31a84620b 100644
--- a/tests/Browser/ChannelInsightsTest.php
+++ b/tests/Browser/ChannelInsightsTest.php
@@ -12,7 +12,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\AnalyticsSyncState;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -163,13 +162,8 @@ test('finishing the import refreshes the available metrics and the publication t
});
test('the channel header exports this channel and rows open the post details or the network post', function () {
- $post = Post::factory()->published()->create(['workspace_id' => $this->instagram->workspace_id, 'user_id' => $this->user->id]);
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->instagram->id,
- 'platform' => Platform::Instagram,
- ]);
- $this->mostReactions->update(['post_platform_id' => $destination->id]);
+ $post = Post::factory()->forAccount($this->instagram)->published()->create(['user_id' => $this->user->id]);
+ $this->mostReactions->update(['post_id' => $post->id]);
$this->mostViews->update(['permalink' => 'https://www.instagram.com/p/most-views/']);
$page = visit(route('app.channels.insights', ['account' => $this->instagram, 'range' => '7d']));
@@ -192,18 +186,12 @@ test('the channel header exports this channel and rows open the post details or
});
test('a publication with a TryPost post opens the post details on the insights page', function () {
- $post = Post::factory()->published()->create([
- 'workspace_id' => $this->instagram->workspace_id,
+ $post = Post::factory()->forAccount($this->instagram)->published()->create([
'user_id' => $this->user->id,
'content' => 'Published through TryPost',
'published_at' => $this->mostReactions->provider_published_at,
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->instagram->id,
- 'platform' => Platform::Instagram,
- ]);
- $this->mostReactions->update(['post_platform_id' => $target->id]);
+ $this->mostReactions->update(['post_id' => $post->id]);
$insightsUrl = route('app.channels.insights', $this->instagram);
$page = visit($insightsUrl);
diff --git a/tests/Browser/ChannelMediaIssueTest.php b/tests/Browser/ChannelMediaIssueTest.php
index 4434fa542..963a8984c 100644
--- a/tests/Browser/ChannelMediaIssueTest.php
+++ b/tests/Browser/ChannelMediaIssueTest.php
@@ -7,7 +7,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -50,7 +49,7 @@ test('an Instagram media warning links to the network limits', function () {
/**
* @param array<string, string> $platformMeta
* @param array<string, int> $imageMeta
- * @return array{Post, PostPlatform}
+ * @return array{Post}
*/
function seedInstagramFeedImagePost(array $platformMeta = [], array $imageMeta = ['width' => 1080, 'height' => 1600], int $size = 1024, int $imageCount = 5, Platform $platform = Platform::Instagram): array
{
@@ -60,9 +59,9 @@ function seedInstagramFeedImagePost(array $platformMeta = [], array $imageMeta =
$user->update(['current_workspace_id' => $workspace->id]);
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, $platform === Platform::Facebook ? ContentType::FacebookPost : ContentType::InstagramFeed)->create([
'user_id' => $user->id,
+ 'meta' => $platformMeta,
'content' => 'A five-image carousel',
'media' => array_map(fn (int $index): array => [
'id' => "image-{$index}",
@@ -74,17 +73,9 @@ function seedInstagramFeedImagePost(array $platformMeta = [], array $imageMeta =
'meta' => $imageMeta,
], range(1, $imageCount)),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => $platform === Platform::Facebook ? ContentType::FacebookPost : ContentType::InstagramFeed,
- 'meta' => $platformMeta,
- ]);
-
test()->actingAs($user);
- return [$post, $postPlatform];
+ return [$post];
}
test('Instagram feed has no global aspect control and asks to adjust unsupported images', function () {
@@ -107,10 +98,10 @@ test('Instagram feed has no global aspect control and asks to adjust unsupported
});
test('Facebook has no aspect ratio selector and accepts an image of any ratio', function (int $width, int $height) {
- [$post, $postPlatform] = seedInstagramFeedImagePost(imageMeta: ['width' => $width, 'height' => $height], imageCount: 1, platform: Platform::Facebook);
+ [$post] = seedInstagramFeedImagePost(imageMeta: ['width' => $width, 'height' => $height], imageCount: 1, platform: Platform::Facebook);
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, "channel-{$postPlatform->id}");
+ waitForChannelIssueTestId($page, "composer-account-{$post->social_account_id}");
expect($page->script('document.querySelectorAll("[data-testid^=facebook-aspect-]").length'))->toBe(0);
@@ -122,7 +113,7 @@ test('Facebook has no aspect ratio selector and accepts an image of any ratio',
]);
test('saving an Instagram post stores no global aspect ratio', function () {
- [$post, $postPlatform] = seedInstagramFeedImagePost([], ['width' => 1080, 'height' => 1350], imageCount: 1);
+ [$post] = seedInstagramFeedImagePost([], ['width' => 1080, 'height' => 1350], imageCount: 1);
$asset = Media::factory()->ownedByPost($post)->create([
'meta' => ['width' => 1080, 'height' => 1350],
]);
@@ -147,7 +138,7 @@ test('saving an Instagram post stores no global aspect ratio', function () {
JS);
expect($page->script('Boolean(document.querySelector("[data-testid=post-composer-dialog]"))'))->toBeFalse();
- expect(data_get($postPlatform->fresh()->meta, 'aspect_ratio'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'aspect_ratio'))->toBeNull();
Storage::delete([$asset->path, ...$post->ownedMedia()->pluck('path')->all()]);
});
@@ -240,7 +231,7 @@ test('Instagram image editor saves alt text on the selected slide', function ()
});
test('appearance filter saves a new image without cropping its original dimensions', function () {
- [$post, $postPlatform] = seedInstagramFeedImagePost(imageMeta: ['width' => 200, 'height' => 200], imageCount: 1);
+ [$post] = seedInstagramFeedImagePost(imageMeta: ['width' => 200, 'height' => 200], imageCount: 1);
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$media = $post->media;
$media[0]['url'] = "data:image/png;base64,{$base64}";
@@ -248,8 +239,8 @@ test('appearance filter saves a new image without cropping its original dimensio
$page = visit(route('app.posts.edit', $post));
- waitForChannelIssueTestId($page, "composer-{$postPlatform->social_account_id}-edit-0");
- $page->click("@composer-{$postPlatform->social_account_id}-edit-0")
+ waitForChannelIssueTestId($page, "composer-{$post->social_account_id}-edit-0");
+ $page->click("@composer-{$post->social_account_id}-edit-0")
->click('@media-editor-appearance-section')
->click('@media-filter-mono');
@@ -286,7 +277,7 @@ test('appearance filter saves a new image without cropping its original dimensio
});
test('a media ratio warning names the destination with the same message the server returns', function () {
- [$post, $postPlatform] = seedInstagramFeedImagePost(imageCount: 1);
+ [$post] = seedInstagramFeedImagePost(imageCount: 1);
$post->update(['media' => [[
'id' => 'reel-1',
'type' => 'video',
@@ -296,7 +287,7 @@ test('a media ratio warning names the destination with the same message the serv
'size' => 1024,
'meta' => ['width' => 2200, 'height' => 200, 'duration' => 10],
]]]);
- $postPlatform->update(['content_type' => ContentType::InstagramReel]);
+ $post->update(['content_type' => ContentType::InstagramReel]);
$page = visit(route('app.posts.edit', $post));
waitForChannelIssueTestId($page, 'media-rules-warning');
@@ -313,11 +304,11 @@ test('a media ratio warning names the destination with the same message the serv
});
test('an Instagram feed post without media shows the inline warning once, under the post type', function () {
- [$post, $postPlatform] = seedInstagramFeedImagePost();
+ [$post] = seedInstagramFeedImagePost();
$post->update(['media' => []]);
$page = visit(route('app.posts.edit', $post));
- $warning = "composer-media-warning-{$postPlatform->social_account_id}";
+ $warning = "composer-media-warning-{$post->social_account_id}";
waitForChannelIssueTestId($page, $warning);
$page->assertSeeIn("@{$warning}", 'Please include an image or video.')
diff --git a/tests/Browser/ChannelSettingsPageTest.php b/tests/Browser/ChannelSettingsPageTest.php
index 4eaaec109..6fc7226ce 100644
--- a/tests/Browser/ChannelSettingsPageTest.php
+++ b/tests/Browser/ChannelSettingsPageTest.php
@@ -9,7 +9,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\User\TimeFormat;
use App\Enums\User\WeekStart;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -320,14 +319,12 @@ test('changing the time zone asks first and cancel and escape keep the old zone'
test('confirming the time zone saves it and reflows the queue into the new zone slots', function () {
[$user, $channel] = channelSettingsPageSetup();
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $post = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => null,
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id, 'platform' => $channel->platform, 'enabled' => true]);
ReflowChannelQueue::handle($channel, $post, QueuePosition::Next);
$this->actingAs($user);
diff --git a/tests/Browser/ComposerAutosaveTest.php b/tests/Browser/ComposerAutosaveTest.php
index 32578a49d..b2f4f2765 100644
--- a/tests/Browser/ComposerAutosaveTest.php
+++ b/tests/Browser/ComposerAutosaveTest.php
@@ -451,8 +451,8 @@ test('an unfinished post from the old shared editor restores one card per networ
*/
function composerAutosaveSavedContents(Workspace $workspace): array
{
- return Post::query()->where('workspace_id', $workspace->id)->with('postPlatforms')->get()
- ->mapWithKeys(fn (Post $post): array => [$post->postPlatforms->sole()->social_account_id => $post->content])
+ return Post::query()->where('workspace_id', $workspace->id)->get()
+ ->mapWithKeys(fn (Post $post): array => [$post->social_account_id => $post->content])
->all();
}
diff --git a/tests/Browser/ComposerChannelSettingsTest.php b/tests/Browser/ComposerChannelSettingsTest.php
index c0d638e4f..0a68637d4 100644
--- a/tests/Browser/ComposerChannelSettingsTest.php
+++ b/tests/Browser/ComposerChannelSettingsTest.php
@@ -9,7 +9,6 @@ use App\Enums\SocialAccount\Platform;
use App\Enums\User\TimeFormat;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -22,7 +21,7 @@ use Illuminate\Support\Str;
/**
* @param array<int, array<string, mixed>> $media
*/
-function seedChannelSettingsPost(Platform $platform, ContentType $contentType, array $media = []): PostPlatform
+function seedChannelSettingsPost(Platform $platform, ContentType $contentType, array $media = []): Post
{
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
@@ -37,24 +36,15 @@ function seedChannelSettingsPost(Platform $platform, ContentType $contentType, a
'token_expires_at' => now()->addDays(20),
]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, $contentType)->create([
'user_id' => $user->id,
'content' => 'Channel settings',
'media' => $media,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => $contentType,
- 'meta' => [],
- ]);
-
test()->actingAs($user);
- return $postPlatform;
+ return $post;
}
function waitForChannelSettingsCondition(mixed $page, string $condition): void
@@ -108,9 +98,9 @@ function fakeChannelSettingsApis(): void
test('every network with settings renders them as label and control rows under the editor', function (Platform $platform, ContentType $contentType, array $media) {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost($platform, $contentType, $media);
+ $post = seedChannelSettingsPost($platform, $contentType, $media);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'channel-settings-rows');
$layout = $page->script(<<<'JS'
@@ -165,10 +155,10 @@ test('every network with settings renders them as label and control rows under t
test('the instagram channel card picks its content type from a radio row above the editor', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, "composer-type-{$id}-instagram_feed");
$page->assertAttribute("@composer-type-{$id}-instagram_feed", 'aria-checked', 'true')
@@ -190,17 +180,17 @@ test('the instagram channel card picks its content type from a radio row above t
->assertNoJavaScriptErrors();
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->content_type)->toBe(ContentType::InstagramReel);
+ expect($post->fresh()->content_type)->toBe(ContentType::InstagramReel);
});
test('a pinterest pin takes its type from the media', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Pinterest, ContentType::PinterestPin);
- $id = $postPlatform->social_account_id;
- $images = Media::factory()->count(2)->temporaryUpload($postPlatform->post->workspace)->create(['mime_type' => 'image/png']);
- $postPlatform->post->update(['media' => $images->map(fn (Media $media): array => MediaItem::fromMedia($media)->toArray())->all()]);
+ $post = seedChannelSettingsPost(Platform::Pinterest, ContentType::PinterestPin);
+ $id = $post->social_account_id;
+ $images = Media::factory()->count(2)->temporaryUpload($post->workspace)->create(['mime_type' => 'image/png']);
+ $post->update(['media' => $images->map(fn (Media $media): array => MediaItem::fromMedia($media)->toArray())->all()]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'pinterest-board-trigger');
$page->assertMissing("@composer-type-{$id}")
@@ -208,14 +198,14 @@ test('a pinterest pin takes its type from the media', function () {
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->content_type)->toBe(ContentType::PinterestCarousel);
+ expect($post->fresh()->content_type)->toBe(ContentType::PinterestCarousel);
});
test('the pinterest board picker searches, refreshes and creates boards', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Pinterest, ContentType::PinterestPin);
+ $post = seedChannelSettingsPost(Platform::Pinterest, ContentType::PinterestPin);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'pinterest-board-trigger');
$page->click('@pinterest-board-trigger');
@@ -257,14 +247,14 @@ test('the pinterest board picker searches, refreshes and creates boards', functi
waitForChannelSettingsCondition($page, "!document.querySelector('[data-testid=\"pinterest-board-picker\"]')");
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect(data_get($postPlatform->fresh()->meta, 'board_id'))->toBe('board_3');
+ expect(data_get($post->fresh()->meta, 'board_id'))->toBe('board_3');
});
test('the google business card picks its type in the header and lists the fields in the reference order', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'google-business-topic-STANDARD');
$fields = <<<'JS'
[...document.querySelectorAll('[data-testid="composer-customization"] [data-testid^="google-business-"]')]
@@ -310,7 +300,7 @@ test('the google business card picks its type in the header and lists the fields
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- $meta = $postPlatform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'topic_type'))->toBe('EVENT')
->and(data_get($meta, 'event.title'))->toBe('Launch night')
->and(data_get($meta, 'event.start_date'))->not->toBeNull()
@@ -322,9 +312,9 @@ test('the google business card picks its type in the header and lists the fields
test('the google business panel shows a server validation error under its field', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'google-business-cta');
$page->click('@google-business-cta');
waitForChannelSettingsTestId($page, 'google-business-cta-option-BOOK');
@@ -339,15 +329,15 @@ test('the google business panel shows a server validation error under its field'
->toContain(__('validation.url', ['attribute' => __('posts.form.google_business.cta_url')]));
$page->assertVisible('@post-composer-dialog')
->assertNoJavaScriptErrors();
- expect(data_get($postPlatform->fresh()->meta, 'call_to_action'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'call_to_action'))->toBeNull();
});
test('the google business event shows start and end time fields beside the dates when add time is on', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
- $postPlatform->update(['meta' => ['topic_type' => 'EVENT', 'event' => ['title' => 'Launch night', 'start_date' => '2037-03-10', 'end_date' => '2037-03-12']]]);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post->update(['meta' => ['topic_type' => 'EVENT', 'event' => ['title' => 'Launch night', 'start_date' => '2037-03-10', 'end_date' => '2037-03-12']]]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'google-business-add-time');
$page->assertMissing('@google-business-start-time')
->assertMissing('@google-business-end-time')
@@ -374,7 +364,7 @@ test('the google business event shows start and end time fields beside the dates
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect(data_get($postPlatform->fresh()->meta, 'event'))->toEqual([
+ expect(data_get($post->fresh()->meta, 'event'))->toEqual([
'title' => 'Launch night',
'start_date' => '2037-03-10',
'end_date' => '2037-03-12',
@@ -385,9 +375,9 @@ test('the google business event shows start and end time fields beside the dates
test('the youtube card saves its fields in the reference order with the AI label last', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::YouTube, ContentType::YouTubeShort);
+ $post = seedChannelSettingsPost(Platform::YouTube, ContentType::YouTubeShort);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'youtube-title');
$order = ['youtube-title', 'youtube-category', 'youtube-privacy', 'youtube-license',
@@ -428,7 +418,7 @@ test('the youtube card saves its fields in the reference order with the AI label
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual([
+ expect($post->fresh()->meta)->toEqual([
'title' => 'Explicit title',
'category_id' => '27',
'privacy_status' => 'unlisted',
@@ -441,9 +431,9 @@ test('the youtube card saves its fields in the reference order with the AI label
test('the tiktok AI label is the last row and saves is_aigc', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo);
+ $post = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'tiktok-ai-generated');
expect($page->script(<<<'JS'
@@ -458,20 +448,20 @@ test('the tiktok AI label is the last row and saves is_aigc', function () {
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect(data_get($postPlatform->fresh()->meta, 'is_aigc'))->toBeTrue();
+ expect(data_get($post->fresh()->meta, 'is_aigc'))->toBeTrue();
});
test('google business seeds event dates in the user time zone and an offer drops the event times', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
$timezone = now('Pacific/Kiritimati')->toDateString() === now('UTC')->toDateString() ? 'Pacific/Pago_Pago' : 'Pacific/Kiritimati';
- $postPlatform->post->user->update(['timezone' => $timezone]);
- $this->actingAs($postPlatform->post->user->fresh());
+ $post->user->update(['timezone' => $timezone]);
+ $this->actingAs($post->user->fresh());
$today = now($timezone);
expect($today->format('Y-m-d'))->not->toBe(now('UTC')->format('Y-m-d'));
- $page = visit(route('app.posts.edit', $postPlatform->post))->withTimezone('UTC')->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->withTimezone('UTC')->resize(1280, 900);
waitForChannelSettingsTestId($page, 'google-business-topic-EVENT');
$page->click('@google-business-topic-EVENT');
waitForChannelSettingsTestId($page, 'google-business-add-time');
@@ -488,7 +478,7 @@ test('google business seeds event dates in the user time zone and an offer drops
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- $meta = $postPlatform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'topic_type'))->toBe('OFFER')
->and(data_get($meta, 'event'))->toEqual([
'title' => 'Launch night',
@@ -501,10 +491,10 @@ test('google business seeds event dates in the user time zone and an offer drops
test('the instagram card shows share to feed on reels, the AI label last and on every type', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramReel);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramReel);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'instagram-share-to-feed');
expect($page->script("document.querySelector('[data-testid=\"instagram-share-to-feed\"]').getAttribute('aria-checked')"))->toBe('true')
@@ -539,7 +529,7 @@ test('the instagram card shows share to feed on reels, the AI label last and on
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual([
+ expect($post->fresh()->meta)->toEqual([
'share_to_feed' => false,
'is_ai_generated' => true,
]);
@@ -547,10 +537,10 @@ test('the instagram card shows share to feed on reels, the AI label last and on
test('the instagram card counts hashtags down to five and warns past the limit', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, "composer-hashtags-remaining-{$id}");
expect($page->script(<<<JS
@@ -581,11 +571,11 @@ test('the instagram card counts hashtags down to five and warns past the limit',
test('the mastodon content warning counts against the post', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
+ $id = $post->social_account_id;
$limit = Platform::Mastodon->maxContentLength();
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'mastodon-content-warning');
$page->assertSeeIn("@composer-char-count-{$id}", (string) ($limit - mb_strlen('Channel settings')))
@@ -595,16 +585,16 @@ test('the mastodon content warning counts against the post', function () {
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual(['spoiler_text' => 'Spoilers']);
+ expect($post->fresh()->meta)->toEqual(['spoiler_text' => 'Spoilers']);
});
test('the threads card offers a topic and a ghost post drops the topic and the media tray', function () {
fakeChannelSettingsApis();
config(['services.unsplash.access_key' => 'test-unsplash-key']);
- $postPlatform = seedChannelSettingsPost(Platform::Threads, ContentType::ThreadsPost);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Threads, ContentType::ThreadsPost);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'threads-topic-tag');
$page->fill('@threads-topic-tag', '#laravel')
@@ -624,7 +614,7 @@ test('the threads card offers a topic and a ghost post drops the topic and the m
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual(['topic_tag' => 'laravel']);
+ expect($post->fresh()->meta)->toEqual(['topic_tag' => 'laravel']);
});
test('a threads card with a link card can switch to a ghost post, which keeps the link and drops the card', function () {
@@ -633,12 +623,12 @@ test('a threads card with a link card can switch to a ghost post, which keeps th
$url => Http::response('<meta property="og:title" content="Article card">'),
'*' => Http::response([], 200),
]);
- $postPlatform = seedChannelSettingsPost(Platform::Threads, ContentType::ThreadsPost);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Threads, ContentType::ThreadsPost);
+ $id = $post->social_account_id;
$ghost = "composer-type-{$id}-threads_ghost_post";
- $postPlatform->post->update(['content' => "Read {$url}"]);
+ $post->update(['content' => "Read {$url}"]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, "composer-link-card-{$id}");
expect($page->script("document.querySelector('[data-testid=\"{$ghost}\"]').disabled"))->toBeFalse();
@@ -650,16 +640,16 @@ test('a threads card with a link card can switch to a ghost post, which keeps th
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->content_type)->toBe(ContentType::ThreadsGhostPost);
+ expect($post->fresh()->content_type)->toBe(ContentType::ThreadsGhostPost);
});
test('a bluesky thread starts from the toolbar and stacks its replies under the post', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
+ $id = $post->social_account_id;
$limit = Platform::Bluesky->maxContentLength();
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'thread-start');
expect($page->script("!!document.querySelector('[data-testid=\"composer-{$id}-toolbar\"] [data-testid=\"thread-start\"]')"))->toBeTrue();
@@ -682,14 +672,14 @@ test('a bluesky thread starts from the toolbar and stacks its replies under the
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual(['thread_replies' => [['text' => 'Third post', 'media' => []]]]);
+ expect($post->fresh()->meta)->toEqual(['thread_replies' => [['text' => 'Third post', 'media' => []]]]);
});
test('a thread reply of invisible characters is empty like on the server', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
+ $post = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'thread-start');
$page->click('@thread-start');
waitForChannelSettingsTestId($page, 'thread-reply-0');
@@ -709,9 +699,9 @@ test('a server error on a thread reply shows under that reply', function () {
return $content === 'Too long for the server' ? str_repeat('a', 400) : parent::displayText($content, $platform);
}
});
- $postPlatform = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
+ $post = seedChannelSettingsPost(Platform::Bluesky, ContentType::BlueskyPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'thread-start');
$page->click('@thread-start');
waitForChannelSettingsTestId($page, 'thread-reply-0');
@@ -727,12 +717,12 @@ test('a server error on a thread reply shows under that reply', function () {
test('a thread reply shows its own media under it and keeps it on save', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $id = $postPlatform->social_account_id;
- $image = Media::factory()->ownedByPost($postPlatform->post)->create(['mime_type' => 'image/png']);
- $postPlatform->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]], 'Plain reply']]]);
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $id = $post->social_account_id;
+ $image = Media::factory()->ownedByPost($post)->create(['mime_type' => 'image/png']);
+ $post->update(['meta' => ['thread_replies' => [['text' => 'With a photo', 'media' => [MediaItem::fromMedia($image)->toArray()]], 'Plain reply']]]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, "composer-{$id}-reply-0-media-item-0");
$page->assertMissing("@composer-{$id}-media-item-0")
@@ -755,20 +745,20 @@ test('a thread reply shows its own media under it and keeps it on save', functio
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- $replies = $postPlatform->fresh()->meta['thread_replies'];
+ $replies = $post->fresh()->meta['thread_replies'];
expect($replies[0]['text'])->toBe('Still with a photo')
->and($replies[0]['media'][0]['id'])->toBe($image->id)
->and($replies[1])->toEqual(['text' => 'Plain reply', 'media' => []])
- ->and($postPlatform->post->fresh()->media)->toBe([]);
+ ->and($post->fresh()->media)->toBe([]);
});
test('the mastodon preview hides the post behind its content warning on every post of the thread', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
- $postPlatform->update(['meta' => ['spoiler_text' => 'Spoilers', 'thread_replies' => ['Hidden reply']]]);
+ $post = seedChannelSettingsPost(Platform::Mastodon, ContentType::MastodonPost);
+ $post->update(['meta' => ['spoiler_text' => 'Spoilers', 'thread_replies' => ['Hidden reply']]]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'mastodon-preview-content-warning');
expect($page->script("[...document.querySelectorAll('[data-testid=\"preview-thread\"] [data-testid=\"mastodon-preview-content-warning\"]')].map((warning) => warning.innerText.replace(/\\s+/g, ' ').trim())"))
@@ -781,11 +771,11 @@ test('the mastodon preview hides the post behind its content warning on every po
test('an x thread starts from the toolbar and counts each reply against the account limit', function (array $accountMeta, int $limit) {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $postPlatform->socialAccount->update(['meta' => [...(array) $postPlatform->socialAccount->meta, ...$accountMeta]]);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $post->socialAccount->update(['meta' => [...(array) $post->socialAccount->meta, ...$accountMeta]]);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'thread-start');
$page->click('@thread-start');
@@ -798,7 +788,7 @@ test('an x thread starts from the toolbar and counts each reply against the acco
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual(['thread_replies' => [['text' => 'Second tweet', 'media' => []]]]);
+ expect($post->fresh()->meta)->toEqual(['thread_replies' => [['text' => 'Second tweet', 'media' => []]]]);
})->with([
'standard account' => [[], 280],
'premium account' => [['x_subscription_type' => 'Premium'], 25000],
@@ -806,9 +796,9 @@ test('an x thread starts from the toolbar and counts each reply against the acco
test('the x card offers the ai-generated switch with its explanation and saves it', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'x-ai-generated');
$page->assertVisible('@x-ai-generated-info')
@@ -817,15 +807,15 @@ test('the x card offers the ai-generated switch with its explanation and saves i
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect($postPlatform->fresh()->meta)->toEqual(['is_ai_generated' => true]);
+ expect($post->fresh()->meta)->toEqual(['is_ai_generated' => true]);
});
test('shift enter opens the next post of an x thread and backspace on an empty post folds it back', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, "composer-caption-{$id}");
$page->keys("@composer-caption-{$id}", 'Shift+Enter');
@@ -854,12 +844,12 @@ test('shift enter opens the next post of an x thread and backspace on an empty p
test('arrow keys move between the posts of a thread from the end and the start of each one', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $postPlatform->post->update(['content' => 'Root']);
- $postPlatform->update(['meta' => ['thread_replies' => ['First reply', 'Second reply']]]);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $post->update(['content' => 'Root']);
+ $post->update(['meta' => ['thread_replies' => ['First reply', 'Second reply']]]);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, "composer-caption-{$id}");
$page->script("(() => { const c = document.querySelector('[data-testid=\"composer-caption-{$id}\"]'); c.focus(); c.setSelectionRange(c.value.length, c.value.length); })()");
@@ -889,12 +879,12 @@ test('arrow keys move between the posts of a thread from the end and the start o
test('the preview scrolls to the thread post being edited', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $postPlatform->post->update(['content' => str_repeat('Root post text. ', 40)]);
- $postPlatform->update(['meta' => ['thread_replies' => [str_repeat('First reply text. ', 40), str_repeat('Second reply text. ', 40), 'Last reply']]]);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $post->update(['content' => str_repeat('Root post text. ', 40)]);
+ $post->update(['meta' => ['thread_replies' => [str_repeat('First reply text. ', 40), str_repeat('Second reply text. ', 40), 'Last reply']]]);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 700);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 700);
waitForChannelSettingsTestId($page, 'thread-reply-collapsed-2');
$page->click('@thread-reply-collapsed-2');
@@ -910,25 +900,25 @@ test('the preview scrolls to the thread post being edited', function () {
test('editing a scheduled post offers to move it back to drafts', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::X, ContentType::XPost);
- $postPlatform->post->update(['content' => 'Scheduled post', 'status' => Status::Scheduled, 'scheduled_at' => now()->addDays(2)]);
+ $post = seedChannelSettingsPost(Platform::X, ContentType::XPost);
+ $post->update(['content' => 'Scheduled post', 'status' => Status::Scheduled, 'scheduled_at' => now()->addDays(2)]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, 'composer-save-draft');
$page->assertSeeIn('@composer-save-draft', __('posts.publish.actions.move_to_drafts'))
->click('@composer-save-draft');
waitForChannelSettingsCondition($page, "!document.querySelector('[data-testid=\"composer-save-draft\"]')");
- expect($postPlatform->post->fresh()->status)->toBe(Status::Draft);
+ expect($post->fresh()->status)->toBe(Status::Draft);
$page->assertNoJavaScriptErrors();
});
test('the google business preview shows no verified badge', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, 'google-business-preview');
expect($page->script("document.querySelector('[data-testid=\"google-business-preview\"] .text-info.rounded-full, [data-testid=\"google-business-preview\"] [data-testid=\"preview-verified\"]') === null"))->toBeTrue();
@@ -938,11 +928,11 @@ test('the google business preview shows no verified badge', function () {
test('a youtube video with neither text nor a title warns in its card until a title is set', function () {
fakeChannelSettingsApis();
$video = [['id' => (string) Str::uuid(), 'type' => 'video', 'path' => 'medias/clip.mp4', 'url' => 'https://example.com/clip.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'clip.mp4']];
- $postPlatform = seedChannelSettingsPost(Platform::YouTube, ContentType::YouTubeShort, $video);
- $postPlatform->post->update(['content' => '']);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::YouTube, ContentType::YouTubeShort, $video);
+ $post->update(['content' => '']);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, "composer-meta-warning-{$id}");
$page->assertSeeIn("@composer-meta-warning-{$id}", __('posts.form.youtube.title_required'))
@@ -955,9 +945,9 @@ test('a youtube video with neither text nor a title warns in its card until a ti
test('the tiktok interactions read as full sentences and the compliance text lines up with the fields', function () {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo);
+ $post = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'tiktok-privacy-level');
$page->assertMissing('@tiktok-posting-to')
@@ -981,10 +971,10 @@ test('the tiktok interactions read as full sentences and the compliance text lin
test('tiktok has no post type choice: photos make a photo post and a video a video post', function () {
fakeChannelSettingsApis();
$photos = collect(range(1, 2))->map(fn (int $index): array => ['id' => (string) Str::uuid(), 'type' => 'image', 'path' => "medias/photo-{$index}.jpg", 'url' => "https://example.com/photo-{$index}.jpg", 'mime_type' => 'image/jpeg', 'original_filename' => "photo-{$index}.jpg"])->all();
- $postPlatform = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo, $photos);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo, $photos);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, 'tiktok-privacy-level');
$page->assertMissing("@composer-type-{$id}-tiktok_video")
@@ -998,7 +988,7 @@ test('tiktok has no post type choice: photos make a photo post and a video a vid
$page->click('@composer-save-draft');
waitForChannelSettingsCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
- expect($postPlatform->fresh()->meta['auto_add_music'] ?? null)->toBeTrue();
+ expect($post->fresh()->meta['auto_add_music'] ?? null)->toBeTrue();
$page->assertNoJavaScriptErrors();
});
@@ -1007,10 +997,10 @@ test('tiktok takes photos or a single video, never both, and says so in its card
$media = collect($kinds)->map(fn (string $kind, int $index): array => $kind === 'image'
? ['id' => (string) Str::uuid(), 'type' => 'image', 'path' => "medias/photo-{$index}.jpg", 'url' => "https://example.com/photo-{$index}.jpg", 'mime_type' => 'image/jpeg', 'original_filename' => "photo-{$index}.jpg"]
: ['id' => (string) Str::uuid(), 'type' => 'video', 'path' => "medias/clip-{$index}.mp4", 'url' => "https://example.com/clip-{$index}.mp4", 'mime_type' => 'video/mp4', 'original_filename' => "clip-{$index}.mp4"])->all();
- $postPlatform = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo, $media);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokVideo, $media);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, "composer-media-warning-{$id}");
$page->assertSeeIn("@composer-media-warning-{$id}", __("posts.form.warnings.{$warning}", $params))
@@ -1023,10 +1013,10 @@ test('tiktok takes photos or a single video, never both, and says so in its card
test('every action on a media tile shows its name in a tooltip', function () {
fakeChannelSettingsApis();
$media = collect(range(1, 2))->map(fn (int $index): array => ['id' => (string) Str::uuid(), 'type' => 'image', 'path' => "medias/photo-{$index}.jpg", 'url' => "https://example.com/photo-{$index}.jpg", 'mime_type' => 'image/jpeg', 'original_filename' => "photo-{$index}.jpg"])->all();
- $postPlatform = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed, $media);
- $id = $postPlatform->social_account_id;
+ $post = seedChannelSettingsPost(Platform::Instagram, ContentType::InstagramFeed, $media);
+ $id = $post->social_account_id;
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, "composer-{$id}-media-item-1");
foreach ([
@@ -1051,9 +1041,9 @@ test('every action on a media tile shows its name in a tooltip', function () {
test('the tiktok preview shows a photo on black, with no blurred fill around it', function () {
fakeChannelSettingsApis();
$photo = [['id' => (string) Str::uuid(), 'type' => 'image', 'path' => 'medias/photo.jpg', 'url' => 'https://example.com/photo.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg']];
- $postPlatform = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokPhoto, $photo);
+ $post = seedChannelSettingsPost(Platform::TikTok, ContentType::TikTokPhoto, $photo);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, 'tiktok-preview');
expect($page->script("document.querySelectorAll('[data-testid=\"tiktok-preview\"] img[aria-hidden=\"true\"]').length"))->toBe(0)
@@ -1063,11 +1053,11 @@ test('the tiktok preview shows a photo on black, with no blurred fill around it'
test('the google business event times follow the user clock and pick from a list', function (TimeFormat $format, string $typed, string $shown, string $typedShown) {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
+ $post = seedChannelSettingsPost(Platform::GoogleBusiness, ContentType::GoogleBusinessPost);
auth()->user()->update(['time_format' => $format]);
- $postPlatform->update(['meta' => ['topic_type' => 'EVENT', 'event' => ['title' => 'Launch night', 'start_date' => '2037-03-10', 'end_date' => '2037-03-12', 'start_time' => '09:00']]]);
+ $post->update(['meta' => ['topic_type' => 'EVENT', 'event' => ['title' => 'Launch night', 'start_date' => '2037-03-10', 'end_date' => '2037-03-12', 'start_time' => '09:00']]]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1280, 900);
+ $page = visit(route('app.posts.edit', $post))->resize(1280, 900);
waitForChannelSettingsTestId($page, 'google-business-start-time');
expect($page->script("document.querySelector('[data-testid=\"google-business-start-time\"]').type"))->toBe('text');
@@ -1089,19 +1079,19 @@ test('the google business event times follow the user clock and pick from a list
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect(data_get($postPlatform->fresh()->meta, 'event.start_time'))->toBe('18:30')
- ->and(data_get($postPlatform->fresh()->meta, 'event.end_time'))->toBe('21:00');
+ expect(data_get($post->fresh()->meta, 'event.start_time'))->toBe('18:30')
+ ->and(data_get($post->fresh()->meta, 'event.end_time'))->toBe('21:00');
})->with([
'12h' => [TimeFormat::TwelveHour, '9 pm', '6:30 PM', '9:00 PM'],
]);
test('the facebook preview lays several photos out as the feed collage, not stacked', function (int $count, array $spans, ?string $more) {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost(Platform::Facebook, ContentType::FacebookPost);
- $images = Media::factory()->count($count)->temporaryUpload($postPlatform->post->workspace)->create(['mime_type' => 'image/png']);
- $postPlatform->post->update(['media' => $images->map(fn (Media $media): array => MediaItem::fromMedia($media)->toArray())->all()]);
+ $post = seedChannelSettingsPost(Platform::Facebook, ContentType::FacebookPost);
+ $images = Media::factory()->count($count)->temporaryUpload($post->workspace)->create(['mime_type' => 'image/png']);
+ $post->update(['media' => $images->map(fn (Media $media): array => MediaItem::fromMedia($media)->toArray())->all()]);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, 'preview-media-collage');
$layout = $page->script(<<<'JS'
@@ -1124,10 +1114,10 @@ test('the facebook preview lays several photos out as the feed collage, not stac
test('every character counter in the composer shares one design', function (Platform $platform, ContentType $contentType, string $counter) {
fakeChannelSettingsApis();
- $postPlatform = seedChannelSettingsPost($platform, $contentType);
- $testId = str_replace('{id}', $postPlatform->social_account_id, $counter);
+ $post = seedChannelSettingsPost($platform, $contentType);
+ $testId = str_replace('{id}', $post->social_account_id, $counter);
- $page = visit(route('app.posts.edit', $postPlatform->post))->resize(1440, 1000);
+ $page = visit(route('app.posts.edit', $post))->resize(1440, 1000);
waitForChannelSettingsTestId($page, $testId);
$look = $page->script(<<<JS
diff --git a/tests/Browser/ComposerNetworkCardsTest.php b/tests/Browser/ComposerNetworkCardsTest.php
index 2a49a9fc0..5a20d9321 100644
--- a/tests/Browser/ComposerNetworkCardsTest.php
+++ b/tests/Browser/ComposerNetworkCardsTest.php
@@ -88,8 +88,8 @@ function networkCardsCaptionCount(mixed $page): int
*/
function networkCardsSavedContents(Workspace $workspace): array
{
- return Post::query()->where('workspace_id', $workspace->id)->with('postPlatforms')->get()
- ->mapWithKeys(fn (Post $post): array => [$post->postPlatforms->sole()->social_account_id => $post->content])
+ return Post::query()->where('workspace_id', $workspace->id)->get()
+ ->mapWithKeys(fn (Post $post): array => [$post->social_account_id => $post->content])
->all();
}
@@ -289,8 +289,8 @@ test('two pinterest accounts in one card keep their own boards', function () {
$page->assertNoJavaScriptErrors()->click('@composer-save-draft');
waitForNetworkCardsClosed($page);
- $boards = Post::query()->where('workspace_id', $workspace->id)->with('postPlatforms')->get()
- ->mapWithKeys(fn (Post $post): array => [$post->postPlatforms->sole()->social_account_id => data_get($post->postPlatforms->sole()->meta, 'board_id')]);
+ $boards = Post::query()->where('workspace_id', $workspace->id)->get()
+ ->mapWithKeys(fn (Post $post): array => [$post->social_account_id => data_get($post->meta, 'board_id')]);
expect($boards[$second->id])->toBe('board_2')
->and($boards[$first->id])->not->toBe('board_2');
});
diff --git a/tests/Browser/ComposerSharedDataTest.php b/tests/Browser/ComposerSharedDataTest.php
index 354884806..daf44ea20 100644
--- a/tests/Browser/ComposerSharedDataTest.php
+++ b/tests/Browser/ComposerSharedDataTest.php
@@ -4,9 +4,8 @@ declare(strict_types=1);
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
+use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -57,22 +56,14 @@ function composerSharedDataSetup(): array
function composerSharedDataPost(Workspace $workspace, SocialAccount $account, ContentType $contentType, array $meta = []): Post
{
- $post = Post::factory()->create([
+ return Post::factory()->forAccount($account, $contentType)->create([
'workspace_id' => $workspace->id,
'user_id' => $workspace->user_id,
'status' => PostStatus::Scheduled,
'content' => 'Shared data post',
'scheduled_at' => now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
'meta' => $meta,
]);
-
- return $post;
}
function waitForComposerSharedDataCondition(mixed $page, string $condition): void
@@ -221,12 +212,9 @@ test('editing a tiktok post keeps its stored interaction flags', function () {
'max_video_post_duration_sec' => 600,
]]),
]);
- $post = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'TikTok draft']);
- $target = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $tiktok->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($tiktok, ContentType::TikTokVideo)->draft()->create([
+ 'user_id' => $user->id,
+ 'content' => 'TikTok draft',
'meta' => ['privacy_level' => 'SELF_ONLY', 'allow_comments' => true],
]);
$this->actingAs($user);
@@ -236,5 +224,40 @@ test('editing a tiktok post keeps its stored interaction flags', function () {
$page->click('@composer-save-draft');
waitForComposerSharedDataCondition($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
- expect(data_get($target->fresh()->meta, 'allow_comments'))->toBeTrue();
+ expect(data_get($post->fresh()->meta, 'allow_comments'))->toBeTrue();
+});
+
+test('editing a post shows a server media error on the item it belongs to', function () {
+ [$user, $workspace] = composerSharedDataSetup();
+ $linkedin = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->draft()->create(['user_id' => $user->id, 'content' => 'Two images']);
+ $media = collect(['kept.png', 'gone.png'])->map(fn (string $name): Media => Media::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'post_id' => $post->id,
+ 'mediable_type' => null,
+ 'mediable_id' => null,
+ 'collection' => Media::COLLECTION_MEDIA,
+ 'original_filename' => $name,
+ 'mime_type' => 'image/png',
+ ]));
+ $post->update(['media' => $media->map(fn (Media $item): array => [
+ 'id' => $item->id,
+ 'path' => $item->path,
+ 'url' => $item->url,
+ 'type' => 'image',
+ 'mime_type' => 'image/png',
+ 'original_filename' => $item->original_filename,
+ 'meta' => ['width' => 1200, 'height' => 1200],
+ ])->all()]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['edit' => $post->id]));
+ waitForComposerSharedDataCondition($page, "document.querySelectorAll('[data-testid\$=\"-media-item\"]').length === 2");
+ $media->last()->delete();
+
+ $page->click('@composer-save-draft');
+ waitForComposerSharedDataCondition($page, "document.querySelector('[data-testid\$=\"-media-error-1\"]') !== null");
+
+ expect($page->script("document.querySelector('[data-testid\$=\"-media-error-0\"]')"))->toBeNull();
+ $page->assertNoJavaScriptErrors();
});
diff --git a/tests/Browser/ComposerSingleChannelTest.php b/tests/Browser/ComposerSingleChannelTest.php
index 663e59b48..59c00aece 100644
--- a/tests/Browser/ComposerSingleChannelTest.php
+++ b/tests/Browser/ComposerSingleChannelTest.php
@@ -7,7 +7,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -108,7 +107,7 @@ test('one channel opens its own editor directly and a second channel returns to
->assertNoJavaScriptErrors();
});
-test('saving a single channel draft keeps its network fields on the post platform', function () {
+test('saving a single channel draft keeps its network fields on the post', function () {
[$user, $workspace] = singleChannelComposerWorkspace();
$youtube = SocialAccount::factory()->youtube()->create(['workspace_id' => $workspace->id]);
$this->actingAs($user);
@@ -123,12 +122,11 @@ test('saving a single channel draft keeps its network fields on the post platfor
waitForSingleChannelComposerClosed($page);
$post = Post::where('workspace_id', $workspace->id)->sole();
- $platform = $post->postPlatforms()->sole();
expect($post->status)->toBe(PostStatus::Draft)
->and($post->content)->toBe('A short about the launch')
- ->and($platform->social_account_id)->toBe($youtube->id)
- ->and($platform->content_type)->toBe(ContentType::YouTubeShort)
- ->and(data_get($platform->meta, 'title'))->toBe('Launch title');
+ ->and($post->social_account_id)->toBe($youtube->id)
+ ->and($post->content_type)->toBe(ContentType::YouTubeShort)
+ ->and(data_get($post->meta, 'title'))->toBe('Launch title');
});
test('the youtube title follows the caption until the title is edited', function () {
@@ -157,11 +155,11 @@ test('the youtube title follows the caption until the title is edited', function
->click('@composer-save-draft');
waitForSingleChannelComposerClosed($page);
- $platform = Post::where('workspace_id', $workspace->id)->sole()->postPlatforms()->sole();
- expect(data_get($platform->meta, 'title'))->toBe('My own title');
+ $post = Post::where('workspace_id', $workspace->id)->sole();
+ expect(data_get($post->meta, 'title'))->toBe('My own title');
});
-test('scheduling a single channel saves its post platform with the chosen format', function () {
+test('scheduling a single channel saves its post with the chosen format', function () {
[$user, $workspace] = singleChannelComposerWorkspace();
$facebook = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Facebook]);
$this->actingAs($user);
@@ -189,26 +187,23 @@ test('scheduling a single channel saves its post platform with the chosen format
waitForSingleChannelComposerClosed($page);
$post = Post::where('workspace_id', $workspace->id)->sole();
- $platform = $post->postPlatforms()->sole();
expect($post->status)->toBe(PostStatus::Scheduled)
->and($post->schedule_mode)->toBe(ScheduleMode::Custom)
->and($post->scheduled_at)->not->toBeNull()
->and($post->content)->toBe('Scheduled for one page')
- ->and($platform->social_account_id)->toBe($facebook->id)
- ->and($platform->platform)->toBe(Platform::Facebook)
- ->and($platform->content_type)->toBe(ContentType::FacebookPost);
+ ->and($post->social_account_id)->toBe($facebook->id)
+ ->and($post->platform)->toBe(Platform::Facebook)
+ ->and($post->content_type)->toBe(ContentType::FacebookPost);
});
test('editing a single channel post opens its own editor', function () {
[$user, $workspace] = singleChannelComposerWorkspace();
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
'content' => 'Already written',
]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post));
diff --git a/tests/Browser/ComposerTimezoneTest.php b/tests/Browser/ComposerTimezoneTest.php
index 0d911f88e..f258f79ba 100644
--- a/tests/Browser/ComposerTimezoneTest.php
+++ b/tests/Browser/ComposerTimezoneTest.php
@@ -6,7 +6,6 @@ use App\Actions\Post\CreatePosts;
use App\Enums\PostPlatform\ContentType;
use App\Enums\User\TimeFormat;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -301,12 +300,10 @@ test('posting slots already taken by a scheduled post are disabled', function ()
$channel = composerTimezoneChannel($workspace, $zone, PostingSchedule::empty()
->withTime(now($zone)->dayOfWeek, '15:00')
->withTime(now($zone)->dayOfWeek, '16:00'));
- $taken = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ Post::factory()->forAccount($channel)->scheduled()->create([
'user_id' => $user->id,
'scheduled_at' => CarbonImmutable::parse(now($zone)->format('Y-m-d').' 15:00', $zone)->utc(),
]);
- PostPlatform::factory()->create(['post_id' => $taken->id, 'social_account_id' => $channel->id]);
$this->actingAs($user);
$page = visit(route('app.posts.create'));
diff --git a/tests/Browser/DarkModeSurfacesTest.php b/tests/Browser/DarkModeSurfacesTest.php
index 79033e4c8..72ac71d36 100644
--- a/tests/Browser/DarkModeSurfacesTest.php
+++ b/tests/Browser/DarkModeSurfacesTest.php
@@ -9,7 +9,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\Idea;
use App\Models\IdeaStage;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -41,8 +40,7 @@ test('in dark mode a dialog is a raised surface, lighter than the page behind it
$workspace->members()->attach($user->id, membershipPivot('member'));
$user->update(['current_workspace_id' => $workspace->id]);
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::X]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'Surface check']);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::X, 'content_type' => ContentType::XPost, 'meta' => []]);
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create(['user_id' => $user->id, 'content' => 'Surface check']);
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post))->resize(1440, 900);
diff --git a/tests/Browser/DialogFullScreenMobileTest.php b/tests/Browser/DialogFullScreenMobileTest.php
index f40ff4500..bb8b09f2c 100644
--- a/tests/Browser/DialogFullScreenMobileTest.php
+++ b/tests/Browser/DialogFullScreenMobileTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Models\User;
use App\Models\Workspace;
+use App\Models\WorkspaceLabel;
function waitForDialogFullScreenTestId(mixed $page, string $testId): void
{
@@ -133,3 +134,31 @@ test('on a phone an alert dialog fills the screen with its footer in view', func
$page->assertNoJavaScriptErrors();
});
+
+test('on a phone a delete confirmation stays a centered card instead of filling the screen', function () {
+ $user = dialogFullScreenAdmin();
+ $label = WorkspaceLabel::factory()->create(['workspace_id' => $user->current_workspace_id, 'name' => 'Phone label']);
+ $this->actingAs($user);
+
+ $page = visit(route('app.labels.index'))->resize(390, 844);
+ waitForDialogFullScreenTestId($page, "label-menu-{$label->id}");
+ $page->click("@label-menu-{$label->id}");
+ waitForDialogFullScreenTestId($page, "delete-label-{$label->id}");
+ $page->click("@delete-label-{$label->id}");
+ waitForDialogFullScreenTestId($page, 'confirm-delete-modal');
+
+ $geometry = $page->script(<<<'JS'
+ (() => {
+ const box = document.querySelector('[data-testid="confirm-delete-modal"]').getBoundingClientRect();
+
+ return {
+ compact: box.height < window.innerHeight / 2,
+ inset: box.left > 0 && box.right < window.innerWidth,
+ centered: Math.abs((box.top + box.bottom) / 2 - window.innerHeight / 2) <= 2,
+ };
+ })()
+ JS);
+
+ expect($geometry)->toBe(['compact' => true, 'inset' => true, 'centered' => true]);
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/ImportedPostCardTest.php b/tests/Browser/ImportedPostCardTest.php
index 38c1b3b32..382b6f5b3 100644
--- a/tests/Browser/ImportedPostCardTest.php
+++ b/tests/Browser/ImportedPostCardTest.php
@@ -2,7 +2,6 @@
declare(strict_types=1);
-use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
@@ -10,7 +9,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -58,9 +56,10 @@ function importedCardSetup(): array
function importedCardPost(Workspace $workspace, SocialAccount $account, ContentType $contentType = ContentType::InstagramReel): Post
{
- $post = Post::factory()->imported()->create([
+ $post = Post::factory()->forAccount($account, $contentType)->imported()->create([
'workspace_id' => $workspace->id,
'content' => 'Posted straight from the app',
+ 'platform_url' => 'https://www.instagram.com/reel/abc/',
'published_at' => now()->subHour(),
'media' => [[
'id' => (string) Str::uuid(),
@@ -72,29 +71,21 @@ function importedCardPost(Workspace $workspace, SocialAccount $account, ContentT
'size' => 1024,
]],
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => $contentType,
- 'platform_url' => 'https://www.instagram.com/reel/abc/',
- 'published_at' => now()->subHour(),
- ]);
- importedCardMetrics($workspace, $account, $target);
+ importedCardMetrics($workspace, $account, $post);
return $post;
}
-function importedCardMetrics(Workspace $workspace, SocialAccount $account, PostPlatform $target): void
+function importedCardMetrics(Workspace $workspace, SocialAccount $account, Post $post): void
{
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'network' => Platform::Instagram->network(),
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $post->platform_post_id,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
@@ -176,16 +167,9 @@ test('content type badges follow the display rules for each platform', function
$expectations = [];
foreach ($formats as [$contentType, $showsBadge]) {
- $post = Post::factory()->published()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, $contentType)->published()->create([
'user_id' => $user->id,
]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => $contentType,
- ]);
$expectations[] = [$post, $contentType, $showsBadge];
}
@@ -299,19 +283,11 @@ test('on a phone the details dialog of an imported post hides the published via
test('a trypost sent post keeps the created by footer and shows its metrics in its details', function () {
[$user, $workspace, $account] = importedCardSetup();
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->published()->create([
'user_id' => $user->id,
- 'status' => PostStatus::Published,
'published_at' => now()->subHour(),
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- ]);
- importedCardMetrics($workspace, $account, $target);
+ importedCardMetrics($workspace, $account, $post);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'sent']));
@@ -331,16 +307,9 @@ test('a trypost sent post keeps the created by footer and shows its metrics in i
test('a draft shows no metrics band in its details', function () {
[$user, $workspace, $account] = importedCardSetup();
- $post = Post::factory()->draft()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->draft()->create([
'user_id' => $user->id,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
@@ -366,16 +335,9 @@ test('the content type badge has an icon for stories and reels and is hidden for
$tiktok = SocialAccount::factory()->tiktok()->create(['workspace_id' => $workspace->id]);
foreach ([ContentType::TikTokPhoto, ContentType::TikTokVideo] as $contentType) {
- $post = Post::factory()->published()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($tiktok, $contentType)->published()->create([
'user_id' => $user->id,
]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $tiktok->id,
- 'platform' => Platform::TikTok,
- 'content_type' => $contentType,
- ]);
$expectations[] = [$post, null];
}
diff --git a/tests/Browser/InsightsParityTest.php b/tests/Browser/InsightsParityTest.php
index 91bdf0419..cfff52f1e 100644
--- a/tests/Browser/InsightsParityTest.php
+++ b/tests/Browser/InsightsParityTest.php
@@ -13,7 +13,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\AnalyticsSyncState;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -73,23 +72,16 @@ function insightsParitySetup(): array
'date' => now('UTC')->subDays(2)->toDateString(),
'followers_count' => $followers,
]);
- $created = Post::factory()->published()->create([
- 'workspace_id' => $workspace->id,
+ $created = Post::factory()->forAccount($account)->published()->create([
'user_id' => $user->id,
'content' => "Insights parity post {$username}",
'published_at' => now()->subDays(3),
]);
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $created->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'published_at' => now()->subDays(3),
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $created->id,
'platform' => $platform,
'network' => $platform->network(),
'account_username' => $username,
diff --git a/tests/Browser/LinkCardPreviewTest.php b/tests/Browser/LinkCardPreviewTest.php
index 978eba943..b969579da 100644
--- a/tests/Browser/LinkCardPreviewTest.php
+++ b/tests/Browser/LinkCardPreviewTest.php
@@ -10,7 +10,6 @@ use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -49,28 +48,19 @@ function seedLinkCardPreviewPost(
'scopes' => $platform->requiredPublishScopes(),
]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, match ($platform) {
+ Platform::Facebook => ContentType::FacebookPost,
+ Platform::LinkedIn => ContentType::LinkedInPost,
+ Platform::Mastodon => ContentType::MastodonPost,
+ Platform::Bluesky => ContentType::BlueskyPost,
+ Platform::Threads => ContentType::ThreadsPost,
+ default => throw new LogicException('Unsupported link-card browser test platform.'),
+ })->create([
'user_id' => $user->id,
'content' => $content,
'media' => $media,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'enabled' => true,
- 'content_type' => match ($platform) {
- Platform::Facebook => ContentType::FacebookPost,
- Platform::LinkedIn => ContentType::LinkedInPost,
- Platform::Mastodon => ContentType::MastodonPost,
- Platform::Bluesky => ContentType::BlueskyPost,
- Platform::Threads => ContentType::ThreadsPost,
- default => throw new LogicException('Unsupported link-card browser test platform.'),
- },
- ]);
-
test()->actingAs($user);
return [$post, $account];
@@ -292,7 +282,7 @@ test('the editor link card can be dropped and the post saves without it', functi
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect($post->postPlatforms()->sole()->meta)->toEqual(['link_preview' => false]);
+ expect($post->fresh()->meta)->toEqual(['link_preview' => false]);
})->with([
'Facebook' => Platform::Facebook,
]);
@@ -395,5 +385,5 @@ test('a dropped link card comes back when the link changes', function () {
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect(data_get($post->postPlatforms()->sole()->meta, 'link_preview'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'link_preview'))->toBeNull();
});
diff --git a/tests/Browser/MediaEditorTest.php b/tests/Browser/MediaEditorTest.php
index 76e66832e..89c1b4aa4 100644
--- a/tests/Browser/MediaEditorTest.php
+++ b/tests/Browser/MediaEditorTest.php
@@ -6,7 +6,6 @@ use App\Ai\Agents\MediaAltTextGenerator;
use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -16,7 +15,7 @@ use Illuminate\Support\Facades\Storage;
* A draft whose images are the 200x200 quadrant fixture, inlined as data URLs so
* the editor canvas can read their pixels without a signed storage URL.
*
- * @return array{0: Post, 1: PostPlatform}
+ * @return array{0: Post}
*/
function seedMediaEditorPost(ContentType $contentType = ContentType::InstagramFeed, int $imageCount = 1, ?string $firstMediaId = null): array
{
@@ -26,8 +25,14 @@ function seedMediaEditorPost(ContentType $contentType = ContentType::InstagramFe
$user->update(['current_workspace_id' => $workspace->id]);
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
- $post = Post::factory()->create([
+ $platform = $contentType->platform();
+ $account = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
+ 'platform' => $platform,
+ 'scopes' => $platform->requiredPublishScopes(),
+ ]);
+
+ $post = Post::factory()->forAccount($account, $contentType)->create([
'user_id' => $user->id,
'content' => 'Editing media',
'media' => array_map(fn (int $index): array => [
@@ -41,22 +46,9 @@ function seedMediaEditorPost(ContentType $contentType = ContentType::InstagramFe
], range(1, $imageCount)),
]);
- $platform = $contentType->platform();
- $account = SocialAccount::factory()->create([
- 'workspace_id' => $workspace->id,
- 'platform' => $platform,
- 'scopes' => $platform->requiredPublishScopes(),
- ]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => $contentType,
- ]);
-
test()->actingAs($user);
- return [$post, $postPlatform];
+ return [$post];
}
/**
@@ -75,9 +67,9 @@ function waitForMediaEditor(mixed $page, string $condition): void
JS);
}
-function openMediaEditor(mixed $page, PostPlatform $postPlatform, int $index = 0): void
+function openMediaEditor(mixed $page, string $accountId, int $index = 0): void
{
- openMediaEditorPanel($page, $postPlatform->social_account_id, $index);
+ openMediaEditorPanel($page, $accountId, $index);
waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-selection\"]')?.getBoundingClientRect().width > 0");
}
@@ -123,9 +115,9 @@ function saveMediaEditorDraft(mixed $page): void
}
test('the media editor keeps its preview and controls separate at every viewport', function (int $width, int $height) {
- [$post, $postPlatform] = seedMediaEditorPost(imageCount: 2);
+ [$post] = seedMediaEditorPost(imageCount: 2);
$page = visit(route('app.posts.edit', $post))->resize($width, $height);
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->assertScript(<<<'JS'
(() => {
@@ -174,9 +166,9 @@ test('the media editor keeps its preview and controls separate at every viewport
]);
test('rotating an image uploads the rotated pixels', function (int $width, int $height) {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post))->resize($width, $height);
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-rotate-right')
->assertSee('Apply changes to 1 item')
@@ -203,9 +195,9 @@ test('rotating an image uploads the rotated pixels', function (int $width, int $
]);
test('one apply saves edits made to several images', function () {
- [$post, $postPlatform] = seedMediaEditorPost(imageCount: 2);
+ [$post] = seedMediaEditorPost(imageCount: 2);
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@crop-aspect-1-1')
->click('@media-editor-thumb-1')
@@ -222,9 +214,9 @@ test('one apply saves edits made to several images', function () {
});
test('people tagged on an Instagram image are saved with their position', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-tags-tab')
->click('@media-editor-tags-start');
@@ -247,10 +239,10 @@ test('people tagged on an Instagram image are saved with their position', functi
test('alt text can be generated with AI for a post image', function () {
MediaAltTextGenerator::fake(['Four coloured squares in a grid.']);
- [$post, $postPlatform] = seedMediaEditorPost(firstMediaId: '00000000-0000-4000-8000-000000000001');
+ [$post] = seedMediaEditorPost(firstMediaId: '00000000-0000-4000-8000-000000000001');
Media::factory()->ownedByPost($post)->create(['id' => '00000000-0000-4000-8000-000000000001']);
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-alt-tab')
->click('@media-editor-alt-generate');
@@ -262,18 +254,18 @@ test('alt text can be generated with AI for a post image', function () {
});
test('an Instagram feed post offers Edit, Alt Text and Tag People', function () {
- [$post, $postPlatform] = seedMediaEditorPost(ContentType::InstagramFeed);
+ [$post] = seedMediaEditorPost(ContentType::InstagramFeed);
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
expect(mediaEditorSegmentIds($page))->toBe(['media-editor-edit-tab', 'media-editor-alt-tab', 'media-editor-tags-tab']);
$page->assertNoJavaScriptErrors();
});
test('center and reset only enable once the geometry changes', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$isDisabled = fn (string $testId): bool => $page->script("document.querySelector('[data-testid=\"{$testId}\"]').disabled");
@@ -296,9 +288,9 @@ test('center and reset only enable once the geometry changes', function () {
});
test('the stage only takes tags while tagging and switching tabs ends tagging mode', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-tags-tab');
clickMediaEditorStage($page, 0.5, 0.5);
@@ -333,9 +325,9 @@ test('the stage only takes tags while tagging and switching tabs ends tagging mo
});
test('closing with the × discards edits like Cancel', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-rotate-right')
->assertSee('Apply changes to 1 item')
@@ -343,7 +335,7 @@ test('closing with the × discards edits like Cancel', function () {
waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor\"]')");
$page->assertMissing('@media-editor');
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->assertDisabled('@media-editor-apply')
->assertDisabled('@media-editor-reset')
->click('@media-editor-close');
@@ -354,7 +346,7 @@ test('closing with the × discards edits like Cancel', function () {
});
test('at 20 tags tagging cannot start and the stage opens no form', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$media = $post->media;
$media[0]['meta']['user_tags'] = array_map(
fn (int $index): array => ['username' => "person{$index}", 'x' => 0.5, 'y' => 0.5],
@@ -362,7 +354,7 @@ test('at 20 tags tagging cannot start and the stage opens no form', function ()
);
$post->update(['media' => $media]);
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-tags-tab')
->assertDisabled('@media-editor-tags-start');
@@ -527,9 +519,7 @@ function applyMediaEditorAltText(mixed $page, string $prefix, string $altText):
function mediaEditorSavedAltTexts(SocialAccount ...$accounts): array
{
return collect($accounts)->mapWithKeys(fn (SocialAccount $account): array => [
- $account->id => data_get(Post::query()
- ->whereIn('id', PostPlatform::query()->where('social_account_id', $account->id)->pluck('post_id'))
- ->sole()->media, '0.meta.alt_text'),
+ $account->id => data_get(Post::query()->where('social_account_id', $account->id)->sole()->media, '0.meta.alt_text'),
])->all();
}
@@ -618,7 +608,7 @@ test('a step 1 edit replaces the shared item in place and every post owns its ow
$page->click('@composer-save-draft');
waitForMediaEditor($page, "!document.querySelector('[data-testid=\"post-composer-dialog\"]')");
- $posts = Post::query()->whereIn('id', PostPlatform::query()->whereIn('social_account_id', [$first->id, $second->id])->pluck('post_id'))->get();
+ $posts = Post::query()->whereIn('social_account_id', [$first->id, $second->id])->get();
expect($posts)->toHaveCount(2);
$paths = [];
foreach ($posts as $post) {
@@ -640,7 +630,7 @@ test('a step 2 edit replaces only that channel\'s item and leaves the shared lis
$page->click('@composer-next')
->click("@composer-account-{$first->id}");
- openMediaEditor($page, PostPlatform::make(['social_account_id' => $first->id]));
+ openMediaEditor($page, $first->id);
$page->click('@media-editor-rotate-right');
waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-editor-apply\"]')?.disabled === false");
$page->click('@media-editor-apply');
@@ -698,11 +688,11 @@ test('a failed edit upload shows the inline error and keeps the original tile',
});
/**
- * @return array{0: Post, 1: PostPlatform}
+ * @return array{0: Post}
*/
function seedMediaEditorVideoPost(ContentType $contentType): array
{
- [$post, $postPlatform] = seedMediaEditorPost($contentType);
+ [$post] = seedMediaEditorPost($contentType);
$webm = base64_encode((string) file_get_contents(base_path('tests/fixtures/cover-3s.webm')));
$post->update(['media' => [[
'id' => 'video-1',
@@ -714,12 +704,12 @@ function seedMediaEditorVideoPost(ContentType $contentType): array
'meta' => ['width' => 16, 'height' => 16],
]]]);
- return [$post, $postPlatform];
+ return [$post];
}
test('a reel video gets a Thumbnail segment whose frame is saved as the cover offset', function () {
- [$post, $postPlatform] = seedMediaEditorVideoPost(ContentType::InstagramReel);
- $accountId = $postPlatform->social_account_id;
+ [$post] = seedMediaEditorVideoPost(ContentType::InstagramReel);
+ $accountId = $post->social_account_id;
$page = visit(route('app.posts.edit', $post));
waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$accountId}-edit-0\"]')");
$page->click("@composer-{$accountId}-edit-0");
@@ -760,8 +750,8 @@ test('a reel video gets a Thumbnail segment whose frame is saved as the cover of
});
test('a video on an X post shows no pencil', function () {
- [$post, $postPlatform] = seedMediaEditorVideoPost(ContentType::XPost);
- $accountId = $postPlatform->social_account_id;
+ [$post] = seedMediaEditorVideoPost(ContentType::XPost);
+ $accountId = $post->social_account_id;
$page = visit(route('app.posts.edit', $post));
waitForMediaEditor($page, "document.querySelector('[data-testid=\"composer-{$accountId}-media-item-0\"]')");
@@ -771,9 +761,9 @@ test('a video on an X post shows no pencil', function () {
});
test('only a freeform crop can be resized; a chosen ratio only moves', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@crop-aspect-4-5');
waitForMediaEditor($page, "!document.querySelector('[data-testid=\"media-editor-handle-nw\"]')");
@@ -788,9 +778,9 @@ test('only a freeform crop can be resized; a chosen ratio only moves', function
});
test('filter intensity shows for a filter, not for the original, and sliders fill from their origin', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-appearance-section');
waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-filter-sepia\"]')");
@@ -832,7 +822,7 @@ test('filter intensity shows for a filter, not for the original, and sliders fil
});
test('an image stored on another host is edited through the app, so applying works without CORS', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$row = Media::factory()->ownedByPost($post)->create(['path' => 'uploads/remote.png', 'mime_type' => 'image/png', 'collection' => Media::COLLECTION_MEDIA]);
Storage::put('uploads/remote.png', (string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$post->update(['media' => [[
@@ -845,7 +835,7 @@ test('an image stored on another host is edited through the app, so applying wor
'meta' => ['width' => 200, 'height' => 200],
]]]);
$page = visit(route('app.posts.edit', $post));
- openMediaEditorPanel($page, $postPlatform->social_account_id);
+ openMediaEditorPanel($page, $post->social_account_id);
$page->click('@media-editor-rotate-right')
->click('@media-editor-apply');
@@ -872,9 +862,9 @@ function setMediaEditorRange(mixed $page, string $testId, int $value): void
}
test('the filter intensity reaches the saved pixels', function (int $intensity) {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$page = visit(route('app.posts.edit', $post));
- openMediaEditor($page, $postPlatform);
+ openMediaEditor($page, $post->social_account_id);
$page->click('@media-editor-appearance-section')->click('@media-filter-mono');
waitForMediaEditor($page, "document.querySelector('[data-testid=\"media-filter-intensity\"]')");
@@ -895,7 +885,7 @@ test('the filter intensity reaches the saved pixels', function (int $intensity)
})->with([100]);
test('a crop with a filter on an image stored on another host is applied and saved', function () {
- [$post, $postPlatform] = seedMediaEditorPost();
+ [$post] = seedMediaEditorPost();
$row = Media::factory()->ownedByPost($post)->create(['path' => 'uploads/remote.png', 'mime_type' => 'image/png', 'collection' => Media::COLLECTION_MEDIA]);
Storage::put('uploads/remote.png', (string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
$post->update(['media' => [[
@@ -908,7 +898,7 @@ test('a crop with a filter on an image stored on another host is applied and sav
'meta' => ['width' => 200, 'height' => 200],
]]]);
$page = visit(route('app.posts.edit', $post));
- openMediaEditorPanel($page, $postPlatform->social_account_id);
+ openMediaEditorPanel($page, $post->social_account_id);
$page->click('@crop-aspect-1-91-1')
->click('@media-editor-appearance-section')
diff --git a/tests/Browser/MediaLightboxTest.php b/tests/Browser/MediaLightboxTest.php
index 68c6300ae..f4b1281f0 100644
--- a/tests/Browser/MediaLightboxTest.php
+++ b/tests/Browser/MediaLightboxTest.php
@@ -3,11 +3,9 @@
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -95,21 +93,12 @@ function mediaLightboxSetup(array $media, string $state = 'published'): array
subscribeAccount($user->account);
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);
- $post = Post::factory()->{$state}()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->{$state}()->create([
'user_id' => $user->id,
'content' => 'Lightbox post',
'media' => $media,
...($state === 'published' ? ['published_at' => now()->subHour()] : []),
]);
- $target = $state === 'published' ? PostPlatform::factory()->published() : PostPlatform::factory();
- $target->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- ...($state === 'published' ? ['published_at' => now()->subHour()] : []),
- ]);
return [$user, $post];
}
diff --git a/tests/Browser/MobileOverflowTest.php b/tests/Browser/MobileOverflowTest.php
index e3200a37f..c42a9f62e 100644
--- a/tests/Browser/MobileOverflowTest.php
+++ b/tests/Browser/MobileOverflowTest.php
@@ -6,7 +6,6 @@ use App\Enums\User\Goal;
use App\Enums\User\Persona;
use App\Enums\User\ReferralSource;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\User;
use App\Models\Workspace;
@@ -55,12 +54,11 @@ test('key pages do not overflow horizontally on a phone', function () {
$workspace->members()->attach($user->id, membershipPivot('member'));
$user->update(['current_workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
+ $post = Post::factory()->linkedin()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
'content' => 'Launching our new mobile editor today!',
]);
- PostPlatform::factory()->count(2)->create(['post_id' => $post->id]);
$this->actingAs($user);
diff --git a/tests/Browser/PostApprovalsTest.php b/tests/Browser/PostApprovalsTest.php
index 3a8109cf4..eac90953c 100644
--- a/tests/Browser/PostApprovalsTest.php
+++ b/tests/Browser/PostApprovalsTest.php
@@ -8,7 +8,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\User\TimeFormat;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -120,13 +119,11 @@ test('an approver adds a queue request to the queue and rejects another', functi
test('a request whose time has passed asks for a new time or publish now', function () {
Queue::fake([PublishPost::class]);
[$owner, $workspace, $channel, $requester] = approvalsBrowserSetup();
- $late = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $workspace->id,
+ $late = Post::factory()->forAccount($channel)->pendingApproval()->create([
'user_id' => $requester->id,
'content' => 'Too late',
'scheduled_at' => now()->subHour(),
]);
- PostPlatform::factory()->create(['post_id' => $late->id, 'social_account_id' => $channel->id, 'platform' => $channel->platform]);
$this->actingAs($owner);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
@@ -185,13 +182,11 @@ test('a new time for a late request is typed in the channel zone', function () {
[$owner, $workspace, $channel, $requester] = approvalsBrowserSetup();
$owner->update(['timezone' => 'Asia/Tokyo', 'time_format' => TimeFormat::TwentyFourHour]);
$channel->update(['timezone' => 'America/Sao_Paulo']);
- $late = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $workspace->id,
+ $late = Post::factory()->forAccount($channel)->pendingApproval()->create([
'user_id' => $requester->id,
'content' => 'Too late',
'scheduled_at' => now()->subHour(),
]);
- PostPlatform::factory()->create(['post_id' => $late->id, 'social_account_id' => $channel->id, 'platform' => $channel->platform]);
$this->actingAs($owner);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
diff --git a/tests/Browser/PostCardFooterTest.php b/tests/Browser/PostCardFooterTest.php
index ea3112820..6f6ff39e2 100644
--- a/tests/Browser/PostCardFooterTest.php
+++ b/tests/Browser/PostCardFooterTest.php
@@ -3,7 +3,6 @@
declare(strict_types=1);
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -28,8 +27,7 @@ test('a post card footer sits in a rounded muted panel and a draft drops its sta
$user->update(['current_workspace_id' => $workspace->id]);
subscribeAccount($user->account);
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']);
- $draft = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => 'A draft']);
- PostPlatform::factory()->linkedin()->create(['post_id' => $draft->id, 'social_account_id' => $account->id]);
+ $draft = Post::factory()->forAccount($account)->draft()->create(['user_id' => $user->id, 'content' => 'A draft']);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']))->resize(1440, 900);
diff --git a/tests/Browser/PostComposerDialogTest.php b/tests/Browser/PostComposerDialogTest.php
index 0175f9800..e507f5842 100644
--- a/tests/Browser/PostComposerDialogTest.php
+++ b/tests/Browser/PostComposerDialogTest.php
@@ -9,7 +9,6 @@ use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Models\Post;
use App\Models\PostNote;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -146,10 +145,8 @@ test('posts channel filter keeps accounts distinct and persists across tabs', fu
subscribeAccount($user->account);
$firstInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'username' => 'first_channel']);
$secondInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'username' => 'second_channel']);
- $firstPost = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $secondPost = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- PostPlatform::factory()->instagram()->create(['post_id' => $firstPost->id, 'social_account_id' => $firstInstagram->id]);
- PostPlatform::factory()->instagram()->create(['post_id' => $secondPost->id, 'social_account_id' => $secondInstagram->id]);
+ $firstPost = Post::factory()->forAccount($firstInstagram)->draft()->create(['user_id' => $user->id]);
+ $secondPost = Post::factory()->forAccount($secondInstagram)->draft()->create(['user_id' => $user->id]);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
@@ -631,8 +628,7 @@ test('a label created while editing a post on the publish page is listed and sel
$user->update(['current_workspace_id' => $workspace->id]);
subscribeAccount($user->account);
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
+ $post = Post::factory()->forAccount($account)->draft()->create(['user_id' => $user->id]);
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post));
@@ -862,7 +858,7 @@ test('recovering an empty-target draft retains its caption media and labels', fu
->and($owned->path)->toBe($asset->path)
->and(Media::query()->count())->toBe(1)
->and($recovered->labels()->sole()->id)->toBe($label->id)
- ->and($recovered->postPlatforms()->sole()->social_account_id)->toBe($account->id);
+ ->and($recovered->social_account_id)->toBe($account->id);
Storage::delete([$asset->path, $owned->path]);
});
@@ -874,19 +870,15 @@ test('post notes open after creation while the edit dialog still has its AI assi
$user->update(['current_workspace_id' => $workspace->id]);
subscribeAccount($user->account);
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
'content' => 'A draft to discuss',
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
- $postWithoutNotes = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $postWithoutNotes = Post::factory()->forAccount($account)->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->create(['post_id' => $postWithoutNotes->id, 'social_account_id' => $account->id]);
$note = PostNote::factory()->create([
'post_id' => $post->id,
'user_id' => $user->id,
@@ -1138,9 +1130,7 @@ test('cropping in one network card creates a separate asset and leaves the other
JS);
$page->click('@composer-save-draft');
- $posts = Post::where('workspace_id', $workspace->id)->with('postPlatforms')->get()->keyBy(
- fn (Post $post) => $post->postPlatforms->sole()->social_account_id,
- );
+ $posts = Post::where('workspace_id', $workspace->id)->get()->keyBy('social_account_id');
$uncropped = $posts[$accounts[1]->id]->ownedMedia()->sole();
$cropped = $posts[$accounts[0]->id]->ownedMedia()->sole();
expect($posts)->toHaveCount(2)
@@ -1159,15 +1149,13 @@ test('animated GIFs and videos do not offer the static image crop action', funct
$user->update(['current_workspace_id' => $workspace->id]);
subscribeAccount($user->account);
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::X]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $user->id,
'media' => [
['id' => fake()->uuid(), 'url' => '/storage/animation.gif', 'path' => 'animation.gif', 'type' => 'image', 'mime_type' => 'image/gif'],
['id' => fake()->uuid(), 'url' => '/storage/video.mp4', 'path' => 'video.mp4', 'type' => 'video', 'mime_type' => 'video/mp4'],
],
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::X, 'enabled' => true]);
$this->actingAs($user);
visit(route('app.posts.edit', $post))
@@ -1220,19 +1208,11 @@ test('failed crop upload keeps the original asset selected', function () {
subscribeAccount($user->account);
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::X]);
$asset = Media::factory()->temporaryUpload($workspace)->create(['mime_type' => 'image/png', 'original_filename' => 'original.png']);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create([
'user_id' => $user->id,
'content' => 'Keep the original',
'media' => [['id' => $asset->id, 'path' => $asset->path, 'url' => $asset->url, 'type' => 'image', 'mime_type' => 'image/png', 'original_filename' => 'original.png']],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post));
$base64 = base64_encode((string) file_get_contents(base_path('tests/fixtures/crop-quadrants.png')));
@@ -1279,32 +1259,6 @@ test('failed crop upload keeps the original asset selected', function () {
->and(Media::query()->whereKey($asset->id)->exists())->toBeTrue();
});
-test('settled legacy multi-target history appears as one read-only card per target', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
- $workspace->members()->attach($user->id, membershipPivot('admin'));
- $user->update(['current_workspace_id' => $workspace->id]);
- subscribeAccount($user->account);
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'status' => PostStatus::Published]);
- $accounts = SocialAccount::factory()->count(2)->create(['workspace_id' => $workspace->id, 'platform' => Platform::LinkedIn]);
- foreach ($accounts as $account) {
- PostPlatform::factory()->published()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::LinkedIn, 'enabled' => true]);
- }
- $this->actingAs($user);
-
- $page = visit(route('app.posts.index', ['tab' => 'sent']));
- $page->script(<<<'JS'
- (async () => {
- for (let attempt = 0; attempt < 300; attempt++) {
- if (document.querySelectorAll('[data-testid^="post-card-"]:not([data-testid^="post-card-menu-"])').length === 2) return;
- await new Promise((resolve) => setTimeout(resolve, 100));
- }
- })();
- JS);
- expect($page->script('document.querySelectorAll("[data-testid^=post-card-]:not([data-testid^=post-card-menu-])").length'))->toBe(2)
- ->and(Post::where('workspace_id', $workspace->id)->count())->toBe(1);
-});
-
test('customizing several channels uses plural actions and flags the collapsed channel that needs fixing', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id, 'account_id' => $user->account_id]);
@@ -1339,20 +1293,12 @@ test('a persisted image in the composer offers no AI image adjustment', function
subscribeAccount($user->account);
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
$asset = Media::factory()->temporaryUpload($workspace)->create(['mime_type' => 'image/png', 'original_filename' => 'original.png']);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::LinkedInPost)->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
'content' => 'A draft with an image',
'media' => [MediaItem::fromMedia($asset)->toArray()],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.edit', $post));
diff --git a/tests/Browser/PostDetailsDialogTest.php b/tests/Browser/PostDetailsDialogTest.php
index a15644484..27e77acb9 100644
--- a/tests/Browser/PostDetailsDialogTest.php
+++ b/tests/Browser/PostDetailsDialogTest.php
@@ -11,7 +11,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -56,9 +55,9 @@ function postDetailsDialogSetup(): array
*/
function postDetailsDialogPost(SocialAccount $account, int $images = 0, array $metrics = [], PublicationContentType $contentType = PublicationContentType::Image): Post
{
- $post = Post::factory()->published()->create([
- 'workspace_id' => $account->workspace_id,
+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->published()->create([
'content' => 'Details dialog post',
+ 'platform_url' => 'https://www.instagram.com/p/abc/',
'published_at' => now()->subHour(),
'media' => $images === 0 ? [] : collect(range(1, $images))->map(fn (int $index): array => [
'id' => (string) Str::uuid(),
@@ -70,25 +69,17 @@ function postDetailsDialogPost(SocialAccount $account, int $images = 0, array $m
'size' => 1024,
])->all(),
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- 'platform_url' => 'https://www.instagram.com/p/abc/',
- 'published_at' => now()->subHour(),
- ]);
if ($metrics !== []) {
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => $account->platform,
'network' => $account->platform->network(),
'content_type' => $contentType,
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $post->platform_post_id,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
@@ -106,7 +97,7 @@ function postDetailsDialogPost(SocialAccount $account, int $images = 0, array $m
return $post;
}
-test('clicking a sent card opens nothing and the menu opens the post details', function () {
+test('clicking a sent card opens the post details, and so does the menu', function () {
[$user, $account] = postDetailsDialogSetup();
$post = postDetailsDialogPost($account);
$this->actingAs($user);
@@ -116,22 +107,20 @@ test('clicking a sent card opens nothing and the menu opens the post details', f
$before = $page->script('location.href');
$page->click("@post-open-{$post->id}");
- $page->script('new Promise((resolve) => setTimeout(resolve, 400))');
+ waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
- expect($page->script('location.href'))->toBe($before)
- ->and($page->script("document.querySelector('[data-testid=\"post-open-{$post->id}\"]').tagName"))->toBe('DIV');
- $page->assertNotPresent("@post-details-{$post->id}");
+ expect($page->script('location.href'))->toBe($before);
+ $page->assertPresent("@post-details-status-{$post->id}")
+ ->assertSeeIn("@post-details-text-{$post->id}", 'Details dialog post');
+ $page->keys("@post-details-{$post->id}", 'Escape');
+ waitForPostDetailsDialogCondition($page, "!document.querySelector('[data-testid=\"post-details-{$post->id}\"]')");
$page->click("@post-card-menu-{$post->id}");
waitForPostDetailsDialogTestId($page, "post-details-open-{$post->id}");
$page->click("@post-details-open-{$post->id}");
waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
- expect($page->script('location.href'))->toBe($before);
- $page->assertPresent("@post-details-status-{$post->id}")
- ->assertNotPresent('[data-testid^="post-details-target-status-"]');
- $page->assertSeeIn("@post-details-text-{$post->id}", 'Details dialog post')
- ->assertNoJavaScriptErrors();
+ $page->assertNoJavaScriptErrors();
});
test('the post details deep link opens the dialog on the sent tab', function () {
@@ -148,6 +137,19 @@ test('the post details deep link opens the dialog on the sent tab', function ()
expect($page->script('new URLSearchParams(location.search).get("post")'))->toBe($post->id);
});
+test('the post details of a google business post in review say google is reviewing it', function () {
+ [$user, $account] = postDetailsDialogSetup();
+ $channel = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $account->workspace_id, 'timezone' => 'UTC']);
+ $post = Post::factory()->forAccount($channel)->pendingReview()->create(['content' => 'Waiting for Google', 'scheduled_at' => now()->subMinute()]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index', ['post' => $post->id]));
+ waitForPostDetailsDialogTestId($page, "post-details-{$post->id}");
+
+ $page->assertSeeIn("@post-details-status-{$post->id}", __('posts.publish.in_google_review'))
+ ->assertNoJavaScriptErrors();
+});
+
test('the details media sits below the text in a single scrollable row', function (int $images, bool $overflows) {
[$user, $account] = postDetailsDialogSetup();
$post = postDetailsDialogPost($account, $images);
@@ -332,17 +334,9 @@ test('a publishing post shows a spinning status in its details', function () {
test('the details of a sent thread show every post of the thread with its own media', function () {
[$user, $instagram] = postDetailsDialogSetup();
$account = SocialAccount::factory()->x()->create(['workspace_id' => $instagram->workspace_id, 'timezone' => 'UTC', 'meta' => ['x_verified_type' => 'blue']]);
- $post = Post::factory()->published()->create([
- 'workspace_id' => $account->workspace_id,
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->published()->create([
'content' => 'First post of the thread',
'published_at' => now()->subHour(),
- ]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- 'published_at' => now()->subHour(),
'meta' => ['thread_replies' => [
['text' => 'Second post of the thread', 'media' => [[
'id' => (string) Str::uuid(),
diff --git a/tests/Browser/PostDetailsGroupTest.php b/tests/Browser/PostDetailsGroupTest.php
index 1ccc2fe5f..47f87c3e7 100644
--- a/tests/Browser/PostDetailsGroupTest.php
+++ b/tests/Browser/PostDetailsGroupTest.php
@@ -70,7 +70,6 @@ test('post details lists the posts created together and switches between them',
[$first, $second, $draft] = $posts->all();
$draft->update(['status' => PostStatus::Draft, 'schedule_mode' => null, 'scheduled_at' => null]);
$second->update(['scheduled_at' => $second->scheduled_at->addHour()]);
- $secondTarget = $second->postPlatforms()->first();
$this->actingAs($user);
$page = visit(route('app.posts.index'));
@@ -89,7 +88,7 @@ test('post details lists the posts created together and switches between them',
->and($page->script("document.querySelector('[data-testid=\"post-details-rail-item-{$first->id}\"]').getAttribute('aria-current')"))->toBe('true');
$page->click("@post-details-rail-item-{$second->id}");
- waitForDetailsGroupTestId($page, "post-details-target-{$secondTarget->id}");
+ waitForDetailsGroupTestId($page, "post-details-target-{$second->id}");
$page->assertSeeIn("@post-details-text-{$second->id}", 'Grouped details post')
->assertSeeIn("@post-details-status-{$first->id}", __('posts.status.scheduled'));
@@ -101,13 +100,8 @@ test('post details lists the posts created together and switches between them',
$page->assertSeeIn("@post-details-status-{$first->id}", __('posts.status.draft'))
->assertMissing("@post-details-publish-now-{$draft->id}");
- $page->click("@post-details-rail-collapse-{$first->id}");
- waitForDetailsGroupTestId($page, "post-details-rail-expand-{$first->id}");
- $page->assertMissing("@post-details-rail-{$first->id}");
-
- $page->click("@post-details-rail-expand-{$first->id}");
- waitForDetailsGroupTestId($page, "post-details-rail-{$first->id}");
$page->assertVisible("@post-details-rail-{$first->id}")
+ ->assertMissing("@post-details-rail-collapse-{$first->id}")
->assertNoJavaScriptErrors();
});
@@ -122,6 +116,26 @@ test('post details of a post created alone has no rail', function () {
$page->assertSeeIn("@post-details-{$post->id}", 'Grouped details post')
->assertMissing("@post-details-rail-{$post->id}")
->assertMissing("@post-details-rail-loading-{$post->id}")
- ->assertMissing("@post-details-rail-expand-{$post->id}")
->assertNoJavaScriptErrors();
});
+
+test('the channels rail stays in place while only the post details scroll', function () {
+ [$user, $posts] = detailsGroupSetup(3);
+ [$first] = $posts->all();
+ $first->update(['content' => collect(range(1, 80))->map(fn (int $line): string => "<p>Line {$line} of a long post</p>")->implode('')]);
+ $this->actingAs($user);
+ $page = visit(route('app.posts.index'));
+ $page->resize(1440, 900);
+ openDetailsFromCard($page, $first->id);
+ waitForDetailsGroupTestId($page, "post-details-rail-{$first->id}");
+
+ waitForDetailsGroupTestId($page, "post-details-see-more-{$first->id}");
+ $page->click("@post-details-see-more-{$first->id}");
+ $railTop = $page->script("document.querySelector('[data-testid=\"post-details-rail-{$first->id}\"]').getBoundingClientRect().top");
+ $page->script("document.querySelector('[data-testid=\"post-details-body-{$first->id}\"]').scrollTop = 100000");
+
+ expect($page->script("document.querySelector('[data-testid=\"post-details-body-{$first->id}\"]').scrollTop"))->toBeGreaterThan(0)
+ ->and($page->script("document.querySelector('[data-testid=\"post-details-{$first->id}\"]').scrollTop"))->toBe(0)
+ ->and($page->script("document.querySelector('[data-testid=\"post-details-rail-{$first->id}\"]').getBoundingClientRect().top"))->toBe($railTop);
+ $page->assertNoJavaScriptErrors();
+});
diff --git a/tests/Browser/PublishCardActionsTest.php b/tests/Browser/PublishCardActionsTest.php
index 7dd199884..26cf3d73f 100644
--- a/tests/Browser/PublishCardActionsTest.php
+++ b/tests/Browser/PublishCardActionsTest.php
@@ -7,7 +7,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -223,7 +222,6 @@ test('duplicate creates a copy and opens it in the composer', function () {
test('post details opens a read-only preview of the post', function () {
[$user, $workspace, $channel] = cardActionsSetup();
$queued = cardActionsPost($user, $workspace, $channel);
- $target = $queued->postPlatforms()->first();
$this->actingAs($user);
$page = visit(route('app.posts.index'));
@@ -234,7 +232,7 @@ test('post details opens a read-only preview of the post', function () {
$page->assertSeeIn("@post-details-{$queued->id}", __('posts.show.title'))
->assertSeeIn("@post-details-status-{$queued->id}", __('posts.status.scheduled'))
->assertSeeIn("@post-details-text-{$queued->id}", 'Card actions post')
- ->assertSeeIn("@post-details-target-{$target->id}", $channel->display_label)
+ ->assertSeeIn("@post-details-target-{$queued->id}", $channel->display_label)
->assertNoJavaScriptErrors();
expect($page->script("document.querySelector('[data-testid=\"post-details-time-{$queued->id}\"]').textContent.trim()"))
->not->toBe(__('posts.publish.unscheduled'));
@@ -243,17 +241,10 @@ test('post details opens a read-only preview of the post', function () {
test('draft and sent menus only offer the actions valid for their status', function () {
[$user, $workspace, $channel] = cardActionsSetup();
$draft = cardActionsPost($user, $workspace, $channel, ['status' => 'draft', 'queue' => null]);
- $published = Post::factory()->published()->create([
- 'workspace_id' => $workspace->id,
+ $published = Post::factory()->forAccount($channel)->published()->create([
'user_id' => $user->id,
'published_at' => now()->subHour(),
]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $published->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'drafts']));
diff --git a/tests/Browser/PublishListSkeletonTest.php b/tests/Browser/PublishListSkeletonTest.php
index bfa6749d9..39b32368e 100644
--- a/tests/Browser/PublishListSkeletonTest.php
+++ b/tests/Browser/PublishListSkeletonTest.php
@@ -3,10 +3,10 @@
declare(strict_types=1);
use App\Actions\Post\CreatePosts;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -117,25 +117,14 @@ function publishListPost(User $user, Workspace $workspace, SocialAccount $channe
])->first();
}
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ return Post::factory()->forAccount($channel, ContentType::LinkedInPost)->create([
'user_id' => $user->id,
...match ($tab) {
- 'sent' => ['status' => PostStatus::Published, 'published_at' => now()->subHour()],
+ 'sent' => ['status' => PostStatus::Published, 'publish_status' => PublishStatus::Published, 'published_at' => now()->subHour()],
'approvals' => ['status' => PostStatus::PendingApproval, 'approval_requested_by' => $user->id, 'approval_requested_at' => now(), 'scheduled_at' => now()->addDay()],
default => ['status' => PostStatus::Draft],
},
]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'content_type' => ContentType::LinkedInPost,
- 'enabled' => true,
- ]);
-
- return $post;
}
test('each tab shows the skeleton, never the empty state, until its cards arrive', function () {
diff --git a/tests/Browser/PublishPageTest.php b/tests/Browser/PublishPageTest.php
index 58c9078d0..05bb15cd1 100644
--- a/tests/Browser/PublishPageTest.php
+++ b/tests/Browser/PublishPageTest.php
@@ -3,6 +3,7 @@
declare(strict_types=1);
use App\Actions\Post\CreatePosts;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
@@ -10,7 +11,6 @@ use App\Enums\SocialAccount\Platform;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -102,8 +102,7 @@ function publishPagePost(User $user, Workspace $workspace, SocialAccount $channe
test('the weekly goal shows its progress, fills the pie and opens a popover with sent, scheduled and to do', function () {
[$user, $workspace, $channel] = publishPageSetup();
$sent = publishPagePost($user, $workspace, $channel);
- $sent->update(['status' => PostStatus::Published]);
- $sent->postPlatforms()->update(['status' => 'published', 'published_at' => now()]);
+ $sent->forceFill(['status' => PostStatus::Published, 'publish_status' => PublishStatus::Published, 'published_at' => now()])->save();
$this->actingAs($user);
$page = visit(route('app.channels.publish', $channel));
@@ -210,27 +209,19 @@ test('saving a queued post edited on a channel page returns to that page and tab
test('a sent card shows the metrics band in order and links to the publication insights', function () {
[$user, $workspace] = publishPageSetup();
$account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->published()->create([
'user_id' => $user->id,
- 'status' => PostStatus::Published,
'scheduled_at' => now()->subHour(),
'published_at' => now()->subHour(),
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => Platform::X,
'network' => Platform::X->network(),
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $post->platform_post_id,
]);
$metric = fn (float $value, string $unit = 'count'): array => ['value' => $value, 'unit' => $unit, 'availability' => 'available'];
AnalyticsPublicationDailySnapshot::factory()->create([
@@ -259,27 +250,16 @@ test('a sent card shows the metrics band in order and links to the publication i
test('the approvals tab groups pending posts by day with unscheduled requests last', function () {
[$user, $workspace, $channel] = publishPageSetup();
- $timed = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $workspace->id,
+ $timed = Post::factory()->forAccount($channel)->pendingApproval()->create([
'user_id' => $user->id,
'scheduled_at' => now()->utc()->addDays(2)->setTime(12, 0),
]);
- $queued = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $workspace->id,
+ $queued = Post::factory()->forAccount($channel)->pendingApproval()->create([
'user_id' => $user->id,
'scheduled_at' => null,
'schedule_mode' => ScheduleMode::Queue,
]);
- foreach ([$timed, $queued] as $post) {
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
- }
-
$this->actingAs($user);
$page = visit(route('app.posts.index', ['tab' => 'approvals']));
@@ -387,7 +367,7 @@ test('the tabs row border keeps the page padding instead of touching the panel e
$page->assertNoJavaScriptErrors();
});
-test('on a phone the calendar row holds the channels, filter menu, view switch and no date last, with the filters in a sheet', function () {
+test('the calendar keeps its filters in one menu until the screen is wide enough for all of them', function () {
[$user, , $channel] = publishPageSetup();
$this->actingAs($user);
@@ -410,7 +390,7 @@ test('on a phone the calendar row holds the channels, filter menu, view switch a
noDateSquare: Math.round(noDate.width) === Math.round(noDate.height),
noDateLabelHidden: document.querySelector('[data-testid="calendar-no-date"] span').getBoundingClientRect().width <= 1,
channelText: [...channelFilter.querySelectorAll('span')].filter((span) => visible(span) && span.textContent.trim() !== '').length,
- tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')),
+ tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')?.getClientRects().length),
overflow: document.documentElement.scrollWidth > window.innerWidth,
};
})()
@@ -434,12 +414,21 @@ test('on a phone the calendar row holds the channels, filter menu, view switch a
->assertVisible('@publish-timezone-trigger')
->assertVisible('@calendar-toggle-slots');
- $page->resize(1280, 900);
+ $page->keys('@calendar-menu-content', 'Escape');
+ $page->resize(900, 900);
+ waitForPublishPageScript($page, 'Boolean(document.querySelector(\'[data-testid="posts-label-filter"]\')?.getClientRects().length)');
+ waitForPublishPageScript($page, '!document.querySelector(\'[data-testid="calendar-status-filter"]\')');
+
+ expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))'))->toBeFalse()
+ ->and($page->script('Boolean(document.querySelector(\'[data-testid="calendar-menu"]\')?.getClientRects().length)'))->toBeTrue()
+ ->and($page->script('document.documentElement.scrollWidth > window.innerWidth'))->toBeFalse();
+
+ $page->resize(1600, 900);
waitForPublishPageScript($page, 'Boolean(document.querySelector(\'[data-testid="calendar-status-filter"]\'))');
$order = $page->script(<<<'JS'
- (() => ['posts-channel-filter', 'calendar-status-filter', 'posts-label-filter', 'publish-timezone-trigger', 'calendar-no-date', 'calendar-menu']
+ (() => ['posts-channel-filter', 'posts-label-filter', 'calendar-status-filter', 'publish-timezone-trigger', 'calendar-no-date', 'calendar-menu']
.map((id) => document.querySelector(`[data-testid="${id}"]`).getBoundingClientRect().left)
.every((left, index, lefts) => index === 0 || left > lefts[index - 1]))()
JS);
@@ -482,6 +471,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
$page->resize(390, 844);
waitForPublishPageTestId($page, 'publish-tabs-mobile-trigger');
+ waitForPublishPageScript($page, '!document.querySelector(\'[data-testid="posts-label-filter"]\')');
$phone = $page->script(<<<'JS'
(() => {
@@ -492,7 +482,7 @@ test('the channel page adapts its filters, tabs, calendar link and notes button
return {
oneRow: row.every((box) => Math.abs(middle(box) - middle(row[0])) <= 2),
belowGoal: row[0].top >= rect('publish-goal-progress').bottom,
- tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')),
+ tags: Boolean(document.querySelector('[data-testid="posts-label-filter"]')?.getClientRects().length),
overflow: document.documentElement.scrollWidth > window.innerWidth,
};
})()
diff --git a/tests/Browser/PublishQueueTest.php b/tests/Browser/PublishQueueTest.php
index 37ab5ea9c..7c0c82fbe 100644
--- a/tests/Browser/PublishQueueTest.php
+++ b/tests/Browser/PublishQueueTest.php
@@ -4,15 +4,14 @@ declare(strict_types=1);
use App\Actions\Post\CreatePosts;
use App\Actions\Post\Queue\ReflowChannelQueue;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\User\TimeFormat;
use App\Exceptions\Social\ErrorCategory;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -81,21 +80,13 @@ function publishQueueSetup(): array
function publishQueuePost(User $user, SocialAccount $channel, QueuePosition $position = QueuePosition::Next): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $post = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => null,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
-
ReflowChannelQueue::handle($channel, $post, $position);
return $post->refresh();
@@ -171,19 +162,12 @@ test('a member whose posts need approval can still open the composer from an emp
test('scheduled posts replace the slots with a list of only those posts', function () {
[$user, , $channel] = publishQueueSetup();
$queued = publishQueuePost($user, $channel);
- $custom = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $custom = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->utc()->addDays(120)->setTime(15, 30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $custom->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
@@ -305,18 +289,11 @@ test('a far display time zone regroups slots under its own calendar day', functi
test('changing the time zone keeps a tab that came from a notes link', function () {
[$user, , $channel] = publishQueueSetup();
- $draft = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $draft = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
]);
- PostPlatform::factory()->create([
- 'post_id' => $draft->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = publishQueueVisitWithCleanStorage(route('app.posts.index', ['notes' => $draft->id]));
@@ -353,18 +330,11 @@ test('more times extends the queue range', function () {
test('a failed post is listed in sent with its failed badge and actions', function () {
[$user, $workspace, $channel] = publishQueueSetup();
- $failed = Post::factory()->failed()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- 'scheduled_at' => now()->subDays(21),
- ]);
- PostPlatform::factory()->failed()->create([
- 'post_id' => $failed->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
+ $failed = Post::factory()->forAccount($channel)->failed()->create([
'error_message' => 'Video duration exceeds the 90 second limit.',
'error_context' => ['category' => ErrorCategory::MediaFormat->value],
+ 'user_id' => $user->id,
+ 'scheduled_at' => now()->subDays(21),
]);
$this->actingAs($user);
@@ -399,8 +369,7 @@ test('a failed post is listed in sent with its failed badge and actions', functi
function publishQueueCustomPost(User $user, SocialAccount $channel, CarbonInterface $at): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $post = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'content' => 'A post with its own time',
'status' => PostStatus::Scheduled,
@@ -408,13 +377,6 @@ function publishQueueCustomPost(User $user, SocialAccount $channel, CarbonInterf
'scheduled_at' => $at,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
-
return $post;
}
@@ -625,24 +587,17 @@ test('a publishing post waiting for a network limit shows when it retries', func
[$user, $workspace, $channel] = publishQueueSetup();
$user->update(['time_format' => TimeFormat::TwentyFourHour]);
$retryAt = now()->addHours(2)->startOfMinute();
- $waiting = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $waiting = Post::factory()->forAccount($channel)->create([
+ 'publish_status' => PublishStatus::Retrying,
+ 'retry_at' => $retryAt,
+ 'error_message' => 'LinkedIn rate limit reached. Please try again later.',
+ 'error_context' => ['category' => ErrorCategory::RateLimit->value, 'limit_retries' => 1],
'user_id' => $user->id,
'status' => PostStatus::Publishing,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->subMinute(),
'content' => 'Waiting for the limit',
]);
- PostPlatform::factory()->create([
- 'post_id' => $waiting->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- 'status' => PostPlatformStatus::Retrying,
- 'retry_at' => $retryAt,
- 'error_message' => 'LinkedIn rate limit reached. Please try again later.',
- 'error_context' => ['category' => ErrorCategory::RateLimit->value, 'limit_retries' => 1],
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.index'));
@@ -654,23 +609,36 @@ test('a publishing post waiting for a network limit shows when it retries', func
->assertNoJavaScriptErrors();
});
+test('a google business post waiting for review says google is reviewing it', function () {
+ [$user, $workspace] = publishQueueSetup();
+ $channel = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $workspace->id]);
+ $inReview = Post::factory()->forAccount($channel)->pendingReview()->create([
+ 'user_id' => $user->id,
+ 'schedule_mode' => ScheduleMode::Custom,
+ 'scheduled_at' => now()->subMinute(),
+ 'content' => 'Waiting for Google',
+ ]);
+ $this->actingAs($user);
+
+ $page = visit(route('app.posts.index'));
+ waitForPublishQueueTestId($page, "post-google-review-{$inReview->id}");
+
+ $page->assertSeeIn("@post-google-review-{$inReview->id}", __('posts.publish.in_google_review'))
+ ->assertNotPresent("@post-publishing-progress-{$inReview->id}")
+ ->assertDontSeeIn("@post-publishing-{$inReview->id}", __('posts.publish.publishing_on', ['network' => $channel->platform->label()]))
+ ->assertNoJavaScriptErrors();
+});
+
test('a publishing post sits in its own queue group and moves to sent once it settles', function () {
[$user, $workspace, $channel] = publishQueueSetup();
$scheduled = publishQueuePost($user, $channel);
- $publishing = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $publishing = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Publishing,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->subMinute(),
'content' => 'Going out right now',
]);
- PostPlatform::factory()->create([
- 'post_id' => $publishing->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
$this->actingAs($user);
$page = visit(route('app.posts.index'));
diff --git a/tests/Browser/SidebarChannelsTest.php b/tests/Browser/SidebarChannelsTest.php
index 87edea69c..aa616f803 100644
--- a/tests/Browser/SidebarChannelsTest.php
+++ b/tests/Browser/SidebarChannelsTest.php
@@ -3,7 +3,6 @@
declare(strict_types=1);
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -238,13 +237,7 @@ test('an expanded channel shows its scheduled count on the Publish item', functi
$empty = SocialAccount::factory()->linkedin()->create(['workspace_id' => $user->current_workspace_id]);
foreach (range(1, 3) as $ignored) {
- $post = Post::factory()->scheduled()->create(['workspace_id' => $user->current_workspace_id, 'user_id' => $user->id]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'enabled' => true,
- ]);
+ Post::factory()->forAccount($channel)->scheduled()->create(['user_id' => $user->id]);
}
$this->actingAs($user);
diff --git a/tests/Browser/WebhookCreateDialogTest.php b/tests/Browser/WebhookCreateDialogTest.php
index 765ffe024..d102e8e01 100644
--- a/tests/Browser/WebhookCreateDialogTest.php
+++ b/tests/Browser/WebhookCreateDialogTest.php
@@ -72,25 +72,25 @@ test('creating a webhook happens in a centered dialog with cancel before the pri
$checkedCount = "document.querySelectorAll('[data-testid=\"create-webhook-events\"] [role=\"checkbox\"][data-state=\"checked\"]').length";
- $page->assertSeeIn('@create-webhook-events-count', '0 of 7 selected')
+ $page->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')
->assertSeeIn('@create-webhook-events-toggle-all', __('posts.composer.select_all'))
->assertSeeIn('@create-webhook-events-post-published-description', __('webhooks.event_descriptions.post_published'))
->assertSeeIn('@create-webhook-endpoint-help', __('webhooks.create.endpoint_help'))
->click('@create-webhook-events-toggle-all')
- ->assertScript($checkedCount, 7)
- ->assertSeeIn('@create-webhook-events-count', '7 of 7 selected')
+ ->assertScript($checkedCount, 6)
+ ->assertSeeIn('@create-webhook-events-count', '6 of 6 selected')
->assertSeeIn('@create-webhook-events-toggle-all', __('posts.composer.deselect_all'))
->assertEnabled('@create-webhook-submit')
->click('@create-webhook-events-toggle-all')
->assertScript($checkedCount, 0)
- ->assertSeeIn('@create-webhook-events-count', '0 of 7 selected')
+ ->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')
->assertDisabled('@create-webhook-submit')
->click('@create-webhook-events-post-failed-description')
->assertScript("document.querySelector('[data-testid=\"create-webhook-events-post-failed-checkbox\"]').getAttribute('data-state')", 'checked')
- ->assertSeeIn('@create-webhook-events-count', '1 of 7 selected')
+ ->assertSeeIn('@create-webhook-events-count', '1 of 6 selected')
->click('@create-webhook-events-post-failed-checkbox')
->assertScript("document.querySelector('[data-testid=\"create-webhook-events-post-failed-checkbox\"]').getAttribute('data-state')", 'unchecked')
- ->assertSeeIn('@create-webhook-events-count', '0 of 7 selected')
+ ->assertSeeIn('@create-webhook-events-count', '0 of 6 selected')
->click('@create-webhook-events-post-published')
->click('@cancel-create-webhook');
waitForWebhookCreateTestIdGone($page, 'create-webhook-dialog');
diff --git a/tests/Browser/XLinkDefusingTest.php b/tests/Browser/XLinkDefusingTest.php
index f1e3ccd78..c663274cf 100644
--- a/tests/Browser/XLinkDefusingTest.php
+++ b/tests/Browser/XLinkDefusingTest.php
@@ -3,11 +3,9 @@
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -40,20 +38,11 @@ function seedXDefusingPost(string $content): array
$account = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create([
'user_id' => $user->id,
'content' => $content,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- 'enabled' => true,
- ]);
-
test()->actingAs($user);
return [$post, $account];
diff --git a/tests/Browser/YouTubeDescriptionTest.php b/tests/Browser/YouTubeDescriptionTest.php
index f909fdeae..3bc2550d4 100644
--- a/tests/Browser/YouTubeDescriptionTest.php
+++ b/tests/Browser/YouTubeDescriptionTest.php
@@ -4,9 +4,9 @@ declare(strict_types=1);
use App\Dto\MediaItem;
use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -27,29 +27,23 @@ function seedYouTubeDescriptionEditor(): array
]);
Storage::put($asset->path, (string) file_get_contents(base_path('tests/fixtures/sample.mp4')));
- $platforms = collect(range(1, 2))->map(function (int $number) use ($workspace, $user, $asset) {
+ $posts = collect(range(1, 2))->map(function (int $number) use ($workspace, $user, $asset) {
$account = SocialAccount::factory()->youtube()->create([
'workspace_id' => $workspace->id,
'username' => "ytchannel{$number}",
]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+
+ return Post::factory()->forAccount($account, ContentType::YouTubeShort)->create([
'user_id' => $user->id,
'content' => 'Short title',
'status' => Status::Draft,
'media' => [MediaItem::fromMedia($asset)->toArray()],
- ]);
-
- return PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => ['description' => "Channel {$number}"],
]);
});
test()->actingAs($user);
- return [$platforms[0]->post, $platforms];
+ return [$posts[0], $posts];
}
function waitForYouTubeElement(mixed $page, string $testId): void
@@ -66,7 +60,7 @@ function waitForYouTubeElement(mixed $page, string $testId): void
}
test('youtube description editor counts UTF-8 bytes and saves only its independent post', function (int $width, int $height) {
- [$post, $platforms] = seedYouTubeDescriptionEditor();
+ [$post, $posts] = seedYouTubeDescriptionEditor();
$page = visit(route('app.posts.edit', $post))->resize($width, $height);
waitForYouTubeElement($page, 'youtube-description-0');
$page->assertValue('@youtube-description-0', 'Channel 1');
@@ -91,21 +85,21 @@ test('youtube description editor counts UTF-8 bytes and saves only its independe
}
$page->click('@composer-save-draft')->assertMissing('@post-composer-dialog');
- expect(data_get($platforms[0]->fresh()->meta, 'description'))->toBe($description)
- ->and(data_get($platforms[1]->fresh()->meta, 'description'))->toBe('Channel 2')
+ expect(data_get($posts[0]->fresh()->meta, 'description'))->toBe($description)
+ ->and(data_get($posts[1]->fresh()->meta, 'description'))->toBe('Channel 2')
->and($post->fresh()->content)->toBe('Short title');
})->with([[375, 812]]);
test('youtube description clearing restores content fallback without changing another post', function (string $description) {
- [$post, $platforms] = seedYouTubeDescriptionEditor();
+ [$post, $posts] = seedYouTubeDescriptionEditor();
$page = visit(route('app.posts.edit', $post))->resize(375, 812);
waitForYouTubeElement($page, 'youtube-description-0');
$page->fill('@youtube-description-0', $description)
->click('@composer-save-draft')
->assertMissing('@post-composer-dialog');
- expect(data_get($platforms[0]->fresh()->meta, 'description'))->toBeNull()
- ->and(data_get($platforms[1]->fresh()->meta, 'description'))->toBe('Channel 2');
+ expect(data_get($posts[0]->fresh()->meta, 'description'))->toBeNull()
+ ->and(data_get($posts[1]->fresh()->meta, 'description'))->toBe('Channel 2');
$page = visit(route('app.posts.edit', $post))->resize(375, 812);
$page->click('@composer-view-preview')
@@ -117,9 +111,9 @@ test('youtube description clearing restores content fallback without changing an
]);
test('youtube description long preview stays inside the preview card', function (int $width, int $height) {
- [$post, $platforms] = seedYouTubeDescriptionEditor();
+ [$post, $posts] = seedYouTubeDescriptionEditor();
$description = "Full description\n".str_repeat('https://example.com/'.str_repeat('a', 100)."\n", 35);
- $platforms[0]->update(['meta' => ['description' => $description]]);
+ $posts[0]->update(['meta' => ['description' => $description]]);
$page = visit(route('app.posts.edit', $post))->resize($width, $height);
if ($width < 1024) {
$page->click('@composer-view-preview');
diff --git a/tests/Feature/Actions/Post/AppendPostMediaTest.php b/tests/Feature/Actions/Post/AppendPostMediaTest.php
index 1b76532c2..b998a115e 100644
--- a/tests/Feature/Actions/Post/AppendPostMediaTest.php
+++ b/tests/Feature/Actions/Post/AppendPostMediaTest.php
@@ -67,7 +67,7 @@ test('appending media derives the pinterest and tiktok type again', function (st
AppendPostMedia::execute($post, [appendPostMediaItem($this->workspace, $video)], $this->user);
- expect($post->postPlatforms()->sole()->content_type)->toBe($expected);
+ expect($post->fresh()->content_type)->toBe($expected);
})->with([
'pinterest second image' => ['pinterest', false, ContentType::PinterestCarousel],
'pinterest video' => ['pinterest', true, ContentType::PinterestVideoPin],
diff --git a/tests/Feature/Actions/Post/CreatePostsTest.php b/tests/Feature/Actions/Post/CreatePostsTest.php
index b1b54c1ab..c53324f60 100644
--- a/tests/Feature/Actions/Post/CreatePostsTest.php
+++ b/tests/Feature/Actions/Post/CreatePostsTest.php
@@ -15,7 +15,7 @@ use App\Models\WorkspaceLabel;
use Illuminate\Support\Facades\Queue;
use Illuminate\Validation\ValidationException;
-test('a batch creates one independent post and target per selected account in input order', function () {
+test('a batch creates one independent post per selected account in input order', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$accounts = collect([
@@ -42,9 +42,8 @@ test('a batch creates one independent post and target per selected account in in
foreach ($posts as $index => $post) {
expect($post->content)->toBe("Legenda {$index}")
->and($post->status)->toBe(PostStatus::Draft)
- ->and($post->postPlatforms()->count())->toBe(1)
- ->and($post->postPlatforms()->enabled()->count())->toBe(1)
- ->and($post->postPlatforms()->first()->social_account_id)->toBe($accounts[$index]->id);
+ ->and($post->social_account_id)->toBe($accounts[$index]->id)
+ ->and($post->content_type)->toBe($types[$index]);
}
$posts[0]->update(['content' => 'Só este Instagram']);
diff --git a/tests/Feature/Actions/Post/DeletePostTest.php b/tests/Feature/Actions/Post/DeletePostTest.php
index 386d5cb3b..72ad008f3 100644
--- a/tests/Feature/Actions/Post/DeletePostTest.php
+++ b/tests/Feature/Actions/Post/DeletePostTest.php
@@ -6,7 +6,6 @@ use App\Actions\Post\DeletePost;
use App\Enums\Post\Status as PostStatus;
use App\Events\PostDeleted;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -55,18 +54,14 @@ test('execute prunes a google business jpeg still waiting on review', function (
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->create([
+ $account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->pendingReview()->create([
+ 'user_id' => $user->id,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
DeletePost::execute($post);
diff --git a/tests/Feature/Actions/Post/DuplicatePostTest.php b/tests/Feature/Actions/Post/DuplicatePostTest.php
index 59453ffe0..cd9187488 100644
--- a/tests/Feature/Actions/Post/DuplicatePostTest.php
+++ b/tests/Feature/Actions/Post/DuplicatePostTest.php
@@ -4,12 +4,12 @@ declare(strict_types=1);
use App\Actions\Post\DuplicatePost;
use App\Enums\Post\CreatedVia;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Events\PostCreated;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -19,15 +19,12 @@ use Illuminate\Validation\ValidationException;
test('execute clones the post as a draft created via web', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $original = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
+ $original = Post::factory()->forAccount($account)->published()->create([
'user_id' => $user->id,
'content' => 'Original content',
'created_via' => CreatedVia::Api,
- 'status' => PostStatus::Published,
]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->create(['post_id' => $original->id, 'social_account_id' => $account->id, 'enabled' => true]);
$copy = DuplicatePost::execute($original, $user);
@@ -42,12 +39,10 @@ test('execute clones the post as a draft created via web', function () {
test('execute relies on the observer to dispatch PostCreated for the duplicate', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $original = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
+ $original = Post::factory()->forAccount($account)->create([
'user_id' => $user->id,
]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->create(['post_id' => $original->id, 'social_account_id' => $account->id, 'enabled' => true]);
Event::fake([PostCreated::class]);
@@ -59,77 +54,46 @@ test('execute relies on the observer to dispatch PostCreated for the duplicate',
);
});
-test('execute skips platform rows whose social account was removed', function () {
+test('execute copies the channel as a pending destination', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $liveAccount = SocialAccount::factory()->create([
+ $account = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::X,
'display_name' => 'Live Account',
'username' => 'live_user',
]);
- $original = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $original = Post::factory()->forAccount($account)->x()->published()->create([
'user_id' => $user->id,
- 'status' => PostStatus::Published,
- ]);
-
- PostPlatform::factory()->x()->published()->create([
- 'post_id' => $original->id,
- 'social_account_id' => $liveAccount->id,
'platform_name' => 'Live Account',
'platform_username' => 'live_user',
'platform_avatar' => 'avatars/live.jpg',
- 'enabled' => true,
- ]);
-
- // History row left after disconnect: FK nullOnDelete + snapshot fields.
- PostPlatform::factory()->tiktok()->published()->create([
- 'post_id' => $original->id,
- 'social_account_id' => null,
- 'platform_name' => 'Removed Account',
- 'platform_username' => 'gone_user',
- 'platform_avatar' => 'avatars/orphan.jpg',
- 'enabled' => true,
]);
- $copy = DuplicatePost::execute($original->load(['postPlatforms', 'labels']), $user);
-
- $copiedPlatforms = $copy->postPlatforms()->get();
+ $copy = DuplicatePost::execute($original, $user)->fresh();
- expect($copiedPlatforms)->toHaveCount(1)
- ->and($copiedPlatforms->first()->social_account_id)->toBe($liveAccount->id)
- ->and($copiedPlatforms->first()->platform)->toBe(Platform::X)
- ->and($copiedPlatforms->first()->platform_name)->toBe('Live Account')
- ->and($copiedPlatforms->first()->status)->toBe(PostPlatformStatus::Pending)
- ->and($copiedPlatforms->first()->enabled)->toBeTrue();
+ expect($copy->social_account_id)->toBe($account->id)
+ ->and($copy->platform)->toBe(Platform::X)
+ ->and($copy->content_type)->toBe(ContentType::XPost)
+ ->and($copy->platform_name)->toBe('Live Account')
+ ->and($copy->publish_status)->toBe(PublishStatus::Pending)
+ ->and($copy->platform_post_id)->toBeNull();
});
-test('execute refuses a duplicate when no connected account remains', function () {
+test('execute refuses a duplicate when the channel was removed', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id]);
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $original = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $original = Post::factory()->forAccount($account)->published()->create([
'user_id' => $user->id,
- 'status' => PostStatus::Published,
- ]);
-
- $platform = PostPlatform::factory()->published()->create([
- 'post_id' => $original->id,
- 'social_account_id' => $account->id,
'platform_name' => $account->display_name,
'platform_username' => $account->username,
- 'enabled' => true,
]);
- $account->delete();
- $platform->refresh();
-
- expect($platform->social_account_id)->toBeNull();
+ Post::query()->whereKey($original->id)->update(['social_account_id' => null]);
- expect(fn () => DuplicatePost::execute($original->fresh(['postPlatforms', 'labels']), $user))
+ expect(fn () => DuplicatePost::execute($original->fresh(), $user))
->toThrow(ValidationException::class);
});
diff --git a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php b/tests/Feature/Actions/Post/FinalizePostPublicationTest.php
index 39bdd9ff4..30a9d4c19 100644
--- a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php
+++ b/tests/Feature/Actions/Post/FinalizePostPublicationTest.php
@@ -4,14 +4,13 @@ declare(strict_types=1);
use App\Actions\Post\FinalizePostPublication;
use App\Enums\Notification\Type;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\User\Locale;
use App\Jobs\SendNotification;
use App\Mail\PostPublished;
use App\Mail\PostPublishFailed;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -22,26 +21,34 @@ beforeEach(function () {
app()->setLocale(Locale::DEFAULT->value);
});
+/**
+ * A workspace whose owner is a member, as CreateWorkspace leaves it.
+ */
+function finalizeWorkspaceOf(User $owner): Workspace
+{
+ $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
+ $workspace->members()->attach($owner->id, membershipPivot('admin'));
+
+ return $workspace;
+}
+
test('a published post queues the published email for the owner', function () {
$owner = User::factory()->create(['locale' => Locale::PortugueseBrazil]);
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
+ $workspace = finalizeWorkspaceOf($owner);
$account = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspace->id,
'username' => 'inbox',
'display_name' => 'InboxPlacement.io',
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->facebook()->scheduled()->create([
'user_id' => $owner->id,
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => 'fb-1',
]);
app(FinalizePostPublication::class)->handle($post);
+ expect($post->fresh()->status)->toBe(PostStatus::Published);
Queue::assertPushed(SendNotification::class, function (SendNotification $job) use ($owner, $post) {
return $job->type === Type::PostPublished
&& $job->user->is($owner)
@@ -50,26 +57,41 @@ test('a published post queues the published email for the owner', function () {
});
});
+test('every member of the workspace gets the email, the owner included', function () {
+ $owner = User::factory()->create();
+ $workspace = finalizeWorkspaceOf($owner);
+ $member = workspaceMember($workspace, 'member');
+ $requester = workspaceMember($workspace, 'approval');
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
+ 'user_id' => $member->id,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => 'li-1',
+ ]);
+
+ app(FinalizePostPublication::class)->handle($post);
+
+ expect(Queue::pushed(SendNotification::class)->map(fn (SendNotification $job): string => $job->user->id)->sort()->values()->all())
+ ->toBe(collect([$owner->id, $member->id, $requester->id])->sort()->values()->all());
+});
+
test('a failed post queues the failed email for the owner', function () {
$owner = User::factory()->create(['locale' => Locale::PortugueseBrazil]);
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
+ $workspace = finalizeWorkspaceOf($owner);
$account = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspace->id,
'username' => 'inbox',
'display_name' => 'InboxPlacement.io',
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->facebook()->scheduled()->create([
'user_id' => $owner->id,
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->failed()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Failed,
+ 'error_message' => 'Failed to publish',
]);
app(FinalizePostPublication::class)->handle($post);
+ expect($post->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class, function (SendNotification $job) use ($owner, $post) {
return $job->type === Type::PostFailed
&& $job->user->is($owner)
@@ -78,20 +100,14 @@ test('a failed post queues the failed email for the owner', function () {
});
});
-test('a publishing post with no enabled targets is failed', function () {
+test('a publishing post without a destination is failed', function () {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
+ $workspace = finalizeWorkspaceOf($owner);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $owner->id,
'status' => PostStatus::Publishing,
]);
- PostPlatform::factory()->facebook()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
app(FinalizePostPublication::class)->handle($post);
@@ -99,20 +115,14 @@ test('a publishing post with no enabled targets is failed', function () {
Queue::assertPushed(SendNotification::class, fn (SendNotification $job) => $job->type === Type::PostFailed);
});
-test('a draft with no enabled targets is left alone', function () {
+test('a draft without a destination is left alone', function () {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
+ $workspace = finalizeWorkspaceOf($owner);
$post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $owner->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->facebook()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
app(FinalizePostPublication::class)->handle($post);
@@ -120,47 +130,11 @@ test('a draft with no enabled targets is left alone', function () {
Queue::assertNotPushed(SendNotification::class);
});
-test('a google business target still in review does not settle the post', function () {
- $owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $owner->id,
- 'status' => PostStatus::Publishing,
- ]);
- PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
- ]);
-
- app(FinalizePostPublication::class)->handle($post);
-
- expect($post->fresh()->status)->toBe(PostStatus::Publishing);
- Queue::assertNotPushed(SendNotification::class);
-});
-
-test('a published sibling does not settle the post while google business is in review', function () {
+test('a google business post still in review is not settled', function () {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $workspace = finalizeWorkspaceOf($owner);
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->googleBusiness()->pendingReview()->create([
'user_id' => $owner->id,
- 'status' => PostStatus::Publishing,
- ]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
- PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
@@ -170,50 +144,29 @@ test('a published sibling does not settle the post while google business is in r
Queue::assertNotPushed(SendNotification::class);
});
-test('a rejected google business target next to a published sibling is partial', function () {
+test('a google business post rejected in review is failed', function () {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $workspace = finalizeWorkspaceOf($owner);
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->googleBusiness()->publishing()->create([
'user_id' => $owner->id,
- 'status' => PostStatus::Publishing,
- ]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'status' => PostPlatformStatus::Rejected,
+ 'publish_status' => PublishStatus::Rejected,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'error_message' => __('posts.errors.rejected_in_review'),
]);
app(FinalizePostPublication::class)->handle($post);
- expect($post->fresh()->status)->toBe(PostStatus::PartiallyPublished);
+ expect($post->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class, fn (SendNotification $job) => $job->type === Type::PostFailed);
});
test('a second settle does not notify again', function () {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $workspace = finalizeWorkspaceOf($owner);
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([
'user_id' => $owner->id,
- 'status' => PostStatus::Publishing,
- ]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => 'fb-1',
]);
$finalize = app(FinalizePostPublication::class);
@@ -226,20 +179,14 @@ test('a second settle does not notify again', function () {
test('an already settled post is left alone', function (PostStatus $status) {
$owner = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $owner->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $workspace = finalizeWorkspaceOf($owner);
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->create([
'user_id' => $owner->id,
'status' => $status,
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => 'fb-1',
'published_at' => $status === PostStatus::Failed ? null : now(),
]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'enabled' => true,
- ]);
app(FinalizePostPublication::class)->handle($post);
@@ -247,6 +194,18 @@ test('an already settled post is left alone', function (PostStatus $status) {
Queue::assertNotPushed(SendNotification::class);
})->with([
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
]);
+
+test('a google review whose channel is gone is left to the review ceiling', function () {
+ $account = SocialAccount::factory()->googleBusiness()->create();
+ $post = Post::factory()->forAccount($account)->pendingReview()->create(['platform_post_id' => 'accounts/1/locations/1/localPosts/9']);
+ $post->forceFill(['social_account_id' => null])->save();
+
+ app(FinalizePostPublication::class)->handle($post->fresh());
+
+ expect($post->fresh())
+ ->status->toBe(PostStatus::Publishing)
+ ->publish_status->toBe(PublishStatus::PendingReview)
+ ->platform_post_id->toBe('accounts/1/locations/1/localPosts/9');
+});
diff --git a/tests/Feature/Actions/Post/UpdatePostTest.php b/tests/Feature/Actions/Post/UpdatePostTest.php
index 5532d4f5f..ebfdc6ebe 100644
--- a/tests/Feature/Actions/Post/UpdatePostTest.php
+++ b/tests/Feature/Actions/Post/UpdatePostTest.php
@@ -5,11 +5,10 @@ declare(strict_types=1);
use App\Actions\Post\CreatePosts;
use App\Actions\Post\UpdatePost;
use App\Enums\Post\Action as PostAction;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -18,171 +17,91 @@ use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
-test('execute prunes a google business jpeg when the target is switched off', function () {
- Storage::fake();
-
+test('execute rejects a platforms list from a stale client', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'user_id' => $user->id,
+ 'content' => 'Original',
]);
- $linkedin = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
- Storage::put($path, 'image');
- UpdatePost::execute($workspace, $post, [
+ expect(fn () => UpdatePost::execute($workspace, $post, [
'status' => PostStatus::Scheduled->value,
- 'platforms' => [['id' => $linkedin->id]],
- ]);
+ 'content' => 'Edited',
+ 'platforms' => [],
+ ]))->toThrow(ValidationException::class);
- expect($target->fresh()->enabled)->toBeFalse()
- ->and($target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($target->fresh()->error_message)->toBe(__('posts.errors.target_disabled'))
- ->and($linkedin->fresh()->enabled)->toBeTrue()
+ expect($post->fresh()->content)->toBe('Original')
->and($post->fresh()->status)->toBe(PostStatus::Scheduled);
- Storage::assertMissing($path);
});
-test('execute rejects switching off the sole social account', function () {
- Storage::fake();
-
+test('a draft without a channel keeps its edits but cannot be scheduled', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->scheduled()->create([
+ $post = Post::factory()->create([
'workspace_id' => $workspace->id,
'user_id' => $user->id,
+ 'content' => 'Original',
]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
- Storage::put($path, 'image');
- expect(fn () => UpdatePost::execute($workspace, $post, [
+ UpdatePost::execute($workspace, $post, ['status' => PostStatus::Draft->value, 'content' => 'Edited']);
+
+ expect($post->fresh()->content)->toBe('Edited')
+ ->and($post->fresh()->status)->toBe(PostStatus::Draft);
+
+ expect(fn () => UpdatePost::execute($workspace, $post->fresh(), [
'status' => PostStatus::Scheduled->value,
- 'platforms' => [],
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
]))->toThrow(ValidationException::class);
- expect($target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($target->fresh()->enabled)->toBeTrue()
- ->and($post->fresh()->status)->toBe(PostStatus::Scheduled);
- Storage::assertExists($path);
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
});
-test('execute keeps the google business jpeg when the target stays enabled', function () {
+test('execute keeps the google business jpeg on an edit', function () {
Storage::fake();
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->googleBusiness()->pendingReview()->create([
'user_id' => $user->id,
+ 'status' => PostStatus::Scheduled,
+ 'scheduled_at' => now()->addDay(),
'content' => 'Current promotion',
- ]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
UpdatePost::execute($workspace, $post, [
'status' => PostStatus::Scheduled->value,
- 'platforms' => [['id' => $target->id]],
+ 'content' => 'Updated promotion',
]);
- expect($target->fresh()->enabled)->toBeTrue();
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview);
Storage::assertExists($path);
});
-test('invalid publication metadata rolls back before cleaning a disabled google business target', function () {
- Storage::fake();
-
+test('invalid publication metadata rolls the edit back', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->youtube()->create([
'user_id' => $user->id,
'status' => PostStatus::Draft,
- ]);
- $youtube = PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->youtube()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
+ 'content' => 'Original',
'meta' => ['description' => str_repeat('a', 5001)],
]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
- Storage::put($path, 'image');
expect(fn () => UpdatePost::execute($workspace, $post, [
'status' => PostStatus::Scheduled->value,
- 'platforms' => [['id' => $youtube->id]],
+ 'scheduled_at' => now()->addDay()->toIso8601String(),
+ 'content' => 'Edited',
]))->toThrow(ValidationException::class);
expect($post->fresh()->status)->toBe(PostStatus::Draft)
- ->and($target->fresh()->enabled)->toBeTrue()
- ->and($target->fresh()->status)->toBe(PlatformStatus::PendingReview);
- Storage::assertExists($path);
+ ->and($post->fresh()->content)->toBe('Original');
});
-test('disabled youtube metadata does not block scheduling', function (bool $resubmitPlatforms) {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- ]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->youtube()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- 'enabled' => false,
- 'meta' => ['description' => str_repeat('a', 5001)],
- ]);
- $data = ['status' => PostStatus::Scheduled->value];
-
- if ($resubmitPlatforms) {
- $data['platforms'] = [];
- }
-
- UpdatePost::execute($workspace, $post, $data);
-
- expect($post->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($platform->fresh()->enabled)->toBeFalse();
-})->with([
- 'omitted platforms' => [false],
- 'deselected platforms' => [true],
-]);
-
test('an edit does not land on a post the scheduler claimed after it was loaded', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
diff --git a/tests/Feature/Analytics/AnalyticsChannelFilterTest.php b/tests/Feature/Analytics/AnalyticsChannelFilterTest.php
index 0633e3198..a2b54b676 100644
--- a/tests/Feature/Analytics/AnalyticsChannelFilterTest.php
+++ b/tests/Feature/Analytics/AnalyticsChannelFilterTest.php
@@ -11,7 +11,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -43,22 +42,17 @@ beforeEach(function () {
};
$this->publish = function (SocialAccount $account, int $reactions, ?WorkspaceLabel $label = null, ?string $key = null, string $publishedAt = '2026-09-15 12:00:00'): AnalyticsPublication {
- $post = Post::factory()->published()->create(['workspace_id' => $account->workspace_id, 'user_id' => $this->user->id]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $this->user->id]);
if ($label !== null) {
$post->labels()->attach($label);
}
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $key ?? $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => $account->platform,
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
diff --git a/tests/Feature/Analytics/AnalyticsObservabilityTest.php b/tests/Feature/Analytics/AnalyticsObservabilityTest.php
index 376f73507..2665ef3dd 100644
--- a/tests/Feature/Analytics/AnalyticsObservabilityTest.php
+++ b/tests/Feature/Analytics/AnalyticsObservabilityTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Dto\Analytics\TryPostPublicationIdentity;
use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BackfillAccountPublications;
-use App\Jobs\Analytics\BackfillTryPostPublications;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\Analytics\CollectPublicationMetrics;
@@ -30,7 +29,6 @@ test('horizon supervises every analytics job on a dedicated queue', function ()
foreach ([
new BackfillAccountPublications('account', 'state'),
- new BackfillTryPostPublications(['destination']),
new BootstrapAccountAnalytics('account'),
new CollectAccountDailySnapshot('account', '2026-09-23'),
new CollectPublicationMetrics('publication', '2026-09-23'),
diff --git a/tests/Feature/Analytics/AnalyticsSchemaTest.php b/tests/Feature/Analytics/AnalyticsSchemaTest.php
index a33e69248..680050643 100644
--- a/tests/Feature/Analytics/AnalyticsSchemaTest.php
+++ b/tests/Feature/Analytics/AnalyticsSchemaTest.php
@@ -36,7 +36,7 @@ test('analytics tables expose the portable persistence contract', function () {
]))->toBeTrue()
->and(Schema::hasColumns('analytics_publications', [
'id', 'workspace_id', 'social_account_id', 'social_account_key',
- 'post_platform_id', 'network', 'platform_user_id', 'platform',
+ 'post_id', 'network', 'platform_user_id', 'platform',
'remote_id', 'provider_published_at', 'origin', 'content_type',
'availability', 'provider_content_type', 'permalink', 'excerpt',
'preview_metadata', 'account_display_name', 'account_username',
diff --git a/tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php b/tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php
deleted file mode 100644
index 05cc199b4..000000000
--- a/tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php
+++ /dev/null
@@ -1,423 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Actions\Analytics\ResolveAnalyticsAccountKey;
-use App\Actions\Post\ImportExternalPosts;
-use App\Enums\Analytics\SyncCollector;
-use App\Enums\Analytics\SyncStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
-use App\Enums\SocialAccount\Status;
-use App\Jobs\Analytics\BackfillTryPostPublications;
-use App\Jobs\Analytics\BootstrapAccountAnalytics;
-use App\Jobs\Analytics\CollectAccountDailySnapshot;
-use App\Models\Account;
-use App\Models\AnalyticsPublication;
-use App\Models\AnalyticsSyncState;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use Illuminate\Support\Facades\Bus;
-use Illuminate\Support\Facades\DB;
-
-test('local publication backfill persists only successful included destinations with live identities', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $published = PostPlatform::factory()->instagram()->published()->create([
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $published->post->update(['workspace_id' => $workspace->id]);
- $failed = PostPlatform::factory()->instagram()->failed()->create([
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- app()->call([new BackfillTryPostPublications([$published->id, $failed->id]), 'handle']);
-
- expect(AnalyticsPublication::query()->where('post_platform_id', $published->id)->exists())->toBeTrue()
- ->and(AnalyticsPublication::query()->where('post_platform_id', $failed->id)->exists())->toBeFalse();
-});
-
-test('rollout command dispatches bounded jobs only for eligible scoped accounts and destinations', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $eligible = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- $second = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- $published = PostPlatform::factory()->instagram()->published()->create([
- 'social_account_id' => $eligible->id,
- 'platform' => $eligible->platform,
- ]);
- $published->post->update(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->instagram()->create([
- 'social_account_id' => $eligible->id,
- 'platform' => $eligible->platform,
- 'status' => PostPlatformStatus::Failed,
- ]);
- Bus::fake();
-
- expect(SocialAccount::query()->connected()->includedInAnalytics()
- ->where('workspace_id', $workspace->id)->pluck('id')->all())->toEqualCanonicalizing([$eligible->id, $second->id]);
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true])
- ->assertSuccessful();
-
- Bus::assertDispatched(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $eligible->id);
- Bus::assertDispatched(CollectAccountDailySnapshot::class, fn ($job): bool => $job->socialAccountId === $eligible->id && $job->observationDate === now('UTC')->toDateString());
- Bus::assertDispatched(BackfillTryPostPublications::class, fn ($job): bool => $job->postPlatformIds === [$published->id]);
- Bus::assertDispatched(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $second->id);
- Bus::assertDispatchedTimes(BootstrapAccountAnalytics::class, 2);
- Bus::assertDispatchedTimes(BackfillTryPostPublications::class, 1);
-});
-
-test('rollout reports orphaned historical destinations without inventing an identity', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $destination = PostPlatform::factory()->instagram()->published()->create();
- $destination->post->update(['workspace_id' => $workspace->id]);
- $destination->updateQuietly(['social_account_id' => null]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true])
- ->expectsOutputToContain('historical_identity_unrecoverable=1')
- ->assertSuccessful();
-
- Bus::assertNotDispatched(BackfillTryPostPublications::class);
-});
-
-test('deployment rollout follows Cashier subscription eligibility', function () {
- Bus::fake();
- $eligibleAccounts = [];
- $eligibleDestinations = [];
- $workspaces = [];
-
- foreach (['active', 'trialing', 'past_due', 'grace_period', 'ended', 'none'] as $status) {
- $workspace = Workspace::factory()->create();
- $workspaces[$status] = $workspace;
-
- if ($status !== 'none') {
- $workspace->account->subscriptions()->create([
- 'type' => Account::SUBSCRIPTION_NAME,
- 'stripe_id' => 'sub_'.fake()->uuid(),
- 'stripe_status' => in_array($status, ['grace_period', 'ended'], true) ? 'active' : $status,
- 'stripe_price' => 'price_123',
- 'ends_at' => match ($status) {
- 'grace_period' => now()->addDay(),
- 'ended' => now()->subDay(),
- default => null,
- },
- ]);
- }
-
- $socialAccount = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => Post::factory()->create(['workspace_id' => $workspace->id])->id,
- 'social_account_id' => $socialAccount->id,
- ]);
-
- if (in_array($status, ['active', 'grace_period', 'trialing', 'past_due'], true)) {
- $orphan = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => Post::factory()->create(['workspace_id' => $workspace->id])->id,
- 'social_account_id' => $socialAccount->id,
- ]);
- $orphan->updateQuietly(['social_account_id' => null]);
- }
-
- if (in_array($status, ['active', 'grace_period', 'trialing', 'past_due'], true)) {
- $eligibleAccounts[] = $socialAccount->id;
- $eligibleDestinations[] = $destination->id;
- }
- }
-
- Bus::fake();
- $this->artisan('analytics:backfill-existing')
- ->expectsOutputToContain('historical_identity_unrecoverable=4')
- ->assertSuccessful();
-
- expect(Bus::dispatched(BootstrapAccountAnalytics::class)->pluck('socialAccountId')->sort()->values()->all())->toBe(collect($eligibleAccounts)->sort()->values()->all())
- ->and(Bus::dispatched(CollectAccountDailySnapshot::class)->pluck('socialAccountId')->sort()->values()->all())->toBe(collect($eligibleAccounts)->sort()->values()->all())
- ->and(Bus::dispatched(BackfillTryPostPublications::class)->flatMap->postPlatformIds->sort()->values()->all())->toBe(collect($eligibleDestinations)->sort()->values()->all());
-
- Bus::fake();
- $this->artisan('analytics:backfill-existing', [
- '--workspace' => $workspaces['trialing']->id,
- ])->assertSuccessful();
-
- Bus::assertDispatched(BootstrapAccountAnalytics::class);
- Bus::assertDispatched(BackfillTryPostPublications::class);
-});
-
-test('deployment rollout uses the latest Cashier subscription of the account', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $workspace->account->subscriptions()->create([
- 'type' => Account::SUBSCRIPTION_NAME,
- 'stripe_id' => 'sub_'.fake()->uuid(),
- 'stripe_status' => 'active',
- 'stripe_price' => 'price_123',
- 'created_at' => now()->subDays(2),
- ]);
- $workspace->account->subscriptions()->create([
- 'type' => Account::SUBSCRIPTION_NAME,
- 'stripe_id' => 'sub_'.fake()->uuid(),
- 'stripe_status' => 'active',
- 'stripe_price' => 'price_123',
- 'ends_at' => now()->subDay(),
- 'created_at' => now()->subDay(),
- ]);
- $socialAccount = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => Post::factory()->create(['workspace_id' => $workspace->id])->id,
- 'social_account_id' => $socialAccount->id,
- ]);
-
- expect($workspace->account->fresh()->subscriptions->first()->ends_at?->isPast())->toBeTrue()
- ->and($workspace->account->fresh()->subscribed(Account::SUBSCRIPTION_NAME))->toBeFalse();
-
- Bus::fake();
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id])->assertSuccessful();
-
- Bus::assertNotDispatched(BootstrapAccountAnalytics::class);
- Bus::assertNotDispatched(BackfillTryPostPublications::class);
-});
-
-test('account backfill visits every identity once across ID pages despite platform sorting', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- SocialAccount::factory()->instagram()->count(100)->create([
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- SocialAccount::factory()->facebook()->create([
- 'id' => 'ffffffff-ffff-4fff-8fff-ffffffffffff',
- 'workspace_id' => $workspace->id,
- 'status' => Status::Connected,
- ]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true])->assertSuccessful();
-
- $jobs = Bus::dispatched(BootstrapAccountAnalytics::class);
- expect($jobs)->toHaveCount(101)
- ->and($jobs->pluck('socialAccountId')->unique())->toHaveCount(101);
-});
-
-test('manual rollout rerun only redispatches missing publications and unfinished account bootstraps', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $workspace->id,
- ]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => Post::factory()->create(['workspace_id' => $workspace->id])->id,
- 'social_account_id' => $account->id,
- ]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', [
- '--workspace' => $workspace->id,
- '--include-unsubscribed' => true,
- ])->assertSuccessful();
-
- Bus::assertDispatched(CollectAccountDailySnapshot::class, fn ($job): bool => $job->socialAccountId === $account->id);
- Bus::fake();
- $this->artisan('analytics:backfill-existing', [
- '--workspace' => $workspace->id,
- '--include-unsubscribed' => true,
- ])->assertSuccessful();
-
- Bus::assertDispatched(BackfillTryPostPublications::class, fn ($job): bool => $job->postPlatformIds === [$destination->id]);
- Bus::assertDispatched(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $account->id);
- app()->call([new BackfillTryPostPublications([$destination->id]), 'handle']);
- (new BootstrapAccountAnalytics($account->id))->handleFor($account->id);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', [
- '--workspace' => $workspace->id,
- '--include-unsubscribed' => true,
- ])->assertSuccessful();
-
- Bus::assertNotDispatched(BackfillTryPostPublications::class);
- Bus::assertNotDispatched(BootstrapAccountAnalytics::class);
- Bus::assertNotDispatched(CollectAccountDailySnapshot::class);
-});
-
-test('manual rollout rerun recovers a stale bootstrap without repeating a recent one', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $staleAccount = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $recentAccount = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $queueFailedAccount = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $permissionFailedAccount = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
-
- foreach ([$staleAccount, $recentAccount, $queueFailedAccount, $permissionFailedAccount] as $account) {
- AnalyticsSyncState::factory()->create([
- ...AnalyticsSyncState::identityFor($account),
- 'social_account_id' => $account->id,
- 'collector' => SyncCollector::PublicationBackfill,
- 'status' => in_array($account->id, [$queueFailedAccount->id, $permissionFailedAccount->id], true)
- ? SyncStatus::Failed
- : SyncStatus::Pending,
- 'last_error_category' => match ($account->id) {
- $queueFailedAccount->id => 'queue_failed',
- $permissionFailedAccount->id => 'permission',
- default => null,
- },
- 'updated_at' => $account->is($recentAccount) ? now() : now()->subHours(3),
- ]);
- }
-
- Bus::fake();
- $this->artisan('analytics:backfill-existing', [
- '--workspace' => $workspace->id,
- '--include-unsubscribed' => true,
- ])->assertSuccessful();
-
- Bus::assertDispatched(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $staleAccount->id);
- Bus::assertDispatched(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $queueFailedAccount->id);
- Bus::assertDispatchedTimes(BootstrapAccountAnalytics::class, 2);
- Bus::assertNotDispatched(CollectAccountDailySnapshot::class);
-});
-
-test('rollout bootstrap and local publication jobs retry transient failures', function () {
- $bootstrap = new BootstrapAccountAnalytics(fake()->uuid());
- $publications = new BackfillTryPostPublications([fake()->uuid()]);
-
- expect($bootstrap->tries)->toBe(3)
- ->and($bootstrap->backoff())->toBe([60, 300])
- ->and($publications->tries)->toBe(3)
- ->and($publications->backoff())->toBe([60, 300]);
-});
-
-test('local backfill resolves one account identity per batch without repeated account reads', function () {
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $destinations = collect(range(1, 3))->map(function () use ($account, $workspace): PostPlatform {
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $destination->post->update(['workspace_id' => $workspace->id]);
-
- return $destination;
- });
- $accountKeys = Mockery::mock(ResolveAnalyticsAccountKey::class);
- $accountKeys->shouldReceive('for')->once()->andReturn($account->id);
- app()->instance(ResolveAnalyticsAccountKey::class, $accountKeys);
- $accountReads = [];
- DB::listen(function ($query) use (&$accountReads): void {
- if (str_contains($query->sql, 'social_accounts')) {
- $accountReads[] = $query->sql;
- }
- });
-
- app()->call([new BackfillTryPostPublications($destinations->pluck('id')->all()), 'handle']);
-
- expect($accountReads)->toHaveCount(1)
- ->and(AnalyticsPublication::query()->whereIn('post_platform_id', $destinations->pluck('id'))->count())->toBe(3);
-});
-
-test('the rollout can be limited to some platforms', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id, 'status' => Status::Connected]);
- SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'status' => Status::Connected]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true, '--platforms' => 'x'])
- ->expectsOutputToContain('accounts_dispatched=1')
- ->assertSuccessful();
-
- expect(Bus::dispatched(BootstrapAccountAnalytics::class)->pluck('socialAccountId')->all())->toBe([$x->id]);
-});
-
-test('an unknown platform stops the rollout before dispatching anything', function () {
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--platforms' => 'instagram,myspace'])
- ->expectsOutputToContain('myspace')
- ->assertFailed();
-
- Bus::assertNothingDispatched();
-});
-
-test('the rollout spaces account batches by the configured delay', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- SocialAccount::factory()->instagram()->count(3)->create(['workspace_id' => $workspace->id, 'status' => Status::Connected]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true, '--chunk' => 2, '--delay' => 300])
- ->expectsOutputToContain('accounts_dispatched=3')
- ->assertSuccessful();
-
- expect(Bus::dispatched(BootstrapAccountAnalytics::class)->map(fn ($job): int => (int) $job->delay)->sort()->values()->all())
- ->toBe([0, 0, 300]);
-});
-
-test('the rollout reports links queued and posts already imported', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id, 'status' => Status::Connected]);
- $published = PostPlatform::factory()->instagram()->published()->create(['social_account_id' => $account->id, 'platform' => $account->platform]);
- $published->post->update(['workspace_id' => $workspace->id]);
- Post::factory()->imported()->count(2)->create(['workspace_id' => $workspace->id]);
- Bus::fake();
-
- $this->artisan('analytics:backfill-existing', ['--workspace' => $workspace->id, '--include-unsubscribed' => true])
- ->expectsOutputToContain('publications_to_link=1')
- ->expectsOutputToContain('posts_imported=2')
- ->assertSuccessful();
-});
-
-test('a trypost post linked by the rollout is not imported a second time', function () {
- Bus::fake();
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $published = PostPlatform::factory()->instagram()->published()->create([
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'platform_post_id' => 'ours-1',
- ]);
- $published->post->update(['workspace_id' => $workspace->id]);
-
- app()->call([new BackfillTryPostPublications([$published->id]), 'handle']);
- AnalyticsPublication::query()->where('post_platform_id', $published->id)->update(['social_account_id' => $account->id]);
- ImportExternalPosts::execute($account);
-
- expect(Post::query()->imported()->count())->toBe(0)
- ->and(AnalyticsPublication::query()->where('post_platform_id', $published->id)->count())->toBe(1);
-});
-
-test('the rollout counts imported posts one workspace page at a time', function () {
- Bus::fake();
- $workspaces = Workspace::factory()->count(101)->create();
- Post::factory()->imported()->create(['workspace_id' => $workspaces->first()->id]);
- Post::factory()->imported()->create(['workspace_id' => $workspaces->last()->id]);
- $workspaceIds = $workspaces->modelKeys();
- $largestWorkspaceBinding = 0;
- DB::listen(function ($query) use ($workspaceIds, &$largestWorkspaceBinding): void {
- $largestWorkspaceBinding = max($largestWorkspaceBinding, count(array_intersect($query->bindings, $workspaceIds)));
- });
-
- $this->artisan('analytics:backfill-existing', ['--include-unsubscribed' => true])
- ->expectsOutputToContain('posts_imported=2')
- ->assertSuccessful();
-
- expect($largestWorkspaceBinding)->toBeLessThanOrEqual(100);
-});
diff --git a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php b/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
index 4e3e76ee5..15a9d85c1 100644
--- a/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
+++ b/tests/Feature/Analytics/ChannelInsightsFiltersTest.php
@@ -10,7 +10,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -51,20 +50,14 @@ function filteredInsightsPublication(
?WorkspaceLabel $label = null,
PublicationContentType $publicationType = PublicationContentType::Image,
): AnalyticsPublication {
- $destination = null;
+ $post = null;
if ($contentType !== null) {
- $post = Post::factory()->published()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id]);
+ $post = Post::factory()->forAccount($test->instagram, $contentType)->published()->create(['user_id' => $test->user->id]);
if ($label !== null) {
$post->labels()->attach($label);
}
-
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $test->instagram->id,
- 'content_type' => $contentType,
- ]);
}
$publication = AnalyticsPublication::factory()->create([
@@ -74,7 +67,7 @@ function filteredInsightsPublication(
'network' => $test->instagram->platform->network(),
'platform_user_id' => $test->instagram->platform_user_id,
'platform' => Platform::Instagram,
- 'post_platform_id' => $destination?->id,
+ 'post_id' => $post?->id,
'content_type' => $publicationType,
'provider_published_at' => CarbonImmutable::parse($publishedAt, 'UTC'),
]);
diff --git a/tests/Feature/Analytics/ChannelInsightsPageTest.php b/tests/Feature/Analytics/ChannelInsightsPageTest.php
index cb52a83f8..0cf33f53f 100644
--- a/tests/Feature/Analytics/ChannelInsightsPageTest.php
+++ b/tests/Feature/Analytics/ChannelInsightsPageTest.php
@@ -11,7 +11,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -70,15 +69,10 @@ test('the insights page renders the channel report and its publications', functi
$publication = channelInsightsPublication($this->instagram, '2026-09-20 10:00:00', ['reactions_count' => 8, 'comments_count' => 2], [
'preview_metadata' => ['thumbnail_url' => 'https://cdn.example.com/a.jpg'],
]);
- $post = Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->instagram->id,
- 'platform' => Platform::Instagram,
- ]);
+ $post = Post::factory()->forAccount($this->instagram)->published()->create(['user_id' => $this->user->id]);
$insecure = channelInsightsPublication($this->instagram, '2026-09-19 10:00:00', ['reactions_count' => 3], [
'preview_metadata' => ['thumbnail_url' => 'http://cdn.example.com/b.jpg'],
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
]);
$this->actingAs($this->user)
diff --git a/tests/Feature/Analytics/ChannelMetricSeriesTest.php b/tests/Feature/Analytics/ChannelMetricSeriesTest.php
index a3830469e..ecab1fb5a 100644
--- a/tests/Feature/Analytics/ChannelMetricSeriesTest.php
+++ b/tests/Feature/Analytics/ChannelMetricSeriesTest.php
@@ -15,7 +15,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -46,16 +45,11 @@ beforeEach(function () {
*/
function seriesPublication(object $test, SocialAccount $account, string $publishedAt, array $metrics = [], ?WorkspaceLabel $label = null): AnalyticsPublication
{
- $destination = null;
+ $post = null;
if ($label !== null) {
- $post = Post::factory()->published()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id]);
+ $post = Post::factory()->forAccount($account, ContentType::InstagramFeed)->published()->create(['user_id' => $test->user->id]);
$post->labels()->attach($label);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::InstagramFeed,
- ]);
}
$publication = AnalyticsPublication::factory()->create([
@@ -65,7 +59,7 @@ function seriesPublication(object $test, SocialAccount $account, string $publish
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
'platform' => $account->platform,
- 'post_platform_id' => $destination?->id,
+ 'post_id' => $post?->id,
'provider_published_at' => CarbonImmutable::parse($publishedAt, 'UTC'),
]);
AnalyticsPublicationDailySnapshot::factory()->create([
diff --git a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
index fba9d34b8..0960c0ca7 100644
--- a/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
+++ b/tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php
@@ -12,7 +12,6 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\Analytics\AnalyticsCollectionException;
use App\Models\AnalyticsPublication;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Analytics\Collectors\Metrics\BlueskyPublicationMetricsCollector;
use App\Services\Analytics\Collectors\Metrics\FacebookPublicationMetricsCollector;
@@ -364,19 +363,14 @@ test('Meta publication metrics classify missing permission on HTTP 400', functio
test('TikTok resolves a TryPost publish id before collecting the public video', function () {
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
'platform_post_id' => 'v_pub_abc',
]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $postPlatform->id,
+ 'post_id' => $post->id,
'network' => Platform::TikTok->network(),
'platform' => Platform::TikTok,
'platform_user_id' => $account->platform_user_id,
@@ -395,7 +389,7 @@ test('TikTok resolves a TryPost publish id before collecting the public video',
expect($metrics->all())->toBe(['views' => 12, 'reactions' => 0, 'engagements' => 0])
->and($publication->fresh()->remote_id)->toBe('v_pub_abc')
- ->and($postPlatform->fresh()->platform_post_id)->toBe('v_pub_abc');
+ ->and($post->fresh()->platform_post_id)->toBe('v_pub_abc');
Http::assertSentCount(2);
});
diff --git a/tests/Feature/Analytics/InsightsAccountStatusTest.php b/tests/Feature/Analytics/InsightsAccountStatusTest.php
index c81f73ddd..2a7391fa8 100644
--- a/tests/Feature/Analytics/InsightsAccountStatusTest.php
+++ b/tests/Feature/Analytics/InsightsAccountStatusTest.php
@@ -10,7 +10,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -36,13 +35,12 @@ test('insights rows carry the live connection status and the top post avatar of
'date' => '2026-09-15',
'followers_count' => 500,
]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'account_avatar_url' => 'https://example.test/avatar.png',
'provider_published_at' => CarbonImmutable::parse('2026-09-15 12:00:00', 'UTC'),
diff --git a/tests/Feature/Analytics/InsightsExportTest.php b/tests/Feature/Analytics/InsightsExportTest.php
index 5ca88c107..b7c0b8aee 100644
--- a/tests/Feature/Analytics/InsightsExportTest.php
+++ b/tests/Feature/Analytics/InsightsExportTest.php
@@ -10,7 +10,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,22 +30,17 @@ beforeEach(function () {
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->publish = function (SocialAccount $account, int $reactions, string $excerpt, ?WorkspaceLabel $label = null, string $publishedAt = '2026-09-15 12:00:00', array $metrics = []): AnalyticsPublication {
- $post = Post::factory()->published()->create(['workspace_id' => $account->workspace_id, 'user_id' => $this->user->id]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $this->user->id]);
if ($label !== null) {
$post->labels()->attach($label);
}
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => $account->platform,
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
diff --git a/tests/Feature/Analytics/InsightsNoLabelFilterTest.php b/tests/Feature/Analytics/InsightsNoLabelFilterTest.php
index d9b971121..9dff62437 100644
--- a/tests/Feature/Analytics/InsightsNoLabelFilterTest.php
+++ b/tests/Feature/Analytics/InsightsNoLabelFilterTest.php
@@ -8,7 +8,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -26,18 +25,17 @@ test('the workspace insights page ignores label parameters and offers no label f
$label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
foreach ([$label, null] as $attached) {
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id]);
if ($attached !== null) {
$post->labels()->attach($attached);
}
- $destination = PostPlatform::factory()->instagram()->published()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'provider_published_at' => CarbonImmutable::parse('2026-09-15 12:00:00', 'UTC'),
]);
diff --git a/tests/Feature/Analytics/InsightsPostLinksTest.php b/tests/Feature/Analytics/InsightsPostLinksTest.php
index eea0ebc44..e73baaf79 100644
--- a/tests/Feature/Analytics/InsightsPostLinksTest.php
+++ b/tests/Feature/Analytics/InsightsPostLinksTest.php
@@ -9,7 +9,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -42,11 +41,7 @@ test('the post details deep link receives the latest saved post metrics', functi
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$user->update(['current_workspace_id' => $workspace->id]);
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Pinterest]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $destination = PostPlatform::factory()->pinterest()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
@@ -54,7 +49,7 @@ test('the post details deep link receives the latest saved post metrics', functi
'platform' => Platform::Pinterest,
'network' => Platform::Pinterest->network(),
'origin' => PublicationOrigin::TryPost,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
@@ -70,7 +65,7 @@ test('the post details deep link receives the latest saved post metrics', functi
->component('publish/Index')
->where('openPostDetailsId', $post->id)
->loadDeferredProps(fn (Assert $reload) => $reload
- ->where("posts.data.0.metrics.{$destination->id}.metrics.saves.value", 6)
+ ->where('posts.data.0.metrics.metrics.saves.value', 6)
->etc())
->etc());
diff --git a/tests/Feature/Analytics/InstagramStoriesImportTest.php b/tests/Feature/Analytics/InstagramStoriesImportTest.php
index d17f51f10..add91a790 100644
--- a/tests/Feature/Analytics/InstagramStoriesImportTest.php
+++ b/tests/Feature/Analytics/InstagramStoriesImportTest.php
@@ -19,7 +19,6 @@ use App\Jobs\Post\ImportExternalPostMedia;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsSyncState;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Carbon\CarbonImmutable;
use Illuminate\Http\Client\Request;
@@ -113,8 +112,8 @@ test('backfill on connect imports live stories as story posts next to feed posts
app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);
- $types = PostPlatform::query()->pluck('content_type', 'platform_post_id')->all();
- $story = Post::query()->imported()->whereRelation('postPlatforms', 'platform_post_id', 'story-1')->sole();
+ $types = Post::query()->pluck('content_type', 'platform_post_id')->all();
+ $story = Post::query()->imported()->where('platform_post_id', 'story-1')->sole();
expect($types)->toEqual([
'feed-1' => ContentType::InstagramFeed,
@@ -155,7 +154,7 @@ test('discovery picks up a new story even when it is older than the watermark ov
runStoryDiscovery($account, $state);
- expect(PostPlatform::query()->sole())
+ expect(Post::query()->sole())
->platform_post_id->toBe('story-1')
->content_type->toBe(ContentType::InstagramStory);
});
@@ -174,17 +173,8 @@ test('a story seen on every discovery run is imported once', function () {
test('a story trypost published is linked instead of imported again', function () {
$account = SocialAccount::factory()->instagram()->create();
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
- 'status' => PostStatus::Published,
+ $post = Post::factory()->forAccount($account, ContentType::InstagramStory)->published()->create([
'origin' => Origin::TryPost,
- 'published_at' => now()->subHours(2),
- ]);
- $tryPost = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => ContentType::InstagramStory,
'platform_post_id' => 'story-1',
'published_at' => now()->subHours(2),
]);
@@ -194,7 +184,7 @@ test('a story trypost published is linked instead of imported again', function (
runStoryDiscovery($account, $state);
expect(Post::query()->imported()->exists())->toBeFalse()
- ->and(AnalyticsPublication::query()->sole()->post_platform_id)->toBe($tryPost->id);
+ ->and(AnalyticsPublication::query()->sole()->post_id)->toBe($post->id);
});
test('story metrics are scheduled once however many runs see the story', function () {
@@ -224,6 +214,6 @@ test('a stories permission error does not stop the feed page', function () {
app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);
- expect(PostPlatform::query()->sole()->platform_post_id)->toBe('feed-1')
+ expect(Post::query()->sole()->platform_post_id)->toBe('feed-1')
->and($state->fresh()->status)->toBe(SyncStatus::Complete);
});
diff --git a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php b/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
index 61abf671f..d10dca7f8 100644
--- a/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
+++ b/tests/Feature/Analytics/PersistedPostMetricsReadTest.php
@@ -12,7 +12,6 @@ use App\Mcp\Tools\Post\GetPostMetricsTool;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Support\Facades\DB;
@@ -20,23 +19,18 @@ use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Testing\Fluent\AssertableJson;
-test('web REST and MCP post metrics read the same persisted observation without a provider call', function () {
+test('REST and MCP post metrics read the same persisted observation without a provider call', function () {
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
$access = createApiTestToken();
$user = $access['user'];
$workspace = $access['workspace'];
$account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform_post_id' => '123',
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $user->id, 'platform_post_id' => '123']);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'content_type' => PublicationContentType::Reel,
]);
@@ -52,33 +46,31 @@ test('web REST and MCP post metrics read the same persisted observation without
]);
Http::fake();
- $this->actingAs($user)
- ->getJson(route('app.posts.platforms.metrics', [$post, $destination]))
- ->assertOk()
- ->assertJsonPath('available', true)
- ->assertJsonPath('metrics.reactions.value', 7)
- ->assertJsonPath('metrics.watch_time_milliseconds.value', 180000);
-
$this->withHeaders(['Authorization' => 'Bearer '.$access['plain_token']])
->getJson(route('api.posts.metrics', $post))
->assertOk()
- ->assertJsonPath('platforms.0.metrics.available', true)
- ->assertJsonPath('platforms.0.metrics.metrics.reactions.value', 7)
- ->assertJsonPath('platforms.0.metrics.metrics.watch_time_milliseconds.value', 180000)
- ->assertJsonMissingPath('platforms.0.analytics');
+ ->assertJsonPath('post_id', $post->id)
+ ->assertJsonPath('platform', Platform::Instagram->value)
+ ->assertJsonPath('metrics.available', true)
+ ->assertJsonPath('metrics.metrics.reactions.value', 7)
+ ->assertJsonPath('metrics.metrics.watch_time_milliseconds.value', 180000)
+ ->assertJsonMissingPath('platforms')
+ ->assertJsonMissingPath('analytics');
TryPostServer::actingAs($user)
->tool(GetPostMetricsTool::class, ['post_id' => $post->id])
->assertOk()
->assertStructuredContent(fn (AssertableJson $json) => $json
->where('post_id', $post->id)
- ->where('platforms.0.metrics.available', true)
- ->where('platforms.0.metrics.metrics.reactions.value', 7)
- ->where('platforms.0.metrics.metrics.watch_time_milliseconds.value', 180000)
- ->missing('platforms.0.analytics')
+ ->where('platform_post_id', '123')
+ ->where('metrics.available', true)
+ ->where('metrics.metrics.reactions.value', 7)
+ ->where('metrics.metrics.watch_time_milliseconds.value', 180000)
+ ->missing('platforms')
+ ->missing('analytics')
->etc());
- expect(app(ReadPublicationAnalytics::class)->forPlatform($destination)['snapshot']['reactions_count'])->toBe(7);
+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['snapshot']['reactions_count'])->toBe(7);
Http::assertNothingSent();
});
@@ -86,44 +78,30 @@ test('excluded destinations expose no analytics and a foreign post cannot be rea
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
$access = createApiTestToken();
$account = SocialAccount::factory()->create(['workspace_id' => $access['workspace']->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->published()->create(['workspace_id' => $access['workspace']->id, 'user_id' => $access['user']->id]);
- $destination = PostPlatform::factory()->linkedin()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
-
- $this->actingAs($access['user'])
- ->getJson(route('app.posts.platforms.metrics', [$post, $destination]))
- ->assertOk()
- ->assertJsonPath('unsupported', true)
- ->assertJsonPath('reason', 'platform_not_supported');
+ $post = Post::factory()->forAccount($account)->published()->create(['user_id' => $access['user']->id]);
TryPostServer::actingAs($access['user'])
->tool(GetPostMetricsTool::class, ['post_id' => $post->id])
->assertOk()
->assertStructuredContent(fn (AssertableJson $json) => $json
- ->where('platforms.0.metrics.unsupported', true)
- ->where('platforms.0.metrics.reason', 'platform_not_supported')
+ ->where('metrics.unsupported', true)
+ ->where('metrics.reason', 'platform_not_supported')
->etc());
- $foreignPost = Post::factory()->published()->create();
- $this->actingAs($access['user'])
- ->getJson(route('app.posts.platforms.metrics', [$foreignPost, $destination]))
+ $foreignPost = Post::factory()->linkedin()->published()->create();
+ $this->withHeaders(['Authorization' => 'Bearer '.$access['plain_token']])
+ ->getJson(route('api.posts.metrics', $foreignPost))
->assertNotFound();
});
test('post metrics preserve metric keys and availability from persisted observations', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->threads()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create();
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Threads,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
@@ -133,28 +111,27 @@ test('post metrics preserve metric keys and availability from persisted observat
],
]);
- expect(app(ReadPublicationAnalytics::class)->forPlatform($destination)['metrics']['reactions'])->toEqual([
+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['metrics']['reactions'])->toEqual([
'value' => 9,
'unit' => 'count',
'availability' => 'available',
]);
});
-test('post detail loads all destination observations in bounded queries', function () {
+test('post cards load the observations of every post in bounded queries', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
+ $posts = collect();
foreach (range(1, 3) as $number) {
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->published()->create([
'platform_post_id' => "provider-{$number}",
]);
+ $posts->push($post);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'remote_id' => "provider-{$number}",
]);
@@ -173,7 +150,7 @@ test('post detail loads all destination observations in bounded queries', functi
}
}
- $post = $post->fresh();
+ $posts = $posts->map->fresh();
$reads = [];
DB::listen(function ($query) use (&$reads): void {
if (str_starts_with(strtolower(ltrim($query->sql)), 'select')) {
@@ -181,27 +158,23 @@ test('post detail loads all destination observations in bounded queries', functi
}
});
- $metrics = app(ReadPublicationAnalytics::class)->forPost($post);
+ $metrics = collect(app(ReadPublicationAnalytics::class)->latestForPosts($workspace->id, $posts));
expect($metrics)->toHaveCount(3)
- ->and($metrics->pluck('metrics.snapshot.reactions_count')->sort()->values()->all())->toBe([1, 2, 3])
- ->and($reads)->toHaveCount(3);
+ ->and($metrics->keys()->all())->toBe($posts->pluck('id')->all())
+ ->and($metrics->pluck('snapshot.reactions_count')->sort()->values()->all())->toBe([1, 2, 3])
+ ->and($reads)->toHaveCount(2);
});
test('post metrics derive the engagement rate from the snapshot exposure like the channel reports', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->x()->createQuietly(['workspace_id' => $workspace->id]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->x()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform_post_id' => '1840000000000000000',
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create(['platform_post_id' => '1840000000000000000']);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::X,
'content_type' => PublicationContentType::Text,
]);
@@ -218,7 +191,7 @@ test('post metrics derive the engagement rate from the snapshot exposure like th
],
]);
- $metrics = app(ReadPublicationAnalytics::class)->forPlatform($destination)['metrics'];
+ $metrics = app(ReadPublicationAnalytics::class)->latestFor($post)['metrics'];
expect(data_get($metrics, 'engagement_rate.value'))->toBe(3.5)
->and(data_get($metrics, 'engagement_rate.unit'))->toBe('percent')
@@ -228,18 +201,12 @@ test('post metrics derive the engagement rate from the snapshot exposure like th
test('post metrics leave the engagement rate out when the network reports no exposure', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->mastodon()->createQuietly(['workspace_id' => $workspace->id]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Mastodon,
- 'platform_post_id' => '117304063461175259',
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create(['platform_post_id' => '117304063461175259']);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Mastodon,
'content_type' => PublicationContentType::Text,
]);
@@ -252,5 +219,5 @@ test('post metrics leave the engagement rate out when the network reports no exp
'metrics' => ['engagements' => ['value' => 6, 'unit' => 'count', 'availability' => 'available']],
]);
- expect(app(ReadPublicationAnalytics::class)->forPlatform($destination)['metrics'])->not->toHaveKey('engagement_rate');
+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['metrics'])->not->toHaveKey('engagement_rate');
});
diff --git a/tests/Feature/Analytics/PublicationBackfillJobsTest.php b/tests/Feature/Analytics/PublicationBackfillJobsTest.php
index 710b04001..6b0ed5424 100644
--- a/tests/Feature/Analytics/PublicationBackfillJobsTest.php
+++ b/tests/Feature/Analytics/PublicationBackfillJobsTest.php
@@ -981,7 +981,7 @@ test('a backfill page imports its publications as network posts', function () {
$post = Post::query()->imported()->sole();
expect($post->content)->toBe('From the app')
- ->and($post->postPlatforms()->sole()->platform_post_id)->toBe('native-1');
+ ->and($post->platform_post_id)->toBe('native-1');
});
test('discovery imports a post published since the last run', function () {
@@ -1004,7 +1004,7 @@ test('discovery imports a post published since the last run', function () {
app()->call([new DiscoverAccountPublications($account->id, $discovery->id), 'handle']);
- expect(Post::query()->imported()->sole()->postPlatforms()->sole()->platform_post_id)->toBe('fresh-1');
+ expect(Post::query()->imported()->sole()->platform_post_id)->toBe('fresh-1');
});
test('a page dispatches one media import per imported post', function () {
diff --git a/tests/Feature/Analytics/PublicationMetricsJobsTest.php b/tests/Feature/Analytics/PublicationMetricsJobsTest.php
index c6f5ea042..64e897730 100644
--- a/tests/Feature/Analytics/PublicationMetricsJobsTest.php
+++ b/tests/Feature/Analytics/PublicationMetricsJobsTest.php
@@ -16,7 +16,6 @@ use App\Jobs\Analytics\ScheduleInstagramStoryMetrics;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Analytics\Collectors\Metrics\MastodonPublicationMetricsCollector;
use App\Services\Analytics\Collectors\Metrics\PublicationMetricsCollectorFactory;
@@ -65,19 +64,14 @@ test('TikTok metric job reconciles a public video id before persisting metrics',
$date = CarbonImmutable::parse('2026-09-23 12:00:00', 'UTC');
CarbonImmutable::setTestNow($date);
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
'platform_post_id' => 'v_pub_abc',
]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $postPlatform->id,
+ 'post_id' => $post->id,
'network' => Platform::TikTok->network(),
'platform' => Platform::TikTok,
'platform_user_id' => $account->platform_user_id,
@@ -94,7 +88,7 @@ test('TikTok metric job reconciles a public video id before persisting metrics',
app()->call([(new CollectPublicationMetrics($publication->id, $date->toDateString())), 'handle']);
expect($publication->fresh()->remote_id)->toBe('123456789')
- ->and($postPlatform->fresh()->platform_post_id)->toBe('123456789')
+ ->and($post->fresh()->platform_post_id)->toBe('123456789')
->and($publication->dailySnapshots()->first()->views_count)->toBe(12);
Http::assertSentCount(2);
});
diff --git a/tests/Feature/Analytics/PublicationReconciliationTest.php b/tests/Feature/Analytics/PublicationReconciliationTest.php
index 58c97326e..e6bd3846f 100644
--- a/tests/Feature/Analytics/PublicationReconciliationTest.php
+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php
@@ -8,8 +8,8 @@ use App\Actions\Post\ImportExternalPosts;
use App\Dto\Analytics\DiscoveredPublication;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Analytics\PublicationOrigin;
+use App\Enums\Post\PublishStatus as Status;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
use App\Enums\SocialAccount\Platform;
use App\Events\PostDeleted;
use App\Jobs\Analytics\SyncTryPostPublication as SyncTryPostPublicationJob;
@@ -17,7 +17,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Carbon\CarbonImmutable;
@@ -30,22 +29,22 @@ beforeEach(function () {
});
test('external discovery followed by TryPost sync converges on one TryPost publication', function () {
- [$account, $postPlatform] = publicationFixture('remote-1');
+ [$account, $post] = publicationFixture('remote-1');
$upsert = app(UpsertAnalyticsPublication::class);
$upsert->external($account, discoveredPublication('remote-1'));
- app(SyncTryPostPublication::class)->handle($postPlatform);
+ app(SyncTryPostPublication::class)->handle($post);
$publication = AnalyticsPublication::sole();
expect($publication->origin)->toBe(PublicationOrigin::TryPost)
- ->and($publication->post_platform_id)->toBe($postPlatform->id)
+ ->and($publication->post_id)->toBe($post->id)
->and($publication->provider_published_at?->toISOString())->toBe('2026-09-20T12:00:00.000000Z');
});
test('TryPost sync followed by external discovery preserves TryPost ownership', function () {
- [$account, $postPlatform] = publicationFixture('remote-1');
+ [$account, $post] = publicationFixture('remote-1');
- app(SyncTryPostPublication::class)->handle($postPlatform);
+ app(SyncTryPostPublication::class)->handle($post);
app(UpsertAnalyticsPublication::class)->external($account, discoveredPublication(
providerPostId: 'remote-1',
excerpt: 'Provider copy',
@@ -53,7 +52,7 @@ test('TryPost sync followed by external discovery preserves TryPost ownership',
$publication = AnalyticsPublication::sole();
expect($publication->origin)->toBe(PublicationOrigin::TryPost)
- ->and($publication->post_platform_id)->toBe($postPlatform->id)
+ ->and($publication->post_id)->toBe($post->id)
->and($publication->excerpt)->toBe('Provider copy');
});
@@ -69,15 +68,10 @@ test('duplicate provider pages are idempotent', function () {
test('TikTok public video id merges a provisional TryPost post with earlier discovery and snapshots', function () {
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
'platform_post_id' => 'v_pub_provisional',
]);
- $provisional = app(SyncTryPostPublication::class)->handle($postPlatform);
+ $provisional = app(SyncTryPostPublication::class)->handle($post);
$discovered = app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(
providerPostId: '123456789',
publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),
@@ -104,7 +98,7 @@ test('TikTok public video id merges a provisional TryPost post with earlier disc
->and($provisional->fresh()->origin)->toBe(PublicationOrigin::TryPost)
->and(AnalyticsPublicationDailySnapshot::query()->count())->toBe(1)
->and($provisional->dailySnapshots()->sole()->views_count)->toBe(12)
- ->and($postPlatform->fresh()->platform_post_id)->toBe('123456789');
+ ->and($post->fresh()->platform_post_id)->toBe('123456789');
app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(
providerPostId: '123456789',
@@ -117,15 +111,10 @@ test('TikTok public video id merges a provisional TryPost post with earlier disc
test('TikTok public video id replaces a post imported from that video with the TryPost post', function () {
Event::fake([PostDeleted::class]);
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
'platform_post_id' => 'v_pub_provisional',
]);
- $provisional = app(SyncTryPostPublication::class)->handle($postPlatform);
+ $provisional = app(SyncTryPostPublication::class)->handle($post);
$discovered = app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(
providerPostId: '123456789',
publishedAt: now()->subDay()->toImmutable(),
@@ -145,9 +134,9 @@ test('TikTok public video id replaces a post imported from that video with the T
app(UpsertAnalyticsPublication::class)->reconcileRemoteId($provisional, '123456789');
expect(AnalyticsPublication::query()->sole()->id)->toBe($provisional->id)
- ->and($provisional->fresh()->post_platform_id)->toBe($postPlatform->id)
+ ->and($provisional->fresh()->post_id)->toBe($post->id)
->and($provisional->dailySnapshots()->sole()->views_count)->toBe(12)
- ->and($postPlatform->fresh()->platform_post_id)->toBe('123456789')
+ ->and($post->fresh()->platform_post_id)->toBe('123456789')
->and(Post::query()->imported()->exists())->toBeFalse()
->and(Post::query()->sole()->id)->toBe($post->id)
->and(Media::query()->whereKey($media->id)->exists())->toBeFalse();
@@ -159,11 +148,7 @@ test('TikTok public video id replaces a post imported from that video with the T
test('TikTok public id owned by another TryPost post is still refused', function () {
$account = SocialAccount::factory()->create(['platform' => Platform::TikTok]);
- $targets = collect(['v_pub_provisional', '123456789'])->map(fn (string $remoteId): PostPlatform => PostPlatform::factory()->published()->create([
- 'post_id' => Post::factory()->create(['workspace_id' => $account->workspace_id])->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $targets = collect(['v_pub_provisional', '123456789'])->map(fn (string $remoteId): Post => Post::factory()->forAccount($account, ContentType::TikTokVideo)->published()->create([
'platform_post_id' => $remoteId,
]));
$provisional = app(SyncTryPostPublication::class)->handle($targets->first());
@@ -218,17 +203,17 @@ test('the same provider post id remains separate by account and workspace', func
});
test('queued TryPost sync survives social account deletion after dispatch', function () {
- [$account, $postPlatform] = publicationFixture();
- $postPlatform->update(['status' => Status::Pending]);
+ [$account, $post] = publicationFixture();
+ $post->forceFill(['publish_status' => Status::Pending])->save();
$queuedJob = null;
Queue::fake();
- $postPlatform->markAsPublished('remote-1', 'https://x.com/example/status/remote-1');
+ $post->markPublicationPublished('remote-1', 'https://x.com/example/status/remote-1');
- Queue::assertPushed(SyncTryPostPublicationJob::class, function (SyncTryPostPublicationJob $job) use (&$queuedJob, $account, $postPlatform): bool {
+ Queue::assertPushed(SyncTryPostPublicationJob::class, function (SyncTryPostPublicationJob $job) use (&$queuedJob, $account, $post): bool {
$queuedJob = $job;
- return $job->postPlatformId === $postPlatform->id
+ return $job->postId === $post->id
&& $job->identity->socialAccountId === $account->id
&& $job->queue === 'analytics'
&& $job->afterCommit === true;
@@ -241,26 +226,21 @@ test('queued TryPost sync survives social account deletion after dispatch', func
expect($publication->social_account_id)->toBeNull()
->and($publication->social_account_key)->toBe($account->id)
->and($publication->origin)->toBe(PublicationOrigin::TryPost)
- ->and($publication->post_platform_id)->toBe($postPlatform->id);
+ ->and($publication->post_id)->toBe($post->id);
});
-/** @return array{SocialAccount, PostPlatform} */
+/** @return array{SocialAccount, Post} */
function publicationFixture(?string $providerPostId = null): array
{
$account = SocialAccount::factory()->x()->create();
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
+ $post = Post::factory()->forAccount($account)->published()->create([
'content' => '<p>TryPost copy</p>',
- ]);
- $postPlatform = PostPlatform::factory()->x()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
'platform_post_id' => $providerPostId ?? 'remote-1',
'platform_url' => 'https://x.com/example/status/remote-1',
'published_at' => CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),
]);
- return [$account, $postPlatform];
+ return [$account, $post];
}
function discoveredPublication(
@@ -280,8 +260,8 @@ function discoveredPublication(
}
test('a less-than sign typed in a TryPost post stays in its analytics excerpt', function () {
- [, $postPlatform] = publicationFixture('remote-lt');
- $postPlatform->post->update(['content' => 'I <3 TryPost and price < 10']);
+ [, $post] = publicationFixture('remote-lt');
+ $post->update(['content' => 'I <3 TryPost and price < 10']);
- expect(app(SyncTryPostPublication::class)->handle($postPlatform->fresh())->excerpt)->toBe('I <3 TryPost and price < 10');
+ expect(app(SyncTryPostPublication::class)->handle($post->fresh())->excerpt)->toBe('I <3 TryPost and price < 10');
});
diff --git a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php
index 521824d57..77d8d53af 100644
--- a/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php
+++ b/tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php
@@ -18,7 +18,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\AnalyticsSyncState;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Support\Analytics\PeriodBuckets;
@@ -145,13 +144,9 @@ test('workspace report keeps accounts separate and aggregates only latest normal
test('top posts include the source post id for TryPost publications', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create();
$publication = analyticsReportPublication($account, '2026-09-05 10:00:00', 5, 1, 6, 100);
- $publication->update(['post_platform_id' => $destination->id]);
+ $publication->update(['post_id' => $post->id]);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
@@ -324,16 +319,12 @@ test('publication detail uses the latest persisted metric snapshot without provi
Http::fake();
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
- $post = Post::factory()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create();
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
'content_type' => PublicationContentType::Reel,
]);
@@ -354,7 +345,7 @@ test('publication detail uses the latest persisted metric snapshot without provi
],
]);
- $detail = app(ReadPublicationAnalytics::class)->latestForPostPlatform($destination);
+ $detail = app(ReadPublicationAnalytics::class)->latestFor($post);
expect($detail['available'])->toBeTrue()
->and($detail['publication']['content_type'])->toBe('reel')
@@ -367,21 +358,17 @@ test('publication detail uses the latest persisted metric snapshot without provi
test('publication detail remains scoped to the post workspace and excludes unsupported networks', function () {
$workspace = Workspace::factory()->create();
$foreign = analyticsReportAccount(Workspace::factory()->create(), Platform::Instagram);
- $post = Post::factory()->create(['workspace_id' => $workspace->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $foreign->id,
- ]);
+ $post = Post::factory()->forAccount($foreign)->published()->create(['workspace_id' => $workspace->id]);
AnalyticsPublication::factory()->create([
'workspace_id' => $foreign->workspace_id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
]);
- expect(app(ReadPublicationAnalytics::class)->latestForPostPlatform($destination)['available'])->toBeFalse();
+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['available'])->toBeFalse();
- $destination->update(['platform' => Platform::LinkedIn]);
- expect(app(ReadPublicationAnalytics::class)->latestForPostPlatform($destination)['reason'])->toBe('platform_not_supported');
+ $post->update(['platform' => Platform::LinkedIn]);
+ expect(app(ReadPublicationAnalytics::class)->latestFor($post)['reason'])->toBe('platform_not_supported');
});
test('external YouTube upload stays a video and not a short without authoritative metadata', function () {
diff --git a/tests/Feature/Api/ApiRouteSweepTest.php b/tests/Feature/Api/ApiRouteSweepTest.php
index 0d2df442e..c86c1186c 100644
--- a/tests/Feature/Api/ApiRouteSweepTest.php
+++ b/tests/Feature/Api/ApiRouteSweepTest.php
@@ -72,19 +72,12 @@ function apiSweepRecords(Workspace $workspace): array
'posting_schedule' => collect(range(0, 6))->map(fn (int $day): array => ['day' => $day, 'enabled' => true, 'times' => ['09:00']])->all(),
]);
$slots = $channel->posting_schedule->nextSlots(now()->addMinute(), 'UTC', 2);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($channel, ContentType::LinkedInPost)->create([
'status' => Status::Scheduled,
'content' => 'Untouched',
'schedule_mode' => 'queue',
'scheduled_at' => $slots[0],
]);
- $post->postPlatforms()->create([
- 'social_account_id' => $channel->id,
- 'platform' => 'linkedin',
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- ]);
$webhook = Webhook::factory()->create(['workspace_id' => $workspace->id]);
return [
@@ -185,7 +178,6 @@ function apiSweepSnapshot(array $records, string $apiTokenId): array
->filter(fn (mixed $record): bool => is_object($record))
->map(fn (object $record): ?array => $record->fresh()?->makeVisible($record->getHidden())->attributesToArray())
->all(),
- 'post_platforms' => $records['post']->postPlatforms()->get()->toArray(),
'post_media' => $records['post']->ownedMedia()->count(),
'apiToken' => AccessToken::query()->find($apiTokenId)?->attributesToArray(),
];
@@ -283,19 +275,13 @@ test('every api route that names a record answers 404 for one of another workspa
test('a malformed id inside a body is a validation error, never a database error', function () {
$result = createApiTestToken();
$records = apiSweepRecords($result['workspace']);
- $draft = Post::factory()->draft()->create(['workspace_id' => $result['workspace']->id]);
- $target = $draft->postPlatforms()->create([
- 'social_account_id' => $records['channel']->id,
- 'platform' => 'linkedin',
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- ]);
+ $draft = Post::factory()->forAccount($records['channel'], ContentType::LinkedInPost)->draft()->create();
$tomorrow = now()->addDay()->toIso8601String();
$calls = [
- 'post create' => ['POST', route('api.posts.store'), ['content' => 'Hello', 'platforms' => [['social_account_id' => 'not-a-uuid', 'content_type' => 'linkedin_post']]], 'platforms.0.social_account_id'],
- 'post create scheduled' => ['POST', route('api.posts.store'), ['content' => 'Hello', 'status' => 'scheduled', 'scheduled_at' => $tomorrow, 'platforms' => [['social_account_id' => 'not-a-uuid']]], 'platforms.0.social_account_id'],
- 'post update' => ['PUT', route('api.posts.update', $draft), ['status' => 'draft', 'platforms' => [['id' => 'not-a-uuid', 'content_type' => 'linkedin_post']]], 'platforms.0.id'],
- 'post update scheduled' => ['PUT', route('api.posts.update', $draft), ['status' => 'scheduled', 'scheduled_at' => $tomorrow, 'platforms' => [['id' => 'not-a-uuid']]], 'platforms.0.id'],
+ 'post create' => ['POST', route('api.posts.store'), ['content' => 'Hello', 'social_account_id' => 'not-a-uuid', 'content_type' => 'linkedin_post'], 'social_account_id'],
+ 'post create scheduled' => ['POST', route('api.posts.store'), ['content' => 'Hello', 'status' => 'scheduled', 'scheduled_at' => $tomorrow, 'social_account_id' => 'not-a-uuid'], 'social_account_id'],
+ 'post update' => ['PUT', route('api.posts.update', $draft), ['status' => 'draft', 'label_ids' => ['not-a-uuid']], 'label_ids.0'],
+ 'post update scheduled' => ['PUT', route('api.posts.update', $draft), ['status' => 'scheduled', 'scheduled_at' => $tomorrow, 'label_ids' => ['not-a-uuid']], 'label_ids.0'],
'repurpose update' => ['PUT', route('api.repurposes.update', $records['repurpose']), ['destinations' => [['social_account_id' => 'not-a-uuid', 'content_type' => 'linkedin_post']]], 'destinations.0.social_account_id'],
];
@@ -307,7 +293,7 @@ test('a malformed id inside a body is a validation error, never a database error
->assertJsonValidationErrors([$field]);
}
- expect($target->fresh()->enabled)->toBeTrue()
+ expect($draft->fresh()->social_account_id)->toBe($records['channel']->id)
->and($draft->fresh()->content)->toBe($draft->content);
});
diff --git a/tests/Feature/Api/InlineMediaShapeTest.php b/tests/Feature/Api/InlineMediaShapeTest.php
index 79985dcf8..2d14ae69c 100644
--- a/tests/Feature/Api/InlineMediaShapeTest.php
+++ b/tests/Feature/Api/InlineMediaShapeTest.php
@@ -11,7 +11,6 @@ use App\Mcp\Tools\Post\CreatePostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -43,10 +42,7 @@ function inlineMediaUpload(object $test): Media
function inlineMediaPost(object $test): Post
{
- $post = Post::factory()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $test->channel->id, 'enabled' => true]);
-
- return $post;
+ return Post::factory()->forAccount($test->channel)->create(['user_id' => $test->user->id]);
}
function inlineMediaDestinations(object $test): array
@@ -68,7 +64,8 @@ test('an upload token moves to the post and is spent', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Token',
'media' => [['upload_token' => $upload->upload_token]],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertCreated();
$post = Post::query()->sole();
@@ -80,7 +77,8 @@ test('an upload token moves to the post and is spent', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Again',
'media' => [['upload_token' => $upload->upload_token]],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertUnprocessable()->assertJsonValidationErrors(['media.0.upload_token' => __('posts.errors.media_expired')]);
expect(Post::query()->count())->toBe(1);
@@ -148,7 +146,7 @@ test('a batch gives each destination its own alt text and the shared one where i
};
$altText = fn (SocialAccount $channel): ?string => data_get(Post::query()
- ->whereHas('postPlatforms', fn ($query) => $query->where('social_account_id', $channel->id))
+ ->where('social_account_id', $channel->id)
->sole()->media, '0.meta.alt_text');
expect($altText($this->channels[0]))->toBe('First channel description')
@@ -164,7 +162,8 @@ test('an id of another posts media is copied and the other post keeps its file',
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Copy',
'media' => [['id' => $source->id]],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertCreated();
$copy = Post::query()->whereKeyNot($other->id)->sole()->ownedMedia()->sole();
@@ -179,7 +178,8 @@ test('an item with two references or the old snapshot keys fails the shape rule'
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Shape',
'media' => [$item],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertUnprocessable()->assertJsonValidationErrors(['media.0' => __('posts.errors.media_item_shape')]);
})->with([
'id and url' => [['id' => '6f3c0a4e-0000-4000-8000-000000000000', 'url' => 'https://93.184.216.34/a.png']],
@@ -194,7 +194,8 @@ test('an old snapshot with a url downloads that url instead of trusting the path
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Snapshot',
'media' => [['path' => 'medias/forged.jpg', 'url' => 'https://93.184.216.34/photo.png']],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertCreated();
Http::assertSentCount(1);
@@ -204,14 +205,14 @@ test('an old snapshot with a url downloads that url instead of trusting the path
test('every create and update entry point, REST and MCP, enforces the same shape error', function (string $entry) {
$post = inlineMediaPost($this);
$bad = [['id' => '6f3c0a4e-0000-4000-8000-000000000000', 'url' => 'https://93.184.216.34/a.png']];
- $platforms = [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']];
+ $destination = ['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post'];
match ($entry) {
- 'rest create' => $this->withHeaders($this->headers)->postJson(route('api.posts.store'), ['media' => $bad, 'platforms' => $platforms])->assertJsonValidationErrors(['media.0']),
+ 'rest create' => $this->withHeaders($this->headers)->postJson(route('api.posts.store'), ['media' => $bad, ...$destination])->assertJsonValidationErrors(['media.0']),
'rest batch' => $this->withHeaders($this->headers)->postJson(route('api.posts.batch.store'), ['status' => 'draft', 'media' => $bad, 'destinations' => inlineMediaDestinations($this)])->assertJsonValidationErrors(['media.0']),
'rest batch override' => $this->withHeaders($this->headers)->postJson(route('api.posts.batch.store'), ['status' => 'draft', 'destinations' => [[...inlineMediaDestinations($this)[0], 'media' => $bad]]])->assertJsonValidationErrors(['destinations.0.media.0']),
'rest update' => $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), ['status' => 'draft', 'media' => $bad])->assertJsonValidationErrors(['media.0']),
- 'mcp create' => TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, ['media' => $bad, 'platforms' => $platforms])->assertHasErrors([__('posts.errors.media_item_shape')]),
+ 'mcp create' => TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, ['media' => $bad, ...$destination])->assertHasErrors([__('posts.errors.media_item_shape')]),
'mcp batch' => TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, ['status' => 'draft', 'media' => $bad, 'destinations' => inlineMediaDestinations($this)])->assertHasErrors([__('posts.errors.media_item_shape')]),
'mcp update' => TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, 'media' => $bad])->assertHasErrors([__('posts.errors.media_item_shape')]),
};
@@ -228,7 +229,8 @@ test('the mcp tools accept the three shapes', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'media' => [['upload_token' => $upload->upload_token], ['id' => $source->id], ['url' => 'https://93.184.216.34/photo.png', 'alt' => 'Alt']],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertOk();
$post = Post::query()->whereKeyNot($other->id)->sole();
@@ -288,16 +290,16 @@ test('another workspace\'s upload token or media id is rejected on every entry p
$item = $reference === 'token' ? ['upload_token' => $upload->upload_token] : ['id' => $owned->id];
$key = $reference === 'token' ? 'upload_token' : 'id';
$expected = $reference === 'token' ? __('posts.errors.media_expired') : __('validation.exists', ['attribute' => 'media']);
- $platforms = [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']];
+ $destination = ['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post'];
$before = Media::query()->count();
$postsBefore = Post::query()->count();
match ($entry) {
- 'rest create' => $this->withHeaders($this->headers)->postJson(route('api.posts.store'), ['media' => [$item], 'platforms' => $platforms])->assertJsonValidationErrors(["media.0.{$key}" => $expected]),
+ 'rest create' => $this->withHeaders($this->headers)->postJson(route('api.posts.store'), ['media' => [$item], ...$destination])->assertJsonValidationErrors(["media.0.{$key}" => $expected]),
'rest batch' => $this->withHeaders($this->headers)->postJson(route('api.posts.batch.store'), ['status' => 'draft', 'media' => [$item], 'destinations' => inlineMediaDestinations($this)])->assertJsonValidationErrors(["media.0.{$key}" => $expected]),
'rest update' => $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), ['status' => 'draft', 'media' => [$item]])->assertJsonValidationErrors(["media.0.{$key}" => $expected]),
'rest attach' => $this->withHeaders($this->headers)->postJson(route('api.posts.attach-media-from-upload', $post), ['upload_token' => $upload->upload_token])->assertJsonValidationErrors(['upload_token' => __('posts.errors.media_expired')]),
- 'mcp create' => TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, ['media' => [$item], 'platforms' => $platforms])->assertHasErrors([$expected]),
+ 'mcp create' => TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, ['media' => [$item], ...$destination])->assertHasErrors([$expected]),
'mcp batch' => TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, ['status' => 'draft', 'media' => [$item], 'destinations' => inlineMediaDestinations($this)])->assertHasErrors([$expected]),
'mcp update' => TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, 'media' => [$item]])->assertHasErrors([$expected]),
'mcp attach' => TryPostServer::actingAs($this->user)->tool(AttachMediaFromUploadTool::class, ['post_id' => $post->id, 'upload_token' => $upload->upload_token])->assertHasErrors([__('posts.errors.media_expired')]),
@@ -344,7 +346,8 @@ test('a token consumed by a concurrent save between hosting and saving fails wit
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Loser',
'media' => [['upload_token' => $upload->upload_token]],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertUnprocessable()->assertJsonValidationErrors(['media.0' => __('posts.errors.media_expired')]);
expect(Post::query()->where('content', 'Loser')->exists())->toBeFalse()
@@ -354,7 +357,8 @@ test('a token consumed by a concurrent save between hosting and saving fails wit
test('a media object instead of a list is refused', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'media' => ['b' => ['url' => 'https://93.184.216.34/a.png'], 'a' => ['url' => 'https://93.184.216.34/b.png']],
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => 'linkedin_post',
])->assertUnprocessable()->assertJsonValidationErrors(['media']);
});
diff --git a/tests/Feature/Api/PostApiPlatformMetaTest.php b/tests/Feature/Api/PostApiPlatformMetaTest.php
index e76b24807..d809b0b4d 100644
--- a/tests/Feature/Api/PostApiPlatformMetaTest.php
+++ b/tests/Feature/Api/PostApiPlatformMetaTest.php
@@ -11,7 +11,6 @@ use App\Enums\TikTok\PrivacyLevel;
use App\Jobs\PublishPost;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Queue;
@@ -22,33 +21,32 @@ it('youtube description survives create read update omission and clear', functio
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
$response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Short title',
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::YouTubeShort->value,
- 'meta' => ['description' => $description],
- ]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
])->assertCreated();
$post = Post::findOrFail($response->json('id'));
- $platform = $post->postPlatforms()->where('social_account_id', $account->id)->sole();
- expect($platform->meta)->toEqual(['description' => $description]);
- $read = $this->withHeaders($this->headers)->getJson(route('api.posts.show', $post))->assertOk();
- expect(collect($read->json('platforms'))->firstWhere('id', $platform->id)['meta']['description'])->toBe($description);
+ expect($post->social_account_id)->toBe($account->id)
+ ->and($post->meta)->toEqual(['description' => $description]);
+ $this->withHeaders($this->headers)->getJson(route('api.posts.show', $post))
+ ->assertOk()
+ ->assertJsonPath('meta.description', $description);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'meta' => ['description' => str_repeat('é', 2501)],
- ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.description');
- expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.description');
+ expect(data_get($post->fresh()->meta, 'description'))->toBe($description);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'meta' => [],
])->assertOk();
- expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ expect(data_get($post->fresh()->meta, 'description'))->toBe($description);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'meta' => ['description' => null],
])->assertOk();
- expect(data_get($platform->fresh()->meta, 'description'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'description'))->toBeNull();
})->with([
'multiline description' => ["Full description\nhttps://example.com\n#video"],
'programming text' => ["if (a < b && c > d) {}\n<p>Text about HTML</p>"],
@@ -59,12 +57,10 @@ it('youtube description rejects invalid API create input', function (string $des
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Short title',
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::YouTubeShort->value,
- 'meta' => ['description' => $description],
- ]],
- ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.description');
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.description');
})->with([
'multibyte overflow' => [str_repeat('é', 2501)],
'ascii overflow' => [str_repeat('a', 5001)],
@@ -73,8 +69,7 @@ it('youtube description rejects invalid API create input', function (string $des
it('youtube description checks effective API metadata before scheduling or publishing', function (string $patch, bool $allowed, string $status) {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'content' => 'Short title',
'status' => PostStatus::Draft,
@@ -86,11 +81,6 @@ it('youtube description checks effective API metadata before scheduling or publi
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
- ]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => ['description' => str_repeat('a', 5001)],
]);
$data = [
@@ -112,7 +102,8 @@ it('youtube description checks effective API metadata before scheduling or publi
Queue::assertPushed(PublishPost::class);
}
} else {
- $response->assertUnprocessable()->assertJsonValidationErrors(($data['meta'] ?? []) !== [] ? 'platforms.0.meta.description' : 'destinations.0.meta.description');
+ $response->assertUnprocessable();
+ expect(array_keys($response->json('errors')))->toBe(['meta.description']);
expect($post->fresh()->status)->toBe(PostStatus::Draft);
Queue::assertNotPushed(PublishPost::class);
}
@@ -142,19 +133,17 @@ it('persists Discord channel, mentions and embeds meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Hello Discord',
- 'platforms' => [[
- 'social_account_id' => $this->discordAccount->id,
- 'content_type' => ContentType::DiscordMessage->value,
- 'meta' => [
- 'channel_id' => '444555666',
- 'mentions' => [['token' => '@everyone', 'label' => '@everyone']],
- 'embeds' => [['title' => 'Release', 'color' => '#5865F2']],
- ],
- ]],
+ 'social_account_id' => $this->discordAccount->id,
+ 'content_type' => ContentType::DiscordMessage->value,
+ 'meta' => [
+ 'channel_id' => '444555666',
+ 'mentions' => [['token' => '@everyone', 'label' => '@everyone']],
+ 'embeds' => [['title' => 'Release', 'color' => '#5865F2']],
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $this->discordAccount->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $this->discordAccount->id)->sole()->meta;
// Assert nested keys survive validated() — the exact stripping bug this PR fixes.
expect(data_get($meta, 'channel_id'))->toBe('444555666')
@@ -170,23 +159,20 @@ it('persists the LinkedIn document_title meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Check our latest deck',
- 'platforms' => [[
- 'social_account_id' => $linkedin->id,
- 'content_type' => ContentType::LinkedInPost->value,
- 'meta' => ['document_title' => 'Q2 Report'],
- ]],
+ 'social_account_id' => $linkedin->id,
+ 'content_type' => ContentType::LinkedInPost->value,
+ 'meta' => ['document_title' => 'Q2 Report'],
])
->assertCreated();
- expect(PostPlatform::where('social_account_id', $linkedin->id)->sole()->meta['document_title'])->toBe('Q2 Report');
+ expect(Post::where('social_account_id', $linkedin->id)->sole()->meta['document_title'])->toBe('Q2 Report');
});
it('publishes a LinkedIn document post that has a PDF', function () {
Queue::fake();
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'content' => 'Our latest deck',
'media' => [[
@@ -194,15 +180,11 @@ it('publishes a LinkedIn document post that has a PDF', function () {
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
]],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertOk();
@@ -211,44 +193,34 @@ it('publishes a LinkedIn document post that has a PDF', function () {
it('rejects publishing a LinkedIn post that mixes a PDF with an image', function () {
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'media' => [
['id' => 'doc-1', 'path' => 'medias/deck.pdf', 'url' => 'https://example.com/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf'],
['id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg'],
],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('does not reject a Bluesky post whose stored video is a MOV', function () {
Queue::fake();
$bluesky = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Bluesky]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($bluesky, ContentType::BlueskyPost)->create([
'user_id' => $this->user->id,
'media' => [[
'id' => 'vid-1', 'path' => 'medias/clip.mov', 'url' => 'https://example.com/clip.mov',
'type' => 'video', 'mime_type' => 'video/quicktime', 'original_filename' => 'clip.mov',
]],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $bluesky->id,
- 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
@@ -260,18 +232,12 @@ it('does not reject a Bluesky post whose stored video is a MOV', function () {
it('rejects unowned media on the legacy single-platform update payload', function () {
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $target = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedin->id,
- 'enabled' => true,
- ]);
+ $post = Post::factory()->forAccount($linkedin)->create(['user_id' => $this->user->id]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'media' => [['id' => (string) Str::uuid()]],
- 'platforms' => [['id' => $target->id]],
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.0.id']);
@@ -282,11 +248,7 @@ it('rejects unowned media on the legacy single-platform update payload', functio
it('rejects publishing when the uploaded video runs past the content type duration cap', function () {
Storage::fake();
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramStory, 'enabled' => true,
- ]);
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramStory)->create(['user_id' => $this->user->id]);
// Minimal MP4: ftyp + moov[mvhd v0, timescale 1, duration 90 s]. The server reads the duration itself.
$mvhd = pack('N', 108).'mvhd'."\0\0\0\0".pack('N', 0).pack('N', 0).pack('N', 1).pack('N', 90).str_repeat("\0", 80);
@@ -300,39 +262,33 @@ it('rejects publishing when the uploaded video runs past the content type durati
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), ['status' => PostStatus::Publishing->value])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.content_type'])
+ ->assertJsonValidationErrors(['content_type'])
->assertJsonFragment(['Video is 1min 30s long, but this post type allows up to 1min.']);
});
it('rejects publishing a LinkedIn post with a GIF', function () {
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'media' => [[
'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/loop.gif',
'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif',
]],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.content_type'])
+ ->assertJsonValidationErrors(['content_type'])
->assertJsonFragment(['This platform does not accept GIF. Remove the GIF or choose a different network.']);
});
it('rejects publishing an Instagram Reel whose stored video exceeds 300 MB', function () {
$instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramReel)->create([
'user_id' => $this->user->id,
'media' => [[
'id' => 'vid-1', 'path' => 'medias/reel.mp4', 'url' => 'https://example.com/reel.mp4',
@@ -340,16 +296,12 @@ it('rejects publishing an Instagram Reel whose stored video exceeds 300 MB', fun
'size' => 900 * 1024 * 1024,
]],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramReel, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), ['status' => PostStatus::Publishing->value])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '900.0 MB']),
+ 'content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '900.0 MB']),
]);
expect($post->fresh()->status)->not->toBe(PostStatus::Publishing);
@@ -359,8 +311,7 @@ it('publishes a valid LinkedIn document without resubmitting content_type', func
Queue::fake();
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'content' => 'Our deck',
'media' => [[
@@ -368,27 +319,19 @@ it('publishes a valid LinkedIn document without resubmitting content_type', func
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
]],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id]],
])
->assertOk();
Queue::assertPushed(PublishPost::class);
});
-it('rejects only the platform that cannot take a PDF in a multi-platform post', function () {
- $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
+it('rejects publishing a PDF to a platform that cannot take one', function () {
$x = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::X]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($x, ContentType::XPost)->create([
'user_id' => $this->user->id,
'content' => 'Deck',
'media' => [[
@@ -396,26 +339,14 @@ it('rejects only the platform that cannot take a PDF in a multi-platform post',
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
]],
]);
- $linkedinPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
- $xPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $x->id,
- 'platform' => Platform::X, 'content_type' => ContentType::XPost, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [
- ['id' => $linkedinPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
- ['id' => $xPlatform->id, 'content_type' => ContentType::XPost->value],
- ],
+ 'content_type' => ContentType::XPost->value,
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.1.content_type'])
- ->assertJsonMissingValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('persists per-platform meta across networks on store', function () {
@@ -435,10 +366,10 @@ it('persists per-platform meta across networks on store', function () {
])
->assertCreated();
- expect(PostPlatform::where('social_account_id', $instagram->id)->sole()->meta['is_ai_generated'])->toBeTrue()
- ->and(PostPlatform::where('social_account_id', $pinterest->id)->sole()->meta['board_id'])->toBe('board-99')
- ->and(PostPlatform::where('social_account_id', $tiktok->id)->sole()->meta['privacy_level'])->toBe(PrivacyLevel::SelfOnly->value)
- ->and(PostPlatform::where('social_account_id', $tiktok->id)->sole()->meta['allow_comments'])->toBeTrue();
+ expect(Post::where('social_account_id', $instagram->id)->sole()->meta['is_ai_generated'])->toBeTrue()
+ ->and(Post::where('social_account_id', $pinterest->id)->sole()->meta['board_id'])->toBe('board-99')
+ ->and(Post::where('social_account_id', $tiktok->id)->sole()->meta['privacy_level'])->toBe(PrivacyLevel::SelfOnly->value)
+ ->and(Post::where('social_account_id', $tiktok->id)->sole()->meta['allow_comments'])->toBeTrue();
});
it('rejects an unknown TikTok privacy level on store', function () {
@@ -447,29 +378,20 @@ it('rejects an unknown TikTok privacy level on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Unknown privacy',
- 'platforms' => [[
- 'social_account_id' => $tiktok->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => ['privacy_level' => 'EVERYONE'],
- ]],
+ 'social_account_id' => $tiktok->id,
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => 'EVERYONE'],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.privacy_level']);
+ ->assertJsonValidationErrors(['meta.privacy_level']);
});
it('allows saving a Discord draft without a channel', function () {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
- 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($this->discordAccount)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
- 'platforms' => [['id' => $platform->id]],
])
->assertOk();
});
@@ -477,93 +399,72 @@ it('allows saving a Discord draft without a channel', function () {
it('rejects publishing without TikTok privacy and Pinterest board', function () {
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
+ $video = [[
+ 'id' => 'video-1', 'type' => 'video', 'path' => 'medias/video.mp4', 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4',
+ ]];
+ $image = [[
+ 'id' => 'image-1', 'type' => 'image', 'path' => 'medias/pin.jpg', 'url' => 'https://example.com/pin.jpg',
+ 'mime_type' => 'image/jpeg', 'original_filename' => 'pin.jpg',
+ ]];
+ $pinterestPost = Post::factory()->forAccount($pinterest)->pinterest()->create(['user_id' => $this->user->id, 'media' => $image, 'meta' => []]);
+ $tiktokPost = Post::factory()->forAccount($tiktok)->tiktok()->create(['user_id' => $this->user->id, 'media' => $video, 'meta' => []]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $post->id, 'social_account_id' => $pinterest->id, 'enabled' => true, 'meta' => [],
- ]);
- $tiktokPlatform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id, 'social_account_id' => $tiktok->id, 'enabled' => true, 'meta' => [],
- ]);
+ $this->withHeaders($this->headers)
+ ->putJson(route('api.posts.update', $pinterestPost), ['status' => PostStatus::Publishing->value])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['meta.board_id']);
$this->withHeaders($this->headers)
- ->putJson(route('api.posts.update', $post), [
- 'status' => PostStatus::Publishing->value,
- 'platforms' => [
- ['id' => $pinterestPlatform->id],
- ['id' => $tiktokPlatform->id],
- ],
- ])
+ ->putJson(route('api.posts.update', $tiktokPost), ['status' => PostStatus::Publishing->value])
->assertUnprocessable()
- ->assertJsonValidationErrors([
- 'platforms.0.meta.board_id',
- 'platforms.1.meta.privacy_level',
- ]);
+ ->assertJsonValidationErrors(['meta.privacy_level']);
});
it('rejects publishing TikTok as self only branded content', function () {
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $tiktokPlatform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id, 'social_account_id' => $tiktok->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($tiktok)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [[
- 'id' => $tiktokPlatform->id,
- 'meta' => [
- 'privacy_level' => PrivacyLevel::SelfOnly->value,
- 'brand_content_toggle' => true,
- ],
- ]],
+ 'meta' => [
+ 'privacy_level' => PrivacyLevel::SelfOnly->value,
+ 'brand_content_toggle' => true,
+ ],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.privacy_level']);
+ ->assertJsonValidationErrors(['meta.privacy_level']);
});
it('rejects publishing a Discord post without a channel', function () {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
- 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($this->discordAccount)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id]],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.channel_id']);
+ ->assertJsonValidationErrors(['meta.channel_id']);
});
it('publishes a Discord post when the channel is set', function () {
Queue::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->discordAccount)->create([
'user_id' => $this->user->id,
'content' => 'Ready for Discord',
- ]);
- $platform = PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
'meta' => [],
]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'meta' => ['channel_id' => '444555666']]],
+ 'meta' => ['channel_id' => '444555666'],
])
->assertOk();
- expect($platform->fresh()->meta['channel_id'])->toBe('444555666');
+ expect($post->fresh()->meta['channel_id'])->toBe('444555666');
Queue::assertPushed(PublishPost::class);
});
@@ -573,19 +474,17 @@ it('persists Pinterest title and link meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Shared caption',
- 'platforms' => [[
- 'social_account_id' => $pinterest->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'title' => 'Pin Title',
- 'link' => 'https://example.com/product',
- ],
- ]],
+ 'social_account_id' => $pinterest->id,
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'title' => 'Pin Title',
+ 'link' => 'https://example.com/product',
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $pinterest->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $pinterest->id)->sole()->meta;
expect(data_get($meta, 'board_id'))->toBe('board-1')
->and(data_get($meta, 'title'))->toBe('Pin Title')
@@ -595,33 +494,24 @@ it('persists Pinterest title and link meta on store', function () {
it('updates Pinterest title and link meta', function () {
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($pinterest)->create([
'user_id' => $this->user->id,
'content' => 'Shared caption',
- ]);
- $platform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pinterest->id,
- 'enabled' => true,
'meta' => ['board_id' => 'board-1'],
]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'meta' => [
- 'board_id' => 'board-1',
- 'title' => 'Updated Title',
- 'link' => 'https://example.com/updated',
- ],
- ]],
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'title' => 'Updated Title',
+ 'link' => 'https://example.com/updated',
+ ],
])
->assertOk();
- $meta = $platform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'title'))->toBe('Updated Title')
->and(data_get($meta, 'link'))->toBe('https://example.com/updated')
@@ -634,19 +524,17 @@ it('rejects invalid Pinterest title and link on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Hello',
- 'platforms' => [[
- 'social_account_id' => $pinterest->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'title' => str_repeat('t', 101),
- 'link' => 'not-a-url',
- ],
- ]],
+ 'social_account_id' => $pinterest->id,
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'title' => str_repeat('t', 101),
+ 'link' => 'not-a-url',
+ ],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.title' => __('posts.form.pinterest.title_max'),
- 'platforms.0.meta.link' => __('posts.form.pinterest.link_invalid'),
+ 'meta.title' => __('posts.form.pinterest.title_max'),
+ 'meta.link' => __('posts.form.pinterest.link_invalid'),
]);
});
@@ -656,33 +544,24 @@ it('rejects non-http Pinterest links', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Hello',
- 'platforms' => [[
- 'social_account_id' => $pinterest->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => ['link' => 'ftp://files.example.com/pin'],
- ]],
+ 'social_account_id' => $pinterest->id,
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => ['link' => 'ftp://files.example.com/pin'],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.link' => __('posts.form.pinterest.link_invalid'),
+ 'meta.link' => __('posts.form.pinterest.link_invalid'),
]);
});
it('rejects scheduling an independent Pinterest draft without a board when settings are omitted', function () {
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
$image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($pinterest, ContentType::PinterestPin)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'A pin',
'media' => [MediaItem::fromMedia($image)->toArray()],
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pinterest->id,
- 'platform' => Platform::Pinterest,
- 'content_type' => ContentType::PinterestPin,
'meta' => [],
]);
@@ -692,7 +571,7 @@ it('rejects scheduling an independent Pinterest draft without a board when setti
'scheduled_at' => now()->addDay()->toIso8601String(),
])
->assertUnprocessable()
- ->assertJsonValidationErrors('destinations.0.meta.board_id');
+ ->assertJsonValidationErrors('meta.board_id');
expect($post->fresh()->status)->toBe(PostStatus::Draft);
});
@@ -701,19 +580,12 @@ it('accepts changing an independent Instagram reel to a feed image during schedu
Storage::fake(null, ['url' => 'https://cdn.example.com']);
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramReel)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Instagram image',
'media' => [MediaItem::fromMedia($image)->toArray()],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramReel,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
@@ -724,7 +596,7 @@ it('accepts changing an independent Instagram reel to a feed image during schedu
->assertOk();
expect($post->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($post->postPlatforms()->sole()->content_type)->toBe(ContentType::InstagramFeed);
+ ->and($post->fresh()->content_type)->toBe(ContentType::InstagramFeed);
});
it('persists Google Business topic_type and offer meta on store', function () {
@@ -733,18 +605,16 @@ it('persists Google Business topic_type and offer meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Big sale this week',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'offer' => ['coupon_code' => 'SAVE10'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'offer' => ['coupon_code' => 'SAVE10'],
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'topic_type'))->toBe('OFFER')
->and(data_get($meta, 'offer.coupon_code'))->toBe('SAVE10');
@@ -756,17 +626,15 @@ it('persists Google Business call_to_action meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Book a table tonight',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'call_to_action' => ['action_type' => 'BOOK', 'url' => 'https://example.com'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'call_to_action' => ['action_type' => 'BOOK', 'url' => 'https://example.com'],
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'call_to_action.action_type'))->toBe('BOOK')
->and(data_get($meta, 'call_to_action.url'))->toBe('https://example.com');
@@ -778,24 +646,22 @@ it('persists Google Business event time meta on store', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Grand opening',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => 'Grand Opening',
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- 'start_time' => '09:00',
- 'end_time' => '17:00',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => 'Grand Opening',
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
+ 'start_time' => '09:00',
+ 'end_time' => '17:00',
],
- ]],
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'event.title'))->toBe('Grand Opening')
->and(data_get($meta, 'event.start_date'))->toBe('2026-09-01')
@@ -810,21 +676,19 @@ it('persists Google Business offer redeem url and terms meta on store', function
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Big sale this week',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'offer' => [
- 'coupon_code' => 'SAVE10',
- 'redeem_online_url' => 'https://example.com/redeem',
- 'terms_conditions' => 'Some terms',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'offer' => [
+ 'coupon_code' => 'SAVE10',
+ 'redeem_online_url' => 'https://example.com/redeem',
+ 'terms_conditions' => 'Some terms',
],
- ]],
+ ],
])
->assertCreated();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'offer.coupon_code'))->toBe('SAVE10')
->and(data_get($meta, 'offer.redeem_online_url'))->toBe('https://example.com/redeem')
@@ -833,79 +697,63 @@ it('persists Google Business offer redeem url and terms meta on store', function
it('rejects a Google Business event title over the api cap on update', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
],
- ]],
+ ],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.event.title' => __('posts.form.google_business.title_max'),
+ 'meta.event.title' => __('posts.form.google_business.title_max'),
]);
});
it('rejects a Google Business event whose end date is before the start on update', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => ['title' => 'Sale', 'start_date' => '2026-09-10', 'end_date' => '2026-09-01'],
- ],
- ]],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => ['title' => 'Sale', 'start_date' => '2026-09-10', 'end_date' => '2026-09-01'],
+ ],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.event.end_date' => __('posts.form.google_business.event_end_date_before_start'),
+ 'meta.event.end_date' => __('posts.form.google_business.event_end_date_before_start'),
]);
});
it('rejects publishing a Google Business post with a GIF', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'media' => [[
'id' => 'gif-1', 'path' => 'medias/loop.gif', 'url' => 'https://example.com/loop.gif',
'type' => 'image', 'mime_type' => 'image/gif', 'original_filename' => 'loop.gif',
]],
]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::GoogleBusinessPost->value]],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.content_type'])
+ ->assertJsonValidationErrors(['content_type'])
->assertJsonFragment(['This platform does not accept GIF. Remove the GIF or choose a different network.']);
});
@@ -915,107 +763,84 @@ it('rejects a Google Business event title over the api cap on store', function (
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Grand opening',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
],
- ]],
+ ],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.event.title' => __('posts.form.google_business.title_max'),
+ 'meta.event.title' => __('posts.form.google_business.title_max'),
]);
});
it('rejects publishing a Google Business offer post without a title', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'meta' => ['topic_type' => 'OFFER', 'event' => ['start_date' => '2026-09-01', 'end_date' => '2026-09-02']],
- ]],
+ 'meta' => ['topic_type' => 'OFFER', 'event' => ['start_date' => '2026-09-01', 'end_date' => '2026-09-02']],
])
->assertUnprocessable()
->assertJsonValidationErrors([
- 'platforms.0.meta.event.title' => __('posts.form.google_business.offer_title_required'),
+ 'meta.event.title' => __('posts.form.google_business.offer_title_required'),
]);
});
it('rejects publishing a Google Business event post without event fields', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [['id' => $platform->id, 'meta' => ['topic_type' => 'EVENT']]],
+ 'meta' => ['topic_type' => 'EVENT'],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.event.title']);
+ ->assertJsonValidationErrors(['meta.event.title']);
});
it('rejects publishing a Google Business offer post without dates', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'meta' => ['topic_type' => 'OFFER', 'event' => ['title' => 'Summer Sale']],
- ]],
+ 'meta' => ['topic_type' => 'OFFER', 'event' => ['title' => 'Summer Sale']],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.event.start_date']);
+ ->assertJsonValidationErrors(['meta.event.start_date']);
});
it('rejects publishing a Google Business event with a same-day end time before start', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => 'Sale',
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-01',
- 'start_time' => '18:00',
- 'end_time' => '09:00',
- ],
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => 'Sale',
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-01',
+ 'start_time' => '18:00',
+ 'end_time' => '09:00',
],
- ]],
+ ],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.event.end_time']);
+ ->assertJsonValidationErrors(['meta.event.end_time']);
});
it('rejects a Google Business GET_OFFER call to action', function () {
@@ -1024,36 +849,28 @@ it('rejects a Google Business GET_OFFER call to action', function () {
$this->withHeaders($this->headers)
->postJson(route('api.posts.store'), [
'content' => 'Sale',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'STANDARD',
- 'call_to_action' => ['action_type' => 'GET_OFFER'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'STANDARD',
+ 'call_to_action' => ['action_type' => 'GET_OFFER'],
+ ],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.call_to_action.action_type']);
+ ->assertJsonValidationErrors(['meta.call_to_action.action_type']);
});
it('rejects publishing a Google Business post with a url-needing cta and no url', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id, 'social_account_id' => $googleBusiness->id, 'enabled' => true, 'meta' => [],
- ]);
+ $post = Post::factory()->forAccount($googleBusiness)->create(['user_id' => $this->user->id, 'meta' => []]);
$this->withHeaders($this->headers)
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Publishing->value,
- 'platforms' => [[
- 'id' => $platform->id,
- 'meta' => ['topic_type' => 'STANDARD', 'call_to_action' => ['action_type' => 'BOOK']],
- ]],
+ 'meta' => ['topic_type' => 'STANDARD', 'call_to_action' => ['action_type' => 'BOOK']],
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.call_to_action.url']);
+ ->assertJsonValidationErrors(['meta.call_to_action.url']);
});
it('persists youtube metadata on store and merges it on update', function () {
@@ -1065,41 +882,44 @@ it('persists youtube metadata on store and merges it on update', function () {
$response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Short title',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => $meta]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => $meta,
])->assertCreated();
$post = Post::findOrFail($response->json('id'));
- $platform = $post->postPlatforms()->sole();
- expect($platform->meta)->toEqual($meta);
+ expect($post->meta)->toEqual($meta);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'meta' => ['privacy_status' => 'unlisted'],
])->assertOk();
- expect($platform->fresh()->meta)->toEqual([...$meta, 'privacy_status' => 'unlisted']);
+ expect($post->fresh()->meta)->toEqual([...$meta, 'privacy_status' => 'unlisted']);
});
it('rejects scheduling a youtube title with angle brackets', function () {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Short', 'status' => PostStatus::Draft,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Short',
+ 'status' => PostStatus::Draft,
'media' => [['id' => 'video-1', 'type' => 'video', 'path' => 'medias/video.mp4', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4']],
]);
- PostPlatform::factory()->youtube()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'enabled' => true]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
'meta' => ['title' => '<script>'],
- ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.title');
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.title');
});
it('requires a youtube title when the post has no text to take it from', function (string $content, array $meta, bool $allowed) {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => $content, 'status' => PostStatus::Draft,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'content' => $content,
+ 'status' => PostStatus::Draft,
'media' => [['id' => 'video-1', 'type' => 'video', 'path' => 'medias/video.mp4', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4']],
]);
- PostPlatform::factory()->youtube()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'enabled' => true]);
$response = $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
@@ -1113,7 +933,7 @@ it('requires a youtube title when the post has no text to take it from', functio
return;
}
- $response->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.meta.title' => __('posts.form.youtube.title_required')]);
+ $response->assertUnprocessable()->assertJsonValidationErrors(['meta.title' => __('posts.form.youtube.title_required')]);
})->with([
'no text and no title' => ['', [], false],
'blank title and no text' => ['', ['title' => ' '], false],
@@ -1127,8 +947,9 @@ it('saves a youtube draft without a title or text', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => '',
'media' => [['id' => 'video-1', 'type' => 'video', 'path' => 'medias/video.mp4', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4']],
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value]],
- ])->assertJsonMissingValidationErrors('destinations.0.meta.title');
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ ])->assertJsonMissingValidationErrors('meta.title');
});
it('persists instagram options', function () {
@@ -1137,9 +958,11 @@ it('persists instagram options', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Reel',
- 'platforms' => [['social_account_id' => $instagram->id, 'content_type' => ContentType::InstagramReel->value, 'meta' => $meta]],
+ 'social_account_id' => $instagram->id,
+ 'content_type' => ContentType::InstagramReel->value,
+ 'meta' => $meta,
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $instagram->id)->sole()->meta)->toEqual($meta);
+ expect(Post::where('social_account_id', $instagram->id)->sole()->meta)->toEqual($meta);
});
it('rejects a youtube title with angle brackets on a draft', function () {
@@ -1147,8 +970,10 @@ it('rejects a youtube title with angle brackets on a draft', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Short title',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['title' => 'a <b>']]],
- ])->assertUnprocessable()->assertJsonValidationErrors('destinations.0.meta.title');
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['title' => 'a <b>'],
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.title');
});
it('stores a numeric youtube category id as a string', function () {
@@ -1156,18 +981,20 @@ it('stores a numeric youtube category id as a string', function () {
$response = $this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Short title',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['category_id' => 27]]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['category_id' => 27],
])->assertCreated();
- $platform = Post::findOrFail($response->json('id'))->postPlatforms()->sole();
+ $post = Post::findOrFail($response->json('id'));
- expect($platform->meta)->toEqual(['category_id' => '27']);
+ expect($post->meta)->toEqual(['category_id' => '27']);
- $this->withHeaders($this->headers)->putJson(route('api.posts.update', $platform->post_id), [
+ $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post->id), [
'status' => PostStatus::Draft->value,
'meta' => ['category_id' => 10],
])->assertOk();
- expect($platform->fresh()->meta['category_id'])->toBe('10');
+ expect($post->fresh()->meta['category_id'])->toBe('10');
});
it('persists a dropped link preview', function () {
@@ -1175,10 +1002,12 @@ it('persists a dropped link preview', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Read https://example.com/article',
- 'platforms' => [['social_account_id' => $facebook->id, 'content_type' => ContentType::FacebookPost->value, 'meta' => ['link_preview' => false]]],
+ 'social_account_id' => $facebook->id,
+ 'content_type' => ContentType::FacebookPost->value,
+ 'meta' => ['link_preview' => false],
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $facebook->id)->sole()->meta)->toEqual(['link_preview' => false]);
+ expect(Post::where('social_account_id', $facebook->id)->sole()->meta)->toEqual(['link_preview' => false]);
});
it('rejects a non-boolean link preview', function () {
@@ -1186,23 +1015,26 @@ it('rejects a non-boolean link preview', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Read https://example.com/article',
- 'platforms' => [['social_account_id' => $facebook->id, 'content_type' => ContentType::FacebookPost->value, 'meta' => ['link_preview' => 'nope']]],
+ 'social_account_id' => $facebook->id,
+ 'content_type' => ContentType::FacebookPost->value,
+ 'meta' => ['link_preview' => 'nope'],
])->assertUnprocessable();
});
it('rejects scheduling a threads ghost post that carries media', function () {
$threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Boo', 'status' => PostStatus::Draft,
+ $post = Post::factory()->forAccount($threads)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Boo',
+ 'status' => PostStatus::Draft,
'media' => [['id' => 'm', 'type' => 'image', 'path' => 'medias/m.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']],
]);
- $platform = PostPlatform::factory()->threads()->create(['post_id' => $post->id, 'social_account_id' => $threads->id, 'enabled' => true]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::ThreadsGhostPost->value]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.content_type' => __('posts.form.warnings.text_only')]);
+ 'content_type' => ContentType::ThreadsGhostPost->value,
+ ])->assertUnprocessable()->assertJsonValidationErrors(['content_type' => __('posts.form.warnings.text_only')]);
});
it('persists a threads topic tag and rejects a dotted one', function () {
@@ -1210,19 +1042,25 @@ it('persists a threads topic tag and rejects a dotted one', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => 'laravel']]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => 'laravel'],
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => 'laravel']);
+ expect(Post::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => 'laravel']);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => 'web.dev']]],
- ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.topic_tag');
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => 'web.dev'],
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.topic_tag');
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => str_repeat('a', 51)]]],
- ])->assertUnprocessable()->assertJsonValidationErrors('platforms.0.meta.topic_tag');
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => str_repeat('a', 51)],
+ ])->assertUnprocessable()->assertJsonValidationErrors('meta.topic_tag');
});
it('rejects scheduling an instagram caption with more than five hashtags', function () {
@@ -1232,7 +1070,8 @@ it('rejects scheduling an instagram caption with more than five hashtags', funct
'content' => 'Launch #a #b #c #d #e #f',
'status' => 'scheduled',
'scheduled_at' => now()->addHour()->toIso8601String(),
- 'platforms' => [['social_account_id' => $instagram->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'social_account_id' => $instagram->id,
+ 'content_type' => ContentType::InstagramFeed->value,
])->assertUnprocessable();
expect(collect($response->json('errors'))->flatten()->implode(' '))
@@ -1241,8 +1080,7 @@ it('rejects scheduling an instagram caption with more than five hashtags', funct
it('schedules a stored instagram story with more than five hashtags', function () {
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramStory)->create([
'user_id' => $this->user->id,
'content' => 'Launch #a #b #c #d #e #f',
'status' => PostStatus::Draft,
@@ -1251,15 +1089,10 @@ it('schedules a stored instagram story with more than five hashtags', function (
'mime_type' => 'video/mp4', 'original_filename' => 'story.mp4',
]],
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramStory, 'enabled' => true,
- ]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
- 'platforms' => [['id' => $platform->id]],
])->assertOk();
expect($post->fresh()->status)->toBe(PostStatus::Scheduled);
@@ -1268,23 +1101,23 @@ it('schedules a stored instagram story with more than five hashtags', function (
it('persists a mastodon content warning and counts it toward the limit when scheduling', function () {
$mastodon = SocialAccount::factory()->mastodon()->create(['workspace_id' => $this->workspace->id]);
$limit = Platform::Mastodon->maxContentLength();
- $platform = fn (string $warning): array => [[
+ $destination = fn (string $warning): array => [
'social_account_id' => $mastodon->id,
'content_type' => ContentType::MastodonPost->value,
'meta' => ['spoiler_text' => $warning],
- ]];
+ ];
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Toot',
- 'platforms' => $platform('CW'),
+ ...$destination('CW'),
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['spoiler_text' => 'CW']);
+ expect(Post::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['spoiler_text' => 'CW']);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => str_repeat('b', $limit - 9),
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => $platform(str_repeat('a', 10)),
+ ...$destination(str_repeat('a', 10)),
])->assertUnprocessable();
});
@@ -1294,11 +1127,9 @@ it('rejects an array mastodon content warning with 422 when scheduling', functio
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Toot',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [[
- 'social_account_id' => $mastodon->id,
- 'content_type' => ContentType::MastodonPost->value,
- 'meta' => ['spoiler_text' => ['x']],
- ]],
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['spoiler_text' => ['x']],
])->assertUnprocessable();
});
@@ -1307,27 +1138,30 @@ it('rejects a numeric link preview', function (mixed $value) {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Read https://example.com/article',
- 'platforms' => [['social_account_id' => $facebook->id, 'content_type' => ContentType::FacebookPost->value, 'meta' => ['link_preview' => $value]]],
+ 'social_account_id' => $facebook->id,
+ 'content_type' => ContentType::FacebookPost->value,
+ 'meta' => ['link_preview' => $value],
])->assertUnprocessable();
- expect(PostPlatform::where('social_account_id', $facebook->id)->exists())->toBeFalse();
+ expect(Post::where('social_account_id', $facebook->id)->exists())->toBeFalse();
})->with([0, '0', 1, '1']);
it('schedules a threads ghost post whose text carries a link', function () {
$threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Boo', 'status' => PostStatus::Draft,
+ $post = Post::factory()->forAccount($threads)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Boo',
+ 'status' => PostStatus::Draft,
]);
- $platform = PostPlatform::factory()->threads()->create(['post_id' => $post->id, 'social_account_id' => $threads->id, 'enabled' => true]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
'content' => 'Read https://example.com/article',
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::ThreadsGhostPost->value]],
+ 'content_type' => ContentType::ThreadsGhostPost->value,
])->assertOk();
- expect($platform->fresh()->content_type)->toBe(ContentType::ThreadsGhostPost);
+ expect($post->fresh()->content_type)->toBe(ContentType::ThreadsGhostPost);
});
it('judges a threads topic tag without its leading hash and stores it stripped', function () {
@@ -1336,15 +1170,19 @@ it('judges a threads topic tag without its leading hash and stores it stripped',
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => "#{$tag}"]]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => "#{$tag}"],
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => $tag]);
+ expect(Post::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => $tag]);
foreach (["#{$tag}a", '#', '#web.dev'] as $invalid) {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => $invalid]]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.meta.topic_tag' => __('posts.form.threads.topic_invalid')]);
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => $invalid],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['meta.topic_tag' => __('posts.form.threads.topic_invalid')]);
}
});
@@ -1352,29 +1190,39 @@ it('persists thread replies and rejects them where the network cannot chain when
$mastodon = SocialAccount::factory()->mastodon()->create(['workspace_id' => $this->workspace->id]);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['thread_replies' => ['Two', 'Three']]]],
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['thread_replies' => ['Two', 'Three']],
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []], ['text' => 'Three', 'media' => []]]]);
+ expect(Post::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []], ['text' => 'Three', 'media' => []]]]);
$x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Root',
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [['social_account_id' => $x->id, 'content_type' => ContentType::XPost->value, 'meta' => ['thread_replies' => ['Two']]]],
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => ['Two']],
])->assertCreated();
- expect(PostPlatform::where('social_account_id', $x->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []]]]);
+ expect(Post::where('social_account_id', $x->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []]]]);
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Root',
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [['social_account_id' => $x->id, 'content_type' => ContentType::XPost->value, 'meta' => ['thread_replies' => [str_repeat('a', 281)]]]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.meta.thread_replies.0']);
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => [str_repeat('a', 281)]],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.0']);
$threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Root', 'status' => PostStatus::Draft]);
- PostPlatform::factory()->threads()->create(['post_id' => $post->id, 'social_account_id' => $threads->id, 'enabled' => true, 'meta' => ['thread_replies' => ['Two']]]);
+ $post = Post::factory()->forAccount($threads)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Root',
+ 'status' => PostStatus::Draft,
+ 'meta' => ['thread_replies' => ['Two']],
+ ]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Scheduled->value,
@@ -1388,16 +1236,18 @@ it('stores each thread reply media with its reply, from an upload token', functi
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $x->id, 'content_type' => ContentType::XPost->value, 'meta' => ['thread_replies' => [
+ 'social_account_id' => $x->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => [
['text' => 'Two', 'media' => [['upload_token' => $upload->upload_token]]],
- ]]]],
+ ]],
])->assertCreated();
- $platform = PostPlatform::where('social_account_id', $x->id)->sole();
+ $post = Post::where('social_account_id', $x->id)->sole();
- expect($platform->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id)
- ->and($upload->fresh()->post_id)->toBe($platform->post_id)
- ->and($platform->post->media)->toBe([]);
+ expect($post->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id)
+ ->and($upload->fresh()->post_id)->toBe($post->id)
+ ->and($post->media)->toBe([]);
});
it('rejects a bluesky thread reply over the limit when scheduling', function () {
@@ -1407,8 +1257,10 @@ it('rejects a bluesky thread reply over the limit when scheduling', function ()
'content' => 'Root',
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [['social_account_id' => $bluesky->id, 'content_type' => ContentType::BlueskyPost->value, 'meta' => ['thread_replies' => ['ok', str_repeat('a', 301)]]]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.meta.thread_replies.1' => __('posts.form.thread.reply_too_long', ['limit' => 300, 'over' => 1])]);
+ 'social_account_id' => $bluesky->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => ['thread_replies' => ['ok', str_repeat('a', 301)]],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies.1' => __('posts.form.thread.reply_too_long', ['limit' => 300, 'over' => 1])]);
});
it('rejects more than 24 thread replies', function () {
@@ -1416,6 +1268,8 @@ it('rejects more than 24 thread replies', function () {
$this->withHeaders($this->headers)->postJson(route('api.posts.store'), [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')]]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.meta.thread_replies']);
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')],
+ ])->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies']);
});
diff --git a/tests/Feature/Api/PostApiTest.php b/tests/Feature/Api/PostApiTest.php
index 0399f007e..c5b5643ff 100644
--- a/tests/Feature/Api/PostApiTest.php
+++ b/tests/Feature/Api/PostApiTest.php
@@ -8,7 +8,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
@@ -68,12 +67,8 @@ it('cannot show post from another workspace', function () {
it('creates a post', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- [
- 'social_account_id' => $this->socialAccount->id,
- 'content_type' => 'linkedin_post',
- ],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated()
->assertJsonPath('status', PostStatus::Draft->value)
@@ -83,10 +78,11 @@ it('creates a post', function () {
expect($post)->not->toBeNull();
expect($post->created_via)->toBe(CreatedVia::Api);
expect($post->scheduled_at)->toBeNull();
- expect($post->postPlatforms()->count())->toBe(1);
+ expect($post->social_account_id)->toBe($this->socialAccount->id)
+ ->and($post->content_type)->toBe(ContentType::LinkedInPost);
});
-it('rejects multiple destinations on the single post endpoint', function () {
+it('rejects the removed platforms list on the single post endpoint', function () {
$secondAccount = SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
]);
@@ -99,7 +95,7 @@ it('rejects multiple destinations on the single post endpoint', function () {
],
])
->assertUnprocessable()
- ->assertJsonValidationErrors('platforms');
+ ->assertJsonValidationErrors(['platforms' => __('validation.prohibited', ['attribute' => 'platforms'])]);
expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(0);
});
@@ -124,9 +120,9 @@ it('creates an ordered batch of independent posts', function () {
$firstPost = Post::findOrFail($response->json('posts.0.id'));
$secondPost = Post::findOrFail($response->json('posts.1.id'));
expect($firstPost->content)->toBe('Segundo primeiro')
- ->and($firstPost->postPlatforms()->sole()->social_account_id)->toBe($secondAccount->id)
+ ->and($firstPost->social_account_id)->toBe($secondAccount->id)
->and($secondPost->content)->toBe('Base')
- ->and($secondPost->postPlatforms()->sole()->social_account_id)->toBe($this->socialAccount->id);
+ ->and($secondPost->social_account_id)->toBe($this->socialAccount->id);
});
it('rejects the whole batch when a destination belongs to another workspace', function () {
@@ -166,12 +162,8 @@ it('ignores a client-supplied created_via and always records api', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'created_via' => 'web',
- 'platforms' => [
- [
- 'social_account_id' => $this->socialAccount->id,
- 'content_type' => 'linkedin_post',
- ],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -193,9 +185,8 @@ it('creates a post with content, media, and labels', function () {
$payload = [
'content' => 'Hello from the API',
'media' => [['url' => 'https://93.184.216.34/photo.png']],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'label_ids' => [$label->id],
];
@@ -238,42 +229,24 @@ it('cannot delete post from another workspace', function () {
});
it('updates a post', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertOk();
});
it('keeps the account fixed when updating through the API', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $target = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$otherAccount = SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
]);
@@ -286,56 +259,30 @@ it('keeps the account fixed when updating through the API', function () {
->assertUnprocessable()
->assertJsonValidationErrors('social_account_id');
- expect($target->fresh()->social_account_id)->toBe($this->socialAccount->id);
-});
-
-it('keeps an old multi-target post readable by id', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Published,
- ]);
- $otherAccount = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $this->socialAccount->id, 'enabled' => true]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $otherAccount->id, 'enabled' => true]);
-
- $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
- ->getJson(route('api.posts.show', $post))
- ->assertOk()
- ->assertJsonCount(2, 'platforms');
+ expect($post->fresh()->social_account_id)->toBe($this->socialAccount->id);
});
it('rejects creating a post with instagram_carousel — carousel is not a stored content_type', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'instagram_carousel'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'instagram_carousel',
])
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('rejects updating a post with instagram_carousel — carousel is not a stored content_type', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => 'instagram_carousel'],
- ],
+ 'content_type' => 'instagram_carousel',
])
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('cannot update post from another workspace', function () {
@@ -344,56 +291,32 @@ it('cannot update post from another workspace', function () {
'workspace_id' => $otherWorkspace->id,
'platform' => Platform::LinkedIn,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $otherWorkspace->id,
+ $post = Post::factory()->forAccount($otherSocialAccount)->create([
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $otherSocialAccount->id,
- 'enabled' => true,
- ]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertNotFound();
});
it('cannot update post in any terminal state', function (PostStatus $status) {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => $status,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertUnprocessable();
})->with([
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
PostStatus::Publishing,
]);
@@ -406,30 +329,27 @@ it('validates post update fields', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
- 'platforms' => [
- ['content' => 'missing id'],
- ],
+ 'platforms' => [['content' => 'old shape']],
])
- ->assertUnprocessable();
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['platforms']);
});
-it('validates post creation requires platforms', function () {
+it('validates post creation requires a social account', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms']);
+ ->assertJsonValidationErrors(['social_account_id']);
});
it('validates post creation platform fields', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['content' => 'missing social_account_id'],
- ],
+ 'content' => 'missing social_account_id',
])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.social_account_id'])
- ->assertJsonMissingValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['social_account_id'])
+ ->assertJsonMissingValidationErrors(['content_type']);
});
it('validates post update invalid status', function () {
@@ -493,11 +413,10 @@ it('rejects a deleted label on post update', function () {
it('rejects creating a post with content_type not in the enum', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'made_up_type'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'made_up_type',
])
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('rejects scheduling an over-limit threads post via the api store', function () {
@@ -511,9 +430,8 @@ it('rejects scheduling an over-limit threads post via the api store', function (
'content' => str_repeat('a', 537),
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- ['social_account_id' => $threadsAccount->id, 'content_type' => ContentType::ThreadsPost->value],
- ],
+ 'social_account_id' => $threadsAccount->id,
+ 'content_type' => ContentType::ThreadsPost->value,
]);
$response->assertUnprocessable()->assertJsonValidationErrors(['content']);
@@ -532,25 +450,19 @@ it('accepts creating an over-limit draft (no scheduled_at) via the api store', f
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'content' => str_repeat('a', 1000),
- 'platforms' => [
- ['social_account_id' => $threadsAccount->id, 'content_type' => ContentType::ThreadsPost->value],
- ],
+ 'social_account_id' => $threadsAccount->id,
+ 'content_type' => ContentType::ThreadsPost->value,
])
->assertCreated();
});
it('rejects scheduling an over-limit threads post via the api update', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
$threadsAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Threads,
]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $threadsAccount->id,
+ $post = Post::factory()->forAccount($threadsAccount)->create([
+ 'user_id' => $this->user->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
@@ -558,35 +470,26 @@ it('rejects scheduling an over-limit threads post via the api update', function
'status' => PostStatus::Scheduled->value,
'content' => str_repeat('a', 600),
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- ['id' => $threadsPlatform->id, 'content_type' => ContentType::ThreadsPost->value],
- ],
+ 'content_type' => ContentType::ThreadsPost->value,
])
->assertUnprocessable()
->assertJsonValidationErrors(['content']);
});
it('saving an over-limit threads post as draft via api skips the content-length check', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
$threadsAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Threads,
]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $threadsAccount->id,
+ $post = Post::factory()->forAccount($threadsAccount)->create([
+ 'user_id' => $this->user->id,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => PostStatus::Draft->value,
'content' => str_repeat('a', 1000),
- 'platforms' => [
- ['id' => $threadsPlatform->id, 'content_type' => ContentType::ThreadsPost->value],
- ],
+ 'content_type' => ContentType::ThreadsPost->value,
])
->assertSuccessful();
});
@@ -595,11 +498,10 @@ it('rejects creating a post when content_type does not match the social account
// x_post on a LinkedIn account — ContentTypeMatchesPlatform should reject.
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'x_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'x_post',
])
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('rejects creating a post with a label from another workspace', function () {
@@ -608,61 +510,25 @@ it('rejects creating a post with a label from another workspace', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'label_ids' => [$foreignLabel->id],
])
->assertJsonValidationErrors(['label_ids.0']);
});
-it('rejects updating a post with a platforms[].id that belongs to another post', function () {
- $myPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
-
- $otherPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
- $foreignPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $otherPost->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
- $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
- ->putJson(route('api.posts.update', $myPost), [
- 'status' => 'draft',
- 'platforms' => [
- ['id' => $foreignPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
- ],
- ])
- ->assertJsonValidationErrors(['platforms.0.id']);
-});
-
-it('rejects updating a post when content_type does not match the post_platform', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+it('rejects updating a post when content_type does not match the post channel', function () {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => 'x_post'],
- ],
+ 'content_type' => 'x_post',
])
- ->assertJsonValidationErrors(['platforms.0.content_type']);
+ ->assertJsonValidationErrors(['content_type']);
});
it('rejects scheduled status without a future scheduled_at', function (?string $existingScheduledAt) {
@@ -692,9 +558,9 @@ it('rejects scheduled status without a future scheduled_at', function (?string $
it('accepts scheduled status reusing an existing future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
+ 'content' => 'Ready',
'status' => PostStatus::Draft,
'scheduled_at' => $scheduledAt,
]);
@@ -711,9 +577,9 @@ it('accepts scheduled status reusing an existing future scheduled_at', function
it('schedules an unscheduled draft with an explicit future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
+ 'content' => 'Ready',
'status' => PostStatus::Draft,
'scheduled_at' => null,
]);
@@ -751,20 +617,13 @@ it('publishes an unscheduled draft without requiring scheduled_at', function ()
Bus::fake();
$this->freezeTime();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
'content' => 'Ready to publish',
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'publishing',
@@ -779,9 +638,8 @@ it('publishes an unscheduled draft without requiring scheduled_at', function ()
it('rejects creating a post with a past scheduled_at', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'scheduled_at' => now()->subDay()->toIso8601String(),
])
->assertJsonValidationErrors(['scheduled_at']);
@@ -818,88 +676,72 @@ it('show post returns correct structure', function () {
it('creates a post with platform meta (link_preview) and returns it', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => false]],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => false],
])
->assertCreated()
- ->assertJsonPath('platforms.0.meta.link_preview', false);
+ ->assertJsonPath('meta.link_preview', false);
- $platform = Post::where('workspace_id', $this->workspace->id)->first()
- ->postPlatforms()->where('social_account_id', $this->socialAccount->id)->first();
- expect($platform->meta['link_preview'])->toBeFalse();
+ $post = Post::where('workspace_id', $this->workspace->id)->sole();
+ expect($post->meta['link_preview'])->toBeFalse();
});
it('rejects creating a post with an invalid link_preview', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => 'nope']],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => 'nope'],
])
- ->assertJsonValidationErrors(['platforms.0.meta.link_preview']);
+ ->assertJsonValidationErrors(['meta.link_preview']);
});
it('rejects updating a post with an invalid link_preview', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => 'nope']],
- ],
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => 'nope'],
])
- ->assertJsonValidationErrors(['platforms.0.meta.link_preview']);
+ ->assertJsonValidationErrors(['meta.link_preview']);
});
it('accepts a valid platform meta on update and persists it', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => false]],
- ],
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => false],
])
->assertOk()
- ->assertJsonPath('platforms.0.meta.link_preview', false);
+ ->assertJsonPath('meta.link_preview', false);
- expect($postPlatform->fresh()->meta['link_preview'])->toBeFalse();
+ expect($post->fresh()->meta['link_preview'])->toBeFalse();
});
it('no longer stores an aspect_ratio meta on create', function (string $ratio) {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['aspect_ratio' => $ratio]],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['aspect_ratio' => $ratio],
])
->assertCreated()
- ->assertJsonMissingPath('platforms.0.meta.aspect_ratio');
+ ->assertJsonMissingPath('meta.aspect_ratio');
- $platform = Post::where('workspace_id', $this->workspace->id)->first()
- ->postPlatforms()->where('social_account_id', $this->socialAccount->id)->first();
- expect(data_get($platform->meta, 'aspect_ratio'))->toBeNull();
+ $post = Post::where('workspace_id', $this->workspace->id)->sole();
+ expect(data_get($post->meta, 'aspect_ratio'))->toBeNull();
})->with(['4:5', 'original', '3:2']);
it('shows the origin of imported and trypost posts', function () {
@@ -948,17 +790,11 @@ it('orders the post list the same way on every page with null and tied scheduled
});
it('edits a draft whose kept time has passed', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => now()->subDay(),
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), ['content' => 'New text'])
diff --git a/tests/Feature/Api/PostMediaApiTest.php b/tests/Feature/Api/PostMediaApiTest.php
index a8147f96a..6afdb5e9c 100644
--- a/tests/Feature/Api/PostMediaApiTest.php
+++ b/tests/Feature/Api/PostMediaApiTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Http\Client\ConnectionException;
@@ -27,17 +26,10 @@ beforeEach(function () {
'platform' => Platform::LinkedIn,
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
Storage::fake();
});
@@ -157,63 +149,47 @@ it('previews per platform with sanitized content and length', function () {
'post_id',
'original_content',
'original_length',
- 'platforms' => [
- '*' => [
- 'post_platform_id',
- 'platform',
- 'content_type',
- 'sanitized_content',
- 'sanitized_length',
- 'max_content_length',
- 'truncated',
- ],
- ],
+ 'platform',
+ 'content_type',
+ 'sanitized_content',
+ 'sanitized_length',
+ 'max_content_length',
+ 'truncated',
])
->assertJsonPath('original_length', 500);
});
-it('returns metrics shape including unsupported reason for unpublished platforms', function () {
+it('returns metrics shape including unsupported reason for an unpublished post', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $this->post))
->assertOk()
->assertJsonStructure([
'post_id',
- 'platforms' => [
- '*' => [
- 'post_platform_id',
- 'platform',
- 'status',
- 'platform_post_id',
- 'platform_url',
- 'metrics',
- ],
- ],
+ 'platform',
+ 'publish_status',
+ 'platform_post_id',
+ 'platform_url',
+ 'metrics',
])
- ->assertJsonPath('platforms.0.metrics.unsupported', true)
- ->assertJsonPath('platforms.0.metrics.reason', 'not_published');
+ ->assertJsonPath('metrics.unsupported', true)
+ ->assertJsonPath('metrics.reason', 'not_published');
});
it('returns platform_not_supported for a published google business target', function () {
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->published()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->published()->create([
'user_id' => $this->user->id,
- ]);
- PostPlatform::factory()->googleBusiness()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $post))
->assertOk()
- ->assertJsonPath('platforms.0.platform', Platform::GoogleBusiness->value)
- ->assertJsonPath('platforms.0.metrics.unsupported', true)
- ->assertJsonPath('platforms.0.metrics.reason', 'platform_not_supported');
+ ->assertJsonPath('platform', Platform::GoogleBusiness->value)
+ ->assertJsonPath('metrics.unsupported', true)
+ ->assertJsonPath('metrics.reason', 'platform_not_supported');
});
it('cannot get metrics from another workspace post', function () {
@@ -272,22 +248,15 @@ it('rejects upload of an unsupported mime type', function () {
->assertJsonValidationErrors(['media']);
});
-it('rejects upload when the file type is not supported by enabled platforms', function () {
+it('rejects upload when the file type is not supported by the post channel', function () {
$youtubeAccount = SocialAccount::factory()->youtube()->create([
'workspace_id' => $this->workspace->id,
]);
- $youtubeOnlyPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $youtubeOnlyPost = Post::factory()->forAccount($youtubeAccount)->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->youtube()->create([
- 'post_id' => $youtubeOnlyPost->id,
- 'social_account_id' => $youtubeAccount->id,
- 'enabled' => true,
- ]);
-
$file = UploadedFile::fake()->createWithContent(
'photo.png',
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
@@ -333,9 +302,8 @@ it('downloads and hosts an external media url when creating a post', function ()
->postJson(route('api.posts.store'), [
'content' => 'External media post',
'media' => [['url' => 'https://93.184.216.34/listing.jpg']],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -363,9 +331,8 @@ it('persists alt text submitted on a bare external media url', function () {
'url' => 'https://93.184.216.34/car.jpg',
'meta' => ['alt_text' => 'A red car parked on a hill'],
]],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -385,9 +352,8 @@ it('keeps the measured duration when an external video url is submitted with its
'content' => 'External video post',
// A client-sent duration must not replace the one measured from the downloaded file.
'media' => [['url' => 'https://93.184.216.34/clip.mp4', 'meta' => ['alt_text' => 'ignored on video', 'duration' => 9999]]],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -403,9 +369,8 @@ it('rejects creating a post when an external media url cannot be fetched', funct
->postJson(route('api.posts.store'), [
'content' => 'Broken media post',
'media' => [['url' => 'https://93.184.216.34/missing.jpg']],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.0.url']);
@@ -431,9 +396,8 @@ it('rolls back already-hosted media when another url in the batch fails', functi
['url' => 'https://93.184.216.34/good.jpg'],
['url' => 'https://93.184.216.34/missing.jpg'],
],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.1.url']);
@@ -459,9 +423,8 @@ it('rejects and rolls back when a media url connection fails (timeout/dns)', fun
['url' => 'https://93.184.216.34/good.jpg'],
['url' => 'https://93.184.216.34/timeout.jpg'],
],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.1.url']);
@@ -478,9 +441,8 @@ it('rejects creating a post when an external media url is not a supported type',
->postJson(route('api.posts.store'), [
'content' => 'Bad type post',
'media' => [['url' => 'https://93.184.216.34/notes.txt']],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.0.url']);
@@ -508,9 +470,8 @@ it('keeps an already-hosted item and a freshly-hosted url in order', function ()
['id' => $asset->id],
['url' => 'https://93.184.216.34/external.jpg'],
],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -531,9 +492,8 @@ it('passes already-hosted media through on create without downloading', function
->postJson(route('api.posts.store'), [
'content' => 'Hosted media post',
'media' => [['id' => $asset->id]],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -592,9 +552,8 @@ it('accepts and persists media alt text on create', function () {
->postJson(route('api.posts.store'), [
'content' => 'Alt text post',
'media' => [$media],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertCreated();
@@ -649,9 +608,8 @@ it('rejects media alt text over 2000 characters', function () {
'id' => 'media-1',
'meta' => ['alt_text' => str_repeat('a', 2001)],
]],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])
->assertUnprocessable()
->assertJsonValidationErrors(['media.0.meta']);
diff --git a/tests/Feature/Api/PostQueueApiTest.php b/tests/Feature/Api/PostQueueApiTest.php
index 11851e4df..92a20f520 100644
--- a/tests/Feature/Api/PostQueueApiTest.php
+++ b/tests/Feature/Api/PostQueueApiTest.php
@@ -7,7 +7,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
@@ -40,7 +39,8 @@ test('single create with queue next queues the post on a slot', function () {
'status' => 'scheduled',
'queue' => 'next',
'content' => 'Queued',
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertCreated()->assertJsonPath('schedule_mode', ScheduleMode::Queue->value);
@@ -60,18 +60,12 @@ test('batch create with queue next queues each post', function () {
});
test('update with queue next queues a draft', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->channel)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
'content' => 'Draft',
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->channel->id,
- 'enabled' => true,
- ]);
$response = $this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => 'scheduled',
@@ -83,18 +77,12 @@ test('update with queue next queues a draft', function () {
});
test('update with queue next and a null scheduled_at keeps the slot of a queued post', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->channel)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
'content' => 'Draft',
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->channel->id,
- 'enabled' => true,
- ]);
$this->withHeaders($this->headers)->putJson(route('api.posts.update', $post), [
'status' => 'scheduled',
'queue' => 'next',
@@ -120,7 +108,8 @@ test('queue combined with scheduled_at is rejected', function () {
'queue' => 'next',
'scheduled_at' => '2027-01-01T10:00:00Z',
'content' => 'Queued',
- 'platforms' => [['social_account_id' => $this->channel->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertUnprocessable()->assertJsonValidationErrorFor('queue');
$this->withHeaders($this->headers)->postJson(route('api.posts.batch.store'), [
@@ -137,8 +126,9 @@ test('queue on a channel without posting times is rejected', function () {
'status' => 'scheduled',
'queue' => 'next',
'content' => 'Queued',
- 'platforms' => [['social_account_id' => $this->bareChannel->id, 'content_type' => ContentType::LinkedInPost->value]],
- ])->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)->assertJsonValidationErrorFor('destinations.0.social_account_id');
+ 'social_account_id' => $this->bareChannel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
+ ])->assertStatus(Response::HTTP_UNPROCESSABLE_ENTITY)->assertJsonValidationErrorFor('social_account_id');
expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(0);
diff --git a/tests/Feature/Api/RepurposeApiTest.php b/tests/Feature/Api/RepurposeApiTest.php
index 29023c6b1..316881e9e 100644
--- a/tests/Feature/Api/RepurposeApiTest.php
+++ b/tests/Feature/Api/RepurposeApiTest.php
@@ -2,8 +2,8 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\Repurpose\ItemStatus;
use App\Enums\Repurpose\PauseReason;
use App\Enums\Repurpose\PublishMode;
@@ -15,7 +15,6 @@ use App\Enums\TikTok\PrivacyLevel;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -373,20 +372,17 @@ test('the api activity list carries each replicated post status', function () {
$item = RepurposeItem::factory()->for($repurpose)->create();
- $post = Post::factory()->create([
+ $post = Post::factory()->tiktok()->published()->create([
'workspace_id' => $this->workspace->id,
'repurpose_item_id' => $item->id,
]);
- PostPlatform::factory()->for($post)->create([
- 'platform' => Platform::TikTok,
- 'enabled' => true,
- 'status' => PostPlatformStatus::Published,
- ]);
$this->withHeaders(apiHeaders($this->token))
->getJson(route('api.repurposes.items', $repurpose))
->assertOk()
- ->assertJsonPath('data.0.posts.0.platforms.0.status', PostPlatformStatus::Published->value);
+ ->assertJsonPath('data.0.posts.0.id', $post->id)
+ ->assertJsonPath('data.0.posts.0.platform', Platform::TikTok->value)
+ ->assertJsonPath('data.0.posts.0.publish_status', PublishStatus::Published->value);
});
test('the source formats a repurpose can watch are listed', function () {
diff --git a/tests/Feature/Api/TikTokPhotoMediaTest.php b/tests/Feature/Api/TikTokPhotoMediaTest.php
index 0f5e1e717..18f9f39e5 100644
--- a/tests/Feature/Api/TikTokPhotoMediaTest.php
+++ b/tests/Feature/Api/TikTokPhotoMediaTest.php
@@ -7,7 +7,6 @@ use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
@@ -34,7 +33,7 @@ beforeEach(function () {
test('an image url on a tiktok post is hosted and makes a tiktok photo', function () {
$response = $this->postJson(route('api.posts.store'), [
- 'platforms' => [['social_account_id' => $this->tiktok->id]],
+ 'social_account_id' => $this->tiktok->id,
'media' => [['url' => 'https://example.com/a.png']],
], $this->headers);
@@ -43,18 +42,11 @@ test('an image url on a tiktok post is hosted and makes a tiktok photo', functio
$post = Post::query()->findOrFail($response->json('id'));
expect($post->media)->toHaveCount(1)
- ->and($post->postPlatforms()->sole()->content_type)->toBe(ContentType::TikTokPhoto);
+ ->and($post->content_type)->toBe(ContentType::TikTokPhoto);
});
test('an image url attached to a tiktok post is added to the post', function () {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->tiktok->id,
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokPhoto,
- 'enabled' => true,
- ]);
+ $post = Post::factory()->forAccount($this->tiktok, ContentType::TikTokPhoto)->create(['user_id' => $this->user->id]);
$this->postJson(route('api.posts.attach-media-from-url', $post), [
'urls' => [['url' => 'https://example.com/b.png']],
@@ -74,11 +66,9 @@ test('a tiktok video still refuses an image when it is scheduled', function () {
$this->postJson(route('api.posts.store'), [
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [[
- 'social_account_id' => $this->tiktok->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => ['privacy_level' => 'SELF_ONLY'],
- ]],
+ 'social_account_id' => $this->tiktok->id,
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => 'SELF_ONLY'],
'media' => [['url' => 'https://example.com/c.png']],
], $this->headers)->assertUnprocessable();
});
diff --git a/tests/Feature/AuditLegacyPostsTest.php b/tests/Feature/AuditLegacyPostsTest.php
deleted file mode 100644
index 216c70416..000000000
--- a/tests/Feature/AuditLegacyPostsTest.php
+++ /dev/null
@@ -1,39 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\Post\Status;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-
-test('strict legacy audit fails for a scheduled post without an enabled target', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- 'status' => Status::Scheduled,
- 'scheduled_at' => now()->addDay(),
- ]);
-
- $this->artisan('posts:audit-legacy', ['--strict' => true])->assertFailed();
-});
-
-test('audit is read only and reports editable multi-target posts for splitting', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $accounts = SocialAccount::factory()->count(2)->create(['workspace_id' => $workspace->id]);
- foreach ($accounts as $account) {
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
- }
-
- $this->artisan('posts:audit-legacy')->assertSuccessful();
- $this->artisan('posts:audit-legacy', ['--strict' => true])->assertFailed();
-
- expect(Post::count())->toBe(1)
- ->and(PostPlatform::count())->toBe(2);
-});
diff --git a/tests/Feature/BakeAspectRatioCropsTest.php b/tests/Feature/BakeAspectRatioCropsTest.php
deleted file mode 100644
index cf437a076..000000000
--- a/tests/Feature/BakeAspectRatioCropsTest.php
+++ /dev/null
@@ -1,304 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Actions\Post\BakeLegacyAspectRatioCrops;
-use App\Actions\Post\ScheduleNextOccurrence;
-use App\Dto\MediaItem;
-use App\Enums\Post\RecurrenceFrequency;
-use App\Enums\Post\ScheduleMode;
-use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Enums\SocialAccount\Platform;
-use App\Jobs\PublishToSocialPlatform;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-use App\Support\Media\ImageDimensions;
-use Illuminate\Http\Client\Request;
-use Illuminate\Support\Facades\Http;
-use Illuminate\Support\Facades\Mail;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Sleep;
-use Illuminate\Support\Str;
-
-beforeEach(function () {
- Mail::fake();
- Storage::fake();
- Sleep::fake();
-
- $this->migration = require database_path('migrations/2026_10_04_202400_remove_aspect_ratio_from_post_platforms_meta.php');
- $this->user = User::factory()->create();
- $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
- $this->instagram = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_bake',
- 'token_expires_at' => now()->addDays(60),
- ]);
- $this->facebook = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'page_bake',
- 'token_expires_at' => null,
- 'meta' => ['page_id' => 'page_bake'],
- ]);
-});
-
-function bakeJpeg(int $width, int $height): string
-{
- $image = imagecreatetruecolor($width, $height);
- ob_start();
- imagejpeg($image);
- $bytes = (string) ob_get_clean();
- imagedestroy($image);
-
- return $bytes;
-}
-
-/**
- * @param list<array{0: int, 1: int}|'video'> $files
- * @param array<string, mixed> $meta
- * @param array<string, mixed> $postAttributes
- * @return array{post: Post, target: PostPlatform, media: list<Media>}
- */
-function bakeLegacyPost(Workspace $workspace, SocialAccount $account, ContentType $contentType, array $files, array $meta, PostStatus $status = PostStatus::Scheduled, PlatformStatus $targetStatus = PlatformStatus::Pending, array $postAttributes = []): array
-{
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => $status,
- 'content' => 'Legacy caption',
- ...$postAttributes,
- ]);
- $media = [];
-
- foreach ($files as $index => $file) {
- if ($file === 'video') {
- $row = Media::factory()->video()->stored()->ownedByPost($post)->create(['order' => $index]);
- } else {
- $row = Media::factory()->ownedByPost($post)->create([
- 'path' => 'medias/'.Str::uuid().'.jpg',
- 'order' => $index,
- 'meta' => ['width' => $file[0], 'height' => $file[1]],
- ]);
- Storage::put($row->path, bakeJpeg($file[0], $file[1]));
- }
-
- $media[] = $row;
- }
-
- $items = array_map(fn (Media $row): array => MediaItem::fromMedia($row, $row->isImage() ? "alt {$row->id}" : null)->toArray(), $media);
- Post::query()->whereKey($post->id)->update(['media' => json_encode($items)]);
-
- $target = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'status' => $targetStatus,
- 'meta' => $meta,
- 'enabled' => true,
- ]);
-
- return ['post' => $post->fresh(), 'target' => $target, 'media' => $media];
-}
-
-/**
- * @return array{width: int, height: int}
- */
-function bakedDimensions(array $item): array
-{
- return ImageDimensions::fromBytes((string) Storage::get(data_get($item, 'path')));
-}
-
-function runBakeRelease(object $migration): void
-{
- $migration->up();
- test()->artisan('posts:bake-aspect-ratio-crops')->assertSuccessful();
-}
-
-test('a scheduled instagram feed 9:16 photo with 4:5 selected is cropped to 4:5 and publishes that image', function () {
- ['post' => $post, 'target' => $target, 'media' => $media] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5', 'is_ai_generated' => true]);
-
- runBakeRelease($this->migration);
-
- $post->refresh();
- $item = data_get($post->media, 0);
- $row = Media::query()->findOrFail(data_get($item, 'id'));
-
- expect(bakedDimensions($item))->toBe(['width' => 1080, 'height' => 1350])
- ->and($row->post_id)->toBe($post->id)
- ->and($row->collection)->toBe(Media::COLLECTION_MEDIA)
- ->and($row->upload_token)->toBeNull()
- ->and(data_get($row->meta, 'width'))->toBe(1080)
- ->and(data_get($row->meta, 'height'))->toBe(1350)
- ->and(data_get($item, 'meta.alt_text'))->toBe("alt {$media[0]->id}")
- ->and(Media::query()->whereKey($media[0]->id)->exists())->toBeFalse()
- ->and($target->fresh()->meta)->toEqual(['is_ai_generated' => true]);
-
- $graph = (string) config('trypost.platforms.instagram.graph_api');
- Http::fake(fn (Request $request) => match (true) {
- str_ends_with($request->url(), '/ig_bake/media') => Http::response(['id' => 'container-1']),
- str_ends_with($request->url(), '/ig_bake/media_publish') => Http::response(['id' => 'ig-media-1']),
- str_contains($request->url(), '/container-1') => Http::response(['status_code' => 'FINISHED']),
- str_contains($request->url(), '/ig-media-1') => Http::response(['permalink' => 'https://www.instagram.com/p/baked/']),
- default => Http::response([], 404),
- });
-
- (new PublishToSocialPlatform($target->fresh()))->handle();
-
- expect($target->fresh()->status)->toBe(PlatformStatus::Published);
- Http::assertSent(fn (Request $request): bool => $request->url() === "{$graph}/ig_bake/media"
- && data_get($request->data(), 'image_url') === Storage::url($row->path));
-});
-
-test('an instagram carousel crops every image and keeps its video', function () {
- ['post' => $post, 'media' => $media] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920], 'video', [1600, 900]], ['aspect_ratio' => '1:1']);
-
- runBakeRelease($this->migration);
-
- $items = $post->fresh()->media;
-
- expect($items)->toHaveCount(3)
- ->and(bakedDimensions($items[0]))->toBe(['width' => 1080, 'height' => 1080])
- ->and(data_get($items, '1.id'))->toBe($media[1]->id)
- ->and(bakedDimensions($items[2]))->toBe(['width' => 900, 'height' => 900])
- ->and(Media::query()->where('post_id', $post->id)->orderBy('order')->pluck('id')->all())->toBe(array_column($items, 'id'));
-});
-
-test('a facebook post crops its images, and one led by a video keeps them', function () {
- ['post' => $images] = bakeLegacyPost($this->workspace, $this->facebook, ContentType::FacebookPost, [[1000, 1000], [800, 1000]], ['aspect_ratio' => '16:9']);
- ['post' => $video, 'media' => $videoMedia] = bakeLegacyPost($this->workspace, $this->facebook, ContentType::FacebookPost, ['video', [1000, 1000]], ['aspect_ratio' => '16:9']);
-
- runBakeRelease($this->migration);
-
- $items = $images->fresh()->media;
-
- expect(bakedDimensions($items[0]))->toBe(['width' => 1000, 'height' => 563])
- ->and(bakedDimensions($items[1]))->toBe(['width' => 800, 'height' => 450])
- ->and(array_column($video->fresh()->media, 'id'))->toBe([$videoMedia[0]->id, $videoMedia[1]->id]);
-
- Http::fake(['*/page_bake/photos' => Http::response(['id' => 'photo-1']), '*/page_bake/feed' => Http::response(['id' => 'page_bake_1'])]);
-
- $target = $images->postPlatforms()->sole();
- (new PublishToSocialPlatform($target))->handle();
-
- expect($target->fresh()->status)->toBe(PlatformStatus::Published);
- Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/page_bake/photos')
- && data_get($request->data(), 'url') === Storage::url(data_get($items, '0.path')));
-});
-
-test('targets the publishers never cropped keep their media and lose the key', function () {
- ['post' => $story, 'target' => $storyTarget, 'media' => $storyMedia] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramStory, [[1080, 1920]], ['aspect_ratio' => '4:5']);
- ['post' => $published, 'target' => $publishedTarget, 'media' => $publishedMedia] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5'], PostStatus::Published, PlatformStatus::Published);
- ['post' => $original, 'target' => $originalTarget, 'media' => $originalMedia] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1350]], ['aspect_ratio' => 'original']);
- ['post' => $atRatio, 'target' => $atRatioTarget, 'media' => $atRatioMedia] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1350]], ['aspect_ratio' => '4:5']);
- ['post' => $started, 'target' => $startedTarget, 'media' => $startedMedia] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5'], PostStatus::Publishing, PlatformStatus::Publishing);
- $startedTarget->update(['error_context' => ['instagram_workflow' => ['stage' => 'final_container', 'container_id' => 'container-9']]]);
-
- runBakeRelease($this->migration);
-
- foreach ([[$story, $storyTarget, $storyMedia], [$published, $publishedTarget, $publishedMedia], [$original, $originalTarget, $originalMedia], [$atRatio, $atRatioTarget, $atRatioMedia], [$started, $startedTarget, $startedMedia]] as [$post, $target, $media]) {
- expect(data_get($post->fresh()->media, '0.id'))->toBe($media[0]->id)
- ->and($target->fresh()->meta)->toEqual([]);
- }
-});
-
-test('a target that publishes without user action is baked', function (PostStatus $status, PlatformStatus $targetStatus, array $postAttributes) {
- ['post' => $post, 'target' => $target, 'media' => $media] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5'], $status, $targetStatus, $postAttributes);
-
- runBakeRelease($this->migration);
-
- expect(data_get($post->fresh()->media, '0.id'))->not->toBe($media[0]->id)
- ->and(bakedDimensions(data_get($post->fresh()->media, 0)))->toBe(['width' => 1080, 'height' => 1350])
- ->and($target->fresh()->meta)->toEqual([]);
-})->with([
- 'scheduled' => [PostStatus::Scheduled, PlatformStatus::Pending, []],
- 'queued' => [PostStatus::Scheduled, PlatformStatus::Pending, ['schedule_mode' => ScheduleMode::Queue]],
- 'pending approval' => [PostStatus::PendingApproval, PlatformStatus::Pending, []],
- 'publishing' => [PostStatus::Publishing, PlatformStatus::Publishing, []],
- 'retrying' => [PostStatus::Publishing, PlatformStatus::Retrying, []],
-]);
-
-test('a draft or a failed target keeps its original image and loses the key', function (PostStatus $status, PlatformStatus $targetStatus) {
- ['post' => $post, 'target' => $target, 'media' => $media] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5', 'is_ai_generated' => true], $status, $targetStatus);
-
- expect(BakeLegacyAspectRatioCrops::pending())->toBe(0);
-
- runBakeRelease($this->migration);
-
- $item = data_get($post->fresh()->media, 0);
-
- expect(data_get($item, 'id'))->toBe($media[0]->id)
- ->and(bakedDimensions($item))->toBe(['width' => 1080, 'height' => 1920])
- ->and($target->fresh()->meta)->toEqual(['is_ai_generated' => true]);
-})->with([
- 'draft' => [PostStatus::Draft, PlatformStatus::Pending],
- 'failed post' => [PostStatus::Failed, PlatformStatus::Failed],
- 'failed target of a post still publishing' => [PostStatus::Publishing, PlatformStatus::Failed],
-]);
-
-test('an instagram target connected through facebook is baked like a direct one', function () {
- $account = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::InstagramFacebook,
- ]);
- ['post' => $post] = bakeLegacyPost($this->workspace, $account, ContentType::InstagramFeed, [[1080, 1920], [1920, 1080]], ['aspect_ratio' => '1:1']);
-
- runBakeRelease($this->migration);
-
- $items = $post->fresh()->media;
-
- expect(bakedDimensions($items[0]))->toBe(['width' => 1080, 'height' => 1080])
- ->and(bakedDimensions($items[1]))->toBe(['width' => 1080, 'height' => 1080]);
-});
-
-test('a recurring series is baked and its next occurrence carries the cropped image', function () {
- ['post' => $post] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5'], postAttributes: [
- 'recurrence_frequency' => RecurrenceFrequency::Week,
- 'recurrence_interval' => 1,
- 'recurrence_remaining' => 3,
- ]);
-
- runBakeRelease($this->migration);
-
- $next = ScheduleNextOccurrence::execute($post->fresh())->sole();
-
- expect(bakedDimensions(data_get($post->fresh()->media, 0)))->toBe(['width' => 1080, 'height' => 1350])
- ->and(bakedDimensions(data_get($next->media, 0)))->toBe(['width' => 1080, 'height' => 1350])
- ->and($next->postPlatforms()->sole()->meta)->toEqual([]);
-});
-
-test('a post whose media is shared with another enabled target is skipped and reported', function () {
- ['post' => $post, 'target' => $target, 'media' => $media] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920]], ['aspect_ratio' => '4:5'], PostStatus::Publishing, PlatformStatus::Pending);
- PostPlatform::factory()->create(['post_id' => $post->id, 'enabled' => true]);
-
- $this->migration->up();
- $this->artisan('posts:bake-aspect-ratio-crops')
- ->expectsOutputToContain("their media is shared; they keep their aspect ratio until a run after posts:split-legacy-active): {$post->id}")
- ->assertSuccessful();
-
- expect(data_get($post->fresh()->media, '0.id'))->toBe($media[0]->id)
- ->and($target->fresh()->meta)->toEqual(['aspect_ratio' => '4:5']);
-});
-
-test('a second run changes nothing', function () {
- ['post' => $post] = bakeLegacyPost($this->workspace, $this->instagram, ContentType::InstagramFeed, [[1080, 1920], [1920, 1080]], ['aspect_ratio' => '4:5']);
-
- runBakeRelease($this->migration);
- $media = $post->fresh()->media;
- $files = Storage::allFiles();
- $rows = Media::query()->pluck('id')->sort()->values()->all();
-
- $this->artisan('posts:bake-aspect-ratio-crops')
- ->expectsOutputToContain('Baked 0 cropped image(s) into 0 post(s)')
- ->assertSuccessful();
-
- expect($post->fresh()->media)->toBe($media)
- ->and(Storage::allFiles())->toBe($files)
- ->and(Media::query()->pluck('id')->sort()->values()->all())->toBe($rows)
- ->and(bakedDimensions($media[1]))->toBe(['width' => 864, 'height' => 1080]);
-});
diff --git a/tests/Feature/Channels/ChannelDefaultsTest.php b/tests/Feature/Channels/ChannelDefaultsTest.php
index 2e569d874..210f3af26 100644
--- a/tests/Feature/Channels/ChannelDefaultsTest.php
+++ b/tests/Feature/Channels/ChannelDefaultsTest.php
@@ -2,17 +2,12 @@
declare(strict_types=1);
-use App\Actions\SocialAccount\ApplyChannelDefaults;
-use App\Enums\Post\ScheduleMode;
use App\Enums\SocialAccount\Platform;
use App\Events\TelegramChannelConnected;
-use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
-use Illuminate\Support\Facades\Event;
test('the posting schedule casts to and from JSON', function () {
$account = SocialAccount::factory()->linkedin()->create([
@@ -89,33 +84,3 @@ test('the telegram connected broadcast carries the account id and created flag',
expect($event->broadcastWith())->toBe(['nonce' => 'nonce-1', 'account_id' => 'acc-1', 'created' => true]);
});
-
-test('existing channels without a schedule get the new channel defaults from their workspace owner, quietly', function () {
- [$owner, $workspace] = channelDefaultsWorkspace('America/Sao_Paulo');
- $bare = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $custom = PostingSchedule::empty()->withTime(2, '10:15');
- $configured = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'Asia/Tokyo', 'posting_goal' => 7, 'posting_schedule' => $custom]);
- [, $ownerless] = channelDefaultsWorkspace('UTC');
- $utc = SocialAccount::factory()->linkedin()->create(['workspace_id' => $ownerless->id]);
- $scheduledAt = now()->addDays(2)->setTime(13, 37)->startOfSecond();
- $post = Post::factory()->scheduled()->create(['workspace_id' => $workspace->id, 'scheduled_at' => $scheduledAt, 'schedule_mode' => ScheduleMode::Custom]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $bare->id]);
- Event::fake();
-
- expect(ApplyChannelDefaults::pending())->toBe(2)
- ->and(ApplyChannelDefaults::backfill())->toBe(2)
- ->and(ApplyChannelDefaults::backfill())->toBe(0);
-
- $bare = $bare->fresh();
-
- expect($bare->timezone)->toBe('America/Sao_Paulo')
- ->and($bare->posting_goal)->toBe(3)
- ->and($bare->posting_schedule->slotCount())->toBe(3)
- ->and($utc->fresh()->timezone)->toBe('UTC')
- ->and($utc->fresh()->posting_goal)->toBe(3)
- ->and($configured->fresh()->timezone)->toBe('Asia/Tokyo')
- ->and($configured->fresh()->posting_goal)->toBe(7)
- ->and($configured->fresh()->posting_schedule->toArray())->toEqual($custom->toArray())
- ->and($post->fresh()->scheduled_at->equalTo($scheduledAt))->toBeTrue();
- expect(collect(Event::dispatchedEvents())->keys()->reject(fn (string $event): bool => str_starts_with($event, 'eloquent.retrieved') || str_starts_with($event, 'eloquent.booting') || str_starts_with($event, 'eloquent.booted'))->values()->all())->toBe([]);
-});
diff --git a/tests/Feature/Channels/ChannelGridTest.php b/tests/Feature/Channels/ChannelGridTest.php
index b0054ec61..1793fb7fa 100644
--- a/tests/Feature/Channels/ChannelGridTest.php
+++ b/tests/Feature/Channels/ChannelGridTest.php
@@ -2,11 +2,11 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
+use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,12 +31,12 @@ beforeEach(function () {
* @param list<string> $files
* @param array<string, mixed> $attributes
*/
-function gridPost(SocialAccount $account, string $publishedAt, ContentType $contentType = ContentType::InstagramFeed, array $files = ['photo.jpg'], array $attributes = [], bool $imported = false): PostPlatform
+function gridPost(SocialAccount $account, string $publishedAt, ContentType $contentType = ContentType::InstagramFeed, array $files = ['photo.jpg'], array $attributes = [], bool $imported = false): Post
{
- $post = Post::factory()
+ return Post::factory()
+ ->forAccount($account, $contentType)
->when($imported, fn ($factory) => $factory->imported(), fn ($factory) => $factory->published())
->create([
- 'workspace_id' => $account->workspace_id,
'published_at' => $publishedAt,
'media' => array_map(fn (string $file): array => [
'id' => (string) str()->uuid(),
@@ -54,16 +54,8 @@ function gridPost(SocialAccount $account, string $publishedAt, ContentType $cont
},
...(str_ends_with($file, '.mp4') ? ['meta' => ['cover_offset_ms' => 1500]] : []),
], $files),
+ ...$attributes,
]);
-
- return PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'published_at' => $publishedAt,
- ...$attributes,
- ]);
}
test('the grid lists published feed posts and reels newest first, without stories', function () {
@@ -72,9 +64,8 @@ test('the grid lists published feed posts and reels newest first, without storie
$reel = gridPost($this->instagram, '2026-09-20 10:00:00', ContentType::InstagramReel, ['clip.mp4']);
$imported = gridPost($this->instagram, '2026-09-15 10:00:00', imported: true);
gridPost($this->instagram, '2026-09-25 10:00:00', ContentType::InstagramStory);
- gridPost($this->instagram, '2026-09-26 10:00:00', attributes: ['status' => Status::Failed]);
- gridPost($this->instagram, '2026-09-27 10:00:00', attributes: ['status' => Status::Pending, 'published_at' => null]);
- gridPost($this->instagram, '2026-09-28 10:00:00', attributes: ['enabled' => false]);
+ gridPost($this->instagram, '2026-09-26 10:00:00', attributes: ['status' => PostStatus::Failed, 'publish_status' => PublishStatus::Failed]);
+ gridPost($this->instagram, '2026-09-27 10:00:00', attributes: ['status' => PostStatus::Scheduled, 'publish_status' => PublishStatus::Pending, 'published_at' => null]);
$this->actingAs($this->user)
->get(route('app.channels.grid', $this->instagram))
@@ -84,23 +75,23 @@ test('the grid lists published feed posts and reels newest first, without storie
->where('channel.id', $this->instagram->id)
->where('channel.has_grid', true)
->has('posts.data', 4)
- ->where('posts.data.0.id', $reel->post_id)
+ ->where('posts.data.0.id', $reel->id)
->where('posts.data.0.kind', 'reel')
->has('posts.data.0.items', 1)
->where('posts.data.0.items.0.type', 'video')
->where('posts.data.0.items.0.mime_type', 'video/mp4')
->where('posts.data.0.items.0.url', 'https://cdn.example.com/clip.mp4')
->where('posts.data.0.items.0.meta.cover_offset_ms', 1500)
- ->where('posts.data.1.id', $imported->post_id)
+ ->where('posts.data.1.id', $imported->id)
->where('posts.data.1.kind', 'single')
- ->where('posts.data.2.id', $carousel->post_id)
+ ->where('posts.data.2.id', $carousel->id)
->where('posts.data.2.kind', 'carousel')
->has('posts.data.2.items', 2)
->where('posts.data.2.items.0.url', 'https://cdn.example.com/a.jpg')
->where('posts.data.2.items.0.type', 'image')
->where('posts.data.2.items.1.url', 'https://cdn.example.com/b.mp4')
->where('posts.data.2.items.1.type', 'video')
- ->where('posts.data.3.id', $older->post_id)
+ ->where('posts.data.3.id', $older->id)
->has('posts.data.3.items', 1)
->where('posts.data.3.items.0.type', 'image')
);
@@ -113,9 +104,9 @@ test('a single feed video is shown as a reel and a post without media has no cov
$this->actingAs($this->user)
->get(route('app.channels.grid', $this->instagram))
->assertInertia(fn (Assert $page) => $page
- ->where('posts.data.0.id', $video->post_id)
+ ->where('posts.data.0.id', $video->id)
->where('posts.data.0.kind', 'reel')
- ->where('posts.data.1.id', $bare->post_id)
+ ->where('posts.data.1.id', $bare->id)
->where('posts.data.1.items', [])
);
});
@@ -132,7 +123,7 @@ test('the grid only shows the requested channel', function () {
->get(route('app.channels.grid', $this->instagram))
->assertInertia(fn (Assert $page) => $page
->has('posts.data', 1)
- ->where('posts.data.0.id', $mine->post_id)
+ ->where('posts.data.0.id', $mine->id)
);
});
diff --git a/tests/Feature/Channels/ChannelPostingScheduleTest.php b/tests/Feature/Channels/ChannelPostingScheduleTest.php
index 440bc90eb..6bfd379c2 100644
--- a/tests/Feature/Channels/ChannelPostingScheduleTest.php
+++ b/tests/Feature/Channels/ChannelPostingScheduleTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -209,13 +208,11 @@ test('a duplicate time within one day is rejected even when other days share it'
test('a busy queue fails the schedule update, saves nothing and keeps the queued times', function () {
$time = now()->addDays(3)->startOfMinute();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->channel)->create([
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => $time,
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->channel->id]);
$before = $this->channel->only(['timezone', 'posting_goal']);
$lock = Cache::lock("queue:{$this->channel->id}", 10);
$lock->get();
@@ -264,13 +261,11 @@ test('a time zone change saves the zone and moves queued posts together', functi
$this->travelTo(now()->startOfWeek()->addWeek()->setTime(6, 0));
$schedule = PostingSchedule::empty()->withTime(3, '09:00');
$this->channel->update(['timezone' => 'UTC', 'posting_schedule' => $schedule]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->channel)->create([
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => now()->next('Wednesday')->setTime(9, 0),
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->channel->id]);
$this->actingAs($this->user)
->putJson(route('app.channels.posting-schedule.update', $this->channel), [
@@ -311,13 +306,11 @@ test('a time zone change keeps the instant of a post with a custom time', functi
$schedule = PostingSchedule::empty()->withTime(3, '09:00');
$this->channel->update(['timezone' => 'UTC', 'posting_schedule' => $schedule]);
$instant = now()->next('Thursday')->setTime(14, 30);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->channel)->create([
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => $instant,
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->channel->id]);
$this->actingAs($this->user)
->putJson(route('app.channels.posting-schedule.update', $this->channel), [
diff --git a/tests/Feature/Channels/DisconnectChannelPostsTest.php b/tests/Feature/Channels/DisconnectChannelPostsTest.php
index deb8024e3..835e53722 100644
--- a/tests/Feature/Channels/DisconnectChannelPostsTest.php
+++ b/tests/Feature/Channels/DisconnectChannelPostsTest.php
@@ -6,8 +6,7 @@ use App\Actions\Analytics\UpsertAnalyticsPublication;
use App\Actions\Post\ImportExternalPosts;
use App\Dto\Analytics\DiscoveredPublication;
use App\Enums\Analytics\PublicationContentType;
-use App\Enums\Post\Status;
-use App\Enums\PostPlatform\Status as PlatformStatus;
+use App\Enums\Post\PublishStatus;
use App\Events\PostDeleted;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
@@ -16,7 +15,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -39,40 +37,37 @@ beforeEach(function () {
});
/**
- * @return array{0: Post, 1: PostPlatform, 2: Media}
+ * @return array{0: Post, 1: Media}
*/
-function channelPost(SocialAccount $account, Post $post, ?PlatformStatus $status = null): array
+function channelPost(SocialAccount $account, ?string $state = null): array
{
- $target = PostPlatform::factory()->instagram()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => $status ?? PlatformStatus::Pending,
- 'platform_post_id' => $status === PlatformStatus::Published ? fake()->uuid() : null,
- ]);
+ $post = Post::factory()
+ ->forAccount($account)
+ ->when($state, fn ($factory) => $factory->{$state}())
+ ->create();
$media = Media::factory()->ownedByPost($post)->create();
Storage::put($media->path, 'bytes');
- return [$post, $target, $media];
+ return [$post, $media];
}
test('disconnecting deletes every post of the channel, whatever its status or origin, with its media', function () {
Event::fake([PostDeleted::class]);
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $in = ['workspace_id' => $this->workspace->id];
$posts = collect([
- channelPost($account, Post::factory()->draft()->create($in)),
- channelPost($account, Post::factory()->scheduled()->create($in)),
- channelPost($account, Post::factory()->pendingApproval()->create($in)),
- channelPost($account, Post::factory()->failed()->create($in), PlatformStatus::Failed),
- channelPost($account, Post::factory()->published()->create($in), PlatformStatus::Published),
- channelPost($account, Post::factory()->imported()->create($in), PlatformStatus::Published),
+ channelPost($account, 'draft'),
+ channelPost($account, 'scheduled'),
+ channelPost($account, 'pendingApproval'),
+ channelPost($account, 'failed'),
+ channelPost($account, 'published'),
+ channelPost($account, 'imported'),
]);
- [, $importedTarget] = $posts->last();
+ [$importedPost] = $posts->last();
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $this->workspace->id,
'social_account_id' => $account->id,
- 'post_platform_id' => $importedTarget->id,
+ 'post_id' => $importedPost->id,
]);
$snapshot = AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publication->id]);
@@ -80,68 +75,55 @@ test('disconnecting deletes every post of the channel, whatever its status or or
expect(SocialAccount::query()->find($account->id))->toBeNull()
->and(Post::query()->whereKey($posts->map(fn (array $row): string => $row[0]->id))->count())->toBe(0)
- ->and(PostPlatform::query()->whereNull('social_account_id')->count())->toBe(0)
- ->and(Media::query()->whereKey($posts->map(fn (array $row): string => $row[2]->id))->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and(Post::query()->whereNull('social_account_id')->whereNotNull('platform')->count())->toBe(0)
+ ->and(Media::query()->whereKey($posts->map(fn (array $row): string => $row[1]->id))->count())->toBe(0)
+ ->and($publication->fresh()->post_id)->toBeNull()
->and($publication->fresh()->post_dismissed_at)->toBeNull()
->and(AnalyticsPublicationDailySnapshot::query()->whereKey($snapshot->id)->exists())->toBeTrue();
- $posts->each(fn (array $row) => Storage::assertMissing($row[2]->path));
+ $posts->each(fn (array $row) => Storage::assertMissing($row[1]->path));
Event::assertNotDispatched(PostDeleted::class);
Queue::assertNotPushed(SendNotification::class);
});
+test('disconnecting deletes a post waiting for a network limit, so no retry runs for it', function () {
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
+ $waiting = Post::factory()->forAccount($account)->publishing()->create([
+ 'publish_status' => PublishStatus::Retrying,
+ 'retry_at' => now()->subMinute(),
+ ]);
+
+ expect(Post::query()->dueForLimitRetry()->whereKey($waiting->id)->exists())->toBeTrue();
+
+ $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))->assertRedirect();
+
+ expect(Post::query()->find($waiting->id))->toBeNull()
+ ->and(Post::query()->dueForLimitRetry()->exists())->toBeFalse();
+});
+
test('disconnecting leaves other channels and other workspaces alone', function () {
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$sibling = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$elsewhere = SocialAccount::factory()->instagram()->create();
- [$gone] = channelPost($account, Post::factory()->published()->create(['workspace_id' => $this->workspace->id]), PlatformStatus::Published);
- [$siblingPost] = channelPost($sibling, Post::factory()->published()->create(['workspace_id' => $this->workspace->id]), PlatformStatus::Published);
- [$otherWorkspacePost] = channelPost($elsewhere, Post::factory()->published()->create(['workspace_id' => $elsewhere->workspace_id]), PlatformStatus::Published);
+ [$gone] = channelPost($account, 'published');
+ [$siblingPost] = channelPost($sibling, 'published');
+ [$otherWorkspacePost] = channelPost($elsewhere, 'published');
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
expect(Post::query()->whereKey($gone->id)->exists())->toBeFalse()
->and(Post::query()->whereKey($siblingPost->id)->exists())->toBeTrue()
->and(Post::query()->whereKey($otherWorkspacePost->id)->exists())->toBeTrue()
- ->and($siblingPost->postPlatforms()->sole()->social_account_id)->toBe($sibling->id);
-});
-
-test('a legacy post on several channels keeps its other channels and settles once the disconnected one is gone', function () {
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $settled = Post::factory()->published()->create(['workspace_id' => $this->workspace->id]);
- channelPost($account, $settled, PlatformStatus::Published);
- $kept = PostPlatform::factory()->published()->create(['post_id' => $settled->id, 'social_account_id' => $other->id]);
-
- $inFlight = Post::factory()->create(['workspace_id' => $this->workspace->id, 'status' => Status::Publishing]);
- PostPlatform::factory()->instagram()->create(['post_id' => $inFlight->id, 'social_account_id' => $account->id, 'status' => PlatformStatus::Publishing]);
- PostPlatform::factory()->published()->create(['post_id' => $inFlight->id, 'social_account_id' => $other->id]);
-
- $placeholderOnly = Post::factory()->published()->create(['workspace_id' => $this->workspace->id]);
- channelPost($account, $placeholderOnly, PlatformStatus::Published);
- PostPlatform::factory()->disabled()->create(['post_id' => $placeholderOnly->id, 'social_account_id' => $other->id]);
-
- $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
-
- expect($settled->fresh())->not->toBeNull()
- ->and($settled->postPlatforms()->pluck('id')->all())->toBe([$kept->id])
- ->and($inFlight->fresh()->status)->toBe(Status::Published)
- ->and($inFlight->postPlatforms()->count())->toBe(1)
- ->and(Post::query()->whereKey($placeholderOnly->id)->exists())->toBeFalse();
+ ->and($siblingPost->fresh()->social_account_id)->toBe($sibling->id);
});
test('disconnecting prunes the google business image of a post still waiting for review', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'status' => Status::Publishing]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->pendingReview()->create([
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
@@ -167,7 +149,7 @@ test('reconnecting the same identity imports its posts again without duplicates'
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
expect(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBeNull();
+ ->and($publication->fresh()->post_id)->toBeNull();
$reconnected = SocialAccount::factory()->instagram()->create([
'workspace_id' => $this->workspace->id,
@@ -180,35 +162,31 @@ test('reconnecting the same identity imports its posts again without duplicates'
$imported = Post::query()->imported()->sole();
expect(AnalyticsPublication::query()->count())->toBe(1)
- ->and($imported->postPlatforms()->sole()->social_account_id)->toBe($reconnected->id)
- ->and($publication->fresh()->post_platform_id)->toBe($imported->postPlatforms()->sole()->id);
+ ->and($imported->social_account_id)->toBe($reconnected->id)
+ ->and($publication->fresh()->post_id)->toBe($imported->id);
});
test('a disconnect that fails to delete the channel keeps its posts, media and images', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id]);
- $target = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- ]);
+ $post = Post::factory()->forAccount($account)->scheduled()->create();
$media = Media::factory()->ownedByPost($post)->create();
Storage::put($media->path, 'bytes');
- Storage::put(GoogleBusinessDerivativeCleaner::pathFor($target->id), 'jpeg');
+ Storage::put(GoogleBusinessDerivativeCleaner::pathFor($post), 'jpeg');
Event::listen('eloquent.deleting: '.SocialAccount::class, fn () => throw new RuntimeException('delete failed'));
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))->assertServerError();
expect(SocialAccount::query()->find($account->id))->not->toBeNull()
->and(Post::query()->find($post->id))->not->toBeNull()
- ->and(PostPlatform::query()->find($target->id))->not->toBeNull()
+ ->and($post->fresh()->social_account_id)->toBe($account->id)
->and(Media::query()->find($media->id))->not->toBeNull();
Storage::assertExists($media->path);
- Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($target->id));
+ Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($post));
});
test('a disconnect waits for the channel queue lock and changes nothing while a save holds it', function () {
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- [$post] = channelPost($account, Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id]));
+ [$post] = channelPost($account, 'scheduled');
$lock = Cache::lock("queue:{$account->id}", 10);
expect($lock->get())->toBeTrue();
diff --git a/tests/Feature/Channels/ReorderChannelsTest.php b/tests/Feature/Channels/ReorderChannelsTest.php
index 0fa2ffe63..be63f5e3f 100644
--- a/tests/Feature/Channels/ReorderChannelsTest.php
+++ b/tests/Feature/Channels/ReorderChannelsTest.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -168,8 +167,7 @@ test('the global scope orders every list by position, then created_at and id', f
test('the global scope does not break aggregates, grouping, distinct or relation sub-queries', function () {
[$a, $b] = reorderChannelsAccounts($this->workspace, 2);
$x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $x->id]);
+ Post::factory()->forAccount($x)->scheduled()->create();
$accounts = fn () => SocialAccount::query()->where('workspace_id', $this->workspace->id);
@@ -189,7 +187,7 @@ test('the global scope does not break aggregates, grouping, distinct or relation
->and($accounts()->distinct()->pluck('platform')->map->value->sort()->values()->all())->toBe([Platform::LinkedIn->value, Platform::X->value])
->and(Workspace::query()->withCount('socialAccounts')->find($this->workspace->id)->social_accounts_count)->toBe(3)
->and(Workspace::query()->has('socialAccounts', '>=', 3)->whereKey($this->workspace->id)->exists())->toBeTrue()
- ->and(PostPlatform::query()->whereHas('socialAccount', fn ($query) => $query->where('workspace_id', $this->workspace->id))->count())->toBe(1)
- ->and(PostPlatform::query()->whereIn('social_account_id', $accounts()->select('id'))->count())->toBe(1)
+ ->and(Post::query()->whereHas('socialAccount', fn ($query) => $query->where('workspace_id', $this->workspace->id))->count())->toBe(1)
+ ->and(Post::query()->whereIn('social_account_id', $accounts()->select('id'))->count())->toBe(1)
->and($accounts()->whereKey([$a->id, $b->id])->pluck('id')->all())->toBe([$a->id, $b->id]);
});
diff --git a/tests/Feature/Commands/CheckUpcomingPostConnectionsTest.php b/tests/Feature/Commands/CheckUpcomingPostConnectionsTest.php
index 4727e2b84..c5c25029b 100644
--- a/tests/Feature/Commands/CheckUpcomingPostConnectionsTest.php
+++ b/tests/Feature/Commands/CheckUpcomingPostConnectionsTest.php
@@ -2,10 +2,8 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Jobs\VerifyUpcomingPostConnections;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Support\Facades\Event;
@@ -19,16 +17,9 @@ test('dispatches the job once per workspace with at-risk posts, even with multip
$account = SocialAccount::factory()->facebook()->create(['workspace_id' => $workspace->id]);
foreach (range(1, 5) as $i) {
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(10 * $i),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
}
$this->artisan('social:check-upcoming-connections')
@@ -43,37 +34,23 @@ test('dispatches nothing when no workspace has posts in the window', function ()
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addHours(5),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$this->artisan('social:check-upcoming-connections')->assertSuccessful();
Queue::assertNothingPushed();
});
-test('dispatches nothing when the only at-risk post_platform was already warned today', function () {
+test('dispatches nothing when the only at-risk post was already warned today', function () {
Event::fake();
Queue::fake();
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
'connection_warning_sent_at' => now()->subHours(2),
]);
@@ -83,45 +60,15 @@ test('dispatches nothing when the only at-risk post_platform was already warned
Queue::assertNothingPushed();
});
-test('dispatches nothing when the only at-risk post_platform is disabled', function () {
- Event::fake();
- Queue::fake();
-
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(30),
- ]);
- PostPlatform::factory()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
-
- $this->artisan('social:check-upcoming-connections')
- ->assertSuccessful();
-
- Queue::assertNothingPushed();
-});
-
test('dispatches nothing when the only at-risk post is still a draft', function () {
Event::fake();
Queue::fake();
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->draft()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->draft()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$this->artisan('social:check-upcoming-connections')
->assertSuccessful();
@@ -138,16 +85,9 @@ test('dispatches one job per distinct workspace when multiple workspaces have at
foreach ([$workspaceA, $workspaceB] as $workspace) {
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
}
$this->artisan('social:check-upcoming-connections')->assertSuccessful();
diff --git a/tests/Feature/Commands/ProcessScheduledPostsTest.php b/tests/Feature/Commands/ProcessScheduledPostsTest.php
index 2a128ea28..2db620bc9 100644
--- a/tests/Feature/Commands/ProcessScheduledPostsTest.php
+++ b/tests/Feature/Commands/ProcessScheduledPostsTest.php
@@ -6,7 +6,6 @@ use App\Console\Commands\ProcessScheduledPosts;
use App\Enums\Post\Status as PostStatus;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -24,18 +23,12 @@ test('process scheduled posts dispatches publish job for due posts', function ()
$socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $duePost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $duePost = Post::factory()->forAccount($socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->subMinute(),
]);
- PostPlatform::factory()->create([
- 'post_id' => $duePost->id,
- 'social_account_id' => $socialAccount->id,
- ]);
-
$this->artisan(ProcessScheduledPosts::class)->assertSuccessful();
Queue::assertPushed(PublishPost::class, function ($job) use ($duePost) {
@@ -48,18 +41,12 @@ test('process scheduled posts does not dispatch for future posts', function () {
$socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $futurePost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $futurePost = Post::factory()->forAccount($socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->addDay(),
]);
- PostPlatform::factory()->create([
- 'post_id' => $futurePost->id,
- 'social_account_id' => $socialAccount->id,
- ]);
-
$this->artisan(ProcessScheduledPosts::class)->assertSuccessful();
Queue::assertNotPushed(PublishPost::class);
@@ -70,16 +57,10 @@ test('process scheduled posts does not dispatch for draft posts', function () {
$socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $draftPost = Post::factory()->draft()->create([
- 'workspace_id' => $this->workspace->id,
+ $draftPost = Post::factory()->forAccount($socialAccount)->draft()->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->create([
- 'post_id' => $draftPost->id,
- 'social_account_id' => $socialAccount->id,
- ]);
-
$this->artisan(ProcessScheduledPosts::class)->assertSuccessful();
Queue::assertNotPushed(PublishPost::class);
@@ -90,20 +71,12 @@ test('process scheduled posts handles multiple due posts', function () {
$socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $posts = Post::factory()->count(3)->create([
- 'workspace_id' => $this->workspace->id,
+ $posts = Post::factory()->forAccount($socialAccount)->count(3)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->subMinute(),
]);
- foreach ($posts as $post) {
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $socialAccount->id,
- ]);
- }
-
$this->artisan(ProcessScheduledPosts::class)->assertSuccessful();
Queue::assertPushed(PublishPost::class, 3);
@@ -115,13 +88,11 @@ test('a failure claiming one due post does not stop the rest of the tick', funct
$socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
$posts = collect(range(1, 3))->map(function () use ($socialAccount) {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->subMinute(),
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $socialAccount->id]);
return $post;
});
diff --git a/tests/Feature/Commands/ReconcileGoogleBusinessPostsTest.php b/tests/Feature/Commands/ReconcileGoogleBusinessPostsTest.php
index 7ea1afb32..0ce5dee93 100644
--- a/tests/Feature/Commands/ReconcileGoogleBusinessPostsTest.php
+++ b/tests/Feature/Commands/ReconcileGoogleBusinessPostsTest.php
@@ -2,10 +2,10 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status as PlatformStatus;
+use App\Enums\Post\PublishStatus as PlatformStatus;
+use App\Enums\Post\Status as PostStatus;
use App\Jobs\ReconcileGoogleBusinessPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -16,17 +16,11 @@ beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $this->post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
});
$target = function (array $attributes = []) {
- return PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => test()->post->id,
- 'social_account_id' => test()->account->id,
- 'status' => PlatformStatus::PendingReview,
+ return Post::factory()->forAccount(test()->account)->pendingReview()->create([
+ 'user_id' => test()->user->id,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'submitted_at' => now()->subMinutes(30),
...$attributes,
@@ -35,18 +29,18 @@ $target = function (array $attributes = []) {
test('it dispatches a reconciliation for every target still awaiting review', function () use ($target) {
$awaiting = $target();
- $published = $target(['status' => PlatformStatus::Published]);
+ $published = $target(['status' => PostStatus::Published, 'publish_status' => PlatformStatus::Published]);
$this->artisan('social:reconcile-google-business-posts')->assertSuccessful();
Queue::assertPushed(ReconcileGoogleBusinessPost::class, 1);
Queue::assertPushed(
ReconcileGoogleBusinessPost::class,
- fn (ReconcileGoogleBusinessPost $job): bool => $job->postPlatform->id === $awaiting->id,
+ fn (ReconcileGoogleBusinessPost $job): bool => $job->post->id === $awaiting->id,
);
Queue::assertNotPushed(
ReconcileGoogleBusinessPost::class,
- fn (ReconcileGoogleBusinessPost $job): bool => $job->postPlatform->id === $published->id,
+ fn (ReconcileGoogleBusinessPost $job): bool => $job->post->id === $published->id,
);
});
@@ -65,18 +59,10 @@ test('it dispatches again once the reconciliation interval has passed', function
Queue::assertPushed(
ReconcileGoogleBusinessPost::class,
- fn (ReconcileGoogleBusinessPost $job): bool => $job->postPlatform->id === $awaiting->id,
+ fn (ReconcileGoogleBusinessPost $job): bool => $job->post->id === $awaiting->id,
);
});
-test('it skips a disabled target still awaiting review', function () use ($target) {
- $target(['enabled' => false]);
-
- $this->artisan('social:reconcile-google-business-posts')->assertSuccessful();
-
- Queue::assertNotPushed(ReconcileGoogleBusinessPost::class);
-});
-
test('it skips a target that has no remote post id', function () use ($target) {
$target(['platform_post_id' => null]);
diff --git a/tests/Feature/Commands/RecoverStuckPostsTest.php b/tests/Feature/Commands/RecoverStuckPostsTest.php
index ea4fc6c9c..46adc7ab2 100644
--- a/tests/Feature/Commands/RecoverStuckPostsTest.php
+++ b/tests/Feature/Commands/RecoverStuckPostsTest.php
@@ -2,15 +2,14 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
-use App\Events\PostPlatformStatusUpdated;
+use App\Events\PostStatusUpdated;
use App\Jobs\PublishToSocialPlatform;
use App\Jobs\ReconcileGoogleBusinessPost;
use App\Jobs\SendNotification;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -25,6 +24,7 @@ beforeEach(function () {
Queue::fake([SendNotification::class]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
$this->socialAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
@@ -32,144 +32,93 @@ beforeEach(function () {
});
test('it recovers posts stuck in publishing for over 1 hour', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Publishing,
'updated_at' => now()->subHours(2),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- $platform->refresh();
$post->refresh();
- expect($platform->status)->toBe(PlatformStatus::Failed);
- expect($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
- expect($platform->error_context)->toMatchArray([
+ expect($post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($post->error_message)->toBe(__('posts.errors.publishing_timed_out'));
+ expect($post->error_context)->toMatchArray([
'category' => 'timeout',
]);
expect($post->status)->toBe(PostStatus::Failed);
});
test('it broadcasts the timed out target so open publish pages move the post to sent', function () {
- Event::fake([PostPlatformStatusUpdated::class]);
+ Event::fake([PostStatusUpdated::class]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Publishing,
'updated_at' => now()->subHours(2),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
Event::assertDispatched(
- PostPlatformStatusUpdated::class,
- fn (PostPlatformStatusUpdated $event): bool => $event->postPlatform->is($platform)
- && $event->postPlatform->status === PlatformStatus::Failed,
+ PostStatusUpdated::class,
+ fn (PostStatusUpdated $event): bool => $event->post->is($post)
+ && $event->post->publish_status === PlatformStatus::Failed,
);
});
-test('it does not touch posts publishing for less than 1 hour', function () {
+test('it fails a post without a channel left publishing for over 1 hour, notifying once', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subMinutes(30),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subMinutes(30),
+ 'publish_status' => PlatformStatus::Pending,
+ 'updated_at' => now()->subHours(2),
]);
+ $this->artisan('social:recover-stuck-posts')->assertSuccessful();
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- $platform->refresh();
- expect($platform->status)->toBe(PlatformStatus::Publishing);
+ expect($post->fresh()->status)->toBe(PostStatus::Failed);
+ Queue::assertPushed(SendNotification::class, 1);
});
-test('it marks post as partially published when some platforms succeeded', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+test('it does not touch posts publishing for less than 1 hour', function () {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
-
- // One succeeded
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Published,
- 'enabled' => true,
- ]);
-
- // One stuck
- $stuckPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::Instagram,
- ])->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
+ 'publish_status' => PlatformStatus::Publishing,
+ 'updated_at' => now()->subMinutes(30),
+ 'publication_updated_at' => now()->subMinutes(30),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- $stuckPlatform->refresh();
$post->refresh();
-
- expect($stuckPlatform->status)->toBe(PlatformStatus::Failed);
- expect($post->status)->toBe(PostStatus::PartiallyPublished);
+ expect($post->publish_status)->toBe(PlatformStatus::Publishing);
});
test('it recovers platforms stuck in retrying for over 1 hour', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::Retrying,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- $platform->refresh();
$post->refresh();
- expect($platform->status)->toBe(PlatformStatus::Failed)
- ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
+ expect($post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($post->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($post->status)->toBe(PostStatus::Failed);
});
@@ -178,31 +127,25 @@ test('it keeps TikTok photo derivatives when recovering a stuck in-flight publis
$path = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($path, 'image');
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
$account = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $this->workspace->id,
]);
- $platform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_publish_id' => 'publish-stuck',
'tiktok_derivative_paths' => [$path],
],
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
Storage::assertExists($path);
- expect($platform->fresh()->error_context)->toMatchArray([
+ expect($post->fresh()->error_context)->toMatchArray([
'tiktok_publish_id' => 'publish-stuck',
'category' => 'timeout',
]);
@@ -213,30 +156,24 @@ test('it prunes TikTok photo derivatives when recovering a stuck retry with no p
$path = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($path, 'image');
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
$account = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $this->workspace->id,
]);
- $platform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_derivative_paths' => [$path],
],
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
Storage::assertMissing($path);
- expect($platform->fresh()->error_context['category'] ?? null)->toBe('timeout');
+ expect($post->fresh()->error_context['category'] ?? null)->toBe('timeout');
});
test('it preserves an Instagram workflow when recovering a stuck retry', function () {
@@ -244,157 +181,104 @@ test('it preserves an Instagram workflow when recovering a stuck retry', functio
'stage' => 'final_container',
'container_id' => 'container-stuck',
];
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
$account = SocialAccount::factory()->instagram()->create([
'workspace_id' => $this->workspace->id,
]);
- $platform = PostPlatform::factory()->instagram()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'instagram_workflow' => $workflow,
'retry_count' => 40,
],
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($platform->fresh()->status)->toBe(PlatformStatus::Failed)
- ->and($platform->fresh()->error_context)->toMatchArray([
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($post->fresh()->error_context)->toMatchArray([
'instagram_workflow' => $workflow,
'category' => 'timeout',
]);
});
test('it does not finalize a post while a platform is still actively retrying', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::Retrying,
'error_message' => __('posts.errors.platform_unavailable'),
- 'updated_at' => now()->subMinutes(5),
+ 'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subMinutes(5),
]);
$this->artisan('social:recover-stuck-posts')
->assertSuccessful();
- $platform->refresh();
$post->refresh();
- expect($platform->status)->toBe(PlatformStatus::Retrying)
+ expect($post->publish_status)->toBe(PlatformStatus::Retrying)
->and($post->status)->toBe(PostStatus::Publishing);
});
-test('it does not finalize a post while a platform is still actively pending or publishing', function (PlatformStatus $status) {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+test('it does not fail a retry still waiting for its limit window', function () {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Retrying,
+ 'retry_at' => now()->addHours(3),
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => $status,
- 'enabled' => true,
- 'updated_at' => now()->subMinutes(5),
- ]);
-
- $this->artisan('social:recover-stuck-posts')
- ->assertSuccessful();
-
- $platform->refresh();
- $post->refresh();
+ $this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($platform->status)->toBe($status)
- ->and($post->status)->toBe(PostStatus::Publishing);
-})->with([
- PlatformStatus::Pending,
- PlatformStatus::Publishing,
-]);
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
+ ->and($post->fresh()->status)->toBe(PostStatus::Publishing);
+});
-test('it fails stale platforms but keeps the post publishing when another platform is still retrying', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+test('it does not finalize a post while a platform is still actively pending or publishing', function (PlatformStatus $status) {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => $status,
'updated_at' => now()->subHours(2),
- ]);
-
- $stalePlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
- ]);
-
- $activeRetry = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::Pinterest,
- ])->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
- 'error_message' => __('posts.errors.platform_unavailable'),
- 'updated_at' => now()->subMinutes(5),
+ 'publication_updated_at' => now()->subMinutes(5),
]);
$this->artisan('social:recover-stuck-posts')
->assertSuccessful();
- $stalePlatform->refresh();
- $activeRetry->refresh();
$post->refresh();
- expect($stalePlatform->status)->toBe(PlatformStatus::Failed)
- ->and($stalePlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
- ->and($activeRetry->status)->toBe(PlatformStatus::Retrying)
+ expect($post->publish_status)->toBe($status)
->and($post->status)->toBe(PostStatus::Publishing);
-});
+})->with([
+ PlatformStatus::Pending,
+ PlatformStatus::Publishing,
+]);
test('it fails a google business review that outlived the review ceiling', function () {
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(25),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::PendingReview,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::PendingReview,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'submitted_at' => now()->subHours(25),
'updated_at' => now()->subHours(25),
+ 'publication_updated_at' => now()->subHours(25),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($platform->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($platform->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($post->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
->and($post->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class);
@@ -405,89 +289,46 @@ test('it prunes the google business jpeg when a publish times out before review'
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::Publishing,
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Publishing,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($platform->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
Storage::assertMissing($path);
- expect($platform->fresh()->status)->toBe(PlatformStatus::Failed)
- ->and($platform->fresh()->error_message)->toBe(__('posts.errors.publishing_timed_out'))
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($post->fresh()->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($post->fresh()->status)->toBe(PostStatus::Failed);
});
-test('it rejects a disabled google business review and fails the parent', function () {
- Storage::fake();
- $account = SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $this->workspace->id,
- ]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => false,
- 'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
- 'updated_at' => now()->subHours(2),
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($platform->id);
- Storage::put($path, 'image');
-
- $this->artisan('social:recover-stuck-posts')->assertSuccessful();
-
- Storage::assertMissing($path);
- expect($platform->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($platform->fresh()->enabled)->toBeFalse()
- ->and($platform->fresh()->error_message)->toBe(__('posts.errors.target_disabled'))
- ->and($post->fresh()->status)->toBe(PostStatus::Failed);
- Queue::assertPushed(SendNotification::class);
-});
-
test('recover then reconcile on an expired review notifies once and prunes the jpeg', function () {
Storage::fake();
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->pendingReview()->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(25),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'submitted_at' => now()->subHours(25),
'updated_at' => now()->subHours(25),
+ 'publication_updated_at' => now()->subHours(25),
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($platform->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- (new ReconcileGoogleBusinessPost($platform->fresh()))->handle();
+ (new ReconcileGoogleBusinessPost($post->fresh()))->handle();
Storage::assertMissing($path);
- expect($platform->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($platform->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($post->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
->and($post->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class, 1);
});
@@ -497,51 +338,39 @@ test('it prunes the google business jpeg when a review outlives the ceiling', fu
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(25),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::PendingReview,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::PendingReview,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'submitted_at' => now()->subHours(25),
'updated_at' => now()->subHours(25),
+ 'publication_updated_at' => now()->subHours(25),
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($platform->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
Storage::assertMissing($path);
- expect($platform->fresh()->status)->toBe(PlatformStatus::Rejected);
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::Rejected);
});
test('it does not fail a google business post still sitting in review', function () {
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
+ 'publish_status' => PlatformStatus::PendingReview,
'updated_at' => now()->subHours(2),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::PendingReview,
- 'enabled' => true,
- 'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($platform->fresh()->status)->toBe(PlatformStatus::PendingReview)
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
->and($post->fresh()->status)->toBe(PostStatus::Publishing);
});
@@ -549,26 +378,20 @@ test('it does not fail a google business review whose submitted_at is still miss
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(25),
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::PendingReview,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::PendingReview,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'submitted_at' => null,
'created_at' => now()->subDays(3),
'updated_at' => now()->subHours(25),
+ 'publication_updated_at' => now()->subHours(25),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($platform->fresh()->status)->toBe(PlatformStatus::PendingReview)
+ expect($post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
->and($post->fresh()->status)->toBe(PostStatus::Publishing);
});
@@ -576,38 +399,30 @@ test('delayed publish job no-ops after recover fails a stuck retrying platform',
Event::fake();
Mail::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- 'updated_at' => now()->subHours(2),
- ]);
-
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => PlatformStatus::Retrying,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::Retrying,
'error_message' => __('posts.errors.platform_unavailable'),
'updated_at' => now()->subHours(2),
+ 'publication_updated_at' => now()->subHours(2),
]);
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- $platform->refresh();
- expect($platform->status)->toBe(PlatformStatus::Failed)
- ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
+ $post->refresh();
+ expect($post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($post->error_message)->toBe(__('posts.errors.publishing_timed_out'));
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($platform))->handle();
+ (new PublishToSocialPlatform($post->fresh()))->handle();
- $platform->refresh();
$post->refresh();
- expect($platform->status)->toBe(PlatformStatus::Failed)
- ->and($platform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
+ expect($post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($post->error_message)->toBe(__('posts.errors.publishing_timed_out'))
->and($post->status)->toBe(PostStatus::Failed);
});
diff --git a/tests/Feature/Commands/RetryFailedPostTest.php b/tests/Feature/Commands/RetryFailedPostTest.php
index 38461ca88..f8a4848a8 100644
--- a/tests/Feature/Commands/RetryFailedPostTest.php
+++ b/tests/Feature/Commands/RetryFailedPostTest.php
@@ -2,15 +2,14 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Exceptions\Social\ErrorCategory;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -27,12 +26,6 @@ beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::PartiallyPublished,
- 'published_at' => now()->subHour(),
- ]);
});
test('it does not expose retry filters or confirmation bypasses', function () {
@@ -42,57 +35,36 @@ test('it does not expose retry filters or confirmation bypasses', function () {
->and($command->getDefinition()->hasOption('platform'))->toBeFalse();
});
-test('it queues fresh attempts only for failed enabled platforms', function () {
+test('it queues a fresh attempt for a failed post and clears its stale result', function () {
Bus::fake([PublishToSocialPlatform::class]);
- $publishedPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->threads()->create([
+ 'workspace_id' => $this->workspace->id,
]);
- $failedThreads = PostPlatform::factory()->threads()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->threads()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $failedThreads = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'platform_post_id' => 'stale-post-id',
'platform_url' => 'https://threads.net/stale',
'published_at' => now()->subHour(),
'error_context' => ['remote_operation_id' => 'stale-operation'],
]);
- $failedPinterest = PostPlatform::factory()->pinterest()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->pinterest()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
- ]);
- $disabledFailedPlatform = PostPlatform::factory()->tiktok()->failed()->disabled()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
- ]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedThreads->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->assertSuccessful();
- expect($this->post->fresh()->status)->toBe(PostStatus::Publishing)
- ->and($failedThreads->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedThreads->fresh()->status)->toBe(PostStatus::Publishing)
+ ->and($failedThreads->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedThreads->fresh()->platform_post_id)->toBeNull()
->and($failedThreads->fresh()->platform_url)->toBeNull()
->and($failedThreads->fresh()->published_at)->toBeNull()
->and($failedThreads->fresh()->error_message)->toBeNull()
- ->and($failedThreads->fresh()->error_context)->toBeNull()
- ->and($failedPinterest->fresh()->status)->toBe(PlatformStatus::Pending)
- ->and($publishedPlatform->fresh()->status)->toBe(PlatformStatus::Published)
- ->and($disabledFailedPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ ->and($failedThreads->fresh()->error_context)->toBeNull();
- Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 2);
+ Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 1);
Bus::assertDispatched(
PublishToSocialPlatform::class,
- fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($failedThreads) && $job->uniqueAttempt === 0,
+ fn (PublishToSocialPlatform $job): bool => $job->post->is($failedThreads) && $job->uniqueAttempt === 0,
);
});
@@ -102,11 +74,11 @@ test('it resumes a TikTok publish_id instead of starting from scratch', function
$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($derivativePath, 'temporary image');
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'tiktok_publish_id' => 'stale-publish-id',
'tiktok_derivative_paths' => [$derivativePath],
@@ -116,41 +88,41 @@ test('it resumes a TikTok publish_id instead of starting from scratch', function
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
Storage::assertExists($derivativePath);
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedTikTok->fresh()->error_context)->toBe([
'tiktok_publish_id' => 'stale-publish-id',
'tiktok_derivative_paths' => [$derivativePath],
]);
- Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($failedTikTok));
+ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->post->is($failedTikTok));
});
test('it resumes a TikTok publish_id after an account or job interruption', function (ErrorCategory $category) {
Bus::fake([PublishToSocialPlatform::class]);
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'tiktok_publish_id' => 'pub_in_flight',
'category' => $category->value,
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedTikTok->fresh()->error_context)->toBe([
'tiktok_publish_id' => 'pub_in_flight',
]);
@@ -166,11 +138,11 @@ test('it keeps an Instagram workflow checkpoint on retry', function () {
'stage' => 'final_container',
'container_id' => 'container-123',
];
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'instagram_workflow' => $workflow,
'retry_count' => 90,
@@ -179,12 +151,12 @@ test('it keeps an Instagram workflow checkpoint on retry', function () {
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedInstagram->fresh()->error_context)->toBe([
'instagram_workflow' => $workflow,
]);
@@ -196,55 +168,58 @@ test('it removes stale TikTok derivatives when there is no publish_id to resume'
$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($derivativePath, 'temporary image');
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'tiktok_derivative_paths' => [$derivativePath],
'category' => 'unknown',
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
Storage::assertMissing($derivativePath);
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedTikTok->fresh()->error_context)->toBeNull();
- Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($failedTikTok));
+ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->post->is($failedTikTok));
});
test('it does not change the post when confirmation is declined', function () {
Bus::fake([PublishToSocialPlatform::class]);
- $failedPlatform = PostPlatform::factory()->threads()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->threads()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->threads()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedPlatform = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'no')
+ $this->artisan('posts:retry', ['post' => $failedPlatform->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'no')
->assertSuccessful();
- expect($this->post->fresh()->status)->toBe(PostStatus::PartiallyPublished)
- ->and($failedPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($failedPlatform->fresh()->status)->toBe(PostStatus::Failed)
+ ->and($failedPlatform->fresh()->publish_status)->toBe(PlatformStatus::Failed);
Bus::assertNotDispatched(PublishToSocialPlatform::class);
});
test('it rejects posts that are not in a terminal failure state', function () {
Bus::fake([PublishToSocialPlatform::class]);
- $this->post->update(['status' => PostStatus::Publishing]);
+ $post = Post::factory()->linkedin()->publishing()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ ]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsOutput('Only failed or partially published posts can be retried.')
+ $this->artisan('posts:retry', ['post' => $post->id])
+ ->expectsOutput('Only failed posts with a channel can be retried.')
->assertFailed();
Bus::assertNotDispatched(PublishToSocialPlatform::class);
@@ -252,38 +227,35 @@ test('it rejects posts that are not in a terminal failure state', function () {
test('it retries a completely failed post', function () {
Bus::fake([PublishToSocialPlatform::class]);
- $this->post->update(['status' => PostStatus::Failed]);
- $failedPlatform = PostPlatform::factory()->threads()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->threads()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->threads()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedPlatform = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedPlatform->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->assertSuccessful();
- expect($this->post->fresh()->status)->toBe(PostStatus::Publishing)
- ->and($failedPlatform->fresh()->status)->toBe(PlatformStatus::Pending);
+ expect($failedPlatform->fresh()->status)->toBe(PostStatus::Publishing)
+ ->and($failedPlatform->fresh()->publish_status)->toBe(PlatformStatus::Pending);
- Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($failedPlatform));
+ Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->post->is($failedPlatform));
});
-test('it fails when no failed enabled platform matches', function () {
+test('it rejects a failed post without a channel', function () {
Bus::fake([PublishToSocialPlatform::class]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $post = Post::factory()->failed()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsOutput('No failed enabled platforms matched this post.')
+ $this->artisan('posts:retry', ['post' => $post->id])
+ ->expectsOutput('Only failed posts with a channel can be retried.')
->assertFailed();
- expect($this->post->fresh()->status)->toBe(PostStatus::PartiallyPublished);
+ expect($post->fresh()->status)->toBe(PostStatus::Failed);
Bus::assertNotDispatched(PublishToSocialPlatform::class);
});
@@ -298,7 +270,13 @@ test('it fails when the post does not exist', function () {
});
test('a TikTok retry with a publish_id resumes instead of calling init', function () {
- $this->post->update([
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => 'tiktoker',
+ 'token_expires_at' => now()->addDay(),
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
@@ -306,15 +284,6 @@ test('a TikTok retry with a publish_id resumes instead of calling init', functio
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
]],
- ]);
-
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => 'tiktoker',
- 'token_expires_at' => now()->addDay(),
- ]),
'error_context' => [
'tiktok_publish_id' => 'pub_existing',
'retry_count' => 120,
@@ -326,8 +295,8 @@ test('a TikTok retry with a publish_id resumes instead of calling init', functio
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->assertSuccessful();
$api = config('trypost.platforms.tiktok.api');
@@ -342,14 +311,20 @@ test('a TikTok retry with a publish_id resumes instead of calling init', functio
(new PublishToSocialPlatform($failedTikTok->fresh()))->handle();
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedTikTok->fresh()->platform_post_id)->toBe('video_123');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('an Instagram retry with a workflow resumes instead of creating a container', function () {
- $this->post->update([
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform_user_id' => 'ig_123456789',
+ 'token_expires_at' => now()->addDays(60),
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'media' => [[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
@@ -357,15 +332,6 @@ test('an Instagram retry with a workflow resumes instead of creating a container
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
]],
- ]);
-
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_123456789',
- 'token_expires_at' => now()->addDays(60),
- ]),
'content_type' => ContentType::InstagramFeed,
'error_context' => [
'instagram_workflow' => [
@@ -381,8 +347,8 @@ test('an Instagram retry with a workflow resumes instead of creating a container
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->assertSuccessful();
Http::fake([
@@ -395,7 +361,7 @@ test('an Instagram retry with a workflow resumes instead of creating a container
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedInstagram->fresh()->platform_post_id)->toBe('media-123456789');
Http::assertNotSent(fn ($request) => $request->method() === 'POST' && str_ends_with($request->url(), '/ig_123456789/media'));
@@ -407,11 +373,11 @@ test('it treats an empty TikTok publish_id as a new attempt', function () {
$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($derivativePath, 'temporary image');
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'tiktok_publish_id' => '',
'tiktok_derivative_paths' => [$derivativePath],
@@ -419,81 +385,39 @@ test('it treats an empty TikTok publish_id as a new attempt', function () {
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
Storage::assertMissing($derivativePath);
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedTikTok->fresh()->error_context)->toBeNull();
});
test('it treats an empty Instagram workflow as a new attempt', function () {
Bus::fake([PublishToSocialPlatform::class]);
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => [
'instagram_workflow' => [],
'category' => 'unknown',
],
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedInstagram->fresh()->error_context)->toBeNull();
});
-test('it keeps TikTok and Instagram checkpoints independently on the same post', function () {
- Bus::fake([PublishToSocialPlatform::class]);
-
- $workflow = [
- 'stage' => 'final_container',
- 'container_id' => 'container-123',
- ];
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
- 'error_context' => [
- 'tiktok_publish_id' => 'pub_existing',
- 'retry_count' => 12,
- 'category' => 'platform_unavailable',
- ],
- ]);
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
- 'error_context' => [
- 'instagram_workflow' => $workflow,
- 'retry_count' => 8,
- 'category' => 'timeout',
- ],
- ]);
-
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
- ->expectsOutputToContain('Resume')
- ->assertSuccessful();
-
- expect($failedTikTok->fresh()->error_context)->toBe([
- 'tiktok_publish_id' => 'pub_existing',
- ])->and($failedInstagram->fresh()->error_context)->toBe([
- 'instagram_workflow' => $workflow,
- ]);
-});
-
test('it starts over when the failure category is not resumable', function (?string $category) {
Bus::fake([PublishToSocialPlatform::class]);
@@ -503,20 +427,20 @@ test('it starts over when the failure category is not resumable', function (?str
$errorContext['category'] = $category;
}
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => $errorContext,
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedTikTok->fresh()->error_context)->toBeNull();
})->with([
'media format' => ['media_format'],
@@ -529,7 +453,13 @@ test('it starts over when the failure category is not resumable', function (?str
]);
test('a TikTok retry after a remote FAILED starts a new publish', function () {
- $this->post->update([
+ $account = SocialAccount::factory()->tiktok()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => 'tiktoker',
+ 'token_expires_at' => now()->addDay(),
+ ]);
+ $failedTikTok = Post::factory()->tiktok()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'media' => [[
'id' => 'test-media-video',
'path' => 'media/2026-01/test-video.mp4',
@@ -537,15 +467,6 @@ test('a TikTok retry after a remote FAILED starts a new publish', function () {
'mime_type' => 'video/mp4',
'original_filename' => 'test-video.mp4',
]],
- ]);
-
- $failedTikTok = PostPlatform::factory()->tiktok()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => 'tiktoker',
- 'token_expires_at' => now()->addDay(),
- ]),
'error_context' => [
'tiktok_publish_id' => 'pub_dead',
'category' => 'media_format',
@@ -555,8 +476,8 @@ test('a TikTok retry after a remote FAILED starts a new publish', function () {
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedTikTok->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
@@ -577,14 +498,20 @@ test('a TikTok retry after a remote FAILED starts a new publish', function () {
(new PublishToSocialPlatform($failedTikTok->fresh()))->handle();
- expect($failedTikTok->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedTikTok->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedTikTok->fresh()->platform_post_id)->toBe('video_456');
Http::assertSent(fn ($request) => str_contains($request->url(), '/init/'));
});
test('an Instagram retry after a container ERROR starts a new container', function () {
- $this->post->update([
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform_user_id' => 'ig_123456789',
+ 'token_expires_at' => now()->addDays(60),
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'media' => [[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
@@ -592,15 +519,6 @@ test('an Instagram retry after a container ERROR starts a new container', functi
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
]],
- ]);
-
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_123456789',
- 'token_expires_at' => now()->addDays(60),
- ]),
'content_type' => ContentType::InstagramFeed,
'error_context' => [
'instagram_workflow' => [
@@ -614,8 +532,8 @@ test('an Instagram retry after a container ERROR starts a new container', functi
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
@@ -632,7 +550,7 @@ test('an Instagram retry after a container ERROR starts a new container', functi
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedInstagram->fresh()->platform_post_id)->toBe('media-456');
Http::assertSent(fn ($request) => $request->method() === 'POST' && str_ends_with($request->url(), '/ig_123456789/media'));
@@ -640,7 +558,13 @@ test('an Instagram retry after a container ERROR starts a new container', functi
});
test('an Instagram retry after a container EXPIRED starts a new container', function () {
- $this->post->update([
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform_user_id' => 'ig_123456789',
+ 'token_expires_at' => now()->addDays(60),
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'media' => [[
'id' => 'test-media-id',
'path' => 'media/2026-01/test-image.jpg',
@@ -648,15 +572,6 @@ test('an Instagram retry after a container EXPIRED starts a new container', func
'mime_type' => 'image/jpeg',
'original_filename' => 'test.jpg',
]],
- ]);
-
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_123456789',
- 'token_expires_at' => now()->addDays(60),
- ]),
'content_type' => ContentType::InstagramFeed,
'error_context' => [
'instagram_workflow' => [
@@ -670,8 +585,8 @@ test('an Instagram retry after a container EXPIRED starts a new container', func
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
@@ -681,13 +596,13 @@ test('an Instagram retry after a container EXPIRED starts a new container', func
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($failedInstagram->fresh()->error_context['category'] ?? null)->toBe('server_error');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/media_publish'));
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('New')
->assertSuccessful();
@@ -704,7 +619,7 @@ test('an Instagram retry after a container EXPIRED starts a new container', func
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedInstagram->fresh()->platform_post_id)->toBe('media-789');
Http::assertSent(fn ($request) => $request->method() === 'POST' && str_ends_with($request->url(), '/ig_123456789/media'));
@@ -712,13 +627,13 @@ test('an Instagram retry after a container EXPIRED starts a new container', func
});
test('an Instagram resume of a published container completes without media_publish', function () {
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_123456789',
- 'token_expires_at' => now()->addDays(60),
- ]),
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform_user_id' => 'ig_123456789',
+ 'token_expires_at' => now()->addDays(60),
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'content_type' => ContentType::InstagramFeed,
'error_context' => [
'instagram_workflow' => [
@@ -732,8 +647,8 @@ test('an Instagram resume of a published container completes without media_publi
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
@@ -756,7 +671,7 @@ test('an Instagram resume of a published container completes without media_publi
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedInstagram->fresh()->platform_post_id)->toBe('container-123')
->and($failedInstagram->fresh()->platform_url)->toBeNull();
@@ -766,13 +681,13 @@ test('an Instagram resume of a published container completes without media_publi
});
test('an Instagram resume of a checkpointed media id completes without media_publish', function () {
- $failedInstagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform_user_id' => 'ig_123456789',
- 'token_expires_at' => now()->addDays(60),
- ]),
+ $account = SocialAccount::factory()->instagram()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform_user_id' => 'ig_123456789',
+ 'token_expires_at' => now()->addDays(60),
+ ]);
+ $failedInstagram = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'content_type' => ContentType::InstagramFeed,
'error_context' => [
'instagram_workflow' => [
@@ -787,8 +702,8 @@ test('an Instagram resume of a checkpointed media id completes without media_pub
Mail::fake();
Queue::fake();
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedInstagram->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
@@ -804,7 +719,7 @@ test('an Instagram resume of a checkpointed media id completes without media_pub
(new PublishToSocialPlatform($failedInstagram->fresh()))->handle();
- expect($failedInstagram->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($failedInstagram->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($failedInstagram->fresh()->platform_post_id)->toBe('media-persisted')
->and($failedInstagram->fresh()->platform_url)->toBe('https://www.instagram.com/p/PERSISTED/');
@@ -817,20 +732,20 @@ test('it keeps the live segments of a thread whatever the failure category', fun
Bus::fake([PublishToSocialPlatform::class]);
$progress = [['hash' => 'h0', 'id' => '1'], ['hash' => 'h1', 'id' => '2']];
- $failedMastodon = PostPlatform::factory()->mastodon()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => SocialAccount::factory()->mastodon()->create([
- 'workspace_id' => $this->workspace->id,
- ]),
+ $account = SocialAccount::factory()->mastodon()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $failedMastodon = Post::factory()->forAccount($account)->failed()->create([
+ 'user_id' => $this->user->id,
'error_context' => array_filter(['category' => $category, 'thread_progress' => $progress, 'failed_at' => now()->toIso8601String()]),
]);
- $this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ $this->artisan('posts:retry', ['post' => $failedMastodon->id])
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->expectsOutputToContain('Resume')
->assertSuccessful();
- expect($failedMastodon->fresh()->status)->toBe(PlatformStatus::Pending)
+ expect($failedMastodon->fresh()->publish_status)->toBe(PlatformStatus::Pending)
->and($failedMastodon->fresh()->error_context)->toEqual(['thread_progress' => $progress]);
})->with([
'media format' => ['media_format'],
diff --git a/tests/Feature/Composer/ComposerLiveDataTest.php b/tests/Feature/Composer/ComposerLiveDataTest.php
index 8055b0d34..210449964 100644
--- a/tests/Feature/Composer/ComposerLiveDataTest.php
+++ b/tests/Feature/Composer/ComposerLiveDataTest.php
@@ -6,7 +6,6 @@ use App\Actions\Post\Queue\ListTakenSlots;
use App\Enums\SocialAccount\Platform;
use App\Http\Resources\App\HandleInertiaRequests\ComposerResource;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -162,9 +161,7 @@ test('only pinterest and tiktok channels of the current workspace have account d
test('taken slots cover only the asked day and never the past', function () {
$from = now()->addDays(3)->startOfDay();
- $at = fn (CarbonInterface $instant): Post => tap(Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => $instant]), function (Post $post): void {
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->pinterest->id]);
- });
+ $at = fn (CarbonInterface $instant): Post => Post::factory()->forAccount($this->pinterest)->scheduled()->create(['user_id' => $this->user->id, 'scheduled_at' => $instant]);
$at($from->copy()->subMinute());
$first = $at($from->copy());
$last = $at($from->copy()->addDay()->subMinute());
@@ -267,8 +264,7 @@ test('taken slots are read in one query whatever the number of channels', functi
$count = function (int $channels) use (&$queries): int {
$ids = SocialAccount::factory()->count($channels)->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::X])
->each(function (SocialAccount $account): void {
- $post = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => now()->addDay()]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
+ Post::factory()->forAccount($account)->scheduled()->create(['user_id' => $this->user->id, 'scheduled_at' => now()->addDay()]);
})
->modelKeys();
diff --git a/tests/Feature/InstagramFacebookIntegrationTest.php b/tests/Feature/InstagramFacebookIntegrationTest.php
index 2bcaece1c..479ca9736 100644
--- a/tests/Feature/InstagramFacebookIntegrationTest.php
+++ b/tests/Feature/InstagramFacebookIntegrationTest.php
@@ -6,7 +6,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status as AccountStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -78,16 +77,9 @@ test('instagram facebook has its own queue', function () {
});
test('instagram facebook publisher uses graph.facebook.com', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->instagramFacebookAccount)->create([
'user_id' => $this->user->id,
'content' => 'Test post via Facebook Business',
- ]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->instagramFacebookAccount->id,
- 'platform' => Platform::InstagramFacebook,
'content_type' => ContentType::InstagramFeed,
]);
@@ -112,7 +104,7 @@ test('instagram facebook publisher uses graph.facebook.com', function () {
]);
$publisher = new InstagramPublisher;
- $result = $publisher->publish($postPlatform);
+ $result = $publisher->publish($post);
expect($result)->toHaveKey('id');
@@ -135,16 +127,9 @@ test('instagram standalone publisher uses graph.instagram.com', function () {
'status' => AccountStatus::Connected,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($standaloneAccount)->create([
'user_id' => $this->user->id,
'content' => 'Test post via standalone',
- ]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $standaloneAccount->id,
- 'platform' => Platform::Instagram,
'content_type' => ContentType::InstagramFeed,
]);
@@ -169,7 +154,7 @@ test('instagram standalone publisher uses graph.instagram.com', function () {
]);
$publisher = new InstagramPublisher;
- $result = $publisher->publish($postPlatform);
+ $result = $publisher->publish($post);
expect($result)->toHaveKey('id');
diff --git a/tests/Feature/Jobs/ImportExternalPostMediaTest.php b/tests/Feature/Jobs/ImportExternalPostMediaTest.php
index d68a7ed45..3f300a496 100644
--- a/tests/Feature/Jobs/ImportExternalPostMediaTest.php
+++ b/tests/Feature/Jobs/ImportExternalPostMediaTest.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
use App\Dto\RemoteFile;
use App\Enums\Analytics\PublicationContentType;
-use App\Enums\PostPlatform\ContentType;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\Media\ImportRemoteMedia;
@@ -12,7 +11,6 @@ use App\Jobs\Post\ImportExternalPostMedia;
use App\Models\AnalyticsPublication;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Post\ExternalMedia\ExternalMediaResolver;
use App\Services\Post\ExternalMedia\ExternalMediaResolverFactory;
@@ -38,19 +36,12 @@ beforeEach(function () {
function importedPostWithPublication(SocialAccount $account, array $publication = []): Post
{
- $post = Post::factory()->imported()->create(['workspace_id' => $account->workspace_id]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => ContentType::defaultFor($account->platform),
- 'platform_post_id' => 'remote-1',
- ]);
+ $post = Post::factory()->forAccount($account)->imported()->create(['platform_post_id' => 'remote-1']);
AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => $account->platform,
'network' => $account->platform->network(),
'remote_id' => 'remote-1',
@@ -283,7 +274,7 @@ test('a post whose account is gone uses the cover without asking the network', f
Http::fake(['https://cdn.example.test/cover.png' => Http::response($this->png)]);
$resolver = bindExternalFiles([]);
$post = importedPostWithPublication($this->account);
- $post->postPlatforms()->update(['social_account_id' => null]);
+ Post::query()->whereKey($post->id)->update(['social_account_id' => null]);
runExternalMediaJob($post);
@@ -351,7 +342,7 @@ test('the limiter middleware and its key read the post platform once per attempt
$job = new ImportExternalPostMedia($post->id);
$reads = 0;
DB::listen(function ($query) use (&$reads): void {
- $reads += str_contains($query->sql, 'post_platforms') ? 1 : 0;
+ $reads += str_contains($query->sql, 'posts') ? 1 : 0;
});
$job->middleware();
diff --git a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php
index 93406eed3..954a2c361 100644
--- a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php
+++ b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php
@@ -2,12 +2,10 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PostHog\SyncAccountPublishingActivity;
use App\Models\Account;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\User;
use App\Models\Workspace;
use App\Services\PostHogService;
@@ -35,29 +33,26 @@ test('handle sends the latest confirmed account publication directly to PostHog'
'account_id' => $this->account->id,
'user_id' => $this->user->id,
]);
- $olderPost = Post::factory()->create([
+ Post::factory()->x()->published()->create([
'workspace_id' => $olderWorkspace->id,
'user_id' => $this->user->id,
+ 'published_at' => now()->subDay(),
]);
- $latestPost = Post::factory()->create([
+ $latestPublication = Post::factory()->linkedin()->published()->create([
'workspace_id' => $latestWorkspace->id,
'user_id' => $this->user->id,
- ]);
- PostPlatform::factory()->published()->recycle($olderPost)->create([
- 'platform' => Platform::X,
- 'published_at' => now()->subDay(),
- ]);
- $latestPublication = PostPlatform::factory()->published()->recycle($latestPost)->create([
'platform' => Platform::LinkedInPage,
'published_at' => now()->subHour(),
]);
- PostPlatform::factory()->published()->create(['published_at' => now()]);
- PostPlatform::factory()->recycle($latestPost)->create([
- 'status' => Status::PendingReview,
+ Post::factory()->x()->published()->create(['published_at' => now()]);
+ Post::factory()->linkedin()->pendingReview()->create([
+ 'workspace_id' => $latestWorkspace->id,
+ 'user_id' => $this->user->id,
'published_at' => now()->addHour(),
]);
- PostPlatform::factory()->recycle($latestPost)->create([
- 'status' => Status::Published,
+ Post::factory()->linkedin()->published()->create([
+ 'workspace_id' => $latestWorkspace->id,
+ 'user_id' => $this->user->id,
'published_at' => null,
]);
@@ -69,7 +64,7 @@ test('handle sends the latest confirmed account publication directly to PostHog'
&& $groupKey === (string) $this->account->id
&& $properties['last_post_published_at'] === $latestPublication->published_at->toIso8601String()
&& $properties['last_post_published_network'] === 'linkedin'
- && $properties['last_published_post_id'] === $latestPublication->post_id;
+ && $properties['last_published_post_id'] === $latestPublication->id;
});
$job->handle($postHog);
@@ -80,11 +75,10 @@ test('handle clears publishing activity when the account has no confirmed public
'account_id' => $this->account->id,
'user_id' => $this->user->id,
]);
- $post = Post::factory()->create([
+ Post::factory()->linkedin()->pendingReview()->create([
'workspace_id' => $workspace->id,
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->recycle($post)->create(['status' => Status::PendingReview]);
$postHog = Mockery::mock(PostHogService::class);
$postHog->shouldReceive('groupIdentifyNow')
diff --git a/tests/Feature/Jobs/PublishLegacyTargetMediaTest.php b/tests/Feature/Jobs/PublishLegacyTargetMediaTest.php
deleted file mode 100644
index ce718134a..000000000
--- a/tests/Feature/Jobs/PublishLegacyTargetMediaTest.php
+++ /dev/null
@@ -1,169 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Dto\MediaItem;
-use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Jobs\PublishToSocialPlatform;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-use App\Services\Social\BlueskyPublisher;
-use App\Services\Social\FacebookPublisher;
-use App\Services\Social\GoogleBusinessPublisher;
-use App\Services\Social\InstagramPublisher;
-use App\Services\Social\PinterestPublisher;
-use App\Services\Social\Telegram\TelegramPublisher;
-use App\Services\Social\TikTokPublisher;
-use App\Services\Social\YouTubePublisher;
-use Illuminate\Http\Client\Request;
-use Illuminate\Support\Facades\Http;
-use Illuminate\Support\Facades\Mail;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Sleep;
-
-beforeEach(function () {
- Mail::fake();
- Storage::fake();
- Sleep::fake();
-
- $this->migration = require database_path('migrations/2026_10_06_112101_mark_post_platforms_scheduled_before_media_checks.php');
- $this->user = User::factory()->create();
- $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
-});
-
-/**
- * @param list<array{0: int, 1: int}|'image'> $files Videos with their width and height, or a plain image.
- */
-function legacyMediaTarget(Workspace $workspace, string $accountState, ContentType $contentType, array $files, PostStatus $status = PostStatus::Scheduled, PlatformStatus $targetStatus = PlatformStatus::Pending): PostPlatform
-{
- $account = SocialAccount::factory()->{$accountState}()->create(['workspace_id' => $workspace->id, 'platform_user_id' => 'legacy_account']);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => $status,
- 'content' => 'Legacy caption',
- ]);
-
- $items = collect($files)->map(function (array|string $file, int $index) use ($post): array {
- $row = $file === 'image'
- ? Media::factory()->stored()->ownedByPost($post)->create(['order' => $index])
- : Media::factory()->video()->stored()->ownedByPost($post)->create(['order' => $index, 'meta' => ['width' => $file[0], 'height' => $file[1], 'duration' => 20]]);
-
- return MediaItem::fromMedia($row)->toArray();
- })->all();
-
- Post::query()->whereKey($post->id)->update(['media' => json_encode($items)]);
-
- return PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'status' => $targetStatus,
- 'enabled' => true,
- ]);
-}
-
-dataset('media main published and 2.0 rejects', [
- 'instagram reel 11:1 video' => ['instagram', ContentType::InstagramReel, [[2200, 200]], InstagramPublisher::class],
- 'instagram feed 11:1 video' => ['instagram', ContentType::InstagramFeed, [[2200, 200]], InstagramPublisher::class],
- 'instagram story 11:1 video' => ['instagram', ContentType::InstagramStory, [[2200, 200]], InstagramPublisher::class],
- 'facebook reel 16:9 video' => ['facebook', ContentType::FacebookReel, [[1920, 1080]], FacebookPublisher::class],
- 'tiktok video with two videos' => ['tiktok', ContentType::TikTokVideo, [[1080, 1920], [1080, 1920]], TikTokPublisher::class],
- 'pinterest pin with two images' => ['pinterest', ContentType::PinterestPin, ['image', 'image'], PinterestPublisher::class],
- 'bluesky post with five images' => ['bluesky', ContentType::BlueskyPost, ['image', 'image', 'image', 'image', 'image'], BlueskyPublisher::class],
- 'google business post with two images' => ['googleBusiness', ContentType::GoogleBusinessPost, ['image', 'image'], GoogleBusinessPublisher::class],
- 'telegram post with eleven images' => ['telegram', ContentType::TelegramPost, array_fill(0, 11, 'image'), TelegramPublisher::class],
-]);
-
-test('a video ratio the network accepts publishes without the legacy flag', function (string $accountState, ContentType $contentType, array $files, string $publisherClass) {
- $this->migration->up();
- $target = legacyMediaTarget($this->workspace, $accountState, $contentType, $files);
-
- $publisher = Mockery::mock($publisherClass);
- $publisher->shouldReceive('publish')->once()->andReturn(['id' => 'relaxed-1', 'url' => 'https://example.com/relaxed-1']);
- $this->app->instance($publisherClass, $publisher);
-
- (new PublishToSocialPlatform($target->fresh()))->handle();
-
- expect($target->fresh()->scheduled_before_media_checks)->toBeFalse()
- ->and($target->fresh()->status)->toBe(PlatformStatus::Published);
-})->with([
- 'instagram reel 16:9 video' => ['instagram', ContentType::InstagramReel, [[1920, 1080]], InstagramPublisher::class],
- 'instagram feed 9:16 video' => ['instagram', ContentType::InstagramFeed, [[1080, 1920]], InstagramPublisher::class],
- 'instagram story square video' => ['instagram', ContentType::InstagramStory, [[1080, 1080]], InstagramPublisher::class],
- 'youtube short 16:9 video' => ['youtube', ContentType::YouTubeShort, [[1920, 1080]], YouTubePublisher::class],
-]);
-
-test('a target scheduled before the deploy reaches the publisher with the media main published', function (string $accountState, ContentType $contentType, array $files, string $publisherClass) {
- $target = legacyMediaTarget($this->workspace, $accountState, $contentType, $files);
- $this->migration->up();
-
- $publisher = Mockery::mock($publisherClass);
- $publisher->shouldReceive('publish')->once()->andReturn(['id' => 'legacy-1', 'url' => 'https://example.com/legacy-1']);
- $this->app->instance($publisherClass, $publisher);
-
- (new PublishToSocialPlatform($target->fresh()))->handle();
-
- expect($target->fresh()->scheduled_before_media_checks)->toBeTrue()
- ->and($target->fresh()->status)->toBe(PlatformStatus::Published);
-})->with('media main published and 2.0 rejects');
-
-test('a target created after the deploy with the same media fails before calling the network', function (string $accountState, ContentType $contentType, array $files, string $publisherClass) {
- $this->migration->up();
- $target = legacyMediaTarget($this->workspace, $accountState, $contentType, $files);
-
- $publisher = Mockery::mock($publisherClass);
- $publisher->shouldNotReceive('publish');
- $this->app->instance($publisherClass, $publisher);
-
- (new PublishToSocialPlatform($target->fresh()))->handle();
-
- expect($target->fresh()->scheduled_before_media_checks)->toBeFalse()
- ->and($target->fresh()->status)->toBe(PlatformStatus::Failed)
- ->and(data_get($target->fresh()->error_context, 'reason'))->toBe('media_invalid');
-})->with('media main published and 2.0 rejects');
-
-test('only targets that publish without user action are marked', function (PostStatus $status, PlatformStatus $targetStatus, bool $marked) {
- $target = legacyMediaTarget($this->workspace, 'instagram', ContentType::InstagramReel, [[1080, 1920]], $status, $targetStatus);
-
- $this->migration->up();
-
- expect($target->fresh()->scheduled_before_media_checks)->toBe($marked);
-})->with([
- 'scheduled' => [PostStatus::Scheduled, PlatformStatus::Pending, true],
- 'pending approval' => [PostStatus::PendingApproval, PlatformStatus::Pending, true],
- 'publishing' => [PostStatus::Publishing, PlatformStatus::Publishing, true],
- 'retrying' => [PostStatus::Publishing, PlatformStatus::Retrying, true],
- 'draft' => [PostStatus::Draft, PlatformStatus::Pending, false],
- 'failed post' => [PostStatus::Failed, PlatformStatus::Failed, false],
- 'failed target of a post still publishing' => [PostStatus::Publishing, PlatformStatus::Failed, false],
- 'published' => [PostStatus::Published, PlatformStatus::Published, false],
-]);
-
-test('a legacy 16:9 instagram reel publishes through instagram as on main', function () {
- $target = legacyMediaTarget($this->workspace, 'instagram', ContentType::InstagramReel, [[1920, 1080]]);
- $this->migration->up();
-
- $graph = (string) config('trypost.platforms.instagram.graph_api');
- Http::fake(fn (Request $request) => match (true) {
- str_ends_with($request->url(), '/legacy_account/media') => Http::response(['id' => 'container-1']),
- str_ends_with($request->url(), '/legacy_account/media_publish') => Http::response(['id' => 'ig-media-1']),
- str_contains($request->url(), '/container-1') => Http::response(['status_code' => 'FINISHED']),
- str_contains($request->url(), '/ig-media-1') => Http::response(['permalink' => 'https://www.instagram.com/reel/legacy/']),
- default => Http::response([], 404),
- });
-
- (new PublishToSocialPlatform($target->fresh()))->handle();
-
- expect($target->fresh()->status)->toBe(PlatformStatus::Published);
- Http::assertSent(fn (Request $request): bool => $request->url() === "{$graph}/legacy_account/media"
- && data_get($request->data(), 'media_type') === 'REELS'
- && data_get($request->data(), 'video_url') === data_get($target->post->fresh()->media, '0.url'));
-});
diff --git a/tests/Feature/Jobs/PublishLimitRetryTest.php b/tests/Feature/Jobs/PublishLimitRetryTest.php
index a4053aa21..445d48011 100644
--- a/tests/Feature/Jobs/PublishLimitRetryTest.php
+++ b/tests/Feature/Jobs/PublishLimitRetryTest.php
@@ -3,9 +3,9 @@
declare(strict_types=1);
use App\Enums\Notification\Type;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\BlueskyPublishException;
use App\Exceptions\Social\DiscordPublishException;
@@ -25,7 +25,6 @@ use App\Exceptions\Social\YouTubePublishException;
use App\Jobs\PublishToSocialPlatform;
use App\Jobs\SendNotification;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -60,12 +59,7 @@ beforeEach(function () {
$this->travelTo(CarbonImmutable::parse('2026-10-06 12:00:00', 'UTC'));
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Publishing,
- 'scheduled_at' => now()->subMinute(),
- ]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
});
/**
@@ -79,7 +73,7 @@ function limitRetryResponse(int $status, array $body, array $headers = []): Resp
return Http::get('https://limit-retry.test/refusal');
}
-function limitRetryTarget(object $test, Platform $platform, array $attributes = []): PostPlatform
+function limitRetryTarget(object $test, Platform $platform, array $attributes = []): Post
{
$factory = SocialAccount::factory();
$state = match ($platform) {
@@ -100,13 +94,11 @@ function limitRetryTarget(object $test, Platform $platform, array $attributes =
};
$account = $state->create(['workspace_id' => $test->workspace->id]);
- return PostPlatform::factory()->create([
- 'post_id' => $test->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => ContentType::defaultFor($platform),
- 'enabled' => true,
- 'status' => PlatformStatus::Pending,
+ return Post::factory()->forAccount($account, ContentType::defaultFor($platform))->create([
+ 'user_id' => $test->user->id,
+ 'status' => PostStatus::Publishing,
+ 'scheduled_at' => now()->subMinute(),
+ 'publish_status' => PlatformStatus::Pending,
'scheduled_before_media_checks' => true,
...$attributes,
]);
@@ -157,12 +149,12 @@ test('a network limit waits an hour instead of failing', function (Platform $pla
$target->refresh();
expect($exception->category)->toBe(ErrorCategory::RateLimit)
- ->and($target->status)->toBe(PlatformStatus::Retrying)
+ ->and($target->publish_status)->toBe(PlatformStatus::Retrying)
->and($target->retry_at->toIso8601String())->toBe(now()->addHour()->toIso8601String())
->and($target->error_message)->toBe($exception->userMessage)
->and(data_get($target->error_context, 'category'))->toBe(ErrorCategory::RateLimit->value)
->and(data_get($target->error_context, LimitRetryPolicy::ATTEMPTS_KEY))->toBe(1)
- ->and($this->post->fresh()->status)->toBe(PostStatus::Publishing);
+ ->and($target->fresh()->status)->toBe(PostStatus::Publishing);
Queue::assertNotPushed(SendNotification::class);
})->with('network limit refusals');
@@ -174,7 +166,7 @@ test('a limit retries after 1h, 2h and 4h through the scheduler, then fails with
(new PublishToSocialPlatform($target))->handle();
foreach ([1, 2, 4] as $attempt => $hours) {
- expect($target->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($target->fresh()->retry_at->toIso8601String())->toBe(now()->addHours($hours)->toIso8601String());
$this->travel(($hours * 60) - 1)->minutes();
@@ -190,11 +182,11 @@ test('a limit retries after 1h, 2h and 4h through the scheduler, then fails with
}
$target->refresh();
- expect($target->status)->toBe(PlatformStatus::Failed)
+ expect($target->publish_status)->toBe(PlatformStatus::Failed)
->and($target->retry_at)->toBeNull()
->and($target->error_message)->toBe('LinkedIn rate limit reached. Please try again later.')
->and(data_get($target->error_context, LimitRetryPolicy::ATTEMPTS_KEY))->toBe(3)
- ->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
+ ->and($target->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class, 1);
Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::PostFailed);
});
@@ -212,10 +204,10 @@ test('a limit that lifts publishes on the next attempt', function () {
$this->artisan('posts:process-scheduled')->assertSuccessful();
(new PublishToSocialPlatform($target->fresh()))->handle();
- expect($target->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($target->fresh()->retry_at)->toBeNull()
->and($target->fresh()->error_context)->toBeNull()
- ->and($this->post->fresh()->status)->toBe(PostStatus::Published);
+ ->and($target->fresh()->status)->toBe(PostStatus::Published);
Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::PostPublished);
});
@@ -251,7 +243,7 @@ test('a bluesky 429 retries when the pds RateLimit-Reset says the limit lifts',
(new PublishToSocialPlatform($target))->handle();
- expect($target->fresh()->status)->not->toBe(PlatformStatus::Failed)
+ expect($target->fresh()->publish_status)->not->toBe(PlatformStatus::Failed)
->and($target->fresh()->retry_at->toIso8601String())->toBe($resetAt->toIso8601String());
});
@@ -262,9 +254,9 @@ test('a permanent refusal still fails at once', function (Platform $platform, st
(new PublishToSocialPlatform($target))->handle();
- expect($target->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($target->fresh()->retry_at)->toBeNull()
- ->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
+ ->and($target->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::PostFailed);
})->with([
'tiktok banned from posting' => [Platform::TikTok, TikTokPublisher::class, fn (): SocialPublishException => TikTokPublishException::fromFailReason('spam_risk_user_banned_from_posting')],
@@ -275,7 +267,7 @@ test('a permanent refusal still fails at once', function (Platform $platform, st
test('a job that runs before retry_at does nothing', function () {
$target = limitRetryTarget($this, Platform::LinkedIn, [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => now()->addHour(),
'error_context' => [LimitRetryPolicy::ATTEMPTS_KEY => 1],
]);
@@ -286,23 +278,18 @@ test('a job that runs before retry_at does nothing', function () {
(new PublishToSocialPlatform($target))->handle();
(new PublishToSocialPlatform($target))->failed(new RuntimeException('worker died'));
- expect($target->fresh()->status)->toBe(PlatformStatus::Retrying);
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying);
});
test('a due retry survives a worker restart: the scheduler dispatches it once from the database', function () {
Queue::fake();
$target = limitRetryTarget($this, Platform::LinkedIn, [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => now()->subMinute(),
'error_context' => [LimitRetryPolicy::ATTEMPTS_KEY => 2],
]);
- $disabled = limitRetryTarget($this, Platform::LinkedIn, [
- 'enabled' => false,
- 'status' => PlatformStatus::Retrying,
- 'retry_at' => now()->subMinute(),
- ]);
$notDue = limitRetryTarget($this, Platform::LinkedIn, [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => now()->addMinute(),
]);
@@ -310,17 +297,16 @@ test('a due retry survives a worker restart: the scheduler dispatches it once fr
$this->artisan('posts:process-scheduled')->assertSuccessful();
Queue::assertPushed(PublishToSocialPlatform::class, 1);
- Queue::assertPushed(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($target)
+ Queue::assertPushed(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->post->is($target)
&& $job->uniqueAttempt === LimitRetryPolicy::UNIQUE_ATTEMPT_OFFSET + 2);
expect($target->fresh()->retry_at)->toBeNull()
- ->and($target->fresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($disabled->fresh()->retry_at)->not->toBeNull()
+ ->and($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($notDue->fresh()->retry_at)->not->toBeNull();
});
test('recovering stuck posts never fails a target waiting for a limit', function () {
$target = limitRetryTarget($this, Platform::LinkedIn, [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => now()->addHours(3),
'error_context' => [LimitRetryPolicy::ATTEMPTS_KEY => 2],
]);
@@ -328,54 +314,31 @@ test('recovering stuck posts never fails a target waiting for a limit', function
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($target->fresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($this->post->fresh()->status)->toBe(PostStatus::Publishing);
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
+ ->and($target->fresh()->status)->toBe(PostStatus::Publishing);
});
test('a claimed retry whose worker died is timed out by recover after an hour', function () {
Queue::fake();
$target = limitRetryTarget($this, Platform::LinkedIn, [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => now()->subMinute(),
'error_context' => [LimitRetryPolicy::ATTEMPTS_KEY => 1],
]);
- Post::query()->whereKey($this->post->id)->update(['updated_at' => now()->subHours(2)]);
+ Post::query()->whereKey($target->id)->update(['updated_at' => now()->subHours(2)]);
$this->artisan('posts:process-scheduled')->assertSuccessful();
$this->travel(61)->minutes();
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($target->fresh()->status)->toBe(PlatformStatus::Failed)
- ->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
-});
-
-test('a multi-target post stays publishing while one target waits, then settles partially published', function () {
- Queue::fake();
- $published = limitRetryTarget($this, Platform::Bluesky, [
- 'status' => PlatformStatus::Published,
- 'platform_post_id' => 'at://live',
- ]);
- $waiting = limitRetryTarget($this, Platform::LinkedIn);
- limitRetryPublisherThrows(LinkedInPublisher::class, LinkedInPublishException::fromApiResponse(limitRetryResponse(429, ['message' => 'Throttled'])));
-
- (new PublishToSocialPlatform($waiting))->handle();
-
- expect($this->post->fresh()->status)->toBe(PostStatus::Publishing);
- Queue::assertNotPushed(SendNotification::class);
-
- $waiting->update(['error_context' => [...$waiting->fresh()->error_context, LimitRetryPolicy::ATTEMPTS_KEY => 3], 'retry_at' => null]);
- (new PublishToSocialPlatform($waiting->fresh()))->handle();
-
- expect($waiting->fresh()->status)->toBe(PlatformStatus::Failed)
- ->and($published->fresh()->status)->toBe(PlatformStatus::Published)
- ->and($this->post->fresh()->status)->toBe(PostStatus::PartiallyPublished);
- Queue::assertPushed(SendNotification::class, 1);
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($target->fresh()->status)->toBe(PostStatus::Failed);
});
test('a thread refused for a limit midway resumes after the live segments without posting them again', function () {
Queue::fake();
- $this->post->update(['content' => 'Root']);
$target = limitRetryTarget($this, Platform::Mastodon, [
+ 'content' => 'Root',
'content_type' => ContentType::MastodonPost,
'meta' => ['thread_replies' => ['Two', 'Three']],
]);
@@ -392,7 +355,7 @@ test('a thread refused for a limit midway resumes after the live segments withou
(new PublishToSocialPlatform($target))->handle();
$waiting = $target->fresh();
- expect($waiting->status)->toBe(PlatformStatus::Retrying)
+ expect($waiting->publish_status)->toBe(PlatformStatus::Retrying)
->and(collect(data_get($waiting->error_context, ThreadProgress::KEY))->pluck('id')->all())->toBe(['1', '2']);
$this->travel(1)->hour();
@@ -400,7 +363,7 @@ test('a thread refused for a limit midway resumes after the live segments withou
(new PublishToSocialPlatform($target->fresh()))->handle();
$published = $target->fresh();
- expect($published->status)->toBe(PlatformStatus::Published)
+ expect($published->publish_status)->toBe(PlatformStatus::Published)
->and($published->platform_post_id)->toBe('1')
->and($published->thread_reply_ids)->toEqual(['2', '3']);
Http::assertSent(fn ($request): bool => data_get($request->data(), 'status') === 'Three' && data_get($request->data(), 'in_reply_to_id') === '2');
@@ -420,7 +383,7 @@ test('a refused tiktok publish_id is dropped so the retry starts a new publish',
(new PublishToSocialPlatform($target))->handle();
- expect($target->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and(PublishCheckpoint::tiktokPublishId($target->fresh()->error_context))->toBeNull()
->and(data_get($target->fresh()->error_context, PublishCheckpoint::TIKTOK_STATUS))->toBeNull();
});
@@ -439,7 +402,7 @@ test('a limit wait drops the x media checkpoint so the retry uploads the media a
(new PublishToSocialPlatform($target))->handle();
$context = $target->fresh()->error_context;
- expect($target->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($context)->not->toHaveKey(PublishCheckpoint::X_MEDIA)
->and(PublishCheckpoint::xMedia($context))->toBe([])
->and(data_get($context, ThreadProgress::KEY))->toEqual($threadProgress)
diff --git a/tests/Feature/Jobs/PublishPostTest.php b/tests/Feature/Jobs/PublishPostTest.php
index 7091dd9f1..000dd5685 100644
--- a/tests/Feature/Jobs/PublishPostTest.php
+++ b/tests/Feature/Jobs/PublishPostTest.php
@@ -2,12 +2,12 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Jobs\PublishPost;
use App\Jobs\PublishToSocialPlatform;
use App\Jobs\SendNotification;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -16,80 +16,59 @@ use Illuminate\Support\Facades\Queue;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
$this->socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
});
test('publish post marks post as publishing', function () {
Queue::fake();
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->scheduled()->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
(new PublishPost($post))->handle();
$post->refresh();
expect($post->status)->toBe(PostStatus::Publishing);
});
-test('publish post dispatches publish to social platform for each enabled platform', function () {
+test('publish post dispatches one publish job for the channel of the post', function () {
Queue::fake();
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->scheduled()->create([
'user_id' => $this->user->id,
]);
- $platform1 = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
- $platform2 = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
(new PublishPost($post))->handle();
- Queue::assertPushed(PublishToSocialPlatform::class, 2);
+ Queue::assertPushed(PublishToSocialPlatform::class, 1);
+ Queue::assertPushed(
+ PublishToSocialPlatform::class,
+ fn (PublishToSocialPlatform $job): bool => $job->post->is($post),
+ );
});
-test('publish post dispatches google business targets onto the social publish job', function () {
+test('publish post dispatches google business posts onto the social publish job', function () {
Queue::fake();
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'user_id' => $this->user->id,
]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
- ]);
(new PublishPost($post))->handle();
Queue::assertPushed(
PublishToSocialPlatform::class,
- fn (PublishToSocialPlatform $job): bool => $job->postPlatform->is($platform),
+ fn (PublishToSocialPlatform $job): bool => $job->post->is($post),
);
expect($post->fresh()->status)->toBe(PostStatus::Publishing);
});
-test('publish post does not dispatch for disabled platforms', function () {
+test('publish post sends nothing to a network for a post without a channel', function () {
Queue::fake();
$post = Post::factory()->scheduled()->create([
@@ -97,53 +76,32 @@ test('publish post does not dispatch for disabled platforms', function () {
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
- PostPlatform::factory()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
(new PublishPost($post))->handle();
- Queue::assertPushed(PublishToSocialPlatform::class, 1);
+ Queue::assertNotPushed(PublishToSocialPlatform::class);
});
-test('publish post does nothing when no platforms enabled', function () {
+test('publish post fails a post whose channel is gone right away', function () {
Queue::fake();
+ $post = Post::factory()->forAccount($this->socialAccount)->scheduled()->create(['user_id' => $this->user->id]);
+ $post->forceFill(['social_account_id' => null])->save();
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- PostPlatform::factory()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
- (new PublishPost($post))->handle();
+ (new PublishPost($post->fresh()))->handle();
+ expect($post->fresh())
+ ->status->toBe(PostStatus::Failed)
+ ->publish_status->toBe(PublishStatus::Failed)
+ ->error_message->toBe(__('posts.errors.choose_channel'));
Queue::assertNotPushed(PublishToSocialPlatform::class);
});
-test('publish post failed leaves the post open while targets are still unfinished', function () {
+test('publish post failed leaves the post open while the publication is still unfinished', function () {
Queue::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
- ]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
+ 'publish_status' => PublishStatus::Pending,
]);
(new PublishPost($post))->failed(new RuntimeException('queue exploded'));
@@ -152,21 +110,14 @@ test('publish post failed leaves the post open while targets are still unfinishe
Queue::assertNotPushed(SendNotification::class);
});
-test('publish post failed finalizes when every target already finished', function () {
+test('publish post failed finalizes when the publication already finished', function () {
Queue::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->failed()->create([
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
]);
- PostPlatform::factory()->failed()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
(new PublishPost($post))->failed(new RuntimeException('queue exploded'));
expect($post->fresh()->status)->toBe(PostStatus::Failed);
diff --git a/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php b/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php
index 4d040fc4c..ee5197459 100644
--- a/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php
+++ b/tests/Feature/Jobs/PublishToSocialPlatformMediaRecheckTest.php
@@ -3,14 +3,13 @@
declare(strict_types=1);
use App\Dto\MediaItem;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -28,20 +27,13 @@ beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $this->post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->account, ContentType::InstagramFeed)->scheduled()->create([
'user_id' => $this->user->id,
]);
$this->media = Media::factory()->stored()->ownedByPost($this->post)->create([
'meta' => ['width' => 1080, 'height' => 1350],
]);
$this->post->update(['media' => [MediaItem::fromMedia($this->media)->toArray()]]);
- $this->postPlatform = PostPlatform::factory()->instagram()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->account->id,
- 'content_type' => ContentType::InstagramFeed,
- 'enabled' => true,
- ]);
});
test('a scheduled instagram feed image that became too wide fails without calling instagram', function () {
@@ -51,16 +43,16 @@ test('a scheduled instagram feed image that became too wide fails without callin
$publisher->shouldNotReceive('publish');
$this->app->instance(InstagramPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $platform = $this->postPlatform->fresh();
+ $platform = $this->post->fresh();
$message = trans('posts.form.warnings.aspect_ratio_too_wide', [
'destination' => ContentType::InstagramFeed->destinationLabel(),
'current' => '2.00',
'max' => '1.91',
]);
- expect($platform->status)->toBe(PlatformStatus::Failed)
+ expect($platform->publish_status)->toBe(PlatformStatus::Failed)
->and($platform->error_message)->toBe($message)
->and(data_get($platform->error_context, 'reason'))->toBe('media_invalid')
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
@@ -75,15 +67,15 @@ test('a still valid instagram feed image reaches the publisher', function () {
$publisher->shouldReceive('publish')->once()->andReturn(['id' => 'ig-1', 'url' => 'https://instagram.com/p/ig-1']);
$this->app->instance(InstagramPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($this->account->platform)->toBe(Platform::Instagram);
});
test('a resume of a publish the provider already accepted is not rechecked', function () {
$this->media->update(['meta' => ['width' => 2000, 'height' => 1000]]);
- $this->postPlatform->update(['error_context' => [
+ $this->post->update(['error_context' => [
'category' => 'platform_unavailable',
'instagram_workflow' => ['stage' => 'final_container', 'container_id' => 'container-1'],
]]);
@@ -92,20 +84,20 @@ test('a resume of a publish the provider already accepted is not rechecked', fun
$publisher->shouldReceive('publish')->once()->andReturn(['id' => 'ig-1', 'url' => 'https://instagram.com/p/ig-1']);
$this->app->instance(InstagramPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Published);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published);
});
test('a too-wide image fails the recheck even with a legacy aspect ratio', function (string $legacyRatio) {
$this->media->update(['meta' => ['width' => 2000, 'height' => 1000]]);
- $this->postPlatform->update(['meta' => ['aspect_ratio' => $legacyRatio]]);
+ $this->post->update(['meta' => ['aspect_ratio' => $legacyRatio]]);
$publisher = Mockery::mock(InstagramPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(InstagramPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
})->with(['1:1', '4:5', 'original']);
diff --git a/tests/Feature/Jobs/PublishToSocialPlatformTest.php b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
index b0dec1b13..e91b49a81 100644
--- a/tests/Feature/Jobs/PublishToSocialPlatformTest.php
+++ b/tests/Feature/Jobs/PublishToSocialPlatformTest.php
@@ -5,13 +5,13 @@ declare(strict_types=1);
use App\Enums\GoogleBusiness\LocalPostState;
use App\Enums\GoogleBusiness\TopicType;
use App\Enums\Notification\Type;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status as AccountStatus;
use App\Enums\TikTok\PrivacyLevel;
-use App\Events\PostPlatformStatusUpdated;
+use App\Events\PostStatusUpdated;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\BlueskyPublishException;
use App\Exceptions\Social\ContentLimitException;
@@ -27,7 +27,6 @@ use App\Mail\AccountDisconnected;
use App\Mail\PostPublished;
use App\Mail\PostPublishFailed;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -60,20 +59,31 @@ beforeEach(function () {
Mail::fake();
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
$this->socialAccount = SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
]);
- $this->post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->scheduled()->create([
'user_id' => $this->user->id,
]);
- $this->postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
});
+/**
+ * @param array<string, mixed> $attributes
+ */
+function publishJobRetarget(Post $post, SocialAccount $account, array $attributes = []): Post
+{
+ $post->forceFill([
+ 'social_account_id' => $account->id,
+ 'platform' => $account->platform,
+ 'content_type' => ContentType::defaultFor($account->platform),
+ 'meta' => [],
+ ...$attributes,
+ ])->save();
+
+ return $post->fresh();
+}
+
test('publish to social platform marks platform as publishing', function () {
Event::fake();
@@ -85,9 +95,9 @@ test('publish to social platform marks platform as publishing', function () {
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- Event::assertDispatched(PostPlatformStatusUpdated::class);
+ Event::assertDispatched(PostStatusUpdated::class);
});
test('publish to social platform marks platform as published on success', function () {
@@ -101,12 +111,12 @@ test('publish to social platform marks platform as published on success', functi
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Published);
- expect($this->postPlatform->platform_post_id)->toBe('post-123');
- expect($this->postPlatform->platform_url)->toBe('https://linkedin.com/post/123');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Published);
+ expect($this->post->platform_post_id)->toBe('post-123');
+ expect($this->post->platform_url)->toBe('https://linkedin.com/post/123');
});
test('publish job dispatches a linkedin-page post to the page publisher', function () {
@@ -118,12 +128,9 @@ test('publish job dispatches a linkedin-page post to the page publisher', functi
'workspace_id' => $workspace->id,
'user_id' => $this->user->id,
]);
- $pagePostPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pageAccount->id,
+ $pagePost = publishJobRetarget($post, $pageAccount, [
'platform' => Platform::LinkedInPage,
'content_type' => ContentType::LinkedInPagePost,
- 'enabled' => true,
]);
$publisher = Mockery::mock(LinkedInPagePublisher::class);
@@ -133,11 +140,11 @@ test('publish job dispatches a linkedin-page post to the page publisher', functi
]);
$this->app->instance(LinkedInPagePublisher::class, $publisher);
- (new PublishToSocialPlatform($pagePostPlatform))->handle();
+ (new PublishToSocialPlatform($pagePost))->handle();
- $pagePostPlatform->refresh();
- expect($pagePostPlatform->status)->toBe(PlatformStatus::Published);
- expect($pagePostPlatform->platform_post_id)->toBe('org-post-1');
+ $pagePost->refresh();
+ expect($pagePost->publish_status)->toBe(PlatformStatus::Published);
+ expect($pagePost->platform_post_id)->toBe('org-post-1');
});
test('publish job runs the real document flow end-to-end for a LinkedIn PDF post', function () {
@@ -148,7 +155,7 @@ test('publish job runs the real document flow end-to-end for a LinkedIn PDF post
'platform_user_id' => 'person-xyz',
'token_expires_at' => now()->addDays(60),
]);
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'content' => 'Our deck',
'media' => [[
@@ -181,11 +188,11 @@ test('publish job runs the real document flow end-to-end for a LinkedIn PDF post
return Http::response('fake-pdf-bytes', 200);
});
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Published);
- expect($this->postPlatform->platform_post_id)->toBe('urn:li:share:e2e');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Published);
+ expect($this->post->platform_post_id)->toBe('urn:li:share:e2e');
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/documents') && str_contains($request->url(), 'initializeUpload'));
Http::assertSent(function ($request) {
@@ -203,11 +210,11 @@ test('publish to social platform marks platform as failed on error', function ()
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toBe('An unexpected error occurred while publishing. Please try again.');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toBe('An unexpected error occurred while publishing. Please try again.');
});
test('publish keeps the vetted user message from a publish exception', function () {
@@ -221,11 +228,11 @@ test('publish keeps the vetted user message from a publish exception', function
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toBe('LinkedIn rejected this post.');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toBe('LinkedIn rejected this post.');
});
test('publish reports an unmapped publish exception so Nightwatch sees it', function () {
@@ -242,13 +249,13 @@ test('publish reports an unmapped publish exception so Nightwatch sees it', func
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertReportedCount(1);
Exceptions::assertReported(LinkedInPublishException::class);
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe($exception->userMessage);
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe($exception->userMessage);
});
test('publish logs but does not report a documented rejection the user must act on', function (LinkedInPublishException $exception) {
@@ -261,23 +268,23 @@ test('publish logs but does not report a documented rejection the user must act
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertNothingReported();
Log::shouldHaveReceived('error')
->withArgs(fn (string $message, array $context): bool => $message === 'Social publish failed'
&& $context['exception'] === LinkedInPublishException::class)
->once();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe($exception->userMessage);
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe($exception->userMessage);
})->with([
'permission' => fn () => linkedInRejection(403),
]);
test('a Bluesky email rejection saves actionable failure details without refreshing the valid account', function () {
$this->socialAccount->update(['platform' => Platform::Bluesky]);
- $this->postPlatform->update(['platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost]);
+ $this->post->update(['platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost]);
Event::fake();
Exceptions::fake();
Queue::fake();
@@ -290,14 +297,14 @@ test('a Bluesky email rejection saves actionable failure details without refresh
$this->mock(BlueskyPublisher::class)->shouldReceive('publish')->once()->andThrow($exception);
$this->mock(ConnectionVerifier::class)->shouldNotReceive('refreshToken');
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe('Confirm your email in Bluesky settings, then try publishing again.')
- ->and(data_get($this->postPlatform->error_context, 'category'))->toBe(ErrorCategory::Permission->value)
- ->and(data_get($this->postPlatform->error_context, 'platform_error_code'))->toBe('unconfirmed_email')
- ->and(json_decode(data_get($this->postPlatform->error_context, 'raw_response'), true))->toBe($body)
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe('Confirm your email in Bluesky settings, then try publishing again.')
+ ->and(data_get($this->post->error_context, 'category'))->toBe(ErrorCategory::Permission->value)
+ ->and(data_get($this->post->error_context, 'platform_error_code'))->toBe('unconfirmed_email')
+ ->and(json_decode(data_get($this->post->error_context, 'raw_response'), true))->toBe($body)
->and($this->socialAccount->fresh()->status)->toBe(AccountStatus::Connected);
Queue::assertNotPushed(PublishToSocialPlatform::class);
@@ -314,10 +321,10 @@ test('publish reports a failure that can be ours, even when categorized', functi
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertReported($exception::class);
- expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->refresh()->publish_status)->toBe(PlatformStatus::Failed);
})->with([
'server error' => fn () => new LinkedInPublishException(
userMessage: 'LinkedIn could not process the media.',
@@ -354,19 +361,17 @@ test('publish reports a YouTube download that came back empty, though it is a me
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]]]);
- $postPlatform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'content_type' => ContentType::YouTubeShort,
'scheduled_before_media_checks' => true,
]);
Http::fake(['https://example.com/video.mp4' => Http::response('tiny')]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
Exceptions::assertReported(fn (YouTubePublishException $exception): bool => $exception->category === ErrorCategory::MediaFormat
&& str_contains($exception->userMessage, 'Downloaded video is too small or empty'));
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::Failed);
});
function linkedInRejection(int $status): LinkedInPublishException
@@ -386,12 +391,12 @@ test('publish reports unexpected errors so Nightwatch sees them', function () {
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertReportedCount(1);
Exceptions::assertReported(TypeError::class);
- $this->postPlatform->refresh();
- expect($this->postPlatform->error_message)->toBe('An unexpected error occurred while publishing. Please try again.');
+ $this->post->refresh();
+ expect($this->post->error_message)->toBe('An unexpected error occurred while publishing. Please try again.');
});
test('publish does not report a token expiry it settles', function () {
@@ -408,10 +413,10 @@ test('publish does not report a token expiry it settles', function () {
$verifier->shouldReceive('verify')->andReturnTrue();
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertNothingReported();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
});
test('publish does not report a token refresh that confirms the token is dead', function () {
@@ -427,10 +432,10 @@ test('publish does not report a token refresh that confirms the token is dead',
$verifier->shouldReceive('verify')->andThrow(new TokenExpiredException('Refresh failed'));
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertNothingReported();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
});
test('publish reports an unexpected error from the token refresh once', function () {
@@ -446,11 +451,11 @@ test('publish reports an unexpected error from the token refresh once', function
$verifier->shouldReceive('verify')->andThrow(new RuntimeException('Refresh exploded'));
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertReportedCount(1);
Exceptions::assertReported(fn (RuntimeException $e): bool => $e->getMessage() === 'Refresh exploded');
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
});
test('publish does not report a platform-unavailable retry', function () {
@@ -465,10 +470,10 @@ test('publish does not report a platform-unavailable retry', function () {
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertNothingReported();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Retrying);
});
test('publish log includes media so Nightwatch can tell a CDN miss from an API rejection', function () {
@@ -499,7 +504,7 @@ test('publish log includes media so Nightwatch can tell a CDN miss from an API r
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
$entry = collect($logs)->first(
fn (MessageLogged $event): bool => $event->message === 'Social publish failed'
@@ -528,15 +533,15 @@ test('publish reports when platform-unavailable retries are exhausted', function
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES],
]);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
Exceptions::assertReportedCount(1);
Exceptions::assertReported(PlatformUnavailableException::class);
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
});
test('publish never leaks a raw internal error to the failure record (and the email)', function () {
@@ -549,26 +554,26 @@ test('publish never leaks a raw internal error to the failure record (and the em
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toBe('An unexpected error occurred while publishing. Please try again.')
- ->and($this->postPlatform->error_message)->not->toContain('/home/forge')
- ->and($this->postPlatform->error_message)->not->toContain('getMediaCategory');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toBe('An unexpected error occurred while publishing. Please try again.')
+ ->and($this->post->error_message)->not->toContain('/home/forge')
+ ->and($this->post->error_message)->not->toContain('getMediaCategory');
});
test('the job-failed hook also genericizes a raw internal error', function () {
Event::fake();
- (new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError(
+ (new PublishToSocialPlatform($this->post))->failed(new TypeError(
'boom in /home/forge/app.trypost.it/releases/72198060/app/Services/Social/XPublisher.php on line 130'
));
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe('An unexpected error occurred while publishing. Please try again.')
- ->and($this->postPlatform->error_message)->not->toContain('/home/forge');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe('An unexpected error occurred while publishing. Please try again.')
+ ->and($this->post->error_message)->not->toContain('/home/forge');
});
test('publish to social platform marks account as token expired on auth failure', function () {
@@ -580,12 +585,12 @@ test('publish to social platform marks account as token expired on auth failure'
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
$this->socialAccount->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
expect($this->socialAccount->status)->toBe(AccountStatus::TokenExpired);
});
@@ -605,24 +610,24 @@ test('publish reschedules platform unavailable retry via Bus dispatch (not marke
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
$this->socialAccount->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);
- expect($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable');
- expect($this->postPlatform->error_context['http_status'] ?? null)->toBe(503);
- expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(1);
- expect($this->postPlatform->error_context['operation_id'] ?? null)->toBe('operation-123');
- expect($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'));
- expect($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn API returned 503');
+ expect($this->post->publish_status)->toBe(PlatformStatus::Retrying);
+ expect($this->post->error_context['category'] ?? null)->toBe('platform_unavailable');
+ expect($this->post->error_context['http_status'] ?? null)->toBe(503);
+ expect($this->post->error_context['retry_count'] ?? null)->toBe(1);
+ expect($this->post->error_context['operation_id'] ?? null)->toBe('operation-123');
+ expect($this->post->error_message)->toBe(__('posts.errors.platform_unavailable'));
+ expect($this->post->error_context['detail'] ?? null)->toContain('LinkedIn API returned 503');
expect($this->socialAccount->status)->toBe(AccountStatus::Connected);
Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) {
- return $job->postPlatform->id === $this->postPlatform->id
+ return $job->post->id === $this->post->id
&& $job->uniqueAttempt === 1
- && $job->uniqueId() === "{$this->postPlatform->id}:1";
+ && $job->uniqueId() === "{$this->post->id}:1";
});
});
@@ -644,13 +649,10 @@ test('publish reschedules when pinterest video processing times out', function (
'meta' => ['default_board_id' => 'board_123'],
]);
- $postPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $channelPost = publishJobRetarget($this->post, $pinterestAccount, [
'platform' => Platform::Pinterest,
'content_type' => ContentType::PinterestVideoPin,
- 'enabled' => true,
- 'status' => PlatformStatus::Pending,
+ 'publish_status' => PlatformStatus::Pending,
'meta' => ['board_id' => 'board_123'],
]);
@@ -662,17 +664,17 @@ test('publish reschedules when pinterest video processing times out', function (
);
$this->app->instance(PinterestPublisher::class, $publisher);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- $postPlatform->refresh();
+ $channelPost->refresh();
- expect($postPlatform->status)->toBe(PlatformStatus::Retrying)
- ->and($postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')
- ->and($postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable'))
- ->and($postPlatform->error_context['detail'] ?? null)->toContain('Pinterest media processing timeout');
+ expect($channelPost->publish_status)->toBe(PlatformStatus::Retrying)
+ ->and($channelPost->error_context['category'] ?? null)->toBe('platform_unavailable')
+ ->and($channelPost->error_message)->toBe(__('posts.errors.platform_unavailable'))
+ ->and($channelPost->error_context['detail'] ?? null)->toContain('Pinterest media processing timeout');
- Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) use ($postPlatform) {
- return $job->postPlatform->id === $postPlatform->id
+ Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) use ($channelPost) {
+ return $job->post->id === $channelPost->id
&& $job->uniqueAttempt === 1;
});
});
@@ -696,13 +698,13 @@ test('publish reschedules retry when retry-refresh path hits platform unavailabl
$this->app->instance(LinkedInPublisher::class, $publisher);
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
$this->socialAccount->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);
- expect($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable');
+ expect($this->post->publish_status)->toBe(PlatformStatus::Retrying);
+ expect($this->post->error_context['category'] ?? null)->toBe('platform_unavailable');
expect($this->socialAccount->status)->toBe(AccountStatus::Connected);
Bus::assertDispatched(PublishToSocialPlatform::class);
@@ -722,12 +724,12 @@ test('publish reschedules retry exactly 10 minutes into the future', function ()
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
// error_context tracks the next attempt — must be exactly +10 min
- expect($this->postPlatform->error_context['next_attempt_at'] ?? null)
+ expect($this->post->error_context['next_attempt_at'] ?? null)
->toBe($now->copy()->addMinutes(10)->toIso8601String());
// The actual dispatched job carries the same delay
@@ -761,11 +763,11 @@ test('publish honors a platform-specific retry delay and retry limit', function
));
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->error_context['next_attempt_at'] ?? null)
+ expect($this->post->error_context['next_attempt_at'] ?? null)
->toBe($now->copy()->addSeconds(30)->toIso8601String());
Bus::assertDispatched(PublishToSocialPlatform::class, function ($job) use ($now) {
@@ -773,10 +775,10 @@ test('publish honors a platform-specific retry delay and retry limit', function
&& Carbon::instance($job->delay)->equalTo($now->copy()->addSeconds(30));
});
- $this->postPlatform->update(['error_context' => [...$this->postPlatform->error_context, 'processing_retry_count' => 2]]);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ $this->post->update(['error_context' => [...$this->post->error_context, 'processing_retry_count' => 2]]);
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
Carbon::setTestNow();
});
@@ -795,11 +797,11 @@ test('publish records last_attempt_at when rescheduling for retry', function ()
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->error_context['last_attempt_at'] ?? null)
+ expect($this->post->error_context['last_attempt_at'] ?? null)
->toBe($now->toIso8601String());
Carbon::setTestNow();
@@ -819,7 +821,7 @@ test('publish preserves resumable context when a later transient error has no co
'tiktok_derivative_paths' => ['social-tiktok-photos/pending.jpg'],
'retry_count' => 2,
];
- $this->postPlatform->update(['error_context' => $checkpoint]);
+ $this->post->update(['error_context' => $checkpoint]);
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldReceive('publish')->andThrow(
@@ -827,9 +829,9 @@ test('publish preserves resumable context when a later transient error has no co
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
expect($context['instagram_workflow'] ?? null)->toBe($checkpoint['instagram_workflow'])
->and($context['tiktok_publish_id'] ?? null)->toBe('publish-123')
@@ -844,7 +846,7 @@ test('an unrelated outage after a processing reschedule does not inherit the pro
Mail::fake();
$this->freezeTime();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -862,11 +864,11 @@ test('an unrelated outage after a processing reschedule does not inherit the pro
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($context['instagram_workflow']['container_id'] ?? null)->toBe('container-123')
->and($context['retry_count'] ?? null)->toBe(1)
->and($context['processing_retry_count'] ?? null)->toBe(7)
@@ -880,7 +882,7 @@ test('a processing reschedule keeps counting against its own retry policy', func
Event::fake();
$this->freezeTime();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => 2, 'processing_retry_count' => 7, 'max_retries' => 30, 'retry_delay_seconds' => 60],
]);
@@ -890,11 +892,11 @@ test('a processing reschedule keeps counting against its own retry policy', func
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($context['processing_retry_count'] ?? null)->toBe(8)
->and($context['retry_count'] ?? null)->toBe(2)
->and($context['max_retries'] ?? null)->toBe(30)
@@ -907,7 +909,7 @@ test('alternating processing reschedules and outages still exhausts the outage r
Event::fake();
Mail::fake();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => 6, 'processing_retry_count' => 3, 'max_retries' => 30, 'retry_delay_seconds' => 60],
]);
@@ -917,9 +919,9 @@ test('alternating processing reschedules and outages still exhausts the outage r
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed);
Bus::assertNotDispatched(PublishToSocialPlatform::class);
});
@@ -927,7 +929,7 @@ test('an outage after a processing reschedule is dispatched under a new unique a
Bus::fake([PublishToSocialPlatform::class]);
Event::fake();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['processing_retry_count' => 1, 'max_retries' => 30, 'retry_delay_seconds' => 60],
]);
@@ -937,7 +939,7 @@ test('an outage after a processing reschedule is dispatched under a new unique a
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh(), 1))->handle();
+ (new PublishToSocialPlatform($this->post->fresh(), 1))->handle();
Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->uniqueAttempt === 2);
});
@@ -948,7 +950,7 @@ test('an outage on a status poll rescheduled before 2.0 restarts the outage retr
Mail::fake();
$this->freezeTime();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => 40, 'max_retries' => 90, 'retry_delay_seconds' => 10],
]);
@@ -958,11 +960,11 @@ test('an outage on a status poll rescheduled before 2.0 restarts the outage retr
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh(), 40))->handle();
+ (new PublishToSocialPlatform($this->post->fresh(), 40))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($context['retry_count'] ?? null)->toBe(1)
->and($context['processing_retry_count'] ?? null)->toBe(40)
->and($context)->not->toHaveKey('max_retries')
@@ -976,7 +978,7 @@ test('a status poll rescheduled before 2.0 keeps counting its poll budget', func
Event::fake();
$this->freezeTime();
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => 40, 'max_retries' => 90, 'retry_delay_seconds' => 10],
]);
@@ -986,11 +988,11 @@ test('a status poll rescheduled before 2.0 keeps counting its poll budget', func
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh(), 40))->handle();
+ (new PublishToSocialPlatform($this->post->fresh(), 40))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($context['processing_retry_count'] ?? null)->toBe(41)
->and((int) ($context['retry_count'] ?? 0))->toBe(0)
->and($context['max_retries'] ?? null)->toBe(90);
@@ -998,47 +1000,12 @@ test('a status poll rescheduled before 2.0 keeps counting its poll budget', func
Bus::assertDispatched(PublishToSocialPlatform::class, fn (PublishToSocialPlatform $job): bool => $job->uniqueAttempt > 40);
});
-test('post stays in Publishing while one platform is still Retrying', function () {
- Bus::fake([PublishToSocialPlatform::class]);
- Event::fake();
- Mail::fake();
-
- // Second LinkedIn account on the same post — first one will publish OK,
- // second one will hit PlatformUnavailable and reschedule.
- $secondAccount = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
- $secondPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $secondAccount->id,
- 'enabled' => true,
- 'status' => PlatformStatus::Published, // simulate already published
- 'platform_post_id' => 'sibling-123',
- ]);
-
- // Start the post as Publishing so updatePostStatus sees the in-flight context
- $this->post->update(['status' => PostStatus::Publishing]);
-
- $publisher = Mockery::mock(LinkedInPublisher::class);
- $publisher->shouldReceive('publish')->andThrow(
- new PlatformUnavailableException('LinkedIn 503', 503)
- );
- $this->app->instance(LinkedInPublisher::class, $publisher);
-
- (new PublishToSocialPlatform($this->postPlatform))->handle();
-
- $this->postPlatform->refresh();
- $this->post->refresh();
-
- expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);
- // Post is NOT finalized because one of its platforms is still pending retry.
- expect($this->post->status)->toBe(PostStatus::Publishing);
-});
-
test('successful publish after a retry transitions the platform to Published', function () {
// Pre-condition: this platform already failed once and is currently Retrying.
- $this->postPlatform->update([
- 'status' => PlatformStatus::Retrying,
+ $this->post->forceFill([
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => ['retry_count' => 3, 'category' => 'platform_unavailable'],
- ]);
+ ])->save();
Event::fake();
@@ -1049,12 +1016,12 @@ test('successful publish after a retry transitions the platform to Published', f
]);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Published);
- expect($this->postPlatform->platform_post_id)->toBe('post-after-retry');
+ expect($this->post->publish_status)->toBe(PlatformStatus::Published);
+ expect($this->post->platform_post_id)->toBe('post-after-retry');
});
test('publish retry count increments across successive platform_unavailable attempts', function () {
@@ -1069,16 +1036,16 @@ test('publish retry count increments across successive platform_unavailable atte
$this->app->instance(LinkedInPublisher::class, $publisher);
// Simulate prior attempts
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => 5],
]);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Retrying);
- expect($this->postPlatform->error_context['retry_count'] ?? null)->toBe(6);
+ expect($this->post->publish_status)->toBe(PlatformStatus::Retrying);
+ expect($this->post->error_context['retry_count'] ?? null)->toBe(6);
});
test('publish hard-fails when platform unavailable retries are exhausted', function () {
@@ -1092,19 +1059,19 @@ test('publish hard-fails when platform unavailable retries are exhausted', funct
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['retry_count' => PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES],
]);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))
- ->and($this->postPlatform->error_context['category'] ?? null)->toBe('platform_unavailable')
- ->and($this->postPlatform->error_context['retry_count'] ?? null)->toBe(PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES + 1)
- ->and($this->postPlatform->error_context['detail'] ?? null)->toContain('LinkedIn 503');
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))
+ ->and($this->post->error_context['category'] ?? null)->toBe('platform_unavailable')
+ ->and($this->post->error_context['retry_count'] ?? null)->toBe(PublishToSocialPlatform::MAX_PLATFORM_UNAVAILABLE_RETRIES + 1)
+ ->and($this->post->error_context['detail'] ?? null)->toContain('LinkedIn 503');
Bus::assertNotDispatched(PublishToSocialPlatform::class);
});
@@ -1118,7 +1085,7 @@ test('publish keeps a resumable checkpoint when platform unavailable retries are
'stage' => 'final_container',
'container_id' => 'container-123',
];
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'tiktok_publish_id' => 'pub_in_flight',
'instagram_workflow' => $workflow,
@@ -1132,11 +1099,11 @@ test('publish keeps a resumable checkpoint when platform unavailable retries are
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($context['tiktok_publish_id'] ?? null)->toBe('pub_in_flight')
->and($context['instagram_workflow'] ?? null)->toBe($workflow)
->and($context['category'] ?? null)->toBe('platform_unavailable');
@@ -1148,25 +1115,25 @@ test('publish skips platforms that are already failed', function () {
Event::fake();
Mail::fake();
- $this->postPlatform->update([
- 'status' => PlatformStatus::Failed,
+ $this->post->forceFill([
+ 'publish_status' => PlatformStatus::Failed,
'error_message' => __('posts.errors.publishing_timed_out'),
- ]);
+ ])->save();
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'));
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe(__('posts.errors.publishing_timed_out'));
});
test('publish job timeout leaves headroom above the pinterest media poll budget', function () {
- $job = new PublishToSocialPlatform($this->postPlatform);
+ $job = new PublishToSocialPlatform($this->post);
$horizonTimeout = (int) config('horizon.defaults.social-publishing.timeout');
$retryAfter = (int) config('queue.connections.redis.retry_after');
@@ -1180,20 +1147,20 @@ test('publish job timeout leaves headroom above the pinterest media poll budget'
});
test('publish job unique id includes the platform and attempt', function () {
- $job = new PublishToSocialPlatform($this->postPlatform, 3);
+ $job = new PublishToSocialPlatform($this->post, 3);
expect($job)->toBeInstanceOf(ShouldBeUnique::class)
- ->and($job->uniqueId())->toBe("{$this->postPlatform->id}:3")
+ ->and($job->uniqueId())->toBe("{$this->post->id}:3")
->and($job->uniqueFor)->toBe(960);
});
test('publish job prevents concurrent execution across different attempts', function () {
- $job = new PublishToSocialPlatform($this->postPlatform, 3);
+ $job = new PublishToSocialPlatform($this->post, 3);
$middleware = $job->middleware();
expect($middleware)->toHaveCount(1)
->and($middleware[0])->toBeInstanceOf(WithoutOverlapping::class)
- ->and($middleware[0]->key)->toBe("social-publish:{$this->postPlatform->id}")
+ ->and($middleware[0]->key)->toBe("social-publish:{$this->post->id}")
->and($middleware[0]->releaseAfter)->toBe(60)
->and($middleware[0]->expiresAfter)->toBe($job->timeout + 60)
->and($job->tries)->toBe(20)
@@ -1201,8 +1168,8 @@ test('publish job prevents concurrent execution across different attempts', func
});
test('publish job releases an overlapping execution for the same platform', function () {
- $runningJob = new PublishToSocialPlatform($this->postPlatform, 0);
- $overlappingJob = (new PublishToSocialPlatform($this->postPlatform, 1))->withFakeQueueInteractions();
+ $runningJob = new PublishToSocialPlatform($this->post, 0);
+ $overlappingJob = (new PublishToSocialPlatform($this->post, 1))->withFakeQueueInteractions();
/** @var WithoutOverlapping $middleware */
$middleware = $overlappingJob->middleware()[0];
$lock = Cache::lock($middleware->getLockKey($runningJob), $runningJob->timeout + 60);
@@ -1232,8 +1199,8 @@ test('publish job releases an overlapping execution for the same platform', func
test('publish job unique lock drops a duplicate dispatch for the same platform attempt', function () {
Bus::fake([PublishToSocialPlatform::class]);
- PublishToSocialPlatform::dispatch($this->postPlatform, 0);
- PublishToSocialPlatform::dispatch($this->postPlatform, 0);
+ PublishToSocialPlatform::dispatch($this->post, 0);
+ PublishToSocialPlatform::dispatch($this->post, 0);
Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 1);
});
@@ -1241,8 +1208,8 @@ test('publish job unique lock drops a duplicate dispatch for the same platform a
test('publish job unique lock allows concurrent dispatches for different attempts', function () {
Bus::fake([PublishToSocialPlatform::class]);
- PublishToSocialPlatform::dispatch($this->postPlatform, 0);
- PublishToSocialPlatform::dispatch($this->postPlatform, 1);
+ PublishToSocialPlatform::dispatch($this->post, 0);
+ PublishToSocialPlatform::dispatch($this->post, 1);
Bus::assertDispatchedTimes(PublishToSocialPlatform::class, 2);
Bus::assertDispatched(PublishToSocialPlatform::class, fn ($job) => $job->uniqueAttempt === 0);
@@ -1253,38 +1220,38 @@ test('failed hook skips platforms that are already failed', function () {
Event::fake();
Mail::fake();
- $this->postPlatform->update([
- 'status' => PlatformStatus::Failed,
+ $this->post->forceFill([
+ 'publish_status' => PlatformStatus::Failed,
'error_message' => __('posts.errors.publishing_timed_out'),
'error_context' => ['category' => 'timeout'],
- ]);
+ ])->save();
- (new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));
+ (new PublishToSocialPlatform($this->post))->failed(new TypeError('Simulated worker kill'));
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($this->postPlatform->error_message)->toBe(__('posts.errors.publishing_timed_out'))
- ->and($this->postPlatform->error_context['category'] ?? null)->toBe('timeout');
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($this->post->error_message)->toBe(__('posts.errors.publishing_timed_out'))
+ ->and($this->post->error_context['category'] ?? null)->toBe('timeout');
});
test('failed hook skips platforms that are already published', function () {
Event::fake();
Mail::fake();
- $this->postPlatform->update([
- 'status' => PlatformStatus::Published,
+ $this->post->forceFill([
+ 'publish_status' => PlatformStatus::Published,
'platform_post_id' => 'already-published',
'error_message' => null,
- ]);
+ ])->save();
- (new PublishToSocialPlatform($this->postPlatform))->failed(new TypeError('Simulated worker kill'));
+ (new PublishToSocialPlatform($this->post))->failed(new TypeError('Simulated worker kill'));
- $this->postPlatform->refresh();
+ $this->post->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Published)
- ->and($this->postPlatform->platform_post_id)->toBe('already-published')
- ->and($this->postPlatform->error_message)->toBeNull();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Published)
+ ->and($this->post->platform_post_id)->toBe('already-published')
+ ->and($this->post->error_message)->toBeNull();
});
test('failed hook keeps TikTok photo derivatives while a publish_id can be resumed', function () {
@@ -1296,20 +1263,20 @@ test('failed hook keeps TikTok photo derivatives while a publish_id can be resum
$unrelatedPath = 'customer-media/keep.jpg';
Storage::put($path, 'image');
Storage::put($unrelatedPath, 'image');
- $this->postPlatform->update([
+ $this->post->forceFill([
'platform' => Platform::TikTok,
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_publish_id' => 'publish-123',
'tiktok_derivative_paths' => [$path, 'social-tiktok-photos/../customer-media/keep.jpg'],
],
- ]);
+ ])->save();
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->failed(new TypeError('Simulated worker kill'));
+ (new PublishToSocialPlatform($this->post->fresh()))->failed(new TypeError('Simulated worker kill'));
Storage::assertExists($path);
Storage::assertExists($unrelatedPath);
- expect($this->postPlatform->fresh()->error_context)->toMatchArray([
+ expect($this->post->fresh()->error_context)->toMatchArray([
'tiktok_publish_id' => 'publish-123',
'category' => 'job_failed',
]);
@@ -1322,18 +1289,18 @@ test('failed hook prunes TikTok photo derivatives when there is no publish_id',
$path = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($path, 'image');
- $this->postPlatform->update([
+ $this->post->forceFill([
'platform' => Platform::TikTok,
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_derivative_paths' => [$path],
],
- ]);
+ ])->save();
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->failed(new TypeError('Simulated worker kill'));
+ (new PublishToSocialPlatform($this->post->fresh()))->failed(new TypeError('Simulated worker kill'));
Storage::assertMissing($path);
- expect($this->postPlatform->fresh()->error_context['category'] ?? null)->toBe('job_failed');
+ expect($this->post->fresh()->error_context['category'] ?? null)->toBe('job_failed');
});
test('terminal TikTok account guards keep derivatives while a publish_id can be resumed', function (string $guard) {
@@ -1353,10 +1320,9 @@ test('terminal TikTok account guards keep derivatives while a publish_id can be
'workspace_id' => $this->workspace->id,
...$accountAttributes,
]);
- $platform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Retrying,
+ $platform = publishJobRetarget($this->post, $account, [
+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_publish_id' => "publish-{$guard}",
'tiktok_derivative_paths' => [$path],
@@ -1368,7 +1334,7 @@ test('terminal TikTok account guards keep derivatives while a publish_id can be
Storage::assertExists($path);
$platform->refresh();
- expect($platform->status)->toBe(PlatformStatus::Failed)
+ expect($platform->publish_status)->toBe(PlatformStatus::Failed)
->and($platform->error_context['tiktok_publish_id'] ?? null)->toBe("publish-{$guard}");
if ($guard === 'missing_scopes') {
@@ -1408,10 +1374,9 @@ test('terminal TikTok account guards prune derivatives when there is no publish_
'workspace_id' => $this->workspace->id,
...$accountAttributes,
]);
- $platform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Retrying,
+ $platform = publishJobRetarget($this->post, $account, [
+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
+ 'publish_status' => PlatformStatus::Retrying,
'error_context' => [
'tiktok_derivative_paths' => [$path],
],
@@ -1420,7 +1385,7 @@ test('terminal TikTok account guards prune derivatives when there is no publish_
(new PublishToSocialPlatform($platform))->handle();
Storage::assertMissing($path);
- expect($platform->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($platform->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($platform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBeNull();
})->with([
'disconnected account' => 'disconnected',
@@ -1448,12 +1413,10 @@ test('tiktok photo publish resumes after a status-fetch token expiry without a s
'meta' => ['width' => 1254, 'height' => 1254],
]],
]);
- $platform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $platform = publishJobRetarget($this->post, $account, [
+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
'content_type' => ContentType::TikTokPhoto,
- 'status' => PlatformStatus::Pending,
- 'enabled' => true,
+ 'publish_status' => PlatformStatus::Pending,
'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
]);
@@ -1495,7 +1458,7 @@ test('tiktok photo publish resumes after a status-fetch token expiry without a s
$platform->refresh();
- expect($platform->status)->toBe(PlatformStatus::Published)
+ expect($platform->publish_status)->toBe(PlatformStatus::Published)
->and($platform->platform_post_id)->toBe('video_123')
->and($platform->error_context)->toBeNull()
->and(Storage::allFiles('social-tiktok-photos'))->toBeEmpty()
@@ -1516,13 +1479,10 @@ test('pinterest media status 401 marks the account token expired and notifies to
'meta' => ['default_board_id' => 'board_123'],
]);
- $postPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $channelPost = publishJobRetarget($this->post, $pinterestAccount, [
'platform' => Platform::Pinterest,
'content_type' => ContentType::PinterestVideoPin,
- 'enabled' => true,
- 'status' => PlatformStatus::Pending,
+ 'publish_status' => PlatformStatus::Pending,
'meta' => ['board_id' => 'board_123'],
]);
@@ -1564,13 +1524,13 @@ test('pinterest media status 401 marks the account token expired and notifies to
$verifier->shouldReceive('verify')->once()->andThrow(new Exception('Refresh failed'));
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- $postPlatform->refresh();
+ $channelPost->refresh();
$pinterestAccount->refresh();
- expect($postPlatform->status)->toBe(PlatformStatus::Failed)
- ->and($postPlatform->error_context['category'] ?? null)->toBe('token_expired')
+ expect($channelPost->publish_status)->toBe(PlatformStatus::Failed)
+ ->and($channelPost->error_context['category'] ?? null)->toBe('token_expired')
->and($pinterestAccount->status)->toBe(AccountStatus::TokenExpired);
Queue::assertPushed(SendNotification::class, function ($job) use ($pinterestAccount) {
@@ -1591,39 +1551,12 @@ test('publish to social platform updates post status when all platforms finished
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
$this->post->refresh();
expect($this->post->status)->toBe(PostStatus::Published);
});
-test('publish to social platform marks post as partially published when some fail', function () {
- Event::fake();
-
- $socialAccount2 = SocialAccount::factory()->x()->create([
- 'workspace_id' => $this->workspace->id,
- ]);
-
- $postPlatform2 = PostPlatform::factory()->x()->failed()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $socialAccount2->id,
- 'enabled' => true,
- ]);
-
- $publisher = Mockery::mock(LinkedInPublisher::class);
- $publisher->shouldReceive('publish')->andReturn([
- 'id' => 'post-123',
- 'url' => 'https://linkedin.com/post/123',
- ]);
-
- $this->app->instance(LinkedInPublisher::class, $publisher);
-
- (new PublishToSocialPlatform($this->postPlatform))->handle();
-
- $this->post->refresh();
- expect($this->post->status)->toBe(PostStatus::PartiallyPublished);
-});
-
test('publish to social platform marks post as failed when all platforms fail', function () {
Event::fake();
@@ -1632,7 +1565,7 @@ test('publish to social platform marks post as failed when all platforms fail',
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
$this->post->refresh();
expect($this->post->status)->toBe(PostStatus::Failed);
@@ -1651,11 +1584,11 @@ test('publish to social platform skips publishing when account is disconnected',
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toBe(__('posts.errors.account_disconnected'));
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toBe(__('posts.errors.account_disconnected'));
});
test('publish to social platform skips publishing when account token is expired', function () {
@@ -1671,12 +1604,12 @@ test('publish to social platform skips publishing when account token is expired'
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toBe(__('posts.errors.account_token_expired'));
- expect($this->postPlatform->error_context['category'])->toBe('token_expired');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toBe(__('posts.errors.account_token_expired'));
+ expect($this->post->error_context['category'])->toBe('token_expired');
});
test('publish to social platform dispatches success notification when all platforms published', function () {
@@ -1691,9 +1624,7 @@ test('publish to social platform dispatches success notification when all platfo
$this->app->instance(LinkedInPublisher::class, $publisher);
- $this->workspace->members()->attach($this->user->id, membershipPivot('member'));
-
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
$this->post->refresh();
expect($this->post->status)->toBe(PostStatus::Published);
@@ -1709,9 +1640,7 @@ test('publish to social platform dispatches failure notification when platform f
$this->app->instance(LinkedInPublisher::class, $publisher);
- $this->workspace->members()->attach($this->user->id, membershipPivot('member'));
-
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
$this->post->refresh();
expect($this->post->status)->toBe(PostStatus::Failed);
@@ -1731,11 +1660,8 @@ test('a published post queues the published email for the owner', function () {
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'platform' => $account->platform,
- 'enabled' => true,
]);
$publisher = Mockery::mock(FacebookPublisher::class);
@@ -1745,7 +1671,7 @@ test('a published post queues the published email for the owner', function () {
]);
$this->app->instance(FacebookPublisher::class, $publisher);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
Queue::assertPushed(SendNotification::class, function (SendNotification $job) use ($post) {
return $job->type === Type::PostPublished
@@ -1768,18 +1694,15 @@ test('a failed post queues the failed email for the owner', function () {
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'platform' => $account->platform,
- 'enabled' => true,
]);
$publisher = Mockery::mock(FacebookPublisher::class);
$publisher->shouldReceive('publish')->andThrow(new Exception('API error'));
$this->app->instance(FacebookPublisher::class, $publisher);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
Queue::assertPushed(SendNotification::class, function (SendNotification $job) use ($post) {
return $job->type === Type::PostFailed
@@ -1812,12 +1735,12 @@ test('it retries with token refresh when token expires during publish', function
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
$this->socialAccount->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Published);
+ expect($this->post->publish_status)->toBe(PlatformStatus::Published);
expect($this->socialAccount->status)->not->toBe(AccountStatus::Disconnected);
});
@@ -1836,12 +1759,12 @@ test('it marks account as token expired when refresh fails during publish retry'
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
+ $this->post->refresh();
$this->socialAccount->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
expect($this->socialAccount->status)->toBe(AccountStatus::TokenExpired);
});
@@ -1849,21 +1772,21 @@ test('publish to social platform skips if already published (idempotency)', func
Event::fake();
// Mark as already published
- $this->postPlatform->update([
- 'status' => PlatformStatus::Published,
+ $this->post->forceFill([
+ 'publish_status' => PlatformStatus::Published,
'platform_post_id' => 'existing-123',
- ]);
+ ])->save();
$publisher = Mockery::mock(LinkedInPublisher::class);
$publisher->shouldNotReceive('publish');
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
// Should not have called publish
- $this->postPlatform->refresh();
- expect($this->postPlatform->platform_post_id)->toBe('existing-123');
+ $this->post->refresh();
+ expect($this->post->platform_post_id)->toBe('existing-123');
});
test('publish to social platform saves error context on generic failure', function () {
@@ -1876,14 +1799,14 @@ test('publish to social platform saves error context on generic failure', functi
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->error_context)->toBeArray();
- expect($this->postPlatform->error_context['category'])->toBe('unknown');
- expect($this->postPlatform->error_context['failed_at'])->toBeString();
- expect($this->postPlatform->error_context['content_length'])->toBe(17);
- expect($this->postPlatform->error_context['media_count'])->toBe(0);
+ $this->post->refresh();
+ expect($this->post->error_context)->toBeArray();
+ expect($this->post->error_context['category'])->toBe('unknown');
+ expect($this->post->error_context['failed_at'])->toBeString();
+ expect($this->post->error_context['content_length'])->toBe(17);
+ expect($this->post->error_context['media_count'])->toBe(0);
});
test('publish to social platform saves error context on social publish exception', function () {
@@ -1903,14 +1826,14 @@ test('publish to social platform saves error context on social publish exception
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->error_context)->toBeArray();
- expect($this->postPlatform->error_context['category'])->toBe('permission');
- expect($this->postPlatform->error_context['platform_error_code'])->toBe('403');
- expect($this->postPlatform->error_context['content_length'])->toBe(11);
- expect($this->postPlatform->error_context['raw_response'])->toBe('{"error": "forbidden"}');
+ $this->post->refresh();
+ expect($this->post->error_context)->toBeArray();
+ expect($this->post->error_context['category'])->toBe('permission');
+ expect($this->post->error_context['platform_error_code'])->toBe('403');
+ expect($this->post->error_context['content_length'])->toBe(11);
+ expect($this->post->error_context['raw_response'])->toBe('{"error": "forbidden"}');
});
test('publish keeps a resumable checkpoint when a later publish exception is terminal', function () {
@@ -1920,7 +1843,7 @@ test('publish keeps a resumable checkpoint when a later publish exception is ter
'stage' => 'final_container',
'container_id' => 'container-123',
];
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'tiktok_publish_id' => 'pub_dead',
'instagram_workflow' => $workflow,
@@ -1938,11 +1861,11 @@ test('publish keeps a resumable checkpoint when a later publish exception is ter
);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform->fresh()))->handle();
+ (new PublishToSocialPlatform($this->post->fresh()))->handle();
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
- expect($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($context['tiktok_publish_id'] ?? null)->toBe('pub_dead')
->and($context['instagram_workflow'] ?? null)->toBe($workflow)
->and($context['category'] ?? null)->toBe('content_policy');
@@ -1952,15 +1875,15 @@ test('publish to social platform fails when scopes are missing', function () {
Event::fake();
$this->socialAccount->update(['scopes' => ['user.info.basic']]); // missing w_member_social
- $this->postPlatform->refresh();
+ $this->post->refresh();
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->status)->toBe(PlatformStatus::Failed);
- expect($this->postPlatform->error_message)->toContain('Missing permissions');
- expect($this->postPlatform->error_context['category'])->toBe('permission');
- expect($this->postPlatform->error_context['missing_scopes'])->toContain('w_member_social');
+ $this->post->refresh();
+ expect($this->post->publish_status)->toBe(PlatformStatus::Failed);
+ expect($this->post->error_message)->toContain('Missing permissions');
+ expect($this->post->error_context['category'])->toBe('permission');
+ expect($this->post->error_context['missing_scopes'])->toContain('w_member_social');
});
test('publish to social platform saves error context on token expired', function () {
@@ -1976,12 +1899,12 @@ test('publish to social platform saves error context on token expired', function
$verifier->shouldReceive('verify')->andThrow(new TokenExpiredException('Refresh failed'));
$this->app->instance(ConnectionVerifier::class, $verifier);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- $this->postPlatform->refresh();
- expect($this->postPlatform->error_context)->toBeArray();
- expect($this->postPlatform->error_context['category'])->toBe('token_expired');
- expect($this->postPlatform->error_context['platform_error_code'])->toBe('190');
+ $this->post->refresh();
+ expect($this->post->error_context)->toBeArray();
+ expect($this->post->error_context['category'])->toBe('token_expired');
+ expect($this->post->error_context['platform_error_code'])->toBe('190');
});
test('dispatches google business posts to GoogleBusinessPublisher', function () {
@@ -1989,9 +1912,7 @@ test('dispatches google business posts to GoogleBusinessPublisher', function ()
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2002,9 +1923,9 @@ test('dispatches google business posts to GoogleBusinessPublisher', function ()
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Published);
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::Published);
});
test('a google business post rejected in review is not reported as published', function () {
@@ -2012,9 +1933,7 @@ test('a google business post rejected in review is not reported as published', f
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => 'STANDARD'],
]);
@@ -2025,16 +1944,16 @@ test('a google business post rejected in review is not reported as published', f
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- $this->assertDatabaseHas('post_platforms', [
- 'id' => $postPlatform->id,
- 'status' => 'rejected',
+ $this->assertDatabaseHas('posts', [
+ 'id' => $channelPost->id,
+ 'publish_status' => 'rejected',
]);
- expect($postPlatform->fresh()->error_message)
+ expect($channelPost->fresh()->error_message)
->toBe(__('posts.errors.rejected_in_review'))
- ->and($postPlatform->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3')
- ->and($postPlatform->fresh()->platform_url)->toBe('https://business.google.com/dashboard/l/u987654321');
+ ->and($channelPost->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3')
+ ->and($channelPost->fresh()->platform_url)->toBe('https://business.google.com/dashboard/l/u987654321');
});
test('a rejected google business target finalizes the post instead of leaving it publishing', function () {
@@ -2048,9 +1967,7 @@ test('a rejected google business target finalizes the post instead of leaving it
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'meta' => ['topic_type' => 'STANDARD'],
]);
@@ -2061,7 +1978,7 @@ test('a rejected google business target finalizes the post instead of leaving it
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
expect($post->fresh()->status)->toBe(PostStatus::Failed);
Queue::assertPushed(SendNotification::class);
@@ -2072,9 +1989,7 @@ test('a google business post still in review is held, not reported as published'
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => 'STANDARD'],
]);
@@ -2085,14 +2000,14 @@ test('a google business post still in review is held, not reported as published'
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- $this->assertDatabaseHas('post_platforms', [
- 'id' => $postPlatform->id,
- 'status' => 'pending_review',
+ $this->assertDatabaseHas('posts', [
+ 'id' => $channelPost->id,
+ 'publish_status' => 'pending_review',
]);
- expect($postPlatform->fresh()->submitted_at)->not->toBeNull()
- ->and($postPlatform->fresh()->published_at)->toBeNull();
+ expect($channelPost->fresh()->submitted_at)->not->toBeNull()
+ ->and($channelPost->fresh()->published_at)->toBeNull();
});
test('a google business post Google scheduled is held in review', function () {
@@ -2100,9 +2015,7 @@ test('a google business post Google scheduled is held in review', function () {
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => 'STANDARD'],
]);
@@ -2113,10 +2026,10 @@ test('a google business post Google scheduled is held in review', function () {
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($postPlatform->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3');
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($channelPost->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3');
});
test('a google business post that Google reports as recurring is published', function () {
@@ -2124,9 +2037,7 @@ test('a google business post that Google reports as recurring is published', fun
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2137,9 +2048,9 @@ test('a google business post that Google reports as recurring is published', fun
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Published);
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::Published);
});
test('an unspecified google business create state is held in review and keeps the jpeg', function () {
@@ -2158,9 +2069,7 @@ test('an unspecified google business create state is held in review and keeps th
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2171,11 +2080,11 @@ test('an unspecified google business create state is held in review and keeps th
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($postPlatform->fresh()->published_at)->toBeNull();
- Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($postPlatform->id));
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($channelPost->fresh()->published_at)->toBeNull();
+ Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($channelPost));
});
test('a failed google business publish prunes the jpeg derivative', function () {
@@ -2194,9 +2103,7 @@ test('a failed google business publish prunes the jpeg derivative', function ()
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2206,10 +2113,10 @@ test('a failed google business publish prunes the jpeg derivative', function ()
], 400),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Failed);
- Storage::assertMissing(GoogleBusinessDerivativeCleaner::pathFor($postPlatform->id));
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::Failed);
+ Storage::assertMissing(GoogleBusinessDerivativeCleaner::pathFor($channelPost));
});
test('an unknown google business create state is held in review and keeps the jpeg', function () {
@@ -2228,9 +2135,7 @@ test('an unknown google business create state is held in review and keeps the jp
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($this->post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2241,11 +2146,11 @@ test('an unknown google business create state is held in review and keeps the jp
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($postPlatform->fresh()->published_at)->toBeNull();
- Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($postPlatform->id));
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($channelPost->fresh()->published_at)->toBeNull();
+ Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($channelPost));
});
test('a publishing parent stays publishing while google business is in review', function () {
@@ -2259,9 +2164,7 @@ test('a publishing parent stays publishing while google business is in review',
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2272,9 +2175,9 @@ test('a publishing parent stays publishing while google business is in review',
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
->and($post->fresh()->status)->toBe(PostStatus::Publishing);
Queue::assertNotPushed(SendNotification::class);
});
@@ -2289,9 +2192,7 @@ test('a google business target in review on its own post does not settle or noti
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2302,51 +2203,13 @@ test('a google business target in review on its own post does not settle or noti
], 200),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
->and($post->fresh()->status)->toBe(PostStatus::Scheduled);
Queue::assertNotPushed(SendNotification::class);
});
-test('a published sibling stays unpublished at the post while google business is in review', function () {
- Queue::fake([SendNotification::class]);
- $linkedin = SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
- 'token_expires_at' => now()->addHour(),
- ]);
- $gbp = SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $this->workspace->id,
- 'token_expires_at' => now()->addHour(),
- ]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
- PostPlatform::factory()->linkedin()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedin->id,
- ]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $gbp->id,
- 'meta' => ['topic_type' => TopicType::Standard->value],
- ]);
-
- Http::fake([
- config('trypost.platforms.google_business.local_posts_api').'/*' => Http::response([
- 'name' => 'accounts/1/locations/2/localPosts/3',
- 'state' => LocalPostState::Processing->value,
- ], 200),
- ]);
-
- (new PublishToSocialPlatform($postPlatform))->handle();
-
- expect($post->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview);
- Queue::assertNotPushed(SendNotification::class);
-});
-
test('a google business create that is rate limited waits for a retry instead of failing', function () {
$account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
@@ -2356,9 +2219,7 @@ test('a google business create that is rate limited waits for a retry instead of
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $channelPost = publishJobRetarget($post, $account, [
'meta' => ['topic_type' => TopicType::Standard->value],
]);
@@ -2368,11 +2229,11 @@ test('a google business create that is rate limited waits for a retry instead of
], 429),
]);
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($postPlatform->fresh()->retry_at)->not->toBeNull()
- ->and(Storage::exists("google-business-derivatives/{$postPlatform->id}.jpg"))->toBeFalse()
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::Retrying)
+ ->and($channelPost->fresh()->retry_at)->not->toBeNull()
+ ->and(Storage::exists("google-business-derivatives/{$channelPost->id}.jpg"))->toBeFalse()
->and($post->fresh()->status)->not->toBe(PostStatus::Failed);
});
@@ -2381,21 +2242,19 @@ test('a google business target already in review is not published a second time'
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::PendingReview,
+ $channelPost = publishJobRetarget($this->post, $account, [
+ 'publish_status' => PlatformStatus::PendingReview,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
'meta' => ['topic_type' => 'STANDARD'],
]);
Http::fake();
- (new PublishToSocialPlatform($postPlatform))->handle();
+ (new PublishToSocialPlatform($channelPost))->handle();
Http::assertNothingSent();
- expect($postPlatform->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($postPlatform->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3');
+ expect($channelPost->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($channelPost->fresh()->platform_post_id)->toBe('accounts/1/locations/2/localPosts/3');
});
test('a thread result stores the reply ids on the target', function () {
@@ -2404,22 +2263,18 @@ test('a thread result stores the reply ids on the target', function () {
$publisher->shouldReceive('publish')->andReturn(['id' => 'root-1', 'url' => 'https://example.com/root-1', 'thread_reply_ids' => ['a', 'b']]);
$this->app->instance(LinkedInPublisher::class, $publisher);
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- expect($this->postPlatform->fresh()->thread_reply_ids)->toEqual(['a', 'b'])
- ->and($this->postPlatform->fresh()->platform_post_id)->toBe('root-1')
- ->and($this->postPlatform->fresh()->status)->toBe(PlatformStatus::Published);
+ expect($this->post->fresh()->thread_reply_ids)->toEqual(['a', 'b'])
+ ->and($this->post->fresh()->platform_post_id)->toBe('root-1')
+ ->and($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published);
});
test('a mastodon thread that fails midway is visible and its retry never posts a live segment again', function () {
Event::fake();
$account = SocialAccount::factory()->mastodon()->create(['workspace_id' => $this->workspace->id]);
$this->post->update(['content' => 'Root']);
- $this->postPlatform->update(['enabled' => false]);
- $target = PostPlatform::factory()->mastodon()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $target = publishJobRetarget($this->post, $account, [
'meta' => ['thread_replies' => ['Two', 'Three']],
]);
$instance = data_get($account->meta, 'instance');
@@ -2432,18 +2287,18 @@ test('a mastodon thread that fails midway is visible and its retry never posts a
(new PublishToSocialPlatform($target))->handle();
$failed = $target->fresh();
- expect($failed->status)->toBe(PlatformStatus::Failed)
+ expect($failed->publish_status)->toBe(PlatformStatus::Failed)
->and($failed->error_message)->toBe(__('posts.errors.thread_incomplete', ['published' => 2, 'total' => 3, 'error' => 'Validation failed']))
->and(collect(data_get($failed->error_context, 'thread_progress'))->pluck('id')->all())->toBe(['1', '2']);
Bus::fake([PublishToSocialPlatform::class]);
$this->artisan('posts:retry', ['post' => $this->post->id])
- ->expectsConfirmation('Queue publish attempts for these failed platforms?', 'yes')
+ ->expectsConfirmation('Queue a publish attempt for this post?', 'yes')
->assertSuccessful();
(new PublishToSocialPlatform($target->fresh()))->handle();
$published = $target->fresh();
- expect($published->status)->toBe(PlatformStatus::Published)
+ expect($published->publish_status)->toBe(PlatformStatus::Published)
->and($published->platform_post_id)->toBe('1')
->and($published->platform_url)->toBe("{$instance}/@t/1")
->and($published->thread_reply_ids)->toEqual(['2', '3'])
@@ -2464,7 +2319,7 @@ test('the reply ids are written in the same update that publishes the target', f
}
});
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
expect($writes)->toHaveCount(1)
->and($writes[0])->toContain('platform_post_id')
@@ -2475,11 +2330,7 @@ test('a thread that stops on any error says how much of it is live', function ()
Event::fake();
$account = SocialAccount::factory()->mastodon()->create(['workspace_id' => $this->workspace->id]);
$this->post->update(['content' => 'Root']);
- $this->postPlatform->update(['enabled' => false]);
- $target = PostPlatform::factory()->mastodon()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $target = publishJobRetarget($this->post, $account, [
'meta' => ['thread_replies' => ['Two', 'Three']],
]);
$instance = data_get($account->meta, 'instance');
@@ -2489,7 +2340,7 @@ test('a thread that stops on any error says how much of it is live', function ()
(new PublishToSocialPlatform($target))->handle();
- expect($target->fresh()->status)->toBe(PlatformStatus::Failed)
+ expect($target->fresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($target->fresh()->error_message)->toBe(__('posts.errors.thread_incomplete', [
'published' => 1,
'total' => 3,
diff --git a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php
index 805256d44..e9ab6cdd9 100644
--- a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php
+++ b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php
@@ -2,14 +2,13 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Status as AccountStatus;
use App\Jobs\PostHog\SyncAccountPublishingActivity;
use App\Jobs\ReconcileGoogleBusinessPost;
use App\Jobs\SendNotification;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -22,18 +21,14 @@ use Illuminate\Support\Facades\Storage;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->workspace->members()->attach($this->user->id, membershipPivot('admin'));
$this->account = SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addHour(),
]);
- $this->post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->account)->scheduled()->create([
'user_id' => $this->user->id,
- ]);
- $this->target = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->account->id,
- 'status' => PlatformStatus::PendingReview,
+ 'publish_status' => PlatformStatus::PendingReview,
'platform_post_id' => 'accounts/123456789/locations/987654321/localPosts/999',
'submitted_at' => now()->subMinutes(10),
]);
@@ -42,17 +37,17 @@ beforeEach(function () {
test('a connection failure during review is deferred until the ceiling', function () {
Http::fake(fn () => throw new ConnectionException('timed out'));
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
test('settling a live review prunes the JPEG derivative', function () {
Queue::fake([SendNotification::class]);
Storage::fake();
- $path = GoogleBusinessDerivativeCleaner::pathFor($this->target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($this->post);
Storage::put($path, 'image');
Http::fake([
config('trypost.platforms.google_business.local_posts_api').'/*' => Http::response([
@@ -62,7 +57,7 @@ test('settling a live review prunes the JPEG derivative', function () {
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
Storage::assertMissing($path);
});
@@ -79,10 +74,10 @@ test('a live review on a publishing parent settles the post as published', funct
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Published)
- ->and($this->target->fresh()->platform_url)->toBe('https://posts.google.com/999')
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published)
+ ->and($this->post->fresh()->platform_url)->toBe('https://posts.google.com/999')
->and($this->post->fresh()->status)->toBe(PostStatus::Published);
Queue::assertPushed(SendNotification::class, 1);
Queue::assertPushed(
@@ -101,11 +96,11 @@ test('a post that went live is published with the search URL Google returned', f
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Published)
- ->and($this->target->fresh()->platform_url)->toBe('https://posts.google.com/999')
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published)
+ ->and($this->post->fresh()->platform_url)->toBe('https://posts.google.com/999')
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Published);
});
@@ -118,10 +113,10 @@ test('a post Google refused in review is rejected and fails the post', function
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.rejected_in_review'))
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.rejected_in_review'))
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
@@ -133,10 +128,10 @@ test('a scheduled post is left in review and marked as checked', function () {
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
@@ -148,10 +143,10 @@ test('an unspecified post is left in review and marked as checked', function ()
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
@@ -163,16 +158,16 @@ test('a post still processing is left in review and marked as checked', function
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
test('a post that never settles is given up on once the review ceiling passes', function () {
Queue::fake([SendNotification::class]);
- $this->target->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
+ $this->post->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
Http::fake([
config('trypost.platforms.google_business.local_posts_api').'/*' => Http::response([
'name' => 'accounts/123456789/locations/987654321/localPosts/999',
@@ -180,10 +175,10 @@ test('a post that never settles is given up on once the review ceiling passes',
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
@@ -197,13 +192,13 @@ test('a recurring post is treated as live', function () {
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($this->post->fresh()->status)->toBe(PostStatus::Published);
});
-test('a dead token during review is refreshed before the target is deferred', function () {
+test('a dead token during review is refreshed before the post is deferred', function () {
Queue::fake([SendNotification::class]);
$posts = 0;
$info = 0;
@@ -238,9 +233,9 @@ test('a dead token during review is refreshed before the target is deferred', fu
]);
});
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Published)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Published)
->and($this->account->fresh()->access_token)->toBe('rotated-token')
->and($this->post->fresh()->status)->toBe(PostStatus::Published);
});
@@ -255,10 +250,10 @@ test('a local posts 401 after a successful verify defers without expiring the ac
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->account->fresh()->status)->toBe(AccountStatus::Connected)
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
@@ -276,10 +271,10 @@ test('a dead token during review is deferred and expires the account when refres
], 400),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->account->fresh()->status)->toBe(AccountStatus::TokenExpired)
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
@@ -291,10 +286,10 @@ test('a rate limit during review is deferred until the ceiling', function () {
], 429),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
@@ -307,30 +302,30 @@ test('an unknown remote state during review is left in review', function () {
]),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->platform_url)->toBe('https://posts.google.com/updated')
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->platform_url)->toBe('https://posts.google.com/updated')
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
-test('reconcile does not call google when the target is no longer in review', function () {
+test('reconcile does not call google when the post is no longer in review', function () {
Http::fake();
- $this->target->update(['status' => PlatformStatus::Published]);
+ $this->post->forceFill(['publish_status' => PlatformStatus::Published])->save();
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
Http::assertNothingSent();
});
test('reconcile does not call google when the remote post id is missing', function () {
Http::fake();
- $this->target->update(['platform_post_id' => null]);
+ $this->post->forceFill(['platform_post_id' => null])->save();
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
Http::assertNothingSent();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview);
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview);
});
test('a google 5xx during review is deferred until the ceiling', function () {
@@ -340,10 +335,10 @@ test('a google 5xx during review is deferred until the ceiling', function () {
], 503),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull();
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull();
});
test('a missing remote post during review fails immediately', function () {
@@ -354,11 +349,11 @@ test('a missing remote post during review fails immediately', function () {
], 404),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.google_business.not_found'))
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.google_business.not_found'))
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
@@ -370,11 +365,11 @@ test('an invalid argument during review fails immediately', function () {
], 400),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe('summary too long')
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe('summary too long')
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
@@ -386,54 +381,54 @@ test('permission denied during review fails immediately', function () {
], 403),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.google_business.permission_denied'))
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.google_business.permission_denied'))
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
test('a disconnected account during review is given up on immediately', function () {
Queue::fake([SendNotification::class]);
Storage::fake();
- $path = GoogleBusinessDerivativeCleaner::pathFor($this->target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($this->post);
Storage::put($path, 'image');
$this->account->delete();
- (new ReconcileGoogleBusinessPost($this->target->fresh()))->handle();
+ (new ReconcileGoogleBusinessPost($this->post->fresh()))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.account_disconnected'))
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.account_disconnected'))
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
Storage::assertMissing($path);
Queue::assertPushed(SendNotification::class, 1);
});
test('an exhausted reconcile job defers until the review ceiling', function () {
- (new ReconcileGoogleBusinessPost($this->target))->failed(new RuntimeException('worker died'));
+ (new ReconcileGoogleBusinessPost($this->post))->failed(new RuntimeException('worker died'));
- expect($this->target->fresh()->status)->toBe(PlatformStatus::PendingReview)
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::PendingReview)
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Scheduled);
});
test('an exhausted reconcile job gives up once the review ceiling passes', function () {
Queue::fake([SendNotification::class]);
- $this->target->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
+ $this->post->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
- (new ReconcileGoogleBusinessPost($this->target))->failed(new RuntimeException('worker died'));
+ (new ReconcileGoogleBusinessPost($this->post))->failed(new RuntimeException('worker died'));
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
- ->and($this->target->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
- ->and($this->target->fresh()->last_reconciled_at)->not->toBeNull()
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
+ ->and($this->post->fresh()->error_message)->toBe(__('posts.errors.review_unconfirmed'))
+ ->and($this->post->fresh()->last_reconciled_at)->not->toBeNull()
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
test('a dead token after the review ceiling gives up', function () {
Queue::fake([SendNotification::class]);
- $this->target->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
+ $this->post->update(['submitted_at' => now()->subHours(ReconcileGoogleBusinessPost::REVIEW_CEILING_HOURS + 1)]);
Http::fake([
config('trypost.platforms.google_business.local_posts_api').'/*' => Http::response([
'error' => ['status' => 'UNAUTHENTICATED'],
@@ -446,8 +441,8 @@ test('a dead token after the review ceiling gives up', function () {
], 400),
]);
- (new ReconcileGoogleBusinessPost($this->target))->handle();
+ (new ReconcileGoogleBusinessPost($this->post))->handle();
- expect($this->target->fresh()->status)->toBe(PlatformStatus::Rejected)
+ expect($this->post->fresh()->publish_status)->toBe(PlatformStatus::Rejected)
->and($this->post->fresh()->status)->toBe(PostStatus::Failed);
});
diff --git a/tests/Feature/Jobs/SocialPublishingPipelineTest.php b/tests/Feature/Jobs/SocialPublishingPipelineTest.php
index eae68e05c..a51396c6b 100644
--- a/tests/Feature/Jobs/SocialPublishingPipelineTest.php
+++ b/tests/Feature/Jobs/SocialPublishingPipelineTest.php
@@ -4,9 +4,9 @@ declare(strict_types=1);
use App\Actions\Analytics\UpsertAnalyticsPublication;
use App\Actions\Post\ImportExternalPosts;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status as AccountStatus;
use App\Enums\TikTok\PrivacyLevel;
@@ -15,7 +15,6 @@ use App\Jobs\PublishPost;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;
use App\Services\Analytics\Collectors\Publications\InstagramPublicationCollector;
@@ -57,19 +56,19 @@ beforeEach(function () {
$this->workerOptions = new WorkerOptions(sleep: 0, maxTries: 1);
});
-function scheduledPipelineTarget(Platform $platform): PostPlatform
+function scheduledPipelineTarget(Platform $platform): Post
{
$account = SocialAccount::factory()->create([
'platform' => $platform,
'scopes' => $platform->requiredPublishScopes(),
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $account->workspace_id,
+ $contentType = ContentType::defaultFor($platform);
+ $post = Post::factory()->forAccount($account, $contentType)->scheduled()->create([
'user_id' => $account->workspace->user_id,
'scheduled_at' => now()->subMinute(),
'content' => 'Publishing pipeline regression',
+ 'meta' => $platform === Platform::TikTok ? ['privacy_level' => PrivacyLevel::SelfOnly->value] : [],
]);
- $contentType = ContentType::defaultFor($platform);
if ($contentType->requiresMedia()) {
$factory = Media::factory()->ownedByPost($post)->stored();
@@ -80,21 +79,15 @@ function scheduledPipelineTarget(Platform $platform): PostPlatform
$post->update(['media' => [$media->toArray()]]);
}
- return PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $platform,
- 'content_type' => $contentType,
- 'meta' => $platform === Platform::TikTok ? ['privacy_level' => PrivacyLevel::SelfOnly->value] : [],
- ]);
+ return $post->fresh();
}
test('a published facebook photo is not imported again when publishing returned only the photo id', function () {
$target = scheduledPipelineTarget(Platform::Facebook);
$account = $target->socialAccount;
$account->update(['scopes' => [...$account->scopes, 'pages_read_engagement']]);
- $media = Media::factory()->ownedByPost($target->post)->stored()->create(['size' => 100000]);
- $target->post->update(['media' => [$media->toArray()]]);
+ $media = Media::factory()->ownedByPost($target)->stored()->create(['size' => 100000]);
+ $target->update(['media' => [$media->toArray()]]);
$base = config('trypost.platforms.facebook.graph_api');
Http::fake([
@@ -102,7 +95,7 @@ test('a published facebook photo is not imported again when publishing returned
"{$base}/{$account->platform_user_id}/published_posts*" => Http::response(['data' => [[
'id' => 'page_post-123',
'status_type' => 'added_photos',
- 'message' => $target->post->content,
+ 'message' => $target->content,
'created_time' => now()->toIso8601String(),
'attachments' => ['data' => [[
'type' => 'photo',
@@ -114,7 +107,7 @@ test('a published facebook photo is not imported again when publishing returned
(new PublishToSocialPlatform($target))->handle();
- expect($target->refresh()->status)->toBe(PlatformStatus::Published)
+ expect($target->refresh()->publish_status)->toBe(PlatformStatus::Published)
->and($target->platform_post_id)->toBe('photo-123');
$page = app(FacebookPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());
@@ -122,7 +115,7 @@ test('a published facebook photo is not imported again when publishing returned
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($target->post->refresh()->status)->toBe(PostStatus::Published);
+ ->and($target->refresh()->status)->toBe(PostStatus::Published);
Http::assertSentCount(2);
Exceptions::assertNothingReported();
});
@@ -141,14 +134,14 @@ test('a published threads post keeps its identity through a failed permalink loo
"{$base}/{$account->platform_user_id}/threads?*" => Http::response(['data' => [[
'id' => 'post-123',
'media_type' => 'TEXT_POST',
- 'text' => $target->post->content,
+ 'text' => $target->content,
'timestamp' => now()->toIso8601String(),
]]]),
]);
(new PublishToSocialPlatform($target))->handle();
- expect($target->refresh()->status)->toBe(PlatformStatus::Published)
+ expect($target->refresh()->publish_status)->toBe(PlatformStatus::Published)
->and($target->platform_post_id)->toBe('post-123')
->and($target->platform_url)->toBeNull();
@@ -157,7 +150,7 @@ test('a published threads post keeps its identity through a failed permalink loo
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($target->post->refresh()->status)->toBe(PostStatus::Published);
+ ->and($target->refresh()->status)->toBe(PostStatus::Published);
expect(Http::recorded(fn (Request $request): bool => $request->method() === 'POST'
&& Str::endsWith($request->url(), '/threads_publish')))->toHaveCount(1);
Exceptions::assertNothingReported();
@@ -165,7 +158,7 @@ test('a published threads post keeps its identity through a failed permalink loo
test('instagram does not duplicate a captionless publication after losing its media id', function (Platform $platform, ContentType $contentType) {
$target = scheduledPipelineTarget($platform);
- $target->post->update(['content' => '']);
+ $target->update(['content' => '']);
$target->update([
'content_type' => $contentType,
'error_context' => ['instagram_workflow' => [
@@ -193,23 +186,23 @@ test('instagram does not duplicate a captionless publication after losing its me
]);
(new PublishToSocialPlatform($target))->handle();
- expect($target->refresh()->status)->toBe(PlatformStatus::Retrying);
+ expect($target->refresh()->publish_status)->toBe(PlatformStatus::Retrying);
$page = app(InstagramPublicationCollector::class)->page($account, null, now()->subDay()->toImmutable());
expect($page->publications)->toHaveCount(1);
$publication = app(UpsertAnalyticsPublication::class)->external($account, $page->publications[0]);
expect(ImportExternalPosts::execute($account))->toBe([])
- ->and($publication->refresh()->post_platform_id)->toBeNull();
+ ->and($publication->refresh()->post_id)->toBeNull();
$this->travel(61)->seconds();
(new PublishToSocialPlatform($target))->handle();
- expect($target->refresh()->status)->toBe(PlatformStatus::Published)
+ expect($target->refresh()->publish_status)->toBe(PlatformStatus::Published)
->and($target->platform_post_id)->toBe('container-123');
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->refresh()->post_platform_id)->toBeNull()
+ ->and($publication->refresh()->post_id)->toBeNull()
->and($target->refresh()->platform_post_id)->toBe('container-123');
})->with([
'Instagram feed' => [Platform::Instagram, ContentType::InstagramFeed],
@@ -223,7 +216,7 @@ test('each network queue consumes scheduled posts and delayed retries through th
$broken = scheduledPipelineTarget($platform);
$retryCalls = 0;
$publisher = Mockery::mock($publisherClass);
- $publisher->shouldReceive('publish')->times(4)->andReturnUsing(function (PostPlatform $target) use ($retrying, $broken, &$retryCalls): array {
+ $publisher->shouldReceive('publish')->times(4)->andReturnUsing(function (Post $target) use ($retrying, $broken, &$retryCalls): array {
if ($target->is($retrying) && ++$retryCalls === 1) {
throw new PlatformUnavailableException('Temporary outage');
}
@@ -252,8 +245,8 @@ test('each network queue consumes scheduled posts and delayed retries through th
$this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);
}
- expect($retrying->refresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($broken->refresh()->status)->toBe(PlatformStatus::Failed)
+ expect($retrying->refresh()->publish_status)->toBe(PlatformStatus::Retrying)
+ ->and($broken->refresh()->publish_status)->toBe(PlatformStatus::Failed)
->and($this->publishingQueue->pendingSize($platform->queue()))->toBe(0)
->and($this->publishingQueue->delayedSize($platform->queue()))->toBe(1);
@@ -262,14 +255,14 @@ test('each network queue consumes scheduled posts and delayed retries through th
$this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);
$this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);
- expect($healthy->refresh()->status)->toBe(PlatformStatus::Published)
- ->and($healthy->post->status)->toBe(PostStatus::Published);
+ expect($healthy->refresh()->publish_status)->toBe(PlatformStatus::Published)
+ ->and($healthy->status)->toBe(PostStatus::Published);
$this->travel(10)->minutes();
$this->publishingWorker->runNextJob('database', $platform->queue(), $this->workerOptions);
- expect($retrying->refresh()->status)->toBe(PlatformStatus::Published)
- ->and($retrying->post->status)->toBe(PostStatus::Published)
+ expect($retrying->refresh()->publish_status)->toBe(PlatformStatus::Published)
+ ->and($retrying->status)->toBe(PostStatus::Published)
->and($this->publishingQueue->size($platform->queue()))->toBe(0);
$this->assertDatabaseCount('failed_jobs', 0);
})->with([
@@ -326,18 +319,18 @@ test('the TikTok worker publishes through the real publisher and token refresh f
$this->publishingWorker->runNextJob('database', 'default', $this->workerOptions);
$this->publishingWorker->runNextJob('database', Platform::TikTok->queue(), $this->workerOptions);
- expect($healthy->refresh()->status)->toBe(PlatformStatus::Published)
+ expect($healthy->refresh()->publish_status)->toBe(PlatformStatus::Published)
->and($healthy->socialAccount->status)->toBe(AccountStatus::Connected)
- ->and($healthy->post->status)->toBe(PostStatus::Published);
+ ->and($healthy->status)->toBe(PostStatus::Published);
if ($scenario === 'temporary refresh') {
- expect($affected->refresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($affected->refresh()->publish_status)->toBe(PlatformStatus::Retrying)
->and($affected->socialAccount->status)->toBe(AccountStatus::Connected);
$this->travel(10)->minutes();
$this->publishingWorker->runNextJob('database', Platform::TikTok->queue(), $this->workerOptions);
}
- expect($affected->refresh()->status)->toBe($scenario === 'dead refresh' ? PlatformStatus::Failed : PlatformStatus::Published)
+ expect($affected->refresh()->publish_status)->toBe($scenario === 'dead refresh' ? PlatformStatus::Failed : PlatformStatus::Published)
->and($affected->socialAccount->status)->toBe($scenario === 'dead refresh' ? AccountStatus::TokenExpired : AccountStatus::Connected)
->and($this->publishingQueue->size(Platform::TikTok->queue()))->toBe(0);
expect(Http::recorded(fn (Request $request) => str_ends_with($request->url(), '/post/publish/video/init/')))
diff --git a/tests/Feature/Jobs/VerifyUpcomingPostConnectionsTest.php b/tests/Feature/Jobs/VerifyUpcomingPostConnectionsTest.php
index 9d5eb9b12..f5bcde571 100644
--- a/tests/Feature/Jobs/VerifyUpcomingPostConnectionsTest.php
+++ b/tests/Feature/Jobs/VerifyUpcomingPostConnectionsTest.php
@@ -2,7 +2,6 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\SocialAccount\Status as SocialAccountStatus;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\TokenExpiredException;
@@ -11,7 +10,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\VerifyUpcomingPostConnections;
use App\Mail\PostAtRisk;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Social\ConnectionVerifier;
@@ -43,16 +41,9 @@ test('marks the account expired and queues a notification when verify throws Tok
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Threads access token is invalid or expired'));
@@ -60,13 +51,13 @@ test('marks the account expired and queues a notification when verify throws Tok
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
expect($account->fresh()->status)->toBe(SocialAccountStatus::TokenExpired);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($workspace, $postPlatform) {
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($workspace, $post) {
return $mail->workspace->id === $workspace->id
- && count($mail->postPlatformIds) === 1
- && in_array($postPlatform->id, $mail->postPlatformIds, true)
+ && count($mail->postIds) === 1
+ && in_array($post->id, $mail->postIds, true)
&& $mail->recipient->is($workspace->owner);
});
});
@@ -79,16 +70,9 @@ test('emails the workspace owner with the dispatch-time post count', function ()
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Threads access token is invalid or expired'));
@@ -108,16 +92,9 @@ test('defers to the next run instead of warning when markAsTokenExpired loses th
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Threads access token is invalid or expired'));
@@ -133,7 +110,7 @@ test('defers to the next run instead of warning when markAsTokenExpired loses th
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
expect($account->fresh()->status)->toBe(SocialAccountStatus::Connected);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
} finally {
$lock->release();
@@ -149,19 +126,9 @@ test('verifies a distinct account only once even with multiple at-risk posts', f
'status' => SocialAccountStatus::Connected,
]);
- $postPlatforms = collect(range(1, 3))->map(function (int $i) use ($workspace, $account) {
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(20 * $i),
- ]);
-
- return PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
- });
+ $posts = collect(range(1, 3))->map(fn (int $i) => Post::factory()->forAccount($account)->scheduled()->create([
+ 'scheduled_at' => now()->addMinutes(20 * $i),
+ ]));
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Facebook access token is invalid or expired'));
@@ -169,11 +136,11 @@ test('verifies a distinct account only once even with multiple at-risk posts', f
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- foreach ($postPlatforms as $postPlatform) {
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ foreach ($posts as $post) {
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
}
- Mail::assertQueued(PostAtRisk::class, fn ($mail) => count($mail->postPlatformIds) === 3);
+ Mail::assertQueued(PostAtRisk::class, fn ($mail) => count($mail->postIds) === 3);
});
test('ignores posts outside the 1-hour window', function () {
@@ -181,16 +148,9 @@ test('ignores posts outside the 1-hour window', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addHours(3),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -206,16 +166,9 @@ test('ignores draft posts even with a scheduled_at inside the window', function
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->draft()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->draft()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -231,15 +184,8 @@ test('ignores posts already warned', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
'connection_warning_sent_at' => now()->subMinutes(5),
]);
@@ -261,16 +207,9 @@ test('does not re-verify an account already known token_expired, but still warns
'status' => SocialAccountStatus::TokenExpired,
'error_message' => 'Threads access token is invalid or expired',
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -278,52 +217,10 @@ test('does not re-verify an account already known token_expired, but still warns
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
Mail::assertQueued(PostAtRisk::class);
});
-test('counts distinct posts, not post_platforms, when one post spans multiple broken accounts', function () {
- Mail::fake();
-
- $workspace = Workspace::factory()->create();
- $accountOne = SocialAccount::factory()->threads()->create([
- 'workspace_id' => $workspace->id,
- 'status' => SocialAccountStatus::TokenExpired,
- 'error_message' => 'Threads access token is invalid or expired',
- ]);
- $accountTwo = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $workspace->id,
- 'status' => SocialAccountStatus::TokenExpired,
- 'error_message' => 'Facebook access token is invalid or expired',
- ]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(30),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $accountOne->id,
- 'platform' => $accountOne->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $accountTwo->id,
- 'platform' => $accountTwo->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
-
- $verifier = mock(ConnectionVerifier::class);
- $verifier->shouldNotReceive('verify');
- app()->instance(ConnectionVerifier::class, $verifier);
-
- VerifyUpcomingPostConnections::dispatchSync($workspace->id);
-
- // Two post_platforms, but they belong to the same post — the count
- // must reflect distinct posts, not post_platform rows.
- Mail::assertQueued(PostAtRisk::class, fn ($mail) => $mail->count === 1 && count($mail->postPlatformIds) === 2);
-});
-
test('does not re-verify an account already known disconnected, but still warns about new posts', function () {
Mail::fake();
@@ -333,16 +230,9 @@ test('does not re-verify an account already known disconnected, but still warns
'status' => SocialAccountStatus::Disconnected,
'error_message' => 'Threads account was disconnected',
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -350,7 +240,7 @@ test('does not re-verify an account already known disconnected, but still warns
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
Mail::assertQueued(PostAtRisk::class);
});
@@ -365,29 +255,15 @@ test('does not re-notify about an already-broken account within the cooldown, ev
// A post already warned about 10 minutes ago — still within the 1-hour
// renotify cooldown for this account.
- $earlierPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $earlierPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(10),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $earlierPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
'connection_warning_sent_at' => now()->subMinutes(10),
]);
// A brand-new post that just entered the risk window — never warned.
- $newPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $newPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $newPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $newPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -397,7 +273,7 @@ test('does not re-notify about an already-broken account within the cooldown, ev
// Left unstamped so it's picked up once the cooldown expires, instead of
// being silently absorbed without ever being mentioned in an email.
- expect($newPostPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($newPost->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -410,28 +286,14 @@ test('re-notifies about an already-broken account once the cooldown has passed',
'status' => SocialAccountStatus::TokenExpired,
]);
- $earlierPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $earlierPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(10),
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $earlierPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
'connection_warning_sent_at' => now()->subMinutes(90),
]);
- $newPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $newPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $newPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $newPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -439,7 +301,7 @@ test('re-notifies about an already-broken account once the cooldown has passed',
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($newPostPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($newPost->fresh()->connection_warning_sent_at)->not->toBeNull();
Mail::assertQueued(PostAtRisk::class);
});
@@ -452,16 +314,9 @@ test('skips notifying about a freshly-disconnected account to avoid a duplicate
'status' => SocialAccountStatus::TokenExpired,
'disconnected_at' => now()->subMinutes(2),
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -469,7 +324,7 @@ test('skips notifying about a freshly-disconnected account to avoid a duplicate
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -482,16 +337,9 @@ test('notifies about an already-broken account once the disconnection grace peri
'status' => SocialAccountStatus::TokenExpired,
'disconnected_at' => now()->subMinutes(10),
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -499,7 +347,7 @@ test('notifies about an already-broken account once the disconnection grace peri
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
Mail::assertQueued(PostAtRisk::class);
});
@@ -512,16 +360,9 @@ test('trusts a recently successful verification and does not re-verify within th
'status' => SocialAccountStatus::Connected,
'last_verified_at' => now()->subMinutes(10),
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -541,16 +382,9 @@ test('re-verifies an account once the last successful verification has aged out'
'status' => SocialAccountStatus::Connected,
'last_verified_at' => now()->subMinutes(56),
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturn(true);
@@ -570,16 +404,9 @@ test('records last_verified_at after a successful verification', function () {
'status' => SocialAccountStatus::Connected,
'last_verified_at' => null,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturn(true);
@@ -598,16 +425,9 @@ test('defers verification until the post is within 30 minutes of publishing', fu
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(55),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldNotReceive('verify');
@@ -615,7 +435,7 @@ test('defers verification until the post is within 30 minutes of publishing', fu
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
expect($account->fresh()->last_verified_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -629,27 +449,13 @@ test('verifies once the nearest post in the group crosses the 30-minute lead, ev
'status' => SocialAccountStatus::Connected,
]);
- $nearPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $nearPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(25),
]);
- $nearPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $nearPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
- $farPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $farPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(58),
]);
- $farPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $farPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturn(true);
@@ -658,8 +464,8 @@ test('verifies once the nearest post in the group crosses the 30-minute lead, ev
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
expect($account->fresh()->last_verified_at)->not->toBeNull();
- expect($nearPostPlatform->fresh())->not->toBeNull();
- expect($farPostPlatform->fresh())->not->toBeNull();
+ expect($nearPost->fresh())->not->toBeNull();
+ expect($farPost->fresh())->not->toBeNull();
});
test('defers to the next run instead of duplicating AccountDisconnected when another process wins the race', function () {
@@ -670,16 +476,9 @@ test('defers to the next run instead of duplicating AccountDisconnected when ano
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturnUsing(function () use ($account) {
@@ -698,7 +497,7 @@ test('defers to the next run instead of duplicating AccountDisconnected when ano
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -717,25 +516,18 @@ test('skips notifying when a concurrent run already claimed the warning window',
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
- $verifier->shouldReceive('verify')->once()->andReturnUsing(function () use ($postPlatform) {
+ $verifier->shouldReceive('verify')->once()->andReturnUsing(function () use ($post) {
// Simulate a second, overlapping run of this same job (the
// ShouldBeUnique lock's TTL matches the schedule cadence, so two
// instances can briefly overlap if a run takes unusually long)
- // already claiming and warning about this exact post_platform,
+ // already claiming and warning about this exact post,
// between this run's select and its own claim update below.
- $postPlatform->update(['connection_warning_sent_at' => now()]);
+ $post->update(['connection_warning_sent_at' => now()]);
throw new TokenExpiredException('Threads access token is invalid or expired');
});
@@ -755,47 +547,33 @@ test('narrows the notification to only the rows this run actually claimed when a
// connection).
Mail::fake();
- // Both post_platforms belong to the SAME account/group deliberately —
+ // Both posts belong to the SAME account/group deliberately —
// unlike a two-account version, this makes the scenario independent of
// which group a DB result set happens to return first (groupBy()
- // preserves query order, and atRiskPostPlatforms() has no ORDER BY).
+ // preserves query order, and atRiskPosts() has no ORDER BY).
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->threads()->create([
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $claimedByOtherRunPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $claimedByOtherRunPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $claimedByOtherRunPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $claimedByOtherRunPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
- $stillClaimableByThisRunPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $stillClaimableByThisRunPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(25),
]);
- $stillClaimableByThisRunPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $stillClaimableByThisRunPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')
->once()
- ->andReturnUsing(function () use ($claimedByOtherRunPostPlatform) {
+ ->andReturnUsing(function () use ($claimedByOtherRunPost) {
// Simulate a second, overlapping run of this same job claiming
- // one of this account's two post_platforms — mid-call, between
+ // one of this account's two posts — mid-call, between
// this run's own read (already reflected in $atRisk) and its
// claim step below.
- $claimedByOtherRunPostPlatform->update(['connection_warning_sent_at' => now()]);
+ $claimedByOtherRunPost->update(['connection_warning_sent_at' => now()]);
throw new TokenExpiredException('Threads access token is invalid or expired');
});
@@ -803,10 +581,10 @@ test('narrows the notification to only the rows this run actually claimed when a
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($stillClaimableByThisRunPostPlatform, $claimedByOtherRunPostPlatform) {
- return count($mail->postPlatformIds) === 1
- && in_array($stillClaimableByThisRunPostPlatform->id, $mail->postPlatformIds, true)
- && ! in_array($claimedByOtherRunPostPlatform->id, $mail->postPlatformIds, true);
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($stillClaimableByThisRunPost, $claimedByOtherRunPost) {
+ return count($mail->postIds) === 1
+ && in_array($stillClaimableByThisRunPost->id, $mail->postIds, true)
+ && ! in_array($claimedByOtherRunPost->id, $mail->postIds, true);
});
});
@@ -818,16 +596,9 @@ test('does not crash when the account is deleted between being loaded and the To
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturnUsing(function () use ($account) {
@@ -842,7 +613,7 @@ test('does not crash when the account is deleted between being loaded and the To
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -855,31 +626,17 @@ test('a deleted account does not abort the run for other accounts in the same wo
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $deletedPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $deletedPost = Post::factory()->forAccount($deletedAccount)->scheduled()->create([
'scheduled_at' => now()->addMinutes(15),
]);
- $deletedPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $deletedPost->id,
- 'social_account_id' => $deletedAccount->id,
- 'platform' => $deletedAccount->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$survivingAccount = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $survivingPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $survivingPost = Post::factory()->forAccount($survivingAccount)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $survivingPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $survivingPost->id,
- 'social_account_id' => $survivingAccount->id,
- 'platform' => $survivingAccount->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')
@@ -898,17 +655,17 @@ test('a deleted account does not abort the run for other accounts in the same wo
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($deletedPostPlatform->fresh()->connection_warning_sent_at)->toBeNull();
- expect($survivingPostPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($deletedPost->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($survivingPost->fresh()->connection_warning_sent_at)->not->toBeNull();
expect($survivingAccount->fresh()->status)->toBe(SocialAccountStatus::TokenExpired);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($survivingPostPlatform) {
- return count($mail->postPlatformIds) === 1
- && in_array($survivingPostPlatform->id, $mail->postPlatformIds, true);
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($survivingPost) {
+ return count($mail->postIds) === 1
+ && in_array($survivingPost->id, $mail->postIds, true);
});
});
-test('a post deleted between the main query and the eager-loaded post relation resolving does not crash the run', function () {
+test('a post deleted right after the main query does not crash the run', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
@@ -917,40 +674,16 @@ test('a post deleted between the main query and the eager-loaded post relation r
'status' => SocialAccountStatus::Connected,
]);
- $doomedPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $doomedPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(15),
]);
- $doomedPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $doomedPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
- $survivingPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $survivingPost = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $survivingPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $survivingPost->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
-
- // atRiskPostPlatforms() runs the post_platforms select, then a separate
- // eager-load query for the post relation. Deleting the post right after
- // the first query — but before the second — reproduces the race: this
- // job's in-memory PostPlatform row still exists, but its post relation
- // resolves to null once the eager load runs.
- // str_starts_with (not str_contains) deliberately excludes the
- // recentlyWarnedAbout()/recentlyDisconnected() exists() subqueries —
- // Laravel compiles ->exists() as "select exists(select * from
- // post_platforms where ...)", which contains but doesn't start with this
- // prefix, so those never trip the listener.
+
$listener = function ($query) use ($doomedPost) {
- if (verifyUpcomingSelectsFrom($query->sql, 'post_platforms')) {
+ if (verifyUpcomingSelectsFrom($query->sql, 'posts')) {
Post::where('id', $doomedPost->id)->delete();
}
};
@@ -962,19 +695,17 @@ test('a post deleted between the main query and the eager-loaded post relation r
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- // post_platforms.post_id cascades on delete, so the row itself is gone —
- // nothing left to warn about for it.
- expect($doomedPostPlatform->fresh())->toBeNull();
- expect($survivingPostPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($doomedPost->fresh())->toBeNull();
+ expect($survivingPost->fresh()->connection_warning_sent_at)->not->toBeNull();
expect($account->fresh()->status)->toBe(SocialAccountStatus::TokenExpired);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($survivingPostPlatform) {
- return count($mail->postPlatformIds) === 1
- && in_array($survivingPostPlatform->id, $mail->postPlatformIds, true);
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($survivingPost) {
+ return count($mail->postIds) === 1
+ && in_array($survivingPost->id, $mail->postIds, true);
});
});
-test('does not crash or warn when the account is hard-deleted mid-run, after atRiskPostPlatforms() already selected its post_platform', function () {
+test('does not crash or warn when the account is hard-deleted mid-run, after atRiskPosts() already selected its post', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
@@ -982,26 +713,10 @@ test('does not crash or warn when the account is hard-deleted mid-run, after atR
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
-
- // Same race as the two tests above, but the account is hard-deleted —
- // social_account_id is nullOnDelete(), so the post_platform row survives
- // with a dangling reference and the re-fetch guard finds no account row.
- // Deleting after the socialAccount eager-load query (rather than the
- // main post_platforms select, like the two tests above) is deliberate:
- // deleting that early would instead hit the pre-existing, unrelated
- // "$account is null straight out of the eager load" branch — this
- // needs the account to still resolve as non-null going into the loop,
- // then disappear before the guard's own re-fetch runs.
+
$listener = function ($query) use ($account) {
if (verifyUpcomingSelectsFrom($query->sql, 'social_accounts')) {
$account->delete();
@@ -1015,7 +730,7 @@ test('does not crash or warn when the account is hard-deleted mid-run, after atR
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
@@ -1027,16 +742,9 @@ test('does not warn and does not mark connection_warning_sent_at on PlatformUnav
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new PlatformUnavailableException('Threads API returned 503'));
@@ -1044,7 +752,7 @@ test('does not warn and does not mark connection_warning_sent_at on PlatformUnav
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
expect($account->fresh()->status)->toBe(SocialAccountStatus::Connected);
Mail::assertNothingQueued();
});
@@ -1057,16 +765,9 @@ test('does nothing when the account verifies successfully', function () {
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andReturn(true);
@@ -1074,7 +775,7 @@ test('does nothing when the account verifies successfully', function () {
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
expect($account->fresh()->status)->toBe(SocialAccountStatus::Connected);
Mail::assertNothingQueued();
});
@@ -1088,31 +789,17 @@ test('an unexpected exception verifying one account does not abort the run for o
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $brokenPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $brokenPost = Post::factory()->forAccount($brokenAccount)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $brokenPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $brokenPost->id,
- 'social_account_id' => $brokenAccount->id,
- 'platform' => $brokenAccount->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$expiredAccount = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $expiredPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $expiredPost = Post::factory()->forAccount($expiredAccount)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $expiredPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $expiredPost->id,
- 'social_account_id' => $expiredAccount->id,
- 'platform' => $expiredAccount->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')
@@ -1127,43 +814,18 @@ test('an unexpected exception verifying one account does not abort the run for o
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($brokenPostPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($brokenPost->fresh()->connection_warning_sent_at)->toBeNull();
expect($brokenAccount->fresh()->status)->toBe(SocialAccountStatus::Connected);
- expect($expiredPostPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($expiredPost->fresh()->connection_warning_sent_at)->not->toBeNull();
expect($expiredAccount->fresh()->status)->toBe(SocialAccountStatus::TokenExpired);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($expiredPostPlatform) {
- return count($mail->postPlatformIds) === 1
- && in_array($expiredPostPlatform->id, $mail->postPlatformIds, true);
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($expiredPost) {
+ return count($mail->postIds) === 1
+ && in_array($expiredPost->id, $mail->postIds, true);
});
});
-test('ignores disabled platforms even inside the risk window', function () {
- Mail::fake();
-
- $workspace = Workspace::factory()->create();
- $account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(30),
- ]);
- PostPlatform::factory()->disabled()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
-
- $verifier = mock(ConnectionVerifier::class);
- $verifier->shouldNotReceive('verify');
- app()->instance(ConnectionVerifier::class, $verifier);
-
- VerifyUpcomingPostConnections::dispatchSync($workspace->id);
-
- Mail::assertNothingQueued();
-});
-
test('does not leak another workspace\'s at-risk posts into this workspace\'s notification', function () {
Mail::fake();
@@ -1172,32 +834,18 @@ test('does not leak another workspace\'s at-risk posts into this workspace\'s no
'workspace_id' => $workspaceA->id,
'status' => SocialAccountStatus::Connected,
]);
- $postA = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspaceA->id,
+ $postA = Post::factory()->forAccount($accountA)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatformA = PostPlatform::factory()->create([
- 'post_id' => $postA->id,
- 'social_account_id' => $accountA->id,
- 'platform' => $accountA->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$workspaceB = Workspace::factory()->create();
$accountB = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspaceB->id,
'status' => SocialAccountStatus::Connected,
]);
- $postB = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspaceB->id,
+ $postB = Post::factory()->forAccount($accountB)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatformB = PostPlatform::factory()->create([
- 'post_id' => $postB->id,
- 'social_account_id' => $accountB->id,
- 'platform' => $accountB->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')
@@ -1210,20 +858,20 @@ test('does not leak another workspace\'s at-risk posts into this workspace\'s no
VerifyUpcomingPostConnections::dispatchSync($workspaceA->id);
- expect($postPlatformA->fresh()->connection_warning_sent_at)->not->toBeNull();
- expect($postPlatformB->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($postA->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($postB->fresh()->connection_warning_sent_at)->toBeNull();
expect($accountB->fresh()->status)->toBe(SocialAccountStatus::Connected);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($workspaceA, $postPlatformA, $postPlatformB) {
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($workspaceA, $postA, $postB) {
return $mail->workspace->id === $workspaceA->id
- && in_array($postPlatformA->id, $mail->postPlatformIds, true)
- && ! in_array($postPlatformB->id, $mail->postPlatformIds, true);
+ && in_array($postA->id, $mail->postIds, true)
+ && ! in_array($postB->id, $mail->postIds, true);
});
Mail::assertQueuedCount(1);
});
-test('re-evaluates a post_platform warned more than a day ago instead of skipping it forever', function () {
+test('re-evaluates a post warned more than a day ago instead of skipping it forever', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
@@ -1231,15 +879,8 @@ test('re-evaluates a post_platform warned more than a day ago instead of skippin
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
- ]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
'connection_warning_sent_at' => now()->subDay()->subMinute(),
]);
@@ -1249,13 +890,13 @@ test('re-evaluates a post_platform warned more than a day ago instead of skippin
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull()
- ->and($postPlatform->fresh()->connection_warning_sent_at->isAfter(now()->subMinute()))->toBeTrue();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull()
+ ->and($post->fresh()->connection_warning_sent_at->isAfter(now()->subMinute()))->toBeTrue();
Mail::assertQueued(PostAtRisk::class);
});
-test('still skips a post_platform warned less than a day ago', function () {
+test('still skips a post warned less than a day ago', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
@@ -1263,16 +904,9 @@ test('still skips a post_platform warned less than a day ago', function () {
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(30),
- ]);
$warnedAt = now()->subHours(2);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
+ 'scheduled_at' => now()->addMinutes(30),
'connection_warning_sent_at' => $warnedAt,
]);
@@ -1282,12 +916,12 @@ test('still skips a post_platform warned less than a day ago', function () {
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at->format('Y-m-d H:i:s'))
+ expect($post->fresh()->connection_warning_sent_at->format('Y-m-d H:i:s'))
->toBe($warnedAt->format('Y-m-d H:i:s'));
Mail::assertNothingQueued();
});
-test('does not re-warn a re-armed post_platform when the account has since been reconnected', function () {
+test('does not re-warn a re-armed post when the account has since been reconnected', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
@@ -1295,16 +929,9 @@ test('does not re-warn a re-armed post_platform when the account has since been
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'scheduled_at' => now()->addMinutes(30),
- ]);
$warnedAt = now()->subDay()->subMinute();
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
+ 'scheduled_at' => now()->addMinutes(30),
'connection_warning_sent_at' => $warnedAt,
]);
@@ -1319,41 +946,29 @@ test('does not re-warn a re-armed post_platform when the account has since been
// The row was re-evaluated (not skipped — verify() was called), but
// since it came back healthy, nothing about it changes: no new
// warning, no notification, no touch to the account's status.
- expect($postPlatform->fresh()->connection_warning_sent_at->format('Y-m-d H:i:s'))
+ expect($post->fresh()->connection_warning_sent_at->format('Y-m-d H:i:s'))
->toBe($warnedAt->format('Y-m-d H:i:s'));
expect($account->fresh()->status)->toBe(SocialAccountStatus::Connected);
Mail::assertNothingQueued();
});
-test('does not crash the run on a post_platform with a null social_account_id', function () {
+test('does not crash the run on a scheduled post without a channel', function () {
Mail::fake();
$workspace = Workspace::factory()->create();
- $orphanedPost = Post::factory()->scheduled()->create([
+ Post::factory()->scheduled()->create([
'workspace_id' => $workspace->id,
'scheduled_at' => now()->addMinutes(20),
]);
- PostPlatform::factory()->create([
- 'post_id' => $orphanedPost->id,
- 'social_account_id' => null,
- 'status' => PostPlatformStatus::Pending,
- ]);
$account = SocialAccount::factory()->facebook()->create([
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(20),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Facebook access token is invalid or expired'));
@@ -1361,12 +976,12 @@ test('does not crash the run on a post_platform with a null social_account_id',
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->not->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->not->toBeNull();
expect($account->fresh()->status)->toBe(SocialAccountStatus::TokenExpired);
- Mail::assertQueued(PostAtRisk::class, function ($mail) use ($postPlatform) {
- return count($mail->postPlatformIds) === 1
- && in_array($postPlatform->id, $mail->postPlatformIds, true);
+ Mail::assertQueued(PostAtRisk::class, function ($mail) use ($post) {
+ return count($mail->postIds) === 1
+ && in_array($post->id, $mail->postIds, true);
});
});
@@ -1378,16 +993,9 @@ test('leaves posts unwarned and does not send an email when the workspace has no
'workspace_id' => $workspace->id,
'status' => SocialAccountStatus::Connected,
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->addMinutes(30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'status' => PostPlatformStatus::Pending,
- ]);
$verifier = mock(ConnectionVerifier::class);
$verifier->shouldReceive('verify')->once()->andThrow(new TokenExpiredException('Threads access token is invalid or expired'));
@@ -1395,7 +1003,7 @@ test('leaves posts unwarned and does not send an email when the workspace has no
VerifyUpcomingPostConnections::dispatchSync($workspace->id);
- expect($postPlatform->fresh()->connection_warning_sent_at)->toBeNull();
+ expect($post->fresh()->connection_warning_sent_at)->toBeNull();
Mail::assertNothingQueued();
});
diff --git a/tests/Feature/Mail/MailRenderingTest.php b/tests/Feature/Mail/MailRenderingTest.php
index 8fd0e9ede..a27d7b8a2 100644
--- a/tests/Feature/Mail/MailRenderingTest.php
+++ b/tests/Feature/Mail/MailRenderingTest.php
@@ -17,11 +17,10 @@ use App\Models\Account;
use App\Models\Invite;
use App\Models\Post;
use App\Models\PostNote;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-use App\Support\Mail\ApprovalEmailPosts;
+use App\Support\Mail\ApprovalEmailPost;
use Carbon\CarbonImmutable;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Auth\Notifications\VerifyEmail;
@@ -98,27 +97,21 @@ test('the workspace invite names the invited access', function (string $access,
'needs approval' => ['approval', 'needs_approval'],
]);
-test('the post note email renders the note, the post and its channels', function (Locale $locale) {
+test('the post note email renders the note, the post and its channel', function (Locale $locale) {
$author = User::factory()->create(['name' => 'Ana Author']);
$workspace = Workspace::factory()->create([
'account_id' => $author->account_id,
'user_id' => $author->id,
'name' => 'Acme Workspace',
]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $author->id,
- 'content' => '<p>Launch day is <strong>here</strong></p>',
- ]);
$account = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::LinkedIn,
'display_name' => 'Acme Inc',
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::LinkedIn,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $author->id,
+ 'content' => '<p>Launch day is <strong>here</strong></p>',
]);
$note = PostNote::factory()->create([
'post_id' => $post->id,
@@ -139,13 +132,14 @@ test('the post note email renders the note, the post and its channels', function
$mailable->assertSeeInHtml(route('app.posts.edit', ['post' => $post, 'comment' => $note->id]), false);
})->with([Locale::English, Locale::PortugueseBrazil]);
-test('the post note email falls back when the post has no text', function () {
+test('the post note email falls back when the post has no text and no channel', function () {
$author = User::factory()->create();
$post = Post::factory()->create(['user_id' => $author->id, 'content' => '']);
$note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $author->id]);
(new PostNoteAdded($note, $author))
- ->assertSeeInHtml(__('mail.post_note_added.post_without_text'));
+ ->assertSeeInHtml(__('mail.post_note_added.post_without_text'))
+ ->assertDontSeeInHtml('images/accounts/', false);
});
test('the disconnected-connections digest renders every account and reason', function () {
@@ -214,21 +208,19 @@ test('the password reset email is sent in the user locale', function () {
->not->toContain(__('mail.password_reset.body', [], 'en'));
});
-test('the approval request email renders who asked, the channels, the excerpt and the queue slot', function (Locale $locale) {
+test('the approval request email renders who asked, the channel, the excerpt and the queue slot', function (Locale $locale) {
$requester = User::factory()->create(['name' => 'Rita Requester', 'email' => '[email protected]']);
$approver = User::factory()->create(['account_id' => $requester->account_id, 'timezone' => 'UTC']);
$workspace = Workspace::factory()->create(['account_id' => $requester->account_id, 'user_id' => $requester->id, 'name' => 'Acme Workspace']);
- $post = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::LinkedIn, 'display_name' => 'Acme Inc']);
+ $post = Post::factory()->forAccount($account)->pendingApproval()->create([
'user_id' => $requester->id,
'content' => '<p>Big <strong>launch</strong> tomorrow</p>',
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => null,
]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::LinkedIn, 'display_name' => 'Acme Inc']);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::LinkedIn]);
- $mailable = (new PostApprovalRequested([$post->id], $requester, $approver))->locale($locale->value);
+ $mailable = (new PostApprovalRequested($post->id, $requester, $approver))->locale($locale->value);
$mailable->assertHasSubject(__('mail.post_approval_requested.subject', ['name' => 'Rita Requester'], $locale->value));
$mailable->assertSeeInHtml(__('mail.post_approval_requested.heading', [], $locale->value));
@@ -241,20 +233,18 @@ test('the approval request email renders who asked, the channels, the excerpt an
$mailable->assertSeeInHtml(route('app.posts.index', ['tab' => 'approvals']), false);
})->with([Locale::English, Locale::PortugueseBrazil]);
-test('the approved and rejected emails render the approver, the channels and their button', function (Locale $locale) {
+test('the approved and rejected emails render the approver, the channel and their button', function (Locale $locale) {
$author = User::factory()->create(['timezone' => 'UTC']);
$approver = User::factory()->create(['account_id' => $author->account_id, 'name' => 'Ada Approver']);
$workspace = Workspace::factory()->create(['account_id' => $author->account_id, 'user_id' => $author->id, 'name' => 'Acme Workspace']);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::LinkedIn, 'display_name' => 'Acme Inc']);
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $author->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => CarbonImmutable::parse('2026-10-07 15:00', 'UTC'),
]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => Platform::LinkedIn, 'display_name' => 'Acme Inc']);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::LinkedIn]);
- $approved = (new PostApproved([$post->id], $approver, $author))->locale($locale->value);
+ $approved = (new PostApproved($post->id, $approver, $author))->locale($locale->value);
$approved->assertHasSubject(__('mail.post_approved.subject', ['name' => 'Ada Approver'], $locale->value));
$approved->assertSeeInHtml(__('mail.post_approved.heading', [], $locale->value));
@@ -264,7 +254,7 @@ test('the approved and rejected emails render the approver, the channels and the
$approved->assertSeeInHtml('LinkedIn');
$approved->assertSeeInHtml(route('app.posts.index', ['tab' => 'queue']), false);
- $rejected = (new PostRejected([$post->id], $approver))->locale($locale->value);
+ $rejected = (new PostRejected($post->id, $approver))->locale($locale->value);
$rejected->assertSeeInHtml(asset('images/accounts/linkedin.png'));
$approved->assertSeeInHtml(asset('images/accounts/linkedin.png'));
@@ -280,22 +270,19 @@ test('the approved and rejected emails render the approver, the channels and the
*/
function approvalEmailPost(Workspace $workspace, User $author, Platform $platform, string $displayName, array $attributes = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform, 'display_name' => $displayName]);
+
+ return Post::factory()->forAccount($account)->create([
'user_id' => $author->id,
...$attributes,
]);
- $account = SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform, 'display_name' => $displayName]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => $platform]);
-
- return $post;
}
function approvalEmailTimeLabel(CarbonImmutable $at, User $recipient, Locale $locale): string
{
$previous = app()->getLocale();
app()->setLocale($locale->value);
- $label = (string) ApprovalEmailPosts::time($at, $recipient);
+ $label = (string) ApprovalEmailPost::time($at, $recipient);
app()->setLocale($previous);
return $label;
@@ -310,7 +297,7 @@ test('the approval request email keeps the paragraph breaks of the post', functi
'content' => '<p>First paragraph</p><p>Second <strong>paragraph</strong><br>and a line</p>',
]);
- $html = (new PostApprovalRequested([$post->id], $requester, $approver))->render();
+ $html = (new PostApprovalRequested($post->id, $requester, $approver))->render();
expect($html)->toContain("First paragraph\nSecond paragraph\nand a line");
});
@@ -336,7 +323,7 @@ test('a queue request holding its slot shows that time, not the next queue slot'
'scheduled_at' => $at,
]);
- $mailable = (new PostApprovalRequested([$post->id], $requester, $approver))->locale($locale->value);
+ $mailable = (new PostApprovalRequested($post->id, $requester, $approver))->locale($locale->value);
$mailable->assertSeeInHtml(approvalEmailTimeLabel($at, $approver, $locale))
->assertDontSeeInHtml(__('mail.post_approval_requested.next_queue_slot', [], $locale->value));
@@ -352,50 +339,27 @@ test('a publish now request says it goes out as soon as it is approved', functio
'scheduled_at' => null,
]);
- $mailable = (new PostApprovalRequested([$post->id], $requester, $approver))->locale($locale->value);
+ $mailable = (new PostApprovalRequested($post->id, $requester, $approver))->locale($locale->value);
$mailable->assertSeeInHtml(__('mail.post_approval_requested.as_soon_as_approved', [], $locale->value))
->assertDontSeeInHtml(__('mail.post_approval_requested.next_queue_slot', [], $locale->value));
})->with([Locale::English, Locale::PortugueseBrazil]);
-test('the approved email lists the time of each channel when they go out at different times', function (Locale $locale) {
- $author = User::factory()->create(['timezone' => 'UTC']);
- $approver = User::factory()->create(['account_id' => $author->account_id]);
- $workspace = Workspace::factory()->create(['account_id' => $author->account_id, 'user_id' => $author->id]);
- $morning = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');
- $evening = CarbonImmutable::parse('2026-10-08 18:00', 'UTC');
- $linkedIn = approvalEmailPost($workspace, $author, Platform::LinkedIn, 'Acme Inc', ['status' => PostStatus::Scheduled, 'scheduled_at' => $morning]);
- $x = approvalEmailPost($workspace, $author, Platform::X, 'acmex', ['status' => PostStatus::Scheduled, 'scheduled_at' => $evening]);
- $mastodon = approvalEmailPost($workspace, $author, Platform::Mastodon, 'acmetoot', ['status' => PostStatus::Publishing, 'scheduled_at' => null]);
-
- $mailable = (new PostApproved([$linkedIn->id, $x->id, $mastodon->id], $approver, $author))->locale($locale->value);
-
- $mailable->assertSeeInOrderInHtml([
- $linkedIn->postPlatforms()->sole()->display_name,
- approvalEmailTimeLabel($morning, $author, $locale),
- $x->postPlatforms()->sole()->display_name,
- approvalEmailTimeLabel($evening, $author, $locale),
- $mastodon->postPlatforms()->sole()->display_name,
- __('mail.post_approved.publishing_now', [], $locale->value),
- ]);
- $document = new Crawler($mailable->render());
- foreach ([Platform::LinkedIn, Platform::X, Platform::Mastodon] as $platform) {
- expect($document->filter('img[src="'.asset('images/accounts/'.$platform->network().'.png').'"]')->count())->toBe(1);
- }
-})->with([Locale::English, Locale::PortugueseBrazil, Locale::French]);
-
-test('the approved email shows one time when every channel goes out together', function () {
+test('the approved email shows its channel and when its post goes out', function (Locale $locale) {
$author = User::factory()->create(['timezone' => 'UTC']);
$approver = User::factory()->create(['account_id' => $author->account_id]);
$workspace = Workspace::factory()->create(['account_id' => $author->account_id, 'user_id' => $author->id]);
$at = CarbonImmutable::parse('2026-10-07 09:00', 'UTC');
- $linkedIn = approvalEmailPost($workspace, $author, Platform::LinkedIn, 'Acme Inc', ['status' => PostStatus::Scheduled, 'scheduled_at' => $at]);
- $x = approvalEmailPost($workspace, $author, Platform::X, 'acmex', ['status' => PostStatus::Scheduled, 'scheduled_at' => $at]);
+ $scheduled = approvalEmailPost($workspace, $author, Platform::LinkedIn, 'Acme Inc', ['status' => PostStatus::Scheduled, 'scheduled_at' => $at]);
+ $publishing = approvalEmailPost($workspace, $author, Platform::Mastodon, 'acmetoot', ['status' => PostStatus::Publishing, 'scheduled_at' => null]);
- $html = (new PostApproved([$linkedIn->id, $x->id], $approver, $author))->render();
+ (new PostApproved($scheduled->id, $approver, $author))->locale($locale->value)
+ ->assertSeeInOrderInHtml([$scheduled->display_name, approvalEmailTimeLabel($at, $author, $locale)])
+ ->assertDontSeeInHtml(__('mail.post_approved.publishing_now', [], $locale->value));
- expect(substr_count($html, "{$at->locale('en')->isoFormat('LLL')} (UTC)"))->toBe(1);
-});
+ (new PostApproved($publishing->id, $approver, $author))->locale($locale->value)
+ ->assertSeeInOrderInHtml([$publishing->display_name, __('mail.post_approved.publishing_now', [], $locale->value)]);
+})->with([Locale::English, Locale::PortugueseBrazil, Locale::French]);
test('approval emails show the time in the recipient zone and clock', function (TimeFormat $format, Locale $locale, string $expected) {
$author = User::factory()->create(['timezone' => 'America/Sao_Paulo', 'time_format' => $format]);
@@ -406,7 +370,7 @@ test('approval emails show the time in the recipient zone and clock', function (
'scheduled_at' => CarbonImmutable::parse('2026-10-07 15:00', 'UTC'),
]);
- $html = (new PostApproved([$post->id], $approver, $author))->locale($locale->value)->render();
+ $html = (new PostApproved($post->id, $approver, $author))->locale($locale->value)->render();
expect($html)->toContain($expected);
})->with([
@@ -424,7 +388,7 @@ test('approval emails name the canonical zone of a legacy alias', function () {
'scheduled_at' => CarbonImmutable::parse('2026-10-07 15:00', 'UTC'),
]);
- expect((new PostApproved([$post->id], $approver, $author))->render())->toContain('October 7, 2026 20:30 (Asia/Kolkata)');
+ expect((new PostApproved($post->id, $approver, $author))->render())->toContain('October 7, 2026 20:30 (Asia/Kolkata)');
});
test('the email layout carries the recipient locale and direction', function (Locale $locale, string $direction) {
@@ -443,16 +407,15 @@ test('the email layout carries the recipient locale and direction', function (Lo
'portuguese' => [Locale::PortugueseBrazil, 'ltr'],
]);
-test('approval emails keep distinct channels with the same name and escape their names', function () {
+test('approval emails show one channel card and escape its name', function () {
$author = User::factory()->create(['timezone' => 'UTC']);
$workspace = Workspace::factory()->create(['account_id' => $author->account_id, 'user_id' => $author->id]);
- $first = approvalEmailPost($workspace, $author, Platform::Instagram, 'Studio <Team>');
- $second = approvalEmailPost($workspace, $author, Platform::Instagram, 'Studio <Team>');
+ $post = approvalEmailPost($workspace, $author, Platform::Instagram, 'Studio <Team>');
- $html = (new PostRejected([$first->id, $second->id], $author))->render();
+ $html = (new PostRejected($post->id, $author))->render();
$document = new Crawler($html);
- expect($document->filter('img[src="'.asset('images/accounts/instagram.png').'"]')->count())->toBe(2)
+ expect($document->filter('img[src="'.asset('images/accounts/instagram.png').'"]')->count())->toBe(1)
->and($html)->toContain('Studio &lt;Team&gt;')
->not->toContain('Studio <Team>');
});
diff --git a/tests/Feature/Mail/PostAtRiskTest.php b/tests/Feature/Mail/PostAtRiskTest.php
index d240f714e..11bfaa858 100644
--- a/tests/Feature/Mail/PostAtRiskTest.php
+++ b/tests/Feature/Mail/PostAtRiskTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Enums\User\TimeFormat;
use App\Mail\PostAtRisk;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -19,17 +18,11 @@ function postAtRiskRecipient(array $attributes = []): User
test('renders subject and body listing the at-risk account and its post times', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(14, 30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$postPlatform->id], 1, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$post->id], 1, postAtRiskRecipient());
$mailable->assertHasSubject('1 post is at risk in Acme Co');
$mailable->assertSeeInHtml('Posts May Fail to Publish');
@@ -41,100 +34,69 @@ test('renders plural subject and postsLabel when multiple posts are at risk', fu
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $postPlatformIds = collect([
+ $postIds = collect([
['time' => [14, 30]],
['time' => [15, 0]],
- ])->map(function (array $data) use ($workspace, $account) {
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ ])->map(function (array $data) use ($account) {
+ return Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(...$data['time']),
- ]);
-
- return PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
])->id;
})->all();
- $mailable = new PostAtRisk($workspace, $postPlatformIds, 2, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, $postIds, 2, postAtRiskRecipient());
$mailable->assertHasSubject('2 posts are at risk in Acme Co');
$mailable->assertSeeInHtml('2 posts scheduled: 14:30, 15:00 (UTC)');
});
-test('groups post_platforms by account when rehydrating for send', function () {
+test('groups posts by account when rehydrating for send', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$threadsAccount = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
$facebookAccount = SocialAccount::factory()->facebook()->create(['workspace_id' => $workspace->id]);
- $threadsPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $threadsPost = Post::factory()->forAccount($threadsAccount)->scheduled()->create([
'scheduled_at' => now()->setTime(9, 0),
]);
- $threadsPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $threadsPost->id,
- 'social_account_id' => $threadsAccount->id,
- 'platform' => $threadsAccount->platform,
- ]);
- $facebookPost = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $facebookPost = Post::factory()->forAccount($facebookAccount)->scheduled()->create([
'scheduled_at' => now()->setTime(10, 0),
]);
- $facebookPostPlatform = PostPlatform::factory()->create([
- 'post_id' => $facebookPost->id,
- 'social_account_id' => $facebookAccount->id,
- 'platform' => $facebookAccount->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$threadsPostPlatform->id, $facebookPostPlatform->id], 2, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$threadsPost->id, $facebookPost->id], 2, postAtRiskRecipient());
$mailable->assertHasSubject('2 posts are at risk in Acme Co');
$mailable->assertSeeInHtml('1 post scheduled: 09:00 (UTC)');
$mailable->assertSeeInHtml('1 post scheduled: 10:00 (UTC)');
});
-test('only carries the workspace, post_platform IDs, and count on the queue payload, not full model graphs', function () {
+test('only carries the workspace, post IDs, and count on the queue payload, not full model graphs', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create([
'workspace_id' => $workspace->id,
'access_token' => 'super-secret-token-value',
]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(14, 30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$postPlatform->id], 1, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$post->id], 1, postAtRiskRecipient());
$serialized = serialize($mailable);
expect($serialized)->not->toContain('super-secret-token-value')
->and($serialized)->not->toContain(SocialAccount::class)
- ->and($serialized)->not->toContain(PostPlatform::class)
+ ->and($serialized)->not->toContain(Post::class)
->and(strlen($serialized))->toBeLessThan(2000);
});
test('footer links to notification preferences instead of an unsubscribe link', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(14, 30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$postPlatform->id], 1, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$post->id], 1, postAtRiskRecipient());
$mailable->assertSeeInHtml('Manage notifications');
$mailable->assertSeeInHtml(route('app.notifications.preferences'));
@@ -144,30 +106,24 @@ test('footer links to notification preferences instead of an unsubscribe link',
test('subject and previewText stay locked to the dispatch-time count even if a row disappears before send', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(14, 30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$postPlatform->id], 1, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$post->id], 1, postAtRiskRecipient());
// Simulate the row disappearing between when this mailable was
// dispatched and when it's actually rendered for send — the count
// passed at construction (matching the in-app notification's title)
// must not be recomputed from the now-stale rehydrated rows.
- $postPlatform->delete();
+ $post->delete();
$mailable->assertHasSubject('1 post is at risk in Acme Co');
$content = $mailable->content();
expect($content->with['previewText'])->toBe('1 post is at risk in Acme Co');
});
-test('renders without crashing when none of the post_platform ids resolve', function () {
+test('renders without crashing when none of the post ids resolve', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$mailable = new PostAtRisk($workspace, ['00000000-0000-0000-0000-000000000000'], 0, postAtRiskRecipient());
@@ -178,20 +134,14 @@ test('renders without crashing when none of the post_platform ids resolve', func
test('renders without crashing when the account is deleted before send', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => now()->setTime(14, 30),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = new PostAtRisk($workspace, [$postPlatform->id], 1, postAtRiskRecipient());
+ $mailable = new PostAtRisk($workspace, [$post->id], 1, postAtRiskRecipient());
- // Deleting the account (not the post_platform) between dispatch and
- // send: the FK's nullOnDelete sets post_platforms.social_account_id to
+ // Deleting the account (not the post) between dispatch and
+ // send: the FK's nullOnDelete sets posts.social_account_id to
// null, so the rehydrated group's account resolves to null. There's
// nothing meaningful to render for it (no platform, no handle), so it
// must be dropped from the body rather than crash the render.
@@ -204,35 +154,23 @@ test('renders without crashing when the account is deleted before send', functio
test('lists the times in the recipient zone and clock and names the zone', function () {
$workspace = Workspace::factory()->create(['name' => 'Acme Co']);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => CarbonImmutable::parse('2026-10-05 05:30', 'UTC'),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
$owner = postAtRiskRecipient(['timezone' => 'Asia/Tokyo', 'time_format' => TimeFormat::TwelveHour]);
- (new PostAtRisk($workspace, [$postPlatform->id], 1, $owner))->assertSeeInHtml('1 post scheduled: 2:30 PM (Asia/Tokyo)');
+ (new PostAtRisk($workspace, [$post->id], 1, $owner))->assertSeeInHtml('1 post scheduled: 2:30 PM (Asia/Tokyo)');
});
test('a payload queued without a recipient renders for the workspace owner', function () {
$owner = postAtRiskRecipient(['timezone' => 'Asia/Tokyo', 'time_format' => TimeFormat::TwelveHour]);
$workspace = Workspace::factory()->create(['user_id' => $owner->id]);
$account = SocialAccount::factory()->threads()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
+ $post = Post::factory()->forAccount($account)->scheduled()->create([
'scheduled_at' => CarbonImmutable::parse('2037-01-05 05:30', 'UTC'),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
- $mailable = unserialize(serialize(new PostAtRisk($workspace, [$postPlatform->id], 1)));
+ $mailable = unserialize(serialize(new PostAtRisk($workspace, [$post->id], 1)));
$mailable->assertSeeInHtml('1 post scheduled: 2:30 PM (Asia/Tokyo)');
});
diff --git a/tests/Feature/Mail/PostPublicationPreviewTest.php b/tests/Feature/Mail/PostPublicationPreviewTest.php
index e6b447be9..16b26f422 100644
--- a/tests/Feature/Mail/PostPublicationPreviewTest.php
+++ b/tests/Feature/Mail/PostPublicationPreviewTest.php
@@ -2,13 +2,12 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status;
+use App\Enums\Post\PublishStatus as Status;
use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Mail\PostPublished;
use App\Mail\PostPublishFailed;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Support\Mail\PostPreview;
use Symfony\Component\DomCrawler\Crawler;
@@ -34,31 +33,23 @@ test('the email channel component resolves the platform name and its network log
test('publication emails show the channel and escaped post content separately', function (Status $status, Locale $locale) {
app()->setLocale($locale->value);
- $post = Post::factory()->create(['content' => '<p>Tom &amp; Jerry</p><p>New post</p>']);
$account = SocialAccount::factory()->instagram()->create([
- 'workspace_id' => $post->workspace_id,
'display_name' => 'Paulo Castellano',
'username' => 'paulocastellano',
]);
- PostPlatform::factory()->instagram()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'status' => $status,
+ $post = Post::factory()->forAccount($account)->create([
+ 'content' => '<p>Tom &amp; Jerry</p><p>New post</p>',
+ 'publish_status' => $status,
'platform_url' => 'https://www.instagram.com/p/published-post/',
'error_message' => 'Connection expired <script>alert(1)</script>',
]);
- PostPlatform::factory()->disabled()->create([
- 'post_id' => $post->id,
- 'status' => $status,
- 'error_message' => 'Disabled target error',
- ]);
$mail = $status === Status::Published ? new PostPublished($post) : new PostPublishFailed($post);
$html = $mail->render();
$document = new Crawler($html);
expect($html)->toContain("Tom &amp; Jerry\nNew post", 'Paulo Castellano', 'Instagram')
- ->not->toContain('Instagram (@paulocastellano)', 'Disabled target error')
+ ->not->toContain('Instagram (@paulocastellano)')
->and($document->filter('script')->count())->toBe(0)
->and($document->filter('img[src="'.asset('images/accounts/instagram.png').'"]')->count())->toBe(1);
@@ -85,9 +76,8 @@ test('publication emails show the channel and escaped post content separately',
})->with([Status::Published, Status::Failed])->with([Locale::English, Locale::PortugueseBrazil, Locale::Arabic]);
test('published email keeps the channel snapshot and falls back to the app when no public link exists', function () {
- $post = Post::factory()->published()->create(['content' => null]);
- PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
+ $post = Post::factory()->instagram()->published()->create([
+ 'content' => null,
'social_account_id' => null,
'platform_name' => 'Archived profile',
'platform_url' => null,
@@ -145,7 +135,7 @@ test('the email preview does not render a video as an image', function () {
});
test('the image preview renders without a caption and escapes its alternative text', function () {
- $post = Post::factory()->published()->create([
+ $post = Post::factory()->instagram()->published()->create([
'content' => null,
'media' => [[
'path' => 'photo.jpg',
@@ -154,7 +144,6 @@ test('the image preview renders without a caption and escapes its alternative te
'meta' => ['alt_text' => 'Studio " onclick="alert(1)'],
]],
]);
- PostPlatform::factory()->instagram()->published()->create(['post_id' => $post->id]);
$document = new Crawler((new PostPublished($post))->render());
$image = $document->filter('img[src="https://example.test/photo.jpg"]');
diff --git a/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php
index 340a0a7fc..63bfc24eb 100644
--- a/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php
+++ b/tests/Feature/Mcp/AttachMediaFromUrlToolTest.php
@@ -8,7 +8,6 @@ use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -123,10 +122,11 @@ test('attaches a pdf document from a url to a LinkedIn post', function () {
]);
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- PostPlatform::factory()->create([
- 'post_id' => $this->post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
+ $this->post->forceFill([
+ 'social_account_id' => $linkedin->id,
+ 'platform' => Platform::LinkedIn,
+ 'content_type' => ContentType::LinkedInPost,
+ ])->save();
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
@@ -151,10 +151,11 @@ test('rejects a pdf url for a post with no PDF-capable platform', function () {
]);
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
- PostPlatform::factory()->create([
- 'post_id' => $this->post->id, 'social_account_id' => $tiktok->id,
- 'platform' => Platform::TikTok, 'content_type' => ContentType::TikTokVideo, 'enabled' => true,
- ]);
+ $this->post->forceFill([
+ 'social_account_id' => $tiktok->id,
+ 'platform' => Platform::TikTok,
+ 'content_type' => ContentType::TikTokVideo,
+ ])->save();
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
@@ -257,10 +258,11 @@ test('attaches an image from url to a tiktok photo post', function () {
]);
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
- PostPlatform::factory()->create([
- 'post_id' => $this->post->id, 'social_account_id' => $tiktok->id,
- 'platform' => Platform::TikTok, 'content_type' => ContentType::TikTokPhoto, 'enabled' => true,
- ]);
+ $this->post->forceFill([
+ 'social_account_id' => $tiktok->id,
+ 'platform' => Platform::TikTok,
+ 'content_type' => ContentType::TikTokPhoto,
+ ])->save();
TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
diff --git a/tests/Feature/Mcp/MediaFlowTest.php b/tests/Feature/Mcp/MediaFlowTest.php
index eb0628f84..5abfb44ca 100644
--- a/tests/Feature/Mcp/MediaFlowTest.php
+++ b/tests/Feature/Mcp/MediaFlowTest.php
@@ -14,7 +14,6 @@ use App\Mcp\Tools\Post\RequestMediaUploadTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Services\Media\MediaOptimizer;
@@ -84,16 +83,7 @@ function mediaFlowScheduled(): string
function mediaFlowPost(object $test, SocialAccount $account, ContentType $contentType, PostStatus $status = PostStatus::Draft): Post
{
- $post = Post::factory()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id, 'status' => $status]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'enabled' => true,
- ]);
-
- return $post;
+ return Post::factory()->forAccount($account, $contentType)->create(['user_id' => $test->user->id, 'status' => $status]);
}
/**
@@ -119,7 +109,7 @@ test('an agent uploads a file through the signed url, schedules an x post with i
'media' => [['upload_token' => $token, 'alt' => 'A single pixel']],
'status' => 'scheduled',
'scheduled_at' => mediaFlowScheduled(),
- 'platforms' => [['social_account_id' => $this->x->id]],
+ 'social_account_id' => $this->x->id,
])->assertOk();
$post = Post::query()->sole();
@@ -148,7 +138,7 @@ test('an agent uploads a file through the signed url, schedules an x post with i
default => Http::response('', 404),
});
- (new XPublisher)->publish($post->postPlatforms()->sole());
+ (new XPublisher)->publish($post);
Http::assertSent(fn (Request $request): bool => $request->url() === data_get($item, 'url'));
Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/media/metadata')
@@ -169,7 +159,7 @@ test('a heic photo sent to the signed upload url reaches the post as a jpeg', fu
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'From the phone',
'media' => [['upload_token' => $token]],
- 'platforms' => [['social_account_id' => $this->instagram->id]],
+ 'social_account_id' => $this->instagram->id,
])->assertOk();
$item = data_get(Post::query()->sole()->media, '0');
@@ -189,7 +179,8 @@ test('carousel files keep the order the agent gives them', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Carousel',
'media' => array_map(fn (string $token): array => ['upload_token' => $token], $tokens),
- 'platforms' => [['social_account_id' => $this->instagram->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'social_account_id' => $this->instagram->id,
+ 'content_type' => ContentType::InstagramFeed->value,
])->assertOk();
expect(array_column(Post::query()->sole()->media, 'original_filename'))->toBe(['first.png', 'second.png', 'third.png']);
@@ -201,7 +192,8 @@ test('a reply file by upload token is checked against the network at save', func
'content' => 'Root',
'status' => 'scheduled',
'scheduled_at' => mediaFlowScheduled(),
- 'platforms' => [['social_account_id' => $this->x->id, 'meta' => ['thread_replies' => [['text' => 'Reply', 'media' => [['upload_token' => $token]]]]]]],
+ 'social_account_id' => $this->x->id,
+ 'meta' => ['thread_replies' => [['text' => 'Reply', 'media' => [['upload_token' => $token]]]]],
];
$message = __('posts.form.warnings.no_document_allowed');
@@ -239,11 +231,12 @@ test('a reply image by upload token is accepted, owned by the post and stored wh
'content' => 'Root',
'status' => 'scheduled',
'scheduled_at' => mediaFlowScheduled(),
- 'platforms' => [['social_account_id' => $this->x->id, 'meta' => ['thread_replies' => [['text' => 'Reply', 'media' => [['upload_token' => $token]]]]]]],
+ 'social_account_id' => $this->x->id,
+ 'meta' => ['thread_replies' => [['text' => 'Reply', 'media' => [['upload_token' => $token]]]]],
])->assertOk();
$post = Post::query()->sole();
- $reply = data_get($post->postPlatforms()->sole()->meta, 'thread_replies.0.media.0');
+ $reply = data_get($post->meta, 'thread_replies.0.media.0');
$row = Media::query()->sole();
expect(data_get($reply, 'type'))->toBe('image')
@@ -261,7 +254,7 @@ test('a member who needs approval schedules a post with an uploaded file and it
'media' => [['upload_token' => $token]],
'status' => 'scheduled',
'scheduled_at' => mediaFlowScheduled(),
- 'platforms' => [['social_account_id' => $this->linkedin->id]],
+ 'social_account_id' => $this->linkedin->id,
])->assertOk();
$post = Post::query()->sole();
@@ -308,7 +301,7 @@ test('media null is refused and an empty list removes every file', function (str
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Root',
'media' => [['upload_token' => $token]],
- 'platforms' => [['social_account_id' => $this->linkedin->id]],
+ 'social_account_id' => $this->linkedin->id,
])->assertOk();
$post = Post::query()->sole();
@@ -339,13 +332,13 @@ test('a url that cannot be hosted says why, on create and on attach', function (
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'x',
'media' => [['url' => 'https://example.com/huge.png']],
- 'platforms' => [['social_account_id' => $this->linkedin->id]],
+ 'social_account_id' => $this->linkedin->id,
])->assertHasErrors([__('posts.composer.media_sources.errors.too_large')]);
$this->postJson(route('api.posts.store'), [
'content' => 'x',
'media' => [['url' => 'https://example.com/page.html']],
- 'platforms' => [['social_account_id' => $this->linkedin->id]],
+ 'social_account_id' => $this->linkedin->id,
], $this->headers)->assertJsonValidationErrors(['media.0.url' => __('posts.composer.media_sources.errors.type_not_allowed')]);
$post = mediaFlowPost($this, $this->linkedin, ContentType::LinkedInPost);
diff --git a/tests/Feature/Mcp/PostPlatformMetaToolTest.php b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
index 3e477eb15..eb4ea2600 100644
--- a/tests/Feature/Mcp/PostPlatformMetaToolTest.php
+++ b/tests/Feature/Mcp/PostPlatformMetaToolTest.php
@@ -17,7 +17,6 @@ use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -30,32 +29,27 @@ test('youtube description persists reads retains and clears in MCP', function (s
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Short title',
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::YouTubeShort->value,
- 'meta' => ['description' => $description],
- ]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
])->assertOk();
- $platform = PostPlatform::where('social_account_id', $account->id)->sole();
- TryPostServer::actingAs($this->user)->tool(GetPostTool::class, ['post_id' => $platform->post_id])
- ->assertOk()->assertStructuredContent(function (AssertableJson $json) use ($platform, $description) {
- $json->etc();
- expect(collect($json->toArray()['platforms'])->firstWhere('id', $platform->id)['meta']['description'])->toBe($description);
- });
+ $post = Post::where('social_account_id', $account->id)->sole();
+ TryPostServer::actingAs($this->user)->tool(GetPostTool::class, ['post_id' => $post->id])
+ ->assertOk()->assertStructuredContent(fn (AssertableJson $json) => $json->where('meta.description', $description)->etc());
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
- 'post_id' => $platform->post_id,
+ 'post_id' => $post->id,
'meta' => ['description' => str_repeat('é', 2501)],
])->assertHasErrors([__('posts.form.youtube.description_max')]);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
- 'post_id' => $platform->post_id,
+ 'post_id' => $post->id,
'meta' => [],
])->assertOk();
- expect(data_get($platform->fresh()->meta, 'description'))->toBe($description);
+ expect(data_get($post->fresh()->meta, 'description'))->toBe($description);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
- 'post_id' => $platform->post_id,
+ 'post_id' => $post->id,
'meta' => ['description' => null],
])->assertOk();
- expect(data_get($platform->fresh()->meta, 'description'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'description'))->toBeNull();
})->with([
'multiline description' => ["Full text\nhttps://example.com"],
'programming text' => ["if (a < b && c > d) {}\n<p>Text about HTML</p>"],
@@ -65,11 +59,9 @@ test('youtube description rejects invalid MCP create input', function (string $d
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Short title',
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::YouTubeShort->value,
- 'meta' => ['description' => $description],
- ]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['description' => $description],
])->assertHasErrors();
})->with([
'multibyte overflow' => [str_repeat('é', 2501)],
@@ -79,8 +71,7 @@ test('youtube description rejects invalid MCP create input', function (string $d
test('youtube description checks effective MCP metadata on schedule and publish', function (string $patch, bool $allowed) {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'content' => 'Short title',
'status' => PostStatus::Draft,
@@ -92,11 +83,6 @@ test('youtube description checks effective MCP metadata on schedule and publish'
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
- ]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => ['description' => str_repeat('a', 5001)],
]);
Queue::fake();
@@ -144,19 +130,17 @@ test('create post persists Discord channel + embeds meta', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Hello Discord',
- 'platforms' => [[
- 'social_account_id' => $this->discordAccount->id,
- 'content_type' => ContentType::DiscordMessage->value,
- 'meta' => [
- 'channel_id' => '444555666',
- 'embeds' => [['title' => 'Release']],
- ],
- ]],
+ 'social_account_id' => $this->discordAccount->id,
+ 'content_type' => ContentType::DiscordMessage->value,
+ 'meta' => [
+ 'channel_id' => '444555666',
+ 'embeds' => [['title' => 'Release']],
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $this->discordAccount->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $this->discordAccount->id)->sole()->meta;
expect($meta['channel_id'])->toBe('444555666')
->and(data_get($meta, 'embeds.0.title'))->toBe('Release');
@@ -168,28 +152,20 @@ test('create post persists LinkedIn document_title meta', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Check our latest deck',
- 'platforms' => [[
- 'social_account_id' => $linkedin->id,
- 'content_type' => ContentType::LinkedInPost->value,
- 'meta' => ['document_title' => 'Q2 Report'],
- ]],
+ 'social_account_id' => $linkedin->id,
+ 'content_type' => ContentType::LinkedInPost->value,
+ 'meta' => ['document_title' => 'Q2 Report'],
]);
$response->assertOk();
- expect(PostPlatform::where('social_account_id', $linkedin->id)->sole()->meta['document_title'])->toBe('Q2 Report');
+ expect(Post::where('social_account_id', $linkedin->id)->sole()->meta['document_title'])->toBe('Q2 Report');
});
test('update post merges per-platform meta', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->discordAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- $platform = PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
'meta' => ['channel_name' => 'general'],
]);
@@ -201,52 +177,15 @@ test('update post merges per-platform meta', function () {
$response->assertOk();
- $meta = $platform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect($meta['channel_id'])->toBe('444555666')
->and($meta['channel_name'])->toBe('general'); // merged, not overwritten
});
-test('publish guard ignores disabled platforms missing meta', function () {
- Queue::fake();
-
- $linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- 'content' => 'Ready to publish',
- ]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedin->id,
- 'enabled' => true,
- ]);
- // Disabled Discord with no channel must not block the publish.
- PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => false,
- 'meta' => [],
- ]);
-
- $response = TryPostServer::actingAs($this->user)
- ->tool(PublishPostTool::class, ['post_id' => $post->id]);
-
- $response->assertOk();
- Queue::assertPushed(PublishPost::class);
-});
-
test('publish post rejects a Discord platform without a channel', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->discordAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
'meta' => [],
]);
@@ -262,15 +201,9 @@ test('publish guard enforces required meta for TikTok and Pinterest', function (
'platform' => $factoryState === 'tiktok' ? Platform::TikTok : Platform::Pinterest,
]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->{$factoryState}()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => [],
]);
@@ -289,11 +222,9 @@ test('create post rejects an unknown TikTok privacy level', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Unknown privacy',
- 'platforms' => [[
- 'social_account_id' => $tiktok->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => ['privacy_level' => 'EVERYONE'],
- ]],
+ 'social_account_id' => $tiktok->id,
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => 'EVERYONE'],
]);
$response->assertHasErrors();
@@ -302,15 +233,9 @@ test('create post rejects an unknown TikTok privacy level', function () {
test('publish post rejects stored TikTok self only branded content', function () {
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($tiktok)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $tiktok->id,
- 'enabled' => true,
'meta' => [
'privacy_level' => PrivacyLevel::SelfOnly->value,
'brand_content_toggle' => true,
@@ -326,15 +251,9 @@ test('publish post rejects stored TikTok self only branded content', function ()
test('publish post rejects a stored unknown TikTok privacy level', function () {
$tiktok = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::TikTok]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($tiktok)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $tiktok->id,
- 'enabled' => true,
'meta' => ['privacy_level' => 'EVERYONE'],
]);
@@ -347,15 +266,10 @@ test('publish post rejects a stored unknown TikTok privacy level', function () {
test('attach media from upload accepts a PDF for a LinkedIn post', function () {
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$uploadToken = (string) Str::uuid();
$this->workspace->media()->create([
@@ -390,8 +304,7 @@ test('publish post succeeds for a LinkedIn document that has a PDF', function ()
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'media' => [[
@@ -399,10 +312,6 @@ test('publish post succeeds for a LinkedIn document that has a PDF', function ()
'type' => 'document', 'mime_type' => 'application/pdf', 'original_filename' => 'deck.pdf',
]],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
@@ -414,8 +323,7 @@ test('publish post succeeds for a LinkedIn document that has a PDF', function ()
test('publish post rejects a LinkedIn post that mixes a PDF with an image', function () {
$linkedin = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'media' => [
@@ -423,10 +331,6 @@ test('publish post rejects a LinkedIn post that mixes a PDF with an image', func
['id' => 'img-1', 'path' => 'medias/slide.jpg', 'url' => 'https://example.com/slide.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg', 'original_filename' => 'slide.jpg'],
],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn, 'content_type' => ContentType::LinkedInPost, 'enabled' => true,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
@@ -439,18 +343,13 @@ test('publish post accepts a Bluesky post whose stored video is a MOV', function
$bluesky = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Bluesky]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($bluesky, ContentType::BlueskyPost)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'media' => [
['id' => 'vid-1', 'path' => 'medias/clip.mov', 'url' => 'https://example.com/clip.mov', 'type' => 'video', 'mime_type' => 'video/quicktime', 'original_filename' => 'clip.mov'],
],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $bluesky->id,
- 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost, 'enabled' => true,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, [
@@ -465,18 +364,13 @@ test('publish post accepts a Bluesky post whose stored video is a MOV', function
test('publish post rejects an Instagram Reel whose stored video exceeds 300 MB', function () {
$instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramReel)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'media' => [
['id' => 'vid-1', 'path' => 'medias/reel.mp4', 'url' => 'https://example.com/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'original_filename' => 'reel.mp4', 'size' => 900 * 1024 * 1024],
],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramReel, 'enabled' => true,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
@@ -488,16 +382,10 @@ test('publish post rejects an Instagram Reel whose stored video exceeds 300 MB',
test('publish post succeeds for a Discord platform with a channel', function () {
Queue::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->discordAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Ready for Discord',
- ]);
- PostPlatform::factory()->discord()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->discordAccount->id,
- 'enabled' => true,
'meta' => ['channel_id' => '444555666'],
]);
@@ -514,20 +402,18 @@ test('create post persists Pinterest title and link meta', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Shared caption',
- 'platforms' => [[
- 'social_account_id' => $pinterest->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'title' => 'Pin Title',
- 'link' => 'https://example.com/product',
- ],
- ]],
+ 'social_account_id' => $pinterest->id,
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'title' => 'Pin Title',
+ 'link' => 'https://example.com/product',
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $pinterest->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $pinterest->id)->sole()->meta;
expect(data_get($meta, 'title'))->toBe('Pin Title')
->and(data_get($meta, 'link'))->toBe('https://example.com/product')
@@ -536,16 +422,10 @@ test('create post persists Pinterest title and link meta', function () {
test('update post merges Pinterest title and link meta', function () {
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($pinterest)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Shared caption',
- ]);
- $platform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pinterest->id,
- 'enabled' => true,
'meta' => ['board_id' => 'board-1'],
]);
@@ -561,7 +441,7 @@ test('update post merges Pinterest title and link meta', function () {
$response->assertOk();
- $meta = $platform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'title'))->toBe('Updated Title')
->and(data_get($meta, 'link'))->toBe('https://example.com/updated')
@@ -574,14 +454,12 @@ test('create post rejects invalid Pinterest destination link', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Shared caption',
- 'platforms' => [[
- 'social_account_id' => $pinterest->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'link' => 'ftp://files.example.com/pin',
- ],
- ]],
+ 'social_account_id' => $pinterest->id,
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'link' => 'ftp://files.example.com/pin',
+ ],
]);
$response->assertHasErrors();
@@ -590,18 +468,11 @@ test('create post rejects invalid Pinterest destination link', function () {
test('updating an independent Pinterest draft cannot schedule without its stored board', function () {
$pinterest = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Pinterest]);
$image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($pinterest, ContentType::PinterestPin)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'A pin',
'media' => [MediaItem::fromMedia($image)->toArray()],
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pinterest->id,
- 'platform' => Platform::Pinterest,
- 'content_type' => ContentType::PinterestPin,
'meta' => [],
]);
@@ -622,19 +493,17 @@ test('create post persists Google Business topic_type and offer meta', function
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Big sale this week',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'offer' => ['coupon_code' => 'SAVE10'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'offer' => ['coupon_code' => 'SAVE10'],
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'topic_type'))->toBe('OFFER')
->and(data_get($meta, 'offer.coupon_code'))->toBe('SAVE10');
@@ -646,18 +515,16 @@ test('create post persists Google Business call_to_action meta', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Book a table tonight',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'call_to_action' => ['action_type' => 'BOOK', 'url' => 'https://example.com'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'call_to_action' => ['action_type' => 'BOOK', 'url' => 'https://example.com'],
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'call_to_action.action_type'))->toBe('BOOK')
->and(data_get($meta, 'call_to_action.url'))->toBe('https://example.com');
@@ -669,25 +536,23 @@ test('create post persists Google Business event time meta', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Grand opening',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => 'Grand Opening',
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- 'start_time' => '09:00',
- 'end_time' => '17:00',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => 'Grand Opening',
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
+ 'start_time' => '09:00',
+ 'end_time' => '17:00',
],
- ]],
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'event.title'))->toBe('Grand Opening')
->and(data_get($meta, 'event.start_date'))->toBe('2026-09-01')
@@ -702,22 +567,20 @@ test('create post persists Google Business offer redeem url and terms meta', fun
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Big sale this week',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'offer' => [
- 'coupon_code' => 'SAVE10',
- 'redeem_online_url' => 'https://example.com/redeem',
- 'terms_conditions' => 'Some terms',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'offer' => [
+ 'coupon_code' => 'SAVE10',
+ 'redeem_online_url' => 'https://example.com/redeem',
+ 'terms_conditions' => 'Some terms',
],
- ]],
+ ],
]);
$response->assertOk();
- $meta = PostPlatform::where('social_account_id', $googleBusiness->id)->sole()->meta;
+ $meta = Post::where('social_account_id', $googleBusiness->id)->sole()->meta;
expect(data_get($meta, 'offer.coupon_code'))->toBe('SAVE10')
->and(data_get($meta, 'offer.redeem_online_url'))->toBe('https://example.com/redeem')
@@ -730,18 +593,16 @@ test('create post rejects a Google Business event title over the api cap', funct
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Grand opening',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- ],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1),
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
],
- ]],
+ ],
]);
$response->assertHasErrors([__('posts.form.google_business.title_max')]);
@@ -750,15 +611,9 @@ test('create post rejects a Google Business event title over the api cap', funct
test('update post rejects a Google Business event title over the api cap', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [],
]);
@@ -781,15 +636,9 @@ test('update post rejects a Google Business event title over the api cap', funct
test('update post rejects a Google Business event whose end date is before the start', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- $platform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [],
]);
@@ -808,15 +657,9 @@ test('update post rejects a Google Business event whose end date is before the s
test('publish post rejects a Google Business event title over the api cap', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [
'topic_type' => 'EVENT',
'event' => [
@@ -836,15 +679,9 @@ test('publish post rejects a Google Business event title over the api cap', func
test('publish post rejects a Google Business offer post without a title', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [
'topic_type' => 'OFFER',
'event' => ['start_date' => '2026-09-01', 'end_date' => '2026-09-02'],
@@ -860,15 +697,9 @@ test('publish post rejects a Google Business offer post without a title', functi
test('publish post rejects a Google Business event post without event fields', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => ['topic_type' => 'EVENT'],
]);
@@ -881,15 +712,9 @@ test('publish post rejects a Google Business event post without event fields', f
test('publish post rejects a Google Business offer post without dates', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => 'Summer Sale'],
@@ -905,15 +730,9 @@ test('publish post rejects a Google Business offer post without dates', function
test('publish post rejects a Google Business event with a same-day end time before start', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [
'topic_type' => 'EVENT',
'event' => [
@@ -938,14 +757,12 @@ test('create post rejects a Google Business GET_OFFER call to action', function
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Sale',
- 'platforms' => [[
- 'social_account_id' => $googleBusiness->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'STANDARD',
- 'call_to_action' => ['action_type' => 'GET_OFFER'],
- ],
- ]],
+ 'social_account_id' => $googleBusiness->id,
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'STANDARD',
+ 'call_to_action' => ['action_type' => 'GET_OFFER'],
+ ],
]);
$response->assertHasErrors();
@@ -954,15 +771,9 @@ test('create post rejects a Google Business GET_OFFER call to action', function
test('publish post rejects a Google Business post with a url-needing cta and no url', function () {
$googleBusiness = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($googleBusiness)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $googleBusiness->id,
- 'enabled' => true,
'meta' => [
'topic_type' => 'STANDARD',
'call_to_action' => ['action_type' => 'BOOK'],
@@ -980,14 +791,12 @@ test('create post persists youtube metadata in MCP', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Short title',
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => ContentType::YouTubeShort->value,
- 'meta' => ['title' => 'Title', 'privacy_status' => 'unlisted', 'made_for_kids' => true, 'is_ai_generated' => true],
- ]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['title' => 'Title', 'privacy_status' => 'unlisted', 'made_for_kids' => true, 'is_ai_generated' => true],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $account->id)->sole()->meta)
+ expect(Post::where('social_account_id', $account->id)->sole()->meta)
->toEqual(['title' => 'Title', 'privacy_status' => 'unlisted', 'made_for_kids' => true, 'is_ai_generated' => true]);
});
@@ -996,7 +805,9 @@ test('create post rejects an unknown youtube privacy status in MCP', function ()
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Short title',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['privacy_status' => 'friends']]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['privacy_status' => 'friends'],
])->assertHasErrors();
});
@@ -1005,10 +816,12 @@ test('create post persists instagram options in MCP', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Reel',
- 'platforms' => [['social_account_id' => $instagram->id, 'content_type' => ContentType::InstagramReel->value, 'meta' => ['share_to_feed' => false]]],
+ 'social_account_id' => $instagram->id,
+ 'content_type' => ContentType::InstagramReel->value,
+ 'meta' => ['share_to_feed' => false],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $instagram->id)->sole()->meta)->toEqual(['share_to_feed' => false]);
+ expect(Post::where('social_account_id', $instagram->id)->sole()->meta)->toEqual(['share_to_feed' => false]);
});
test('create post rejects a youtube title with angle brackets on a draft in MCP', function () {
@@ -1016,10 +829,12 @@ test('create post rejects a youtube title with angle brackets on a draft in MCP'
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Short title',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['title' => '<b>']]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::YouTubeShort->value,
+ 'meta' => ['title' => '<b>'],
])->assertHasErrors();
- expect(PostPlatform::where('social_account_id', $account->id)->exists())->toBeFalse();
+ expect(Post::where('social_account_id', $account->id)->exists())->toBeFalse();
});
test('create post persists a dropped link preview', function () {
@@ -1028,15 +843,13 @@ test('create post persists a dropped link preview', function () {
TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Read https://example.com/article',
- 'platforms' => [[
- 'social_account_id' => $bluesky->id,
- 'content_type' => ContentType::BlueskyPost->value,
- 'meta' => ['link_preview' => false],
- ]],
+ 'social_account_id' => $bluesky->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => ['link_preview' => false],
])
->assertOk();
- expect(PostPlatform::where('social_account_id', $bluesky->id)->sole()->meta)->toEqual(['link_preview' => false]);
+ expect(Post::where('social_account_id', $bluesky->id)->sole()->meta)->toEqual(['link_preview' => false]);
});
test('create post persists a threads topic tag and rejects one with an ampersand in MCP', function () {
@@ -1044,32 +857,31 @@ test('create post persists a threads topic tag and rejects one with an ampersand
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => 'laravel']]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => 'laravel'],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => 'laravel']);
+ expect(Post::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => 'laravel']);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => 'rock&roll']]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => 'rock&roll'],
])->assertHasErrors();
- expect(PostPlatform::where('social_account_id', $threads->id)->count())->toBe(1);
+ expect(Post::where('social_account_id', $threads->id)->count())->toBe(1);
});
test('scheduling an instagram post with more than five hashtags is rejected in MCP', function () {
$instagram = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramFeed)->create([
'user_id' => $this->user->id,
'content' => 'Launch #a #b #c #d #e #f',
'status' => PostStatus::Draft,
'media' => [['id' => 'image-1', 'type' => 'image', 'path' => 'medias/image.jpg', 'url' => 'https://example.com/image.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'image.jpg']],
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $instagram->id,
- 'platform' => Platform::Instagram, 'content_type' => ContentType::InstagramFeed, 'enabled' => true,
- ]);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $post->id,
@@ -1086,17 +898,19 @@ test('a stored mastodon content warning counts toward the limit when scheduling
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => str_repeat('b', $limit - 9),
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['spoiler_text' => str_repeat('a', 10)]]],
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['spoiler_text' => str_repeat('a', 10)],
])->assertOk();
- $platform = PostPlatform::where('social_account_id', $mastodon->id)->sole();
+ $post = Post::where('social_account_id', $mastodon->id)->sole();
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
- 'post_id' => $platform->post_id,
+ 'post_id' => $post->id,
'status' => PostStatus::Scheduled->value,
'scheduled_at' => '2037-12-31T15:30:00Z',
])->assertHasErrors();
- expect($platform->post->fresh()->status)->toBe(PostStatus::Draft);
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
});
test('create post rejects a numeric link preview in MCP', function (mixed $value) {
@@ -1105,23 +919,22 @@ test('create post rejects a numeric link preview in MCP', function (mixed $value
TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'Read https://example.com/article',
- 'platforms' => [[
- 'social_account_id' => $bluesky->id,
- 'content_type' => ContentType::BlueskyPost->value,
- 'meta' => ['link_preview' => $value],
- ]],
+ 'social_account_id' => $bluesky->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => ['link_preview' => $value],
])
->assertHasErrors();
- expect(PostPlatform::where('social_account_id', $bluesky->id)->exists())->toBeFalse();
+ expect(Post::where('social_account_id', $bluesky->id)->exists())->toBeFalse();
})->with([0, '0']);
test('publish post accepts a stored threads ghost post whose text carries a link in MCP', function () {
$threads = SocialAccount::factory()->threads()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Read https://example.com/article', 'status' => PostStatus::Draft,
+ $post = Post::factory()->forAccount($threads, ContentType::ThreadsGhostPost)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Read https://example.com/article',
+ 'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->threads()->create(['post_id' => $post->id, 'social_account_id' => $threads->id, 'enabled' => true, 'content_type' => ContentType::ThreadsGhostPost]);
Queue::fake();
TryPostServer::actingAs($this->user)->tool(PublishPostTool::class, ['post_id' => $post->id])
@@ -1135,14 +948,18 @@ test('create post judges a threads topic tag without its leading hash in MCP', f
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => "#{$tag}"]]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => "#{$tag}"],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => $tag]);
+ expect(Post::where('social_account_id', $threads->id)->sole()->meta)->toEqual(['topic_tag' => $tag]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Hi',
- 'platforms' => [['social_account_id' => $threads->id, 'content_type' => ContentType::ThreadsPost->value, 'meta' => ['topic_tag' => "#{$tag}a"]]],
+ 'social_account_id' => $threads->id,
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => ['topic_tag' => "#{$tag}a"],
])->assertHasErrors([__('posts.form.threads.topic_invalid')]);
});
@@ -1151,10 +968,12 @@ test('create post persists thread replies in MCP', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['thread_replies' => ['Two']]]],
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['thread_replies' => ['Two']],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []]]]);
+ expect(Post::where('social_account_id', $mastodon->id)->sole()->meta)->toEqual(['thread_replies' => [['text' => 'Two', 'media' => []]]]);
});
test('create post stores thread reply media in MCP', function () {
@@ -1163,12 +982,14 @@ test('create post stores thread reply media in MCP', function () {
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['thread_replies' => [
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['thread_replies' => [
['text' => '', 'media' => [['upload_token' => $upload->upload_token]]],
- ]]]],
+ ]],
])->assertOk();
- expect(PostPlatform::where('social_account_id', $mastodon->id)->sole()->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id);
+ expect(Post::where('social_account_id', $mastodon->id)->sole()->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id);
});
test('a stored mastodon thread reply that does not fit blocks scheduling through MCP', function () {
@@ -1176,23 +997,24 @@ test('a stored mastodon thread reply that does not fit blocks scheduling through
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $mastodon->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['spoiler_text' => 'Ten chars!', 'thread_replies' => [str_repeat('a', 495)]]]],
+ 'social_account_id' => $mastodon->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['spoiler_text' => 'Ten chars!', 'thread_replies' => [str_repeat('a', 495)]],
])->assertOk();
- $platform = PostPlatform::where('social_account_id', $mastodon->id)->sole();
+ $post = Post::where('social_account_id', $mastodon->id)->sole();
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
- 'post_id' => $platform->post_id,
+ 'post_id' => $post->id,
'status' => PostStatus::Scheduled->value,
'scheduled_at' => '2037-12-31T15:30:00Z',
])->assertHasErrors();
- expect($platform->post->fresh()->status)->toBe(PostStatus::Draft);
+ expect($post->fresh()->status)->toBe(PostStatus::Draft);
});
test('publishing a youtube post with neither a title nor text is rejected in MCP', function () {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $this->user->id,
'content' => '',
'status' => PostStatus::Draft,
@@ -1204,11 +1026,6 @@ test('publishing a youtube post with neither a title nor text is rejected in MCP
'mime_type' => 'video/mp4',
'original_filename' => 'video.mp4',
]],
- ]);
- PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => [],
]);
Queue::fake();
diff --git a/tests/Feature/Mcp/PostPublishToolTest.php b/tests/Feature/Mcp/PostPublishToolTest.php
index a6bb6bef2..dff88420d 100644
--- a/tests/Feature/Mcp/PostPublishToolTest.php
+++ b/tests/Feature/Mcp/PostPublishToolTest.php
@@ -10,7 +10,6 @@ use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -54,29 +53,22 @@ test('update post can change content', function () {
expect($post->fresh()->content)->toBe('new content');
});
-test('update post cannot turn a targetless legacy draft into a channel post', function () {
+test('update post cannot turn a channel-less legacy draft into a channel post', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
- $platform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => false,
- ]);
-
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $post->id,
- 'platforms' => [
- ['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertHasErrors();
- expect($platform->fresh()->enabled)->toBeFalse();
+ expect($post->fresh()->social_account_id)->toBeNull()
+ ->and($post->fresh()->content_type)->toBeNull();
});
test('update post can attach labels', function () {
@@ -119,60 +111,46 @@ test('update post rejects posts in any terminal state', function (PostStatus $st
$response->assertHasErrors([__('posts.flash.cannot_edit_finalized')]);
})->with([
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
PostStatus::Publishing,
]);
-test('update post rejects a platforms[].id that belongs to another post', function () {
- $myPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+test('update post rejects the removed platforms input', function () {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
-
- $otherPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
- $foreignPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $otherPost->id,
- 'social_account_id' => $this->socialAccount->id,
+ 'content' => 'Kept',
]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
- 'post_id' => $myPost->id,
+ 'post_id' => $post->id,
+ 'content' => 'Changed',
'platforms' => [
- ['id' => $foreignPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
+ ['social_account_id' => $this->socialAccount->id, 'content_type' => ContentType::LinkedInPost->value],
],
]);
$response->assertHasErrors();
+
+ expect($post->fresh()->content)->toBe('Kept');
});
-test('update post rejects a content_type that does not match the post_platform', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+test('update post rejects a content_type that does not match the post channel', function () {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $post->id,
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => 'x_post'],
- ],
+ 'content_type' => 'x_post',
]);
$response->assertHasErrors();
+
+ expect($post->fresh()->content_type)->toBe(ContentType::LinkedInPost);
});
// PublishPostTool
@@ -181,20 +159,13 @@ test('publish post immediate dispatches PublishPost job', function () {
Queue::fake();
$this->freezeTime();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
'content' => 'Ready to publish',
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
@@ -204,28 +175,18 @@ test('publish post immediate dispatches PublishPost job', function () {
expect($post->fresh()->status)->toBe(PostStatus::Publishing)
->and($post->fresh()->scheduled_at->toDateTimeString())->toBe(now()->toDateTimeString());
- // Regression: previously UpdatePost::execute disabled every platform when
- // called without a `platforms` key, leaving the publish job with nothing
- // to publish. The Arr::has guard keeps the existing toggle state intact.
- expect(PostPlatform::where('post_id', $post->id)->where('enabled', true)->count())->toBe(1);
+ expect($post->fresh()->social_account_id)->toBe($this->socialAccount->id);
});
test('publish post scheduled does not dispatch immediately', function () {
Queue::fake();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Ready to schedule',
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
- ]);
-
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, [
'post_id' => $post->id,
@@ -238,19 +199,13 @@ test('publish post scheduled does not dispatch immediately', function () {
expect($post->fresh()->status)->toBe(PostStatus::Scheduled);
});
-test('publish post fails when no platforms enabled', function () {
+test('publish post fails for a post without a channel', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => false,
- ]);
-
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
@@ -268,24 +223,17 @@ test('publish post 404 from another workspace', function () {
});
test('publish post rejects posts already in a terminal state', function (PostStatus $status) {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => $status,
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
$response->assertHasErrors([__('posts.flash.cannot_edit_finalized')]);
})->with([
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
PostStatus::Publishing,
]);
diff --git a/tests/Feature/Mcp/PostQueueToolTest.php b/tests/Feature/Mcp/PostQueueToolTest.php
index f361d00e8..01c2346e4 100644
--- a/tests/Feature/Mcp/PostQueueToolTest.php
+++ b/tests/Feature/Mcp/PostQueueToolTest.php
@@ -12,7 +12,6 @@ use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Mcp\Tools\SocialAccount\ListSocialAccountsTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -41,20 +40,12 @@ beforeEach(function () {
function mcpQueueDraft(object $test): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $test->workspace->id,
+ return Post::factory()->forAccount($test->channel)->create([
'user_id' => $test->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
'content' => 'Draft',
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $test->channel->id,
- 'enabled' => true,
- ]);
-
- return $post;
}
test('create posts with queue next queues the post', function () {
@@ -163,7 +154,7 @@ test('update post with queue on a channel without posting times is rejected', fu
'platform' => Platform::LinkedIn,
]);
$post = mcpQueueDraft($this);
- $post->postPlatforms()->update(['social_account_id' => $bare->id]);
+ $post->forceFill(['social_account_id' => $bare->id])->save();
$mode = $post->fresh()->schedule_mode;
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
diff --git a/tests/Feature/Mcp/PostToolTest.php b/tests/Feature/Mcp/PostToolTest.php
index 409c41bf1..b5aaa12ad 100644
--- a/tests/Feature/Mcp/PostToolTest.php
+++ b/tests/Feature/Mcp/PostToolTest.php
@@ -13,7 +13,6 @@ use App\Mcp\Tools\Post\ListPostsTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -46,7 +45,8 @@ test('list posts returns wrapped posts array with PostResource shape', function
$response->assertOk()
->assertStructuredContent(function (AssertableJson $json) {
$json->has('posts', 3, function (AssertableJson $post) {
- $post->hasAll(['id', 'post_group_id', 'author', 'content', 'media', 'status', 'schedule_mode', 'scheduled_at', 'published_at', 'approval_requested_by', 'approval_requested_at', 'approved_by', 'approved_at', 'recurrence', 'origin', 'platforms', 'labels', 'created_at', 'updated_at'])
+ $post->hasAll(['id', 'post_group_id', 'author', 'content', 'media', 'status', 'schedule_mode', 'scheduled_at', 'published_at', 'approval_requested_by', 'approval_requested_at', 'approved_by', 'approved_at', 'recurrence', 'origin', 'publish_status', 'platform', 'content_type', 'meta', 'platform_url', 'error_message', 'display_name', 'display_username', 'display_avatar', 'social_account', 'labels', 'created_at', 'updated_at'])
+ ->missing('platforms')
->missing('user_id')
->missing('workspace_id');
})->where('total', 3)->where('current_page', 1)->where('last_page', 1)->has('per_page');
@@ -147,9 +147,8 @@ test('create post with content and date', function () {
->tool(CreatePostTool::class, [
'content' => 'My new post',
'scheduled_at' => '2037-12-31T15:30:00Z',
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
]);
$response->assertOk()
@@ -168,21 +167,18 @@ test('create post with content and date', function () {
test('create post creates unscheduled draft without a schedule', function (string $case) {
$payload = match ($case) {
'empty' => [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
],
'omitted' => [
'content' => 'Draft without schedule',
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
],
'null' => [
'content' => 'Draft without schedule',
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'scheduled_at' => null,
],
};
@@ -205,22 +201,20 @@ test('create post creates unscheduled draft without a schedule', function (strin
'explicit null schedule' => ['null'],
]);
-test('create post with platforms enables only those', function () {
+test('create post stores the chosen social account on the post', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'content' => 'with platforms',
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'content' => 'with an account',
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
]);
$response->assertOk();
- $post = Post::where('workspace_id', $this->workspace->id)->first();
- $enabled = $post->postPlatforms()->where('enabled', true)->get();
- expect($enabled)->toHaveCount(1);
- expect($enabled->first()->social_account_id)->toBe($this->socialAccount->id);
- expect($enabled->first()->content_type->value)->toBe('linkedin_post');
+ $post = Post::where('workspace_id', $this->workspace->id)->sole();
+ expect($post->social_account_id)->toBe($this->socialAccount->id)
+ ->and($post->platform)->toBe(Platform::LinkedIn)
+ ->and($post->content_type->value)->toBe('linkedin_post');
});
test('the single MCP create tool adopts a temporary upload submitted by id', function () {
@@ -228,9 +222,8 @@ test('the single MCP create tool adopts a temporary upload submitted by id', fun
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'media' => [['id' => $asset->id]],
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
])->assertOk();
$post = Post::query()->where('workspace_id', $this->workspace->id)->sole();
@@ -239,12 +232,14 @@ test('the single MCP create tool adopts a temporary upload submitted by id', fun
->and(data_get($post->media, '0.id'))->toBe($asset->id);
});
-test('the single MCP create tool rejects multiple accounts', function () {
+test('the single MCP create tool rejects the removed platforms input', function () {
$secondAccount = SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
['social_account_id' => $secondAccount->id, 'content_type' => 'linkedin_post'],
@@ -294,14 +289,9 @@ test('the MCP batch tool rejects a foreign account without creating a partial ba
});
test('the MCP edit tool rejects a replacement social account', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
]);
- $target = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
$otherAccount = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
@@ -309,7 +299,7 @@ test('the MCP edit tool rejects a replacement social account', function () {
'social_account_id' => $otherAccount->id,
])->assertHasErrors();
- expect($target->fresh()->social_account_id)->toBe($this->socialAccount->id);
+ expect($post->fresh()->social_account_id)->toBe($this->socialAccount->id);
});
test('create post rejects scheduled_at in the past', function () {
@@ -322,9 +312,8 @@ test('create post rejects scheduled_at in the past', function () {
test('create post rejects a content_type not in the enum', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'made_up_type'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'made_up_type',
]);
$response->assertHasErrors();
@@ -333,23 +322,17 @@ test('create post rejects a content_type not in the enum', function () {
test('create post rejects instagram_carousel — carousel is not a stored content_type', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'instagram_carousel'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'instagram_carousel',
]);
$response->assertHasErrors();
});
test('update post rejects instagram_carousel — carousel is not a stored content_type', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
@@ -364,9 +347,8 @@ test('create post rejects a content_type that does not match the social account
// x_post on a LinkedIn account — ContentTypeMatchesPlatform should reject.
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'x_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'x_post',
]);
$response->assertHasErrors();
@@ -378,9 +360,8 @@ test('create post rejects a label_id from another workspace', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'label_ids' => [$foreignLabel->id],
]);
@@ -393,9 +374,8 @@ test('create post rejects a deleted label', function () {
TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
'label_ids' => [$label->id],
])
->assertHasErrors();
@@ -443,52 +423,46 @@ test('delete post validates post_id required', function () {
test('create post persists platform meta (link_preview)', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => false]],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => false],
]);
$response->assertOk();
- $platform = Post::where('workspace_id', $this->workspace->id)->first()
- ->postPlatforms()->where('social_account_id', $this->socialAccount->id)->first();
- expect($platform->meta['link_preview'])->toBeFalse();
+ $post = Post::where('workspace_id', $this->workspace->id)->sole();
+ expect($post->social_account_id)->toBe($this->socialAccount->id)
+ ->and($post->meta['link_preview'])->toBeFalse();
});
test('create post no longer stores an aspect_ratio meta', function () {
TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['aspect_ratio' => '4:5']],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['aspect_ratio' => '4:5'],
])
->assertOk();
- $platform = Post::where('workspace_id', $this->workspace->id)->first()
- ->postPlatforms()->where('social_account_id', $this->socialAccount->id)->first();
- expect(data_get($platform->meta, 'aspect_ratio'))->toBeNull();
+ $post = Post::where('workspace_id', $this->workspace->id)->sole();
+ expect(data_get($post->meta, 'aspect_ratio'))->toBeNull();
});
test('create post rejects an invalid link_preview', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => 'nope']],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => 'nope'],
]);
$response->assertHasErrors();
});
test('update post rejects an invalid link_preview', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
@@ -502,12 +476,12 @@ test('update post rejects an invalid link_preview', function () {
test('create post returns the platform meta in the response (read-back)', function () {
TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
- 'platforms' => [
- ['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post', 'meta' => ['link_preview' => false]],
- ],
+ 'social_account_id' => $this->socialAccount->id,
+ 'content_type' => 'linkedin_post',
+ 'meta' => ['link_preview' => false],
])
->assertOk()
- ->assertStructuredContent(fn (AssertableJson $json) => $json->where('platforms.0.meta.link_preview', false)->etc());
+ ->assertStructuredContent(fn (AssertableJson $json) => $json->where('meta.link_preview', false)->etc());
});
test('update post rejects scheduled status without a future scheduled_at', function (?string $existingScheduledAt) {
@@ -540,8 +514,8 @@ test('update post rejects scheduled status without a future scheduled_at', funct
test('update post accepts scheduled status reusing an existing future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
+ 'content' => 'Ready to schedule',
'user_id' => $this->user->id,
'scheduled_at' => $scheduledAt,
]);
@@ -561,8 +535,8 @@ test('update post accepts scheduled status reusing an existing future scheduled_
test('update post schedules an unscheduled draft with an explicit future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
+ 'content' => 'Ready to schedule',
'user_id' => $this->user->id,
'scheduled_at' => null,
]);
@@ -606,14 +580,9 @@ test('update post keeps an unscheduled draft when saving as draft without schedu
});
test('update post accepts a valid platform meta and persists it', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
@@ -622,7 +591,7 @@ test('update post accepts a valid platform meta and persists it', function () {
])
->assertOk();
- expect($platform->fresh()->meta['link_preview'])->toBeFalse();
+ expect($post->fresh()->meta['link_preview'])->toBeFalse();
});
test('members who need approval can list and get posts via mcp', function () {
@@ -698,16 +667,11 @@ test('get post returns the network origin of an imported post', function () {
});
test('the MCP edit tool edits a draft whose kept time has passed', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'status' => 'draft',
'scheduled_at' => now()->subDay(),
]);
- PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $post->id,
@@ -718,21 +682,15 @@ test('the MCP edit tool edits a draft whose kept time has passed', function () {
});
test('a malformed account or destination id is a validation error, never a database error', function () {
- $post = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $post->postPlatforms()->create([
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => 'linkedin',
- 'content_type' => 'linkedin_post',
- 'enabled' => true,
- ]);
+ $post = Post::factory()->forAccount($this->socialAccount)->draft()->create(['user_id' => $this->user->id]);
TryPostServer::actingAs($this->user)
- ->tool(CreatePostTool::class, ['content' => 'Hello', 'platforms' => [['social_account_id' => 'not-a-uuid', 'content_type' => 'linkedin_post']]])
+ ->tool(CreatePostTool::class, ['content' => 'Hello', 'social_account_id' => 'not-a-uuid', 'content_type' => 'linkedin_post'])
->assertHasErrors(['must be a valid UUID'])
->assertDontSee('SQLSTATE');
TryPostServer::actingAs($this->user)
- ->tool(UpdatePostTool::class, ['post_id' => $post->id, 'platforms' => [['id' => 'not-a-uuid', 'content_type' => 'linkedin_post']]])
+ ->tool(UpdatePostTool::class, ['post_id' => $post->id, 'label_ids' => ['not-a-uuid']])
->assertHasErrors(['must be a valid UUID'])
->assertDontSee('SQLSTATE');
diff --git a/tests/Feature/Mcp/RepurposeToolTest.php b/tests/Feature/Mcp/RepurposeToolTest.php
index c6c29d009..87970b8e7 100644
--- a/tests/Feature/Mcp/RepurposeToolTest.php
+++ b/tests/Feature/Mcp/RepurposeToolTest.php
@@ -2,8 +2,8 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\Repurpose\ItemStatus;
use App\Enums\Repurpose\PauseReason;
use App\Enums\Repurpose\PublishMode;
@@ -25,7 +25,6 @@ use App\Mcp\Tools\Repurpose\ListRepurposesTool;
use App\Mcp\Tools\Repurpose\PauseRepurposeTool;
use App\Mcp\Tools\Repurpose\UpdateRepurposeTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -314,20 +313,15 @@ test('the items tool carries each replicated post status', function () {
$item = RepurposeItem::factory()->for($repurpose)->create();
- $post = Post::factory()->create([
+ $post = Post::factory()->tiktok()->published()->create([
'workspace_id' => $this->workspace->id,
'repurpose_item_id' => $item->id,
]);
- PostPlatform::factory()->for($post)->create([
- 'platform' => Platform::TikTok,
- 'enabled' => true,
- 'status' => PostPlatformStatus::Published,
- ]);
TryPostServer::actingAs($this->user)
->tool(ListRepurposeItemsTool::class, ['repurpose_id' => $repurpose->id])
->assertOk()
- ->assertSee(PostPlatformStatus::Published->value);
+ ->assertSee(PublishStatus::Published->value);
});
test('the update tool keeps a draft destination that is still missing its board', function () {
diff --git a/tests/Feature/Mcp/ToolDocumentationTest.php b/tests/Feature/Mcp/ToolDocumentationTest.php
index 5ecf60843..f94929e93 100644
--- a/tests/Feature/Mcp/ToolDocumentationTest.php
+++ b/tests/Feature/Mcp/ToolDocumentationTest.php
@@ -69,7 +69,7 @@ test('tools that schedule or publish list the required meta', function (string $
]);
test('tools that change a post list the statuses that block it', function (string $tool) {
- expect(mcpToolText($tool))->toContain('partially_published')->toContain('failed');
+ expect(mcpToolText($tool))->toContain('publishing, published or failed');
})->with([
'update-post' => [UpdatePostTool::class],
'delete-post' => [DeletePostTool::class],
diff --git a/tests/Feature/Media/OwnedMediaInvariantTest.php b/tests/Feature/Media/OwnedMediaInvariantTest.php
index 5986d4411..fee0dbccc 100644
--- a/tests/Feature/Media/OwnedMediaInvariantTest.php
+++ b/tests/Feature/Media/OwnedMediaInvariantTest.php
@@ -134,7 +134,8 @@ function ownedMediaInvariantWritePaths(): array
$test->withHeaders(ownedMediaInvariantHeaders($test))->postJson(route('api.posts.store'), [
'content' => 'Invariant',
'media' => [['upload_token' => ownedMediaInvariantToken($test->workspace)]],
- 'platforms' => [['social_account_id' => $test->channel->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'social_account_id' => $test->channel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertCreated();
return Post::query()->sole();
@@ -143,7 +144,8 @@ function ownedMediaInvariantWritePaths(): array
TryPostServer::actingAs($test->user)->tool(CreatePostTool::class, [
'content' => 'Invariant',
'media' => [['upload_token' => ownedMediaInvariantToken($test->workspace)]],
- 'platforms' => [['social_account_id' => $test->channel->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'social_account_id' => $test->channel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertOk();
return Post::query()->sole();
diff --git a/tests/Feature/Media/VideoCoverOffsetTest.php b/tests/Feature/Media/VideoCoverOffsetTest.php
index f4dced711..44b7f09bb 100644
--- a/tests/Feature/Media/VideoCoverOffsetTest.php
+++ b/tests/Feature/Media/VideoCoverOffsetTest.php
@@ -9,7 +9,6 @@ use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -26,19 +25,11 @@ beforeEach(function () {
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($account, ContentType::InstagramReel)->create([
'user_id' => $this->user->id,
'status' => Status::Draft,
'scheduled_at' => null,
]);
- PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => ContentType::InstagramReel,
- 'enabled' => true,
- ]);
$this->video = Media::factory()->video()->ownedByPost($this->post)->stored()->create(['meta' => ['duration' => 10]]);
$this->post->update(['media' => [videoCoverOffsetItem($this->video, [])]]);
});
@@ -126,7 +117,7 @@ test('the rest api rejects a negative or past-the-end cover offset', function (i
expect(data_get($this->post->fresh()->media, '0.meta.cover_offset_ms'))->toBeNull();
})->with([
'negative' => [-1, 'media.0.meta', '0 ms or more'],
- 'past the end of a 10 s video' => [99999999, 'destinations.0.media.0.meta', '10000 ms or less'],
+ 'past the end of a 10 s video' => [99999999, 'media.0.meta', '10000 ms or less'],
]);
test('mcp rejects a negative or past-the-end cover offset', function (int $offset, string $message) {
@@ -146,7 +137,7 @@ test('a forged duration cannot stretch the measured one', function () {
'status' => 'draft',
'content' => 'hi',
'media' => [[...videoCoverOffsetItem($this->video, ['cover_offset_ms' => 60000]), 'meta' => ['duration' => 999, 'cover_offset_ms' => 60000]]],
- ])->assertSessionHasErrors(['destinations.0.media.0.meta' => 'The video cover time must be 10000 ms or less.']);
+ ])->assertSessionHasErrors(['media.0.meta' => 'The video cover time must be 10000 ms or less.']);
expect(data_get($this->post->fresh()->media, '0.meta.cover_offset_ms'))->toBeNull();
});
diff --git a/tests/Feature/Middleware/SharedChannelsPropTest.php b/tests/Feature/Middleware/SharedChannelsPropTest.php
index 4ba876fa8..0aa87942b 100644
--- a/tests/Feature/Middleware/SharedChannelsPropTest.php
+++ b/tests/Feature/Middleware/SharedChannelsPropTest.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -23,14 +22,8 @@ test('channels are shared for the current workspace with their scheduled count',
$channel = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
SocialAccount::factory()->x()->create();
- $scheduled = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->create(['post_id' => $scheduled->id, 'social_account_id' => $channel->id]);
-
- $disabled = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->disabled()->create(['post_id' => $disabled->id, 'social_account_id' => $channel->id]);
-
- $draft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->create(['post_id' => $draft->id, 'social_account_id' => $channel->id]);
+ Post::factory()->forAccount($channel)->scheduled()->create();
+ Post::factory()->forAccount($channel)->draft()->create();
$this->actingAs($this->user)
->get(route('app.workspace.channels'))
@@ -48,8 +41,7 @@ test('posts from another workspace never count toward the scheduled total', func
$channel = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
$otherWorkspace = Workspace::factory()->create();
- $foreign = Post::factory()->scheduled()->create(['workspace_id' => $otherWorkspace->id]);
- PostPlatform::factory()->create(['post_id' => $foreign->id, 'social_account_id' => $channel->id]);
+ Post::factory()->forAccount($channel)->scheduled()->create(['workspace_id' => $otherWorkspace->id]);
$this->actingAs($this->user)
->get(route('app.workspace.channels'))
diff --git a/tests/Feature/Migrations/ClearGiphySourceMigrationTest.php b/tests/Feature/Migrations/ClearGiphySourceMigrationTest.php
deleted file mode 100644
index 118b69b3a..000000000
--- a/tests/Feature/Migrations/ClearGiphySourceMigrationTest.php
+++ /dev/null
@@ -1,72 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Models\Idea;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use Illuminate\Support\Facades\DB;
-
-beforeEach(function () {
- $this->migration = require database_path('migrations/2026_10_06_111329_clear_giphy_source_from_stored_media.php');
- $this->workspace = Workspace::factory()->create();
-});
-
-function giphyItem(string $id, ?string $source = 'giphy'): array
-{
- return ['id' => $id, 'path' => "medias/{$id}.gif", 'url' => "https://example.test/{$id}.gif", 'source' => $source, 'source_meta' => ['attribution' => 'GIPHY']];
-}
-
-test('giphy source becomes null in posts, ideas and thread reply media while everything else is untouched', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->workspace->user_id,
- 'media' => [giphyItem('a'), giphyItem('b', 'unsplash'), giphyItem('c', null)],
- ]);
- $untouched = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->workspace->user_id,
- 'media' => [giphyItem('d', 'canva')],
- ]);
- $idea = Idea::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->workspace->user_id,
- 'media' => [giphyItem('e')],
- ]);
- $target = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $this->workspace->id])->id,
- 'meta' => ['thread_replies' => [['text' => 'one', 'media' => [giphyItem('f'), giphyItem('g', 'ai')]], 'plain text']],
- ]);
-
- $this->migration->up();
-
- $media = collect($post->fresh()->media);
- expect($media->pluck('source')->all())->toBe([null, 'unsplash', null])
- ->and($media->first()['source_meta'])->toEqual(['attribution' => 'GIPHY'])
- ->and($untouched->fresh()->media[0]['source'])->toBe('canva')
- ->and($idea->fresh()->media[0]['source'])->toBeNull()
- ->and($idea->fresh()->media[0]['source_meta'])->toEqual(['attribution' => 'GIPHY']);
-
- $replies = $target->fresh()->meta['thread_replies'];
- expect($replies[0]['media'][0]['source'])->toBeNull()
- ->and($replies[0]['media'][1]['source'])->toBe('ai')
- ->and($replies[1])->toBe('plain text');
-});
-
-test('running it again changes nothing', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->workspace->user_id,
- 'media' => [giphyItem('a')],
- ]);
-
- $this->migration->up();
- $first = DB::table('posts')->where('id', $post->id)->value('media');
- $this->migration->up();
-
- expect(DB::table('posts')->where('id', $post->id)->value('media'))->toBe($first)
- ->and($post->fresh()->media[0]['source'])->toBeNull();
-});
diff --git a/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php b/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php
deleted file mode 100644
index c2afd2011..000000000
--- a/tests/Feature/Migrations/CollapseLinkedInContentTypesTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\PostPlatform\ContentType;
-use App\Models\PostPlatform;
-use Illuminate\Support\Facades\DB;
-
-/**
- * Load the data migration as an instance so its up() can run against rows that
- * still carry the retired per-format content types.
- */
-function collapseLinkedInContentTypesMigration(): object
-{
- return require database_path('migrations/2026_06_24_220651_collapse_linkedin_content_types.php');
-}
-
-test('the migration collapses retired linkedin profile content types onto linkedin_post', function () {
- $platform = PostPlatform::factory()->create(['content_type' => ContentType::LinkedInPost]);
-
- foreach (['linkedin_carousel', 'linkedin_document'] as $legacy) {
- DB::table('post_platforms')->where('id', $platform->id)->update(['content_type' => $legacy]);
-
- collapseLinkedInContentTypesMigration()->up();
-
- expect(DB::table('post_platforms')->where('id', $platform->id)->value('content_type'))
- ->toBe('linkedin_post');
- }
-});
-
-test('the migration collapses retired linkedin page content types onto linkedin_page_post', function () {
- $platform = PostPlatform::factory()->create(['content_type' => ContentType::LinkedInPagePost]);
-
- foreach (['linkedin_page_carousel', 'linkedin_page_document'] as $legacy) {
- DB::table('post_platforms')->where('id', $platform->id)->update(['content_type' => $legacy]);
-
- collapseLinkedInContentTypesMigration()->up();
-
- expect(DB::table('post_platforms')->where('id', $platform->id)->value('content_type'))
- ->toBe('linkedin_page_post');
- }
-});
-
-test('the migration leaves other platforms content types untouched', function () {
- $xPost = PostPlatform::factory()->create(['content_type' => ContentType::XPost]);
-
- collapseLinkedInContentTypesMigration()->up();
-
- expect(DB::table('post_platforms')->where('id', $xPost->id)->value('content_type'))
- ->toBe(ContentType::XPost->value);
-});
diff --git a/tests/Feature/Migrations/MergePostPlatformsIntoPostsMigrationTest.php b/tests/Feature/Migrations/MergePostPlatformsIntoPostsMigrationTest.php
new file mode 100644
index 000000000..7a880f9bc
--- /dev/null
+++ b/tests/Feature/Migrations/MergePostPlatformsIntoPostsMigrationTest.php
@@ -0,0 +1,387 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\PublishStatus;
+use App\Enums\Post\Status as PostStatus;
+use App\Models\AnalyticsPublication;
+use App\Models\Media;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\Webhook;
+use App\Models\Workspace;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+
+beforeEach(function () {
+ $this->prepare = require database_path('migrations/2026_10_08_222940_prepare_post_platforms_for_merge_into_posts.php');
+ $this->backfill = require database_path('migrations/2026_10_08_222943_backfill_posts_from_post_platforms.php');
+ $this->drop = require database_path('migrations/2026_10_08_222944_drop_post_platforms_table.php');
+
+ if (! Schema::hasTable('post_platforms')) {
+ Schema::create('post_platforms', function (Blueprint $table): void {
+ $table->uuid('id')->primary();
+ $table->uuid('post_id');
+ $table->uuid('social_account_id')->nullable();
+ $table->string('platform');
+ $table->string('platform_name')->nullable();
+ $table->string('platform_username')->nullable();
+ $table->string('platform_avatar')->nullable();
+ $table->string('content_type');
+ $table->string('status')->default('pending');
+ $table->string('platform_post_id')->nullable();
+ $table->boolean('enabled')->default(false);
+ $table->text('platform_url')->nullable();
+ $table->text('error_message')->nullable();
+ $table->json('error_context')->nullable();
+ $table->timestamp('connection_warning_sent_at')->nullable();
+ $table->timestamp('published_at')->nullable();
+ $table->timestamp('submitted_at')->nullable();
+ $table->timestamp('last_reconciled_at')->nullable();
+ $table->json('meta')->nullable();
+ $table->json('thread_reply_ids')->nullable();
+ $table->boolean('scheduled_before_media_checks')->default(false);
+ $table->timestamp('retry_at')->nullable();
+ $table->timestamps();
+ });
+ }
+
+ if (! Schema::hasColumn('analytics_publications', 'post_platform_id')) {
+ Schema::table('analytics_publications', function (Blueprint $table): void {
+ $table->uuid('post_platform_id')->nullable()->unique();
+ $table->foreign('post_platform_id')->references('id')->on('post_platforms')->nullOnDelete();
+ });
+ }
+
+ if (! DB::getPdo()->inTransaction()) {
+ DB::getPdo()->beginTransaction();
+ }
+
+ $this->target = function (Post $post, array $attributes = []): string {
+ $id = (string) Str::uuid7();
+
+ DB::table('post_platforms')->insert([
+ 'id' => $id,
+ 'post_id' => $post->id,
+ 'platform' => 'linkedin',
+ 'content_type' => 'linkedin_post',
+ 'status' => 'pending',
+ 'enabled' => true,
+ 'meta' => json_encode([]),
+ 'created_at' => now(),
+ 'updated_at' => now(),
+ ...$attributes,
+ ]);
+
+ return $id;
+ };
+});
+
+afterEach(function () {
+ if (Schema::hasColumn('analytics_publications', 'post_platform_id')) {
+ Schema::table('analytics_publications', function (Blueprint $table): void {
+ $table->dropForeign(['post_platform_id']);
+ $table->dropUnique(['post_platform_id']);
+ $table->dropColumn('post_platform_id');
+ });
+ }
+
+ Schema::dropIfExists('post_platforms');
+});
+
+test('prepare drops disabled destinations that never published', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Failed]);
+ $kept = ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'failed']);
+ ($this->target)($post, ['social_account_id' => $account->id, 'enabled' => false, 'status' => 'rejected', 'platform_post_id' => 'remote']);
+
+ $this->prepare->up();
+
+ expect(DB::table('post_platforms')->where('post_id', $post->id)->pluck('id')->all())->toBe([$kept]);
+});
+
+test('prepare turns non-draft posts left without a destination into drafts and keeps channel-less drafts', function () {
+ $workspace = Workspace::factory()->create();
+ $scheduled = Post::factory()->create([
+ 'workspace_id' => $workspace->id,
+ 'status' => PostStatus::Scheduled,
+ 'schedule_mode' => 'custom',
+ 'scheduled_at' => now()->addDay(),
+ 'recurrence_interval' => 1,
+ 'recurrence_frequency' => 'day',
+ ]);
+ ($this->target)($scheduled, ['enabled' => false]);
+ $failed = Post::factory()->create(['workspace_id' => $workspace->id, 'status' => PostStatus::Failed, 'published_at' => now()]);
+ $draft = Post::factory()->create(['workspace_id' => $workspace->id, 'status' => PostStatus::Draft, 'content' => 'Keep me']);
+
+ $this->prepare->up();
+
+ expect($scheduled->fresh())
+ ->status->toBe(PostStatus::Draft)
+ ->schedule_mode->toBeNull()
+ ->recurrence_interval->toBeNull()
+ ->and($failed->fresh())
+ ->status->toBe(PostStatus::Draft)
+ ->published_at->toBeNull()
+ ->and($draft->fresh())
+ ->status->toBe(PostStatus::Draft)
+ ->content->toBe('Keep me');
+});
+
+test('prepare settles a partially published post from its only destination', function () {
+ $account = SocialAccount::factory()->create();
+ $publishedAt = now()->subHour()->startOfSecond();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ DB::table('posts')->where('id', $post->id)->update(['status' => 'partially_published', 'published_at' => now()]);
+ ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'published', 'published_at' => $publishedAt]);
+ $failed = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ DB::table('posts')->where('id', $failed->id)->update(['status' => 'partially_published', 'published_at' => now()]);
+ ($this->target)($failed, ['social_account_id' => $account->id, 'status' => 'failed']);
+
+ $this->prepare->up();
+
+ expect(DB::table('posts')->where('id', $post->id)->value('status'))->toBe('published')
+ ->and(Post::query()->find($post->id)->published_at->toIso8601String())->toBe($publishedAt->toIso8601String())
+ ->and(DB::table('posts')->where('id', $failed->id)->value('status'))->toBe('failed')
+ ->and(DB::table('posts')->where('id', $failed->id)->value('published_at'))->toBeNull();
+});
+
+test('prepare refuses posts that still have several destinations', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Scheduled]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+
+ $this->prepare->up();
+})->throws(RuntimeException::class, '1 posts with more than one destination');
+
+test('prepare refuses a destination whose account belongs to another workspace', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['status' => PostStatus::Draft]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+
+ $this->prepare->up();
+})->throws(RuntimeException::class, 'account belongs to another workspace');
+
+test('prepare refuses a disabled destination that published', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published]);
+ ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'published']);
+ ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'published', 'enabled' => false]);
+
+ $this->prepare->up();
+})->throws(RuntimeException::class, 'disabled destinations that published');
+
+test('backfill copies every destination onto its post without touching updated_at', function () {
+ $account = SocialAccount::factory()->create();
+ $updatedAt = now()->subDays(3)->startOfSecond();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Publishing]);
+ DB::table('posts')->where('id', $post->id)->update(['updated_at' => $updatedAt]);
+ $targetUpdatedAt = now()->subHour()->startOfSecond();
+ $retryAt = now()->addHour()->startOfSecond();
+ ($this->target)($post, [
+ 'social_account_id' => $account->id,
+ 'platform_name' => 'Acme',
+ 'platform_username' => 'acme',
+ 'platform_avatar' => 'avatars/acme.png',
+ 'content_type' => 'linkedin_post',
+ 'status' => 'retrying',
+ 'platform_post_id' => 'urn:li:share:1',
+ 'platform_url' => 'https://example.com/post',
+ 'error_message' => 'Rate limited',
+ 'error_context' => json_encode(['category' => 'rate_limit', 'thread_progress' => [['id' => '1', 'hash' => 'a']]]),
+ 'meta' => json_encode(['document_title' => 'Deck', 'link_preview' => false]),
+ 'thread_reply_ids' => json_encode(['2', '3']),
+ 'retry_at' => $retryAt,
+ 'scheduled_before_media_checks' => true,
+ 'updated_at' => $targetUpdatedAt,
+ ]);
+
+ $this->backfill->up();
+
+ $fresh = Post::query()->find($post->id);
+
+ expect($fresh)
+ ->social_account_id->toBe($account->id)
+ ->publish_status->toBe(PublishStatus::Retrying)
+ ->platform_name->toBe('Acme')
+ ->platform_username->toBe('acme')
+ ->platform_avatar->toBe('avatars/acme.png')
+ ->platform_post_id->toBe('urn:li:share:1')
+ ->platform_url->toBe('https://example.com/post')
+ ->error_message->toBe('Rate limited')
+ ->thread_reply_ids->toBe(['2', '3'])
+ ->scheduled_before_media_checks->toBeTrue()
+ ->and($fresh->meta)->toEqual(['document_title' => 'Deck', 'link_preview' => false])
+ ->and($fresh->error_context)->toEqual(['category' => 'rate_limit', 'thread_progress' => [['id' => '1', 'hash' => 'a']]])
+ ->and($fresh->retry_at->toIso8601String())->toBe($retryAt->toIso8601String())
+ ->and($fresh->publication_updated_at->toIso8601String())->toBe($targetUpdatedAt->toIso8601String())
+ ->and($fresh->updated_at->toIso8601String())->toBe($updatedAt->toIso8601String());
+});
+
+test('backfill keeps the publish time the post already shows, only for a published destination', function () {
+ $account = SocialAccount::factory()->create();
+ $postTime = now()->subDay()->startOfSecond();
+ $published = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published, 'published_at' => $postTime]);
+ ($this->target)($published, ['social_account_id' => $account->id, 'status' => 'published', 'published_at' => $postTime->subSecond()]);
+ $imported = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published, 'published_at' => null]);
+ ($this->target)($imported, ['social_account_id' => $account->id, 'status' => 'published', 'published_at' => $postTime]);
+ $failed = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Failed, 'published_at' => $postTime]);
+ ($this->target)($failed, ['social_account_id' => $account->id, 'status' => 'failed']);
+
+ $this->backfill->up();
+
+ expect(Post::query()->find($published->id)->published_at->toIso8601String())->toBe($postTime->toIso8601String())
+ ->and(Post::query()->find($imported->id)->published_at->toIso8601String())->toBe($postTime->toIso8601String())
+ ->and(Post::query()->find($failed->id)->published_at)->toBeNull();
+});
+
+test('backfill links analytics publications by post and replaces the partially published webhook event', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published]);
+ $target = ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'published', 'platform_post_id' => 'remote-1']);
+ $publication = AnalyticsPublication::factory()->create(['workspace_id' => $account->workspace_id, 'social_account_id' => $account->id]);
+ DB::table('analytics_publications')->where('id', $publication->id)->update(['post_platform_id' => $target]);
+ $only = Webhook::factory()->create(['workspace_id' => $account->workspace_id, 'events' => ['post.partially_published']]);
+ $mixed = Webhook::factory()->create(['workspace_id' => $account->workspace_id, 'events' => ['post.published', 'post.partially_published']]);
+
+ $this->backfill->up();
+ $this->backfill->up();
+
+ expect($publication->fresh()->post_id)->toBe($post->id)
+ ->and($only->fresh()->events)->toEqualCanonicalizing(['post.published', 'post.failed'])
+ ->and($mixed->fresh()->events)->toEqualCanonicalizing(['post.published', 'post.failed']);
+});
+
+test('backfill clears the copy of a destination that vanished before it runs again', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Draft]);
+ $target = ($this->target)($post, ['social_account_id' => $account->id]);
+
+ $this->backfill->up();
+ DB::table('post_platforms')->where('id', $target)->delete();
+ $this->backfill->up();
+
+ expect(Post::query()->find($post->id))
+ ->social_account_id->toBeNull()
+ ->platform->toBeNull();
+});
+
+test('backfill parity fails when a copied column differs', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ ($this->target)($post, ['social_account_id' => $account->id, 'meta' => json_encode(['title' => 'A'])]);
+
+ $this->backfill->up();
+ DB::table('posts')->where('id', $post->id)->update(['meta' => json_encode(['title' => 'B'])]);
+
+ (fn () => $this->assertParity())->call($this->backfill);
+})->throws(RuntimeException::class, 'Backfill parity failed');
+
+test('drop refuses destinations that were not copied, then drops the table', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+
+ expect(fn () => $this->drop->up())->toThrow(RuntimeException::class, 'were not copied');
+
+ $this->backfill->up();
+ $this->drop->up();
+
+ expect(Schema::hasTable('post_platforms'))->toBeFalse()
+ ->and(Schema::hasColumn('analytics_publications', 'post_platform_id'))->toBeFalse();
+});
+
+test('prepare changes nothing when its guard stops', function () {
+ $account = SocialAccount::factory()->create();
+ $blocked = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Scheduled]);
+ ($this->target)($blocked, ['social_account_id' => $account->id]);
+ ($this->target)($blocked, ['social_account_id' => $account->id]);
+ $orphan = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Failed]);
+ $disabled = ($this->target)($blocked, ['social_account_id' => $account->id, 'enabled' => false]);
+
+ expect(fn () => $this->prepare->up())->toThrow(RuntimeException::class);
+
+ expect($orphan->fresh()->status)->toBe(PostStatus::Failed)
+ ->and(DB::table('post_platforms')->where('id', $disabled)->exists())->toBeTrue();
+});
+
+test('prepare deletes published posts left without a destination, with their media files after commit', function () {
+ Storage::fake();
+ $account = SocialAccount::factory()->create();
+ $orphan = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published, 'published_at' => now()]);
+ $media = Media::factory()->create(['workspace_id' => $account->workspace_id, 'post_id' => $orphan->id, 'mediable_type' => null, 'mediable_id' => null, 'collection' => Media::COLLECTION_MEDIA]);
+ Storage::put($media->path, 'image');
+ $kept = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published, 'published_at' => now()]);
+ ($this->target)($kept, ['social_account_id' => $account->id, 'status' => 'published']);
+ $shared = Media::factory()->create(['workspace_id' => $account->workspace_id, 'post_id' => $orphan->id, 'mediable_type' => null, 'mediable_id' => null, 'collection' => Media::COLLECTION_MEDIA]);
+ Media::factory()->create(['workspace_id' => $account->workspace_id, 'post_id' => $kept->id, 'path' => $shared->path, 'mediable_type' => null, 'mediable_id' => null, 'collection' => Media::COLLECTION_MEDIA]);
+ Storage::put($shared->path, 'image');
+ $disabledOnly = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published, 'published_at' => now()]);
+ ($this->target)($disabledOnly, ['social_account_id' => $account->id, 'enabled' => false]);
+
+ $this->prepare->up();
+
+ expect(Post::query()->whereKey([$orphan->id, $disabledOnly->id])->exists())->toBeFalse()
+ ->and(Media::query()->whereKey([$media->id, $shared->id])->exists())->toBeFalse()
+ ->and($kept->fresh())->not->toBeNull();
+ Storage::assertMissing($media->path);
+ Storage::assertExists($shared->path);
+});
+
+test('prepare drops destinations whose account is gone, as disconnecting a channel does', function () {
+ $workspace = Workspace::factory()->create();
+ $published = Post::factory()->create(['workspace_id' => $workspace->id, 'status' => PostStatus::Published, 'published_at' => now()]);
+ ($this->target)($published, ['social_account_id' => null, 'status' => 'published']);
+ $scheduled = Post::factory()->create(['workspace_id' => $workspace->id, 'status' => PostStatus::Scheduled, 'scheduled_at' => now()->addDay()]);
+ ($this->target)($scheduled, ['social_account_id' => null]);
+
+ $this->prepare->up();
+
+ expect(Post::query()->whereKey($published->id)->exists())->toBeFalse()
+ ->and($scheduled->fresh()->status)->toBe(PostStatus::Draft)
+ ->and(DB::table('post_platforms')->where('post_id', $scheduled->id)->exists())->toBeFalse();
+});
+
+test('backfill refuses a destination that is switched off', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ ($this->target)($post, ['social_account_id' => $account->id, 'enabled' => false]);
+
+ $this->backfill->up();
+})->throws(RuntimeException::class, 'switched off or lost their channel');
+
+test('drop refuses analytics publications that were not linked to their post', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Published]);
+ $target = ($this->target)($post, ['social_account_id' => $account->id, 'status' => 'published']);
+ $this->backfill->up();
+ $publication = AnalyticsPublication::factory()->create(['workspace_id' => $account->workspace_id, 'social_account_id' => $account->id]);
+ DB::table('analytics_publications')->where('id', $publication->id)->update(['post_platform_id' => $target, 'post_id' => null]);
+
+ expect(fn () => $this->drop->up())->toThrow(RuntimeException::class, 'were not linked to their posts')
+ ->and(Schema::hasTable('post_platforms'))->toBeTrue();
+});
+
+test('backfill parity refuses a post that still has two destinations', function () {
+ $account = SocialAccount::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+ ($this->target)($post, ['social_account_id' => $account->id]);
+
+ $this->backfill->up();
+})->throws(RuntimeException::class, 'Backfill parity failed');
+
+test('prepare deletes a partially published post whose only destination lost its account', function () {
+ $workspace = Workspace::factory()->create();
+ $post = Post::factory()->create(['workspace_id' => $workspace->id]);
+ DB::table('posts')->where('id', $post->id)->update(['status' => 'partially_published', 'published_at' => now()]);
+ ($this->target)($post, ['social_account_id' => null, 'status' => 'published']);
+
+ $this->prepare->up();
+
+ expect(DB::table('posts')->where('id', $post->id)->exists())->toBeFalse();
+});
diff --git a/tests/Feature/Migrations/RemoveAspectRatioMetaMigrationTest.php b/tests/Feature/Migrations/RemoveAspectRatioMetaMigrationTest.php
deleted file mode 100644
index ae9eaa319..000000000
--- a/tests/Feature/Migrations/RemoveAspectRatioMetaMigrationTest.php
+++ /dev/null
@@ -1,55 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Enums\SocialAccount\Platform;
-use App\Models\Post;
-use App\Models\PostPlatform;
-
-beforeEach(function () {
- $this->migration = require database_path('migrations/2026_10_04_202400_remove_aspect_ratio_from_post_platforms_meta.php');
-});
-
-test('the aspect ratio is dropped from every target and the rest of its meta is kept', function () {
- $cropped = PostPlatform::factory()->create(['meta' => ['aspect_ratio' => '4:5', 'is_ai_generated' => true]]);
- $onlyRatio = PostPlatform::factory()->create(['meta' => ['aspect_ratio' => 'original']]);
- $untouched = PostPlatform::factory()->create(['meta' => ['link_preview' => false]]);
- $empty = PostPlatform::factory()->create(['meta' => null]);
-
- $this->migration->up();
- $this->migration->up();
-
- expect($cropped->fresh()->meta)->toEqual(['is_ai_generated' => true])
- ->and($onlyRatio->fresh()->meta)->toEqual([])
- ->and($untouched->fresh()->meta)->toEqual(['link_preview' => false])
- ->and($empty->fresh()->meta)->toBeNull();
-});
-
-test('an instagram feed or facebook post target that publishes without user action keeps its crop for the release bake', function () {
- $scheduled = Post::factory()->scheduled()->create();
- $feed = PostPlatform::factory()->instagram()->create(['post_id' => $scheduled->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $facebook = PostPlatform::factory()->create(['post_id' => $scheduled->id, 'platform' => Platform::Facebook, 'content_type' => ContentType::FacebookPost, 'meta' => ['aspect_ratio' => '1:1']]);
- $inFlight = PostPlatform::factory()->instagram()->create(['post_id' => Post::factory()->create(['status' => PostStatus::Publishing])->id, 'status' => PlatformStatus::Retrying, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $pendingApproval = PostPlatform::factory()->instagram()->create(['post_id' => Post::factory()->create(['status' => PostStatus::PendingApproval])->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $published = PostPlatform::factory()->instagram()->published()->create(['post_id' => $scheduled->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $disabled = PostPlatform::factory()->instagram()->disabled()->create(['post_id' => $scheduled->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $story = PostPlatform::factory()->instagram()->create(['post_id' => $scheduled->id, 'content_type' => ContentType::InstagramStory, 'meta' => ['aspect_ratio' => '4:5']]);
- $original = PostPlatform::factory()->instagram()->create(['post_id' => $scheduled->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => 'original']]);
- $draft = PostPlatform::factory()->instagram()->create(['post_id' => Post::factory()->create(['status' => PostStatus::Draft])->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $failed = PostPlatform::factory()->instagram()->failed()->create(['post_id' => Post::factory()->create(['status' => PostStatus::Failed])->id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
- $failedInFlight = PostPlatform::factory()->instagram()->failed()->create(['post_id' => $inFlight->post_id, 'content_type' => ContentType::InstagramFeed, 'meta' => ['aspect_ratio' => '4:5']]);
-
- $this->migration->up();
-
- expect($feed->fresh()->meta)->toEqual(['aspect_ratio' => '4:5'])
- ->and($facebook->fresh()->meta)->toEqual(['aspect_ratio' => '1:1'])
- ->and($inFlight->fresh()->meta)->toEqual(['aspect_ratio' => '4:5'])
- ->and($pendingApproval->fresh()->meta)->toEqual(['aspect_ratio' => '4:5']);
-
- foreach ([$published, $disabled, $story, $original, $draft, $failed, $failedInFlight] as $target) {
- expect($target->fresh()->meta)->toEqual([]);
- }
-});
diff --git a/tests/Feature/Migrations/RemoveChannelPauseMigrationTest.php b/tests/Feature/Migrations/RemoveChannelPauseMigrationTest.php
deleted file mode 100644
index f70057f06..000000000
--- a/tests/Feature/Migrations/RemoveChannelPauseMigrationTest.php
+++ /dev/null
@@ -1,177 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\Post\Status as PostStatus;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use Illuminate\Database\Schema\Blueprint;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\Schema;
-
-beforeEach(function () {
- $this->migration = require database_path('migrations/2026_09_29_133421_add_posting_schedule_and_remove_is_active_on_social_accounts.php');
- $this->seeded = ['post_platforms' => [], 'posts' => [], 'social_accounts' => [], 'workspaces' => []];
-
- if (! Schema::hasColumn('social_accounts', 'is_active')) {
- Schema::table('social_accounts', function (Blueprint $table): void {
- $table->boolean('is_active')->default(true);
- });
- }
-
- $this->dropPostingSchedule = fn () => Schema::dropColumns('social_accounts', ['timezone', 'posting_goal', 'posting_schedule']);
-});
-
-afterEach(function () {
- if (Schema::hasColumn('social_accounts', 'is_active')) {
- Schema::hasColumn('social_accounts', 'timezone')
- ? Schema::dropColumns('social_accounts', ['is_active'])
- : $this->migration->up();
- }
-
- $workspaces = DB::table('workspaces')->whereIn('id', $this->seeded['workspaces']);
- $userIds = (clone $workspaces)->pluck('user_id')->all();
- $accountIds = (clone $workspaces)->pluck('account_id')->all();
-
- $postIds = DB::table('posts')->whereIn('workspace_id', $this->seeded['workspaces'])->pluck('id')->all();
- DB::table('post_platforms')->whereIn('post_id', $postIds)->delete();
- DB::table('posts')->whereIn('id', $postIds)->delete();
-
- foreach (['post_platforms', 'posts', 'social_accounts', 'workspaces'] as $table) {
- DB::table($table)->whereIn('id', $this->seeded[$table])->delete();
- }
-
- DB::table('users')->whereIn('id', $userIds)->delete();
- DB::table('accounts')->whereIn('id', $accountIds)->delete();
-});
-
-test('turns scheduled posts on paused channels into drafts and drops the column', function () {
- $workspace = Workspace::factory()->create();
- $this->seeded['workspaces'][] = $workspace->id;
- $scheduledAt = now()->addDay()->startOfSecond();
-
- $seed = function (SocialAccount $account, PostStatus $status, bool $enabled = true) use ($workspace, $scheduledAt): Post {
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => $status,
- 'scheduled_at' => $scheduledAt,
- ]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'enabled' => $enabled,
- ]);
- $this->seeded['posts'][] = $post->id;
- $this->seeded['post_platforms'][] = $postPlatform->id;
-
- return $post;
- };
-
- $active = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $paused = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $this->seeded['social_accounts'] = [$active->id, $paused->id];
- DB::table('social_accounts')->where('id', $paused->id)->update(['is_active' => false]);
-
- $activeScheduled = $seed($active, PostStatus::Scheduled);
- $activeDraft = $seed($active, PostStatus::Draft);
- $pausedScheduled = $seed($paused, PostStatus::Scheduled);
- $pausedDraft = $seed($paused, PostStatus::Draft);
- $pausedPublishing = $seed($paused, PostStatus::Publishing);
- $pausedPublished = $seed($paused, PostStatus::Published);
- $pausedDisabled = $seed($paused, PostStatus::Scheduled, enabled: false);
-
- ($this->dropPostingSchedule)();
- $this->migration->up();
-
- expect(Schema::hasColumn('social_accounts', 'is_active'))->toBeFalse()
- ->and(Schema::hasColumns('social_accounts', ['timezone', 'posting_goal', 'posting_schedule']))->toBeTrue()
- ->and($pausedScheduled->fresh()->status)->toBe(PostStatus::Draft)
- ->and($pausedScheduled->fresh()->scheduled_at->equalTo($scheduledAt))->toBeTrue()
- ->and($activeScheduled->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($activeDraft->fresh()->status)->toBe(PostStatus::Draft)
- ->and($pausedDraft->fresh()->status)->toBe(PostStatus::Draft)
- ->and($pausedPublishing->fresh()->status)->toBe(PostStatus::Publishing)
- ->and($pausedPublished->fresh()->status)->toBe(PostStatus::Published)
- ->and($pausedDisabled->fresh()->status)->toBe(PostStatus::Scheduled);
-});
-
-test('keeps a post with active and paused channels scheduled and only disables the paused targets', function () {
- $workspace = Workspace::factory()->create();
- $this->seeded['workspaces'][] = $workspace->id;
- $scheduledAt = now()->addDay()->startOfSecond();
-
- $x = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
- $mastodon = SocialAccount::factory()->mastodon()->create(['workspace_id' => $workspace->id]);
- $paused = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $this->seeded['social_accounts'] = [$x->id, $mastodon->id, $paused->id];
- DB::table('social_accounts')->where('id', $paused->id)->update(['is_active' => false]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => PostStatus::Scheduled,
- 'scheduled_at' => $scheduledAt,
- ]);
- $targets = collect([$x, $mastodon, $paused])->mapWithKeys(fn (SocialAccount $account): array => [
- $account->id => PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'enabled' => true,
- ]),
- ]);
-
- $pausedOnly = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => PostStatus::Scheduled,
- 'scheduled_at' => $scheduledAt,
- ]);
- $pausedOnlyTarget = PostPlatform::factory()->create([
- 'post_id' => $pausedOnly->id,
- 'social_account_id' => $paused->id,
- 'platform' => $paused->platform,
- 'enabled' => true,
- ]);
-
- ($this->dropPostingSchedule)();
- $this->migration->up();
-
- expect($post->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($post->fresh()->scheduled_at->equalTo($scheduledAt))->toBeTrue()
- ->and($targets[$x->id]->fresh()->enabled)->toBeTrue()
- ->and($targets[$mastodon->id]->fresh()->enabled)->toBeTrue()
- ->and($targets[$paused->id]->fresh()->enabled)->toBeFalse()
- ->and($pausedOnly->fresh()->status)->toBe(PostStatus::Draft)
- ->and($pausedOnlyTarget->fresh()->enabled)->toBeTrue();
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $channelPosts = Post::query()
- ->where('workspace_id', $workspace->id)
- ->whereKeyNot($pausedOnly->id)
- ->with('postPlatforms')
- ->get();
- $enabledTargets = $channelPosts->flatMap(fn (Post $channelPost) => $channelPost->postPlatforms->where('enabled', true));
-
- expect($channelPosts)->toHaveCount(2)
- ->and($channelPosts->every(fn (Post $channelPost): bool => $channelPost->status === PostStatus::Scheduled
- && $channelPost->scheduled_at->equalTo($scheduledAt)))->toBeTrue()
- ->and($enabledTargets->pluck('social_account_id')->sort()->values()->all())
- ->toEqual(collect([$x->id, $mastodon->id])->sort()->values()->all());
-});
-
-test('down restores is_active and drops the posting schedule columns', function () {
- ($this->dropPostingSchedule)();
- $this->migration->up();
- $this->migration->down();
-
- expect(Schema::hasColumn('social_accounts', 'is_active'))->toBeTrue()
- ->and(Schema::hasColumn('social_accounts', 'timezone'))->toBeFalse()
- ->and(Schema::hasColumn('social_accounts', 'posting_goal'))->toBeFalse()
- ->and(Schema::hasColumn('social_accounts', 'posting_schedule'))->toBeFalse();
-});
diff --git a/tests/Feature/Observers/PostPlatformObserverTest.php b/tests/Feature/Observers/PostPublicationObserverTest.php
similarity index 66%
rename from tests/Feature/Observers/PostPlatformObserverTest.php
rename to tests/Feature/Observers/PostPublicationObserverTest.php
index 909db86d2..cc06ed320 100644
--- a/tests/Feature/Observers/PostPlatformObserverTest.php
+++ b/tests/Feature/Observers/PostPublicationObserverTest.php
@@ -2,12 +2,10 @@
declare(strict_types=1);
-use App\Enums\PostPlatform\Status;
use App\Jobs\Analytics\SyncTryPostPublication;
use App\Jobs\PostHog\SyncAccountPublishingActivity;
use App\Models\Account;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -23,19 +21,15 @@ beforeEach(function () {
'account_id' => $this->account->id,
'user_id' => $this->user->id,
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
});
test('confirmed publication queues an account activity sync', function () {
$this->freezeTime();
- $postPlatform = PostPlatform::factory()->recycle($this->post)->create();
+ $post = Post::factory()->linkedin()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
Queue::fake();
- $postPlatform->markAsPublished('remote-post-id');
+ $post->markPublicationPublished('remote-post-id');
Queue::assertPushed(
SyncAccountPublishingActivity::class,
@@ -46,11 +40,11 @@ test('confirmed publication queues an account activity sync', function () {
});
test('non-published status changes do not queue an account activity sync', function () {
- $postPlatform = PostPlatform::factory()->recycle($this->post)->create();
+ $post = Post::factory()->linkedin()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
Queue::fake();
- $postPlatform->update(['status' => Status::Publishing]);
+ $post->markPublicationPublishing();
Queue::assertNotPushed(SyncAccountPublishingActivity::class);
});
@@ -59,11 +53,9 @@ test('account activity sync is not queued when PostHog is disabled', function ()
config(['services.posthog.enabled' => false]);
Queue::fake();
$socialAccount = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->x()->recycle($this->post)->create([
- 'social_account_id' => $socialAccount->id,
- ]);
+ $post = Post::factory()->forAccount($socialAccount)->create(['user_id' => $this->user->id]);
- $postPlatform->markAsPublished('remote-post-id');
+ $post->markPublicationPublished('remote-post-id');
Queue::assertNotPushed(SyncAccountPublishingActivity::class);
Queue::assertPushed(SyncTryPostPublication::class);
@@ -71,19 +63,19 @@ test('account activity sync is not queued when PostHog is disabled', function ()
test('excluded platform does not queue an analytics publication sync', function () {
config(['services.posthog.enabled' => false]);
- $postPlatform = PostPlatform::factory()->linkedin()->recycle($this->post)->create();
+ $post = Post::factory()->linkedin()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
Queue::fake();
- $postPlatform->markAsPublished('remote-post-id');
+ $post->markPublicationPublished('remote-post-id');
Queue::assertNotPushed(SyncTryPostPublication::class);
});
-test('updating an already published platform does not queue another sync', function () {
- $postPlatform = PostPlatform::factory()->published()->recycle($this->post)->create();
+test('updating an already published post does not queue another sync', function () {
+ $post = Post::factory()->linkedin()->published()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
Queue::fake();
- $postPlatform->update(['platform_url' => 'https://example.com/published-post']);
+ $post->update(['platform_url' => 'https://example.com/published-post']);
Queue::assertNotPushed(SyncAccountPublishingActivity::class);
});
diff --git a/tests/Feature/Parity/ApprovalsParityTest.php b/tests/Feature/Parity/ApprovalsParityTest.php
index 511e58a4e..646f88e87 100644
--- a/tests/Feature/Parity/ApprovalsParityTest.php
+++ b/tests/Feature/Parity/ApprovalsParityTest.php
@@ -74,7 +74,7 @@ test('a member who needs approval ends pending when creating through mcp while t
'content' => 'Needs a review',
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
];
$this->withHeaders(parityApi($this->memberToken))
@@ -95,13 +95,7 @@ test('a member who needs approval ends pending when creating through mcp while t
});
test('a member who needs approval ends pending when scheduling a draft through mcp while the api is closed to them', function () {
- $draft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->member->id, 'content' => 'Draft to schedule']);
- $draft->postPlatforms()->create([
- 'social_account_id' => $this->account->id,
- 'platform' => 'linkedin',
- 'content_type' => 'linkedin_post',
- 'enabled' => true,
- ]);
+ $draft = Post::factory()->forAccount($this->account, ContentType::LinkedInPost)->draft()->create(['user_id' => $this->member->id, 'content' => 'Draft to schedule']);
$at = now()->addDays(2)->toIso8601String();
$this->withHeaders(parityApi($this->memberToken))
@@ -214,13 +208,7 @@ test('a requester queueing or publishing now through mcp ends pending', function
];
TryPostServer::actingAs($this->member)->tool(CreatePostsTool::class, $queued)->assertOk();
- $draft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->member->id, 'content' => 'Publish me']);
- $draft->postPlatforms()->create([
- 'social_account_id' => $this->account->id,
- 'platform' => 'linkedin',
- 'content_type' => 'linkedin_post',
- 'enabled' => true,
- ]);
+ $draft = Post::factory()->forAccount($this->account, ContentType::LinkedInPost)->draft()->create(['user_id' => $this->member->id, 'content' => 'Publish me']);
TryPostServer::actingAs($this->member)->tool(PublishPostTool::class, ['post_id' => $draft->id])->assertOk();
expect($draft->fresh()->status)->toBe(Status::PendingApproval)
@@ -401,15 +389,9 @@ test('the requester and an approver still reach a pending request on web and mcp
});
test('a member who needs approval deletes only their own posts on web, api and mcp', function () {
- $scheduled = fn (User $author): Post => tap(Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
+ $scheduled = fn (User $author): Post => Post::factory()->forAccount($this->account, ContentType::LinkedInPost)->scheduled()->create([
'user_id' => $author->id,
- ]), fn (Post $post) => $post->postPlatforms()->create([
- 'social_account_id' => $this->account->id,
- 'platform' => 'linkedin',
- 'content_type' => 'linkedin_post',
- 'enabled' => true,
- ]));
+ ]);
$othersOnWeb = $scheduled($this->publisher);
$othersOnMcp = $scheduled($this->publisher);
$ownOnWeb = $scheduled($this->member);
diff --git a/tests/Feature/Parity/FullPostParityTest.php b/tests/Feature/Parity/FullPostParityTest.php
index aed5fc760..28eb29396 100644
--- a/tests/Feature/Parity/FullPostParityTest.php
+++ b/tests/Feature/Parity/FullPostParityTest.php
@@ -2,9 +2,9 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\CreatePostsTool;
use App\Mcp\Tools\Post\CreatePostTool;
@@ -456,7 +456,9 @@ function fullPostPayload(array $case, string $status, string $labelId): array
'scheduled_at' => $status === 'scheduled' ? now()->addHour()->toIso8601String() : null,
'label_ids' => [$labelId],
'media' => $case['media'],
- 'platforms' => [['social_account_id' => $case['account']->id, 'content_type' => $case['content_type'], 'meta' => $case['meta']]],
+ 'social_account_id' => $case['account']->id,
+ 'content_type' => $case['content_type'],
+ 'meta' => $case['meta'],
];
}
@@ -1274,7 +1276,7 @@ test('a complete post published now through the api and through mcp reaches the
$post = fullPostCreate($surface, fullPostPayload(fullPostCase($name), 'publishing', $label->id));
- expect($post->postPlatforms()->sole()->status)->toBe(PostPlatformStatus::Published)
+ expect($post->fresh()->publish_status)->toBe(PublishStatus::Published)
->and($post->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id])
->and(fullPostPublished())->toEqual(fullPostExpected($name));
})->with('complete posts')->with('surfaces');
@@ -1292,7 +1294,7 @@ test('a complete post scheduled through the api and through mcp reaches the netw
$this->travel(61)->minutes();
$this->artisan('posts:process-scheduled')->assertSuccessful();
- expect($post->postPlatforms()->sole()->status)->toBe(PostPlatformStatus::Published)
+ expect($post->fresh()->publish_status)->toBe(PublishStatus::Published)
->and(fullPostPublished())->toEqual(fullPostExpected($name));
})->with('complete posts')->with('surfaces');
@@ -1300,7 +1302,7 @@ test('a draft completed and published through api and mcp updates reaches the ne
fullPostFake();
$label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$case = fullPostCase($name);
- $post = fullPostCreate($surface, [...fullPostPayload($case, 'draft', $label->id), 'platforms' => [['social_account_id' => $case['account']->id, 'content_type' => $case['content_type']]]]);
+ $post = fullPostCreate($surface, Arr::except(fullPostPayload($case, 'draft', $label->id), ['meta']));
if ($surface === 'api') {
$this->withHeaders(parityApi($this->token))
@@ -1311,7 +1313,7 @@ test('a draft completed and published through api and mcp updates reaches the ne
TryPostServer::actingAs($this->user)->tool(PublishPostTool::class, ['post_id' => $post->id])->assertOk();
}
- expect($post->postPlatforms()->sole()->status)->toBe(PostPlatformStatus::Published)
+ expect($post->fresh()->publish_status)->toBe(PublishStatus::Published)
->and(fullPostPublished())->toEqual(fullPostExpected($name));
})->with('complete posts')->with('surfaces');
@@ -1331,9 +1333,9 @@ test('a complete post reads back every setting the same way through the api and
$replies = data_get($meta, 'thread_replies');
unset($meta['thread_replies']);
- expect(data_get($api, 'platforms.0.content_type'))->toBe($case['content_type'])
- ->and(Arr::except(data_get($api, 'platforms.0.meta'), ['thread_replies']))->toEqual($meta)
- ->and(collect(data_get($api, 'platforms.0.meta.thread_replies', []))->pluck('text')->all())->toBe(collect($replies ?? [])->pluck('text')->all())
+ expect(data_get($api, 'content_type'))->toBe($case['content_type'])
+ ->and(Arr::except(data_get($api, 'meta'), ['thread_replies']))->toEqual($meta)
+ ->and(collect(data_get($api, 'meta.thread_replies', []))->pluck('text')->all())->toBe(collect($replies ?? [])->pluck('text')->all())
->and(data_get($api, 'labels.0.id'))->toBe($label->id)
->and(data_get($api, 'content'))->toBe($case['content'])
->and(collect(data_get($api, 'media'))->map(fn (array $item): array => Arr::only((array) data_get($item, 'meta'), ['alt_text', 'user_tags', 'cover_offset_ms']))->all())
@@ -1378,8 +1380,8 @@ test('a batch with per-network caption, media and settings reaches each network
test('every per-platform setting the rules accept is documented for mcp clients', function () {
$keys = collect(array_keys(PostPlatformMetaRules::rules()))
- ->filter(fn (string $key): bool => str_starts_with($key, 'platforms.*.meta.'))
- ->map(fn (string $key): string => explode('.', substr($key, strlen('platforms.*.meta.')))[0])
+ ->filter(fn (string $key): bool => str_starts_with($key, 'meta.'))
+ ->map(fn (string $key): string => explode('.', substr($key, strlen('meta.')))[0])
->unique()
->values();
@@ -1394,7 +1396,7 @@ test('every mcp tool that takes per-platform settings describes all of them', fu
expect(data_get((new $tool)->toArray(), "inputSchema.properties.{$path}.description"))
->toContain(PostPlatformMetaRules::documentation());
})->with([
- 'create-post-tool' => [CreatePostTool::class, 'platforms.items.properties.meta'],
+ 'create-post-tool' => [CreatePostTool::class, 'meta'],
'create-posts-tool' => [CreatePostsTool::class, 'destinations.items.properties.meta'],
'update-post-tool' => [UpdatePostTool::class, 'meta'],
]);
diff --git a/tests/Feature/Parity/InsightsParityTest.php b/tests/Feature/Parity/InsightsParityTest.php
index 52c661c46..fc95fa8c3 100644
--- a/tests/Feature/Parity/InsightsParityTest.php
+++ b/tests/Feature/Parity/InsightsParityTest.php
@@ -17,7 +17,6 @@ use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -267,19 +266,17 @@ test('the publication detail is the same through the api and mcp and is isolated
->assertHasErrors(['Publication not found.']);
});
-test('the post metrics are the same on the web platform route, the api and mcp', function () {
+test('the post metrics are the same on the web, the api and mcp', function () {
$account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
- $post = Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->published()->create([
+ 'user_id' => $this->user->id,
'platform_post_id' => '123',
]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $this->workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
- 'post_platform_id' => $destination->id,
+ 'post_id' => $post->id,
'platform' => Platform::Instagram,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
@@ -289,18 +286,25 @@ test('the post metrics are the same on the web platform route, the api and mcp',
'metrics' => ['reactions' => ['value' => 7, 'unit' => 'count', 'availability' => 'available']],
]);
- $web = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', [$post, $destination]))
+ $web = null;
+ $this->actingAs($this->user)
+ ->get(route('app.posts.index', ['tab' => 'sent']))
->assertOk()
- ->assertJsonPath('metrics.reactions.value', 7)
- ->json();
+ ->assertInertia(function (Assert $page) use ($post, &$web): void {
+ $page->loadDeferredProps(function (Assert $reload) use ($post, &$web): void {
+ $reload->where('posts.data.0.id', $post->id)
+ ->where('posts.data.0.metrics.metrics.reactions.value', 7);
+ $web = data_get($reload->toArray(), 'props.posts.data.0.metrics');
+ });
+ });
auth()->forgetGuards();
$api = $this->withHeaders(parityApi($this->token))
->getJson(route('api.posts.metrics', $post))
->assertOk()
- ->assertJsonPath('platforms.0.metrics.metrics.reactions.value', 7)
- ->json('platforms.0.metrics');
+ ->assertJsonPath('post_id', $post->id)
+ ->assertJsonPath('metrics.metrics.reactions.value', 7)
+ ->json('metrics');
expect($api)->toEqual($web);
@@ -308,7 +312,7 @@ test('the post metrics are the same on the web platform route, the api and mcp',
->tool(GetPostMetricsTool::class, ['post_id' => $post->id])
->assertStructuredContent(fn (AssertableJson $json) => $json
->where('post_id', $post->id)
- ->where('platforms.0.metrics.metrics.reactions.value', 7)
+ ->where('metrics', $api)
->etc());
$foreign = Post::factory()->published()->create();
@@ -350,15 +354,10 @@ function seedChannelInsightsParity(Workspace $workspace, User $user): array
}
foreach ([['2026-09-05', 40, 3, ContentType::InstagramFeed, true], ['2026-09-12', 90, 8, ContentType::InstagramReel, true], ['2026-09-18', 60, 11, null, false]] as [$day, $reach, $reactions, $type, $labelled]) {
- $destination = null;
+ $post = null;
if ($type !== null) {
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id]);
- $destination = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'content_type' => $type,
- ]);
+ $post = Post::factory()->forAccount($account, $type)->published()->create(['user_id' => $user->id]);
if ($labelled) {
$post->labels()->attach($label->id);
@@ -372,8 +371,8 @@ function seedChannelInsightsParity(Workspace $workspace, User $user): array
'network' => Platform::Instagram->network(),
'platform_user_id' => $account->platform_user_id,
'platform' => Platform::Instagram,
- 'post_platform_id' => $destination?->id,
- 'origin' => $destination === null ? PublicationOrigin::External : PublicationOrigin::TryPost,
+ 'post_id' => $post?->id,
+ 'origin' => $post === null ? PublicationOrigin::External : PublicationOrigin::TryPost,
'provider_published_at' => "{$day} 10:00:00",
]);
AnalyticsPublicationDailySnapshot::factory()->create([
diff --git a/tests/Feature/Parity/McpAuthorizationParityTest.php b/tests/Feature/Parity/McpAuthorizationParityTest.php
index 453aba1fd..3ebcd352a 100644
--- a/tests/Feature/Parity/McpAuthorizationParityTest.php
+++ b/tests/Feature/Parity/McpAuthorizationParityTest.php
@@ -134,13 +134,7 @@ function mcpAuthParityFixture(Workspace $workspace, User $owner, ?User $actor =
'platform' => Platform::LinkedIn,
'timezone' => 'UTC',
]);
- $post = Post::factory()->draft()->create(['workspace_id' => $workspace->id, 'user_id' => $owner->id, 'content' => 'Draft']);
- $postPlatform = $post->postPlatforms()->create([
- 'social_account_id' => $linkedin->id,
- 'platform' => 'linkedin',
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- ]);
+ $post = Post::factory()->forAccount($linkedin, ContentType::LinkedInPost)->draft()->create(['user_id' => $owner->id, 'content' => 'Draft']);
$pending = CreatePosts::execute($workspace, workspaceMember($workspace, 'approval'), [
'status' => 'scheduled',
'scheduled_at' => now()->addDays(2)->toIso8601String(),
@@ -162,20 +156,13 @@ function mcpAuthParityFixture(Workspace $workspace, User $owner, ?User $actor =
$queued = [];
foreach (['queue', 'custom'] as $mode) {
- $queued[$mode] = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ $queued[$mode] = Post::factory()->forAccount($queueChannel, ContentType::LinkedInPost)->create([
'user_id' => $owner->id,
'status' => Status::Scheduled,
'content' => 'Queued parity post',
'schedule_mode' => $mode,
'scheduled_at' => $mode === 'queue' ? $queueSlots[0] : now()->addDays(9)->setTime(10, 7),
]);
- $queued[$mode]->postPlatforms()->create([
- 'social_account_id' => $queueChannel->id,
- 'platform' => 'linkedin',
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- ]);
}
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
$webhook = Webhook::factory()->create(['workspace_id' => $workspace->id]);
@@ -189,7 +176,6 @@ function mcpAuthParityFixture(Workspace $workspace, User $owner, ?User $actor =
'customPost' => $queued['custom'],
'freeSlot' => $queueSlots[1]->toIso8601ZuluString(),
'post' => $post,
- 'postPlatform' => $postPlatform,
'note' => PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $owner->id]),
'tiktok' => SocialAccount::factory()->tiktok()->create(['workspace_id' => $workspace->id, 'platform_user_id' => (string) Str::uuid()]),
'pending' => $pending,
@@ -276,9 +262,9 @@ function mcpAuthParityTools(): array
'attach-media-from-upload-tool' => [AttachMediaFromUploadTool::class, $everyMember, fn (TestCase $t, array $f) => $t->put(route('app.posts.update', $f['post']), ['status' => 'draft', 'content' => 'Edited', 'media' => []]), fn (array $f) => ['post_id' => $f['post']->id, 'upload_token' => $f['uploadToken']]],
'attach-media-from-url-tool' => [AttachMediaFromUrlTool::class, $everyMember, fn (TestCase $t, array $f) => $t->put(route('app.posts.update', $f['post']), ['status' => 'draft', 'content' => 'Edited', 'media' => []]), fn (array $f) => ['post_id' => $f['post']->id, 'urls' => [['url' => 'https://example.com/photo.jpg']]]],
'create-posts-tool' => [CreatePostsTool::class, $everyMember, fn (TestCase $t, array $f) => $t->post(route('app.posts.store'), ['status' => 'draft', 'content' => 'Hello', 'media' => [], 'destinations' => [mcpAuthParityDestination($f)]]), fn (array $f) => ['status' => 'draft', 'content' => 'Hello', 'destinations' => [mcpAuthParityDestination($f)]]],
- 'create-post-tool' => [CreatePostTool::class, $everyMember, fn (TestCase $t, array $f) => $t->post(route('app.posts.store'), ['status' => 'draft', 'content' => 'Hello', 'media' => [], 'destinations' => [mcpAuthParityDestination($f)]]), fn (array $f) => ['content' => 'Hello', 'platforms' => [mcpAuthParityDestination($f)]]],
+ 'create-post-tool' => [CreatePostTool::class, $everyMember, fn (TestCase $t, array $f) => $t->post(route('app.posts.store'), ['status' => 'draft', 'content' => 'Hello', 'media' => [], 'destinations' => [mcpAuthParityDestination($f)]]), fn (array $f) => ['content' => 'Hello', ...mcpAuthParityDestination($f)]],
'delete-post-tool' => [DeletePostTool::class, $publishers, fn (TestCase $t, array $f) => $t->delete(route('app.posts.destroy', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
- 'get-post-metrics-tool' => [GetPostMetricsTool::class, [], fn (TestCase $t, array $f) => $t->getJson(route('app.posts.platforms.metrics', [$f['post'], $f['postPlatform']])), fn (array $f) => ['post_id' => $f['post']->id]],
+ 'get-post-metrics-tool' => [GetPostMetricsTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
'get-post-tool' => [GetPostTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
'list-post-notes-tool' => [ListPostNotesTool::class, $everyMember, fn (TestCase $t, array $f) => $t->getJson(route('app.posts.notes.index', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
'create-post-note-tool' => [CreatePostNoteTool::class, $everyMember, fn (TestCase $t, array $f) => $t->postJson(route('app.posts.notes.store', $f['post']), ['body' => 'Looks good']), fn (array $f) => ['post_id' => $f['post']->id, 'body' => 'Looks good']],
@@ -287,7 +273,7 @@ function mcpAuthParityTools(): array
'get-tiktok-creator-info-tool' => [GetTikTokCreatorInfoTool::class, $everyMember, fn (TestCase $t, array $f) => $t->getJson(route('app.posts.composer.account', $f['tiktok'])), fn (array $f) => ['account_id' => $f['tiktok']->id]],
'list-posts-tool' => [ListPostsTool::class, $everyMember, fn (TestCase $t, array $f) => $t->get(route('app.posts.index')), fn (array $f) => []],
'preview-post-tool' => [PreviewPostTool::class, [], fn (TestCase $t, array $f) => $t->get(route('app.posts.edit', $f['post'])), fn (array $f) => ['post_id' => $f['post']->id]],
- 'publish-post-tool' => [PublishPostTool::class, $everyMember, fn (TestCase $t, array $f) => $t->put(route('app.posts.update', $f['post']), ['status' => 'scheduled', 'scheduled_at' => now()->addDays(2)->toIso8601String(), 'content' => 'Draft', 'media' => []]), fn (array $f) => ['post_id' => $f['post']->id, 'scheduled_at' => now()->addDays(2)->toIso8601String()]],
+ 'publish-post-tool' => [PublishPostTool::class, $everyMember, fn (TestCase $t, array $f) => $t->put(route('app.posts.update', $f['post']), ['status' => 'scheduled', 'scheduled_at' => now()->addDays(2)->toIso8601String(), 'content' => 'Draft', 'media' => [], 'content_type' => ContentType::LinkedInPost->value]), fn (array $f) => ['post_id' => $f['post']->id, 'scheduled_at' => now()->addDays(2)->toIso8601String()]],
'request-media-upload-tool' => [RequestMediaUploadTool::class, $everyMember, fn (TestCase $t, array $f) => $t->postJson(route('app.media.store-chunked')), fn (array $f) => []],
'update-post-tool' => [UpdatePostTool::class, $everyMember, fn (TestCase $t, array $f) => $t->put(route('app.posts.update', $f['post']), ['status' => 'draft', 'content' => 'Edited', 'media' => []]), fn (array $f) => ['post_id' => $f['post']->id, 'content' => 'Edited']],
'activate-repurpose-tool' => [ActivateRepurposeTool::class, $publishers, fn (TestCase $t, array $f) => $t->post(route('app.repurposes.activate', $f['repurposeReady'])), fn (array $f) => ['repurpose_id' => $f['repurposeReady']->id]],
@@ -374,17 +360,8 @@ test('a member who needs approval ends pending when scheduling through create-po
$requester = workspaceMember($this->workspace, 'approval');
$fixture = mcpAuthParityFixture($this->workspace, $this->owner);
$at = now()->addDays(2)->startOfHour()->toIso8601String();
- $webDraft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $requester->id, 'content' => 'Web draft']);
- $mcpDraft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $requester->id, 'content' => 'Mcp draft']);
-
- foreach ([$webDraft, $mcpDraft] as $draft) {
- $draft->postPlatforms()->create([
- 'social_account_id' => $fixture['linkedin']->id,
- 'platform' => 'linkedin',
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- ]);
- }
+ $webDraft = Post::factory()->forAccount($fixture['linkedin'], ContentType::LinkedInPost)->draft()->create(['user_id' => $requester->id, 'content' => 'Web draft']);
+ $mcpDraft = Post::factory()->forAccount($fixture['linkedin'], ContentType::LinkedInPost)->draft()->create(['user_id' => $requester->id, 'content' => 'Mcp draft']);
$this->actingAs($requester)->post(route('app.posts.store'), [
'status' => 'scheduled',
@@ -398,6 +375,7 @@ test('a member who needs approval ends pending when scheduling through create-po
'scheduled_at' => $at,
'content' => 'Web draft',
'media' => [],
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertRedirect();
auth()->forgetGuards();
@@ -405,7 +383,7 @@ test('a member who needs approval ends pending when scheduling through create-po
'content' => 'Created through mcp',
'status' => 'scheduled',
'scheduled_at' => $at,
- 'platforms' => [mcpAuthParityDestination($fixture)],
+ ...mcpAuthParityDestination($fixture),
])->assertOk();
TryPostServer::actingAs($requester)->tool(UpdatePostTool::class, [
'post_id' => $mcpDraft->id,
diff --git a/tests/Feature/Parity/MediaParityTest.php b/tests/Feature/Parity/MediaParityTest.php
index f3dd04428..7bc233176 100644
--- a/tests/Feature/Parity/MediaParityTest.php
+++ b/tests/Feature/Parity/MediaParityTest.php
@@ -12,7 +12,6 @@ use App\Mcp\Tools\Post\RequestMediaUploadTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Http;
@@ -29,7 +28,6 @@ function mediaParityUpload(object $test, string $kind = 'image'): Media
function mediaParityPost(object $test, string $platform = 'linkedin'): Post
{
- $post = Post::factory()->create(['workspace_id' => $test->workspace->id, 'user_id' => $test->user->id]);
$account = SocialAccount::factory()->create([
'workspace_id' => $test->workspace->id,
'platform' => match ($platform) {
@@ -38,9 +36,8 @@ function mediaParityPost(object $test, string $platform = 'linkedin'): Post
default => Platform::LinkedIn,
},
]);
- PostPlatform::factory()->{$platform}()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'enabled' => true]);
- return $post;
+ return Post::factory()->forAccount($account)->{$platform}()->create(['user_id' => $test->user->id]);
}
function mediaParityShape(Post $post): array
diff --git a/tests/Feature/Parity/NetworkRulesParityTest.php b/tests/Feature/Parity/NetworkRulesParityTest.php
index 025bae660..b5fdf41b7 100644
--- a/tests/Feature/Parity/NetworkRulesParityTest.php
+++ b/tests/Feature/Parity/NetworkRulesParityTest.php
@@ -11,7 +11,6 @@ use App\Mcp\Tools\Post\CreatePostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Support\PostPlatformMetaRules;
use Illuminate\Support\Facades\Queue;
@@ -107,12 +106,12 @@ function netParityAccepted(array $apiPayload, ?array $mcpPayload = null): array
netParityApi()->postJson(route('api.posts.batch.store'), $apiPayload)->assertCreated();
TryPostServer::actingAs(test()->user)->tool(CreatePostsTool::class, $mcpPayload ?? $apiPayload)->assertOk();
- $posts = Post::query()->with('postPlatforms')->where('workspace_id', test()->workspace->id)->whereNotIn('id', $existing)->oldest()->get()->values();
+ $posts = Post::query()->where('workspace_id', test()->workspace->id)->whereNotIn('id', $existing)->oldest()->get()->values();
expect($posts)->toHaveCount(2)
->and($posts[0]->status)->toBe($posts[1]->status)
- ->and($posts[0]->postPlatforms->pluck('content_type'))->toEqual($posts[1]->postPlatforms->pluck('content_type'))
- ->and($posts[0]->postPlatforms->pluck('meta')->all())->toEqual($posts[1]->postPlatforms->pluck('meta')->all());
+ ->and($posts[0]->content_type)->toBe($posts[1]->content_type)
+ ->and($posts[0]->meta)->toEqual($posts[1]->meta);
return [$posts[0], $posts[1]];
}
@@ -125,7 +124,7 @@ test('a scheduled pinterest pin without a board is refused by api and mcp and ac
[$api] = netParityAccepted($payload(['board_id' => 'board-1']), $payload(['board_id' => 'board-1']));
- expect($api->postPlatforms->first()->meta['board_id'])->toBe('board-1');
+ expect($api->meta['board_id'])->toBe('board-1');
});
test('a scheduled discord message without a channel is refused by api and mcp and accepted with one', function () {
@@ -136,7 +135,7 @@ test('a scheduled discord message without a channel is refused by api and mcp an
[$api] = netParityAccepted($payload(['channel_id' => '123']), $payload(['channel_id' => '123']));
- expect($api->postPlatforms->first()->meta['channel_id'])->toBe('123');
+ expect($api->meta['channel_id'])->toBe('123');
});
test('tiktok privacy level is required to schedule and is refused with an unknown value by api and mcp', function () {
@@ -165,7 +164,7 @@ test('tiktok flags and auto music are stored the same way through api and mcp',
[$api] = netParityAccepted($payload(), $payload());
- expect($api->postPlatforms->first()->meta)->toEqual($meta);
+ expect($api->meta)->toEqual($meta);
});
test('tiktok photos need the photo content type and a video the video one, in api and mcp alike', function () {
@@ -203,21 +202,20 @@ test('tiktok photo carousels reject mixed media and more than 35 photos through
netParityPayload($account, ContentType::TikTokPhoto, ['media' => $photos(35)], $meta),
);
- expect($api->postPlatforms->first()->content_type)->toBe(ContentType::TikTokPhoto);
+ expect($api->content_type)->toBe(ContentType::TikTokPhoto);
});
test('a destination without content_type gets the type the web composer would send, on every api and mcp create path', function (Platform $platform, Closure $media, ContentType $composer) {
$account = netParityAccount($platform);
- $items = $media();
- $batch = ['status' => 'draft', 'content' => 'Derived', 'media' => $items, 'destinations' => [['social_account_id' => $account->id]]];
- $single = ['status' => 'draft', 'content' => 'Derived', 'media' => $items, 'platforms' => [['social_account_id' => $account->id]]];
+ $batch = fn (): array => ['status' => 'draft', 'content' => 'Derived', 'media' => $media(), 'destinations' => [['social_account_id' => $account->id]]];
+ $single = fn (): array => ['status' => 'draft', 'content' => 'Derived', 'media' => $media(), 'social_account_id' => $account->id];
- netParityApi()->postJson(route('api.posts.batch.store'), $batch)->assertCreated();
- netParityApi()->postJson(route('api.posts.store'), $single)->assertCreated();
- TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, $batch)->assertOk();
- TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $single)->assertOk();
+ netParityApi()->postJson(route('api.posts.batch.store'), $batch())->assertCreated();
+ netParityApi()->postJson(route('api.posts.store'), $single())->assertCreated();
+ TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, $batch())->assertOk();
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $single())->assertOk();
- $types = PostPlatform::query()->where('social_account_id', $account->id)->pluck('content_type');
+ $types = Post::query()->where('social_account_id', $account->id)->pluck('content_type');
expect($types)->toHaveCount(4)
->and($types->unique()->all())->toBe([$composer]);
@@ -259,8 +257,8 @@ test('a scheduled tiktok post without content_type is validated as the type its
[$api, $mcp] = netParityAccepted($payload($photos(2)), $payload($photos(2)));
- expect($api->postPlatforms->first()->content_type)->toBe(ContentType::TikTokPhoto)
- ->and($mcp->postPlatforms->first()->content_type)->toBe(ContentType::TikTokPhoto);
+ expect($api->content_type)->toBe(ContentType::TikTokPhoto)
+ ->and($mcp->content_type)->toBe(ContentType::TikTokPhoto);
});
test('an explicit content_type that does not match the media is still refused with the media message by api and mcp', function () {
@@ -278,11 +276,13 @@ test('an explicit content_type that does not match the media is still refused wi
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [netParityImage()],
- 'platforms' => [['social_account_id' => $tiktok->id, 'content_type' => ContentType::TikTokVideo->value, 'meta' => ['privacy_level' => 'PUBLIC_TO_EVERYONE']]],
+ 'social_account_id' => $tiktok->id,
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => 'PUBLIC_TO_EVERYONE'],
];
netParityApi()->postJson(route('api.posts.store'), $payload)
- ->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.content_type' => __('posts.form.warnings.no_image_allowed')]);
+ ->assertUnprocessable()->assertJsonValidationErrors(['content_type' => __('posts.form.warnings.no_image_allowed')]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertHasErrors([__('posts.form.warnings.no_image_allowed')]);
expect(netParityPostCount())->toBe(0);
@@ -290,11 +290,8 @@ test('an explicit content_type that does not match the media is still refused wi
test('new media without content_type re-decides a tiktok or pinterest post type on update through api and mcp, other networks keep theirs', function (Platform $platform, ContentType $stored, ContentType $expected, array $meta) {
$account = netParityAccount($platform);
- $posts = collect(['api', 'mcp'])->mapWithKeys(function (string $surface) use ($account, $platform, $stored, $meta): array {
- $post = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => $platform, 'content_type' => $stored, 'meta' => $meta]);
-
- return [$surface => $post];
+ $posts = collect(['api', 'mcp'])->mapWithKeys(function (string $surface) use ($account, $stored, $meta): array {
+ return [$surface => Post::factory()->forAccount($account, $stored)->draft()->create(['user_id' => $this->user->id, 'meta' => $meta])];
});
$update = fn () => [
'status' => 'scheduled',
@@ -306,8 +303,8 @@ test('new media without content_type re-decides a tiktok or pinterest post type
netParityApi()->putJson(route('api.posts.update', $posts['api']), $update())->assertOk();
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, ['post_id' => $posts['mcp']->id, ...$update()])->assertOk();
- expect($posts['api']->refresh()->postPlatforms->first()->content_type)->toBe($expected)
- ->and($posts['mcp']->refresh()->postPlatforms->first()->content_type)->toBe($expected);
+ expect($posts['api']->refresh()->content_type)->toBe($expected)
+ ->and($posts['mcp']->refresh()->content_type)->toBe($expected);
})->with([
'tiktok photo to video' => [Platform::TikTok, ContentType::TikTokPhoto, ContentType::TikTokVideo, ['privacy_level' => 'PUBLIC_TO_EVERYONE']],
'pinterest pin to video pin' => [Platform::Pinterest, ContentType::PinterestPin, ContentType::PinterestVideoPin, ['board_id' => 'board-1']],
@@ -322,7 +319,7 @@ test('scheduling a youtube short with no text and no title is refused by api and
[$api] = netParityAccepted($payload(['title' => 'A title']), $payload(['title' => 'A title']));
- expect($api->postPlatforms->first()->meta['title'])->toBe('A title');
+ expect($api->meta['title'])->toBe('A title');
});
test('a youtube title with angle brackets is refused even as a draft by api and mcp', function () {
@@ -336,11 +333,11 @@ test('a youtube title with angle brackets is refused on the single create path b
$account = netParityAccount(Platform::YouTube);
$payload = [
'content' => 'Text',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['title' => 'Bad <title>']]],
+ 'social_account_id' => $account->id, 'content_type' => ContentType::YouTubeShort->value, 'meta' => ['title' => 'Bad <title>'],
];
netParityApi()->postJson(route('api.posts.store'), $payload)
- ->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.meta.title']);
+ ->assertUnprocessable()->assertJsonValidationErrors(['meta.title' => __('posts.form.youtube.title_invalid')]);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertHasErrors([__('posts.form.youtube.title_invalid')]);
expect(netParityPostCount())->toBe(0);
@@ -414,7 +411,7 @@ test('facebook and instagram stories accept a photo through api and mcp', functi
[$api] = netParityAccepted($payload(), $payload());
- expect($api->postPlatforms->first()->content_type)->toBe($type);
+ expect($api->content_type)->toBe($type);
})->with([
'facebook' => [Platform::Facebook, ContentType::FacebookStory],
'instagram' => [Platform::Instagram, ContentType::InstagramStory],
@@ -470,7 +467,7 @@ test('the mastodon content warning counts toward the 500 character limit through
[$api] = netParityAccepted($payload(), $payload());
- expect($api->postPlatforms->first()->meta['spoiler_text'])->toBe('cw');
+ expect($api->meta['spoiler_text'])->toBe('cw');
});
test('google business event and offer posts need a title and dates, and a url action needs a url, in api and mcp alike', function () {
@@ -506,7 +503,7 @@ test('a google business event is stored the same way through api and mcp', funct
[$api] = netParityAccepted($payload(), $payload());
- expect($api->postPlatforms->first()->meta['event']['title'])->toBe('Launch');
+ expect($api->meta['event']['title'])->toBe('Launch');
});
test('a linkedin document post stores its title the same way and refuses one over 300 characters through api and mcp', function () {
@@ -517,7 +514,7 @@ test('a linkedin document post stores its title the same way and refuses one ove
[$api] = netParityAccepted($payload('Deck'), $payload('Deck'));
- expect($api->postPlatforms->first()->meta['document_title'])->toBe('Deck');
+ expect($api->meta['document_title'])->toBe('Deck');
});
test('a threads topic tag is normalised and validated the same way through api and mcp', function () {
@@ -528,7 +525,7 @@ test('a threads topic tag is normalised and validated the same way through api a
[$api] = netParityAccepted($payload('#ideas'), $payload('#ideas'));
- expect($api->postPlatforms->first()->meta['topic_tag'])->toBe('ideas');
+ expect($api->meta['topic_tag'])->toBe('ideas');
});
test('link preview false is stored the same way and a non boolean is refused through api and mcp', function () {
@@ -539,7 +536,7 @@ test('link preview false is stored the same way and a non boolean is refused thr
[$api] = netParityAccepted($payload(false), $payload(false));
- expect($api->postPlatforms->first()->meta['link_preview'])->toBeFalse();
+ expect($api->meta['link_preview'])->toBeFalse();
});
test('meta aspect_ratio is dropped on the single create path by api and mcp', function () {
@@ -547,13 +544,13 @@ test('meta aspect_ratio is dropped on the single create path by api and mcp', fu
$payload = fn () => [
'content' => 'Ratio',
'media' => [netParityImage()],
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::InstagramFeed->value, 'meta' => ['aspect_ratio' => '1:1', 'share_to_feed' => true]]],
+ 'social_account_id' => $account->id, 'content_type' => ContentType::InstagramFeed->value, 'meta' => ['aspect_ratio' => '1:1', 'share_to_feed' => true],
];
netParityApi()->postJson(route('api.posts.store'), $payload())->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload())->assertOk();
- $metas = PostPlatform::query()->where('social_account_id', $account->id)->get()->pluck('meta');
+ $metas = Post::query()->where('social_account_id', $account->id)->get()->pluck('meta');
expect($metas)->toHaveCount(2)
->and($metas[0])->not->toHaveKey('aspect_ratio')
@@ -567,49 +564,47 @@ test('meta aspect_ratio is stripped on the batch create path by api and mcp alik
[$api, $mcp] = netParityAccepted($payload(), $payload());
- expect($api->postPlatforms->first()->meta)->not->toHaveKey('aspect_ratio')
- ->and($mcp->postPlatforms->first()->meta)->not->toHaveKey('aspect_ratio')
- ->and($api->postPlatforms->first()->meta['share_to_feed'])->toBeFalse()
- ->and($mcp->postPlatforms->first()->meta['share_to_feed'])->toBeFalse();
+ expect($api->meta)->not->toHaveKey('aspect_ratio')
+ ->and($mcp->meta)->not->toHaveKey('aspect_ratio')
+ ->and($api->meta['share_to_feed'])->toBeFalse()
+ ->and($mcp->meta['share_to_feed'])->toBeFalse();
});
test('updating a draft with an invalid threads topic tag is refused by api and mcp', function () {
$account = netParityAccount(Platform::Threads);
- $apiPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $mcpPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $apiPlatform = PostPlatform::factory()->create(['post_id' => $apiPost->id, 'social_account_id' => $account->id, 'platform' => Platform::Threads, 'content_type' => ContentType::ThreadsPost]);
- PostPlatform::factory()->create(['post_id' => $mcpPost->id, 'social_account_id' => $account->id, 'platform' => Platform::Threads, 'content_type' => ContentType::ThreadsPost]);
+ $apiPost = Post::factory()->forAccount($account, ContentType::ThreadsPost)->draft()->create(['user_id' => $this->user->id]);
+ $mcpPost = Post::factory()->forAccount($account, ContentType::ThreadsPost)->draft()->create(['user_id' => $this->user->id]);
netParityApi()
- ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'platforms' => [['id' => $apiPlatform->id, 'meta' => ['topic_tag' => 'bad.tag']]]])
- ->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.meta.topic_tag' => __('posts.form.threads.topic_invalid')]);
+ ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'meta' => ['topic_tag' => 'bad.tag']])
+ ->assertUnprocessable()->assertJsonValidationErrors(['meta.topic_tag' => __('posts.form.threads.topic_invalid')]);
TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, ['post_id' => $mcpPost->id, 'meta' => ['topic_tag' => 'bad.tag']])
->assertHasErrors([__('posts.form.threads.topic_invalid')]);
- expect($apiPost->refresh()->postPlatforms->first()->meta['topic_tag'] ?? null)->toBeNull()
- ->and($mcpPost->refresh()->postPlatforms->first()->meta['topic_tag'] ?? null)->toBeNull()
+ expect($apiPost->refresh()->meta['topic_tag'] ?? null)->toBeNull()
+ ->and($mcpPost->refresh()->meta['topic_tag'] ?? null)->toBeNull()
->and($apiPost->status)->toBe(Status::Draft);
});
test('updating a draft with a non boolean link preview is refused with the same message by api and mcp', function () {
$account = netParityAccount(Platform::Bluesky);
- $apiPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $mcpPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $apiPlatform = PostPlatform::factory()->create(['post_id' => $apiPost->id, 'social_account_id' => $account->id, 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost]);
- PostPlatform::factory()->create(['post_id' => $mcpPost->id, 'social_account_id' => $account->id, 'platform' => Platform::Bluesky, 'content_type' => ContentType::BlueskyPost]);
- $message = __('validation.boolean', ['attribute' => 'platforms.0.meta.link_preview']);
+ $apiPost = Post::factory()->forAccount($account, ContentType::BlueskyPost)->draft()->create(['user_id' => $this->user->id]);
+ $mcpPost = Post::factory()->forAccount($account, ContentType::BlueskyPost)->draft()->create(['user_id' => $this->user->id]);
- netParityApi()
- ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'platforms' => [['id' => $apiPlatform->id, 'meta' => ['link_preview' => 'false']]]])
- ->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.meta.link_preview' => $message]);
+ $message = netParityApi()
+ ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'meta' => ['link_preview' => 'false']])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors(['meta.link_preview'])
+ ->json('errors')['meta.link_preview'][0];
TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, ['post_id' => $mcpPost->id, 'meta' => ['link_preview' => 'false']])
->assertHasErrors([$message]);
- expect($mcpPost->refresh()->postPlatforms->first()->meta['link_preview'] ?? null)->toBeNull();
+ expect($apiPost->refresh()->meta['link_preview'] ?? null)->toBeNull()
+ ->and($mcpPost->refresh()->meta['link_preview'] ?? null)->toBeNull();
});
test('onlyKnown keeps every key that has a meta rule and drops the rest', function () {
@@ -638,7 +633,7 @@ test('the single create path measures caption limits by status, not by a schedul
$message = __('posts.form.content_exceeds_platform', ['platform' => Platform::X->label(), 'limit' => 280, 'over' => 1]);
$payload = fn (array $overrides) => [
'content' => str_repeat('a', 281),
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::XPost->value]],
+ 'social_account_id' => $account->id, 'content_type' => ContentType::XPost->value,
...$overrides,
];
diff --git a/tests/Feature/Parity/PostsParityTest.php b/tests/Feature/Parity/PostsParityTest.php
index 0997c21ce..882bf94a1 100644
--- a/tests/Feature/Parity/PostsParityTest.php
+++ b/tests/Feature/Parity/PostsParityTest.php
@@ -14,7 +14,6 @@ use App\Mcp\Tools\Post\ListPostsTool;
use App\Mcp\Tools\Post\PreviewPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\WorkspaceLabel;
use App\Support\Requests\Post\PostRequestRules;
@@ -25,15 +24,15 @@ use Inertia\Testing\AssertableInertia;
function postsParitySnapshot(Post $post): array
{
- $post->loadMissing('postPlatforms', 'labels');
+ $post->loadMissing('labels');
return [
'status' => $post->status,
'content' => $post->content,
'schedule_mode' => $post->schedule_mode,
'scheduled' => $post->scheduled_at !== null,
- 'channels' => $post->postPlatforms->pluck('social_account_id')->all(),
- 'content_types' => $post->postPlatforms->pluck('content_type')->all(),
+ 'channels' => [$post->social_account_id],
+ 'content_types' => [$post->content_type],
'labels' => $post->labels->pluck('id')->sort()->values()->all(),
];
}
@@ -49,12 +48,14 @@ test('a draft created through the api and through mcp is stored the same way', f
->postJson(route('api.posts.store'), [
'content' => 'Parity draft',
'status' => 'draft',
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => 'linkedin_post',
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Parity draft',
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => 'linkedin_post',
])->assertOk();
$posts = Post::query()->where('workspace_id', $this->workspace->id)->get();
@@ -100,7 +101,8 @@ test('a scheduled post created through the api and through the mcp batch tool is
$this->withHeaders(parityApi($this->token))
->postJson(route('api.posts.store'), [
...$payload,
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => 'linkedin_post',
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, [
@@ -131,8 +133,8 @@ test('updating the content of a draft through the api and through mcp gives the
});
test('moving a scheduled post back to draft through the api and through mcp gives the same result', function () {
- $apiPost = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $mcpPost = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
+ $apiPost = Post::factory()->forAccount($this->account)->scheduled()->create(['user_id' => $this->user->id]);
+ $mcpPost = Post::factory()->forAccount($this->account)->scheduled()->create(['user_id' => $this->user->id]);
$this->withHeaders(parityApi($this->token))
->putJson(route('api.posts.update', $apiPost), ['status' => 'draft'])
@@ -182,8 +184,7 @@ test('a post from another workspace is not shown through the api nor through mcp
});
test('previewing a post returns the same payload through the api and through mcp', function () {
- $post = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Preview parity']);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']);
+ $post = Post::factory()->forAccount($this->account)->draft()->create(['user_id' => $this->user->id, 'content' => 'Preview parity']);
$api = $this->withHeaders(parityApi($this->token))
->getJson(route('api.posts.preview', $post))
@@ -194,7 +195,9 @@ test('previewing a post returns the same payload through the api and through mcp
->assertOk()
->assertStructuredContent($api);
- expect($api)->not->toBeEmpty();
+ expect($api)->toHaveKey('platform', Platform::LinkedIn->value)
+ ->toHaveKey('content_type', 'linkedin_post')
+ ->not->toHaveKey('platforms');
});
test('labels set through the api and through mcp end up on the post', function () {
@@ -227,7 +230,7 @@ test('listing posts: the api has no status filter while mcp filters by status',
->assertDontSee($published->id);
});
-test('deleting a publishing, published, partially published or failed post is refused with the web message on the api and mcp', function (Status $status) {
+test('deleting a publishing, published or failed post is refused with the web message on the api and mcp', function (Status $status) {
$post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'status' => $status]);
$message = __('posts.flash.cannot_delete_published');
@@ -243,11 +246,10 @@ test('deleting a publishing, published, partially published or failed post is re
->assertHasErrors([$message]);
expect(Post::query()->whereKey($post->id)->exists())->toBeTrue();
-})->with([Status::Publishing, Status::Published, Status::PartiallyPublished, Status::Failed]);
+})->with([Status::Publishing, Status::Published, Status::Failed]);
test('a channel disconnect still deletes published posts', function () {
- $post = Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->account->id, 'platform' => Platform::LinkedIn]);
+ $post = Post::factory()->forAccount($this->account)->published()->create(['user_id' => $this->user->id]);
DeleteChannelPosts::forAccount($this->account);
@@ -262,7 +264,8 @@ test('a member who requires approval scheduling through the single-post mcp crea
'content' => 'Member schedule',
'status' => 'scheduled',
'scheduled_at' => now()->addDays(2)->toIso8601String(),
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => 'linkedin_post',
])->assertOk();
$post = Post::query()->where('content', 'Member schedule')->sole();
@@ -276,7 +279,8 @@ test('a scheduled post over the account limit is refused with the same message b
'content' => str_repeat('a', 281),
'status' => 'scheduled',
'scheduled_at' => now()->addDays(2)->toIso8601String(),
- 'platforms' => [['social_account_id' => $this->second->id, 'content_type' => 'x_post']],
+ 'social_account_id' => $this->second->id,
+ 'content_type' => 'x_post',
];
$response = $this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
@@ -298,21 +302,20 @@ test('the shared post rules validate without a request or an authenticated user'
'content' => 'Rules only',
'status' => 'scheduled',
'queue' => 'next',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $account->id,
+ 'content_type' => 'linkedin_post',
];
$validate = fn (array $data) => Validator::make($data, PostRequestRules::store($this->workspace, $data), PostRequestRules::messages(), PostRequestRules::attributes());
expect(auth()->check())->toBeFalse()
->and($validate($input($this->account))->passes())->toBeTrue()
- ->and($validate($input($foreign))->errors()->keys())->toBe(['platforms.0.social_account_id']);
+ ->and($validate($input($foreign))->errors()->keys())->toBe(['social_account_id']);
});
test('publishing now through the api update and the mcp update tool gives the same result', function () {
Queue::fake();
- $apiPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Now']);
- $mcpPost = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => 'Now']);
- PostPlatform::factory()->linkedin()->create(['post_id' => $apiPost->id, 'social_account_id' => $this->account->id]);
- PostPlatform::factory()->linkedin()->create(['post_id' => $mcpPost->id, 'social_account_id' => $this->account->id]);
+ $apiPost = Post::factory()->forAccount($this->account)->draft()->create(['user_id' => $this->user->id, 'content' => 'Now']);
+ $mcpPost = Post::factory()->forAccount($this->account)->draft()->create(['user_id' => $this->user->id, 'content' => 'Now']);
$this->withHeaders(parityApi($this->token))->putJson(route('api.posts.update', $apiPost), ['status' => 'publishing'])->assertOk();
@@ -324,21 +327,21 @@ test('publishing now through the api update and the mcp update tool gives the sa
->and($mcpPost->fresh()->status)->toBe(Status::Publishing);
});
-test('an update naming a disabled destination is refused by the api and the mcp update tool', function () {
- $post = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $disabled = PostPlatform::factory()->linkedin()->create(['post_id' => $post->id, 'social_account_id' => $this->account->id, 'enabled' => false]);
- $payload = ['status' => 'draft', 'platforms' => [['id' => $disabled->id, 'content_type' => 'linkedin_post']]];
+test('an update sending the removed platforms input is refused with the same message by the api and the mcp update tool', function () {
+ $post = Post::factory()->forAccount($this->account)->draft()->create(['user_id' => $this->user->id, 'content' => 'Kept']);
+ $payload = ['status' => 'draft', 'content' => 'Changed', 'platforms' => [['social_account_id' => $this->second->id, 'content_type' => 'x_post']]];
$response = $this->withHeaders(parityApi($this->token))->putJson(route('api.posts.update', $post), $payload)
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.id']);
+ ->assertJsonValidationErrors(['platforms']);
auth()->forgetGuards();
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, ['post_id' => $post->id, ...$payload])
- ->assertHasErrors([$response->json('errors')['platforms.0.id'][0]]);
+ ->assertHasErrors([$response->json('errors.platforms.0')]);
- expect($disabled->fresh()->enabled)->toBeFalse();
+ expect($post->fresh()->content)->toBe('Kept')
+ ->and($post->fresh()->social_account_id)->toBe($this->account->id);
});
test('a deleted label is refused by the api create and the single-post mcp create tool', function () {
@@ -347,7 +350,8 @@ test('a deleted label is refused by the api create and the single-post mcp creat
$payload = [
'content' => 'Labelled',
'label_ids' => [$label->id],
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => 'linkedin_post']],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => 'linkedin_post',
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
@@ -362,9 +366,9 @@ test('a deleted label is refused by the api create and the single-post mcp creat
});
test('filtering posts by channel, label and untagged returns the same posts on the web publish list, the api and mcp', function () {
- $draft = function (SocialAccount $account, array $labels = [], bool $enabled = true): Post {
- $post = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => $account->platform, 'enabled' => $enabled]);
+ $draft = function (?SocialAccount $account, array $labels = []): Post {
+ $factory = $account === null ? Post::factory()->state(['workspace_id' => $this->workspace->id]) : Post::factory()->forAccount($account);
+ $post = $factory->draft()->create(['user_id' => $this->user->id]);
$post->labels()->attach($labels);
return $post;
@@ -378,7 +382,7 @@ test('filtering posts by channel, label and untagged returns the same posts on t
$second = $draft($this->account);
$third = $draft($this->second, [$promo->id]);
$fourth = $draft($this->second, [$launch->id, $promo->id]);
- $disabled = $draft($this->second, [], false);
+ $channelless = $draft(null);
$web = function (array $filters): array {
$ids = [];
@@ -395,15 +399,15 @@ test('filtering posts by channel, label and untagged returns the same posts on t
};
$cases = [
- 'no filter' => [[], [$first, $second, $third, $fourth, $disabled]],
+ 'no filter' => [[], [$first, $second, $third, $fourth, $channelless]],
'one channel' => [['channels' => [$this->account->id]], [$first, $second]],
'two channels' => [['channels' => [$this->account->id, $this->second->id]], [$first, $second, $third, $fourth]],
'a foreign channel' => [['channels' => [$foreignAccount->id]], []],
- 'a channel id that is not a uuid' => [['channels' => ['not-a-uuid']], [$first, $second, $third, $fourth, $disabled]],
+ 'a channel id that is not a uuid' => [['channels' => ['not-a-uuid']], [$first, $second, $third, $fourth, $channelless]],
'one label' => [['labels' => [$launch->id]], [$first, $fourth]],
'two labels' => [['labels' => [$launch->id, $promo->id]], [$first, $third, $fourth]],
- 'untagged' => [['untagged' => '1'], [$second, $disabled]],
- 'label or untagged' => [['labels' => [$promo->id], 'untagged' => '1'], [$second, $third, $fourth, $disabled]],
+ 'untagged' => [['untagged' => '1'], [$second, $channelless]],
+ 'label or untagged' => [['labels' => [$promo->id], 'untagged' => '1'], [$second, $third, $fourth, $channelless]],
'a foreign label' => [['labels' => [$foreignLabel->id]], []],
'channel and label' => [['channels' => [$this->second->id], 'labels' => [$launch->id]], [$fourth]],
];
@@ -477,8 +481,7 @@ test('the api and mcp post lists page by the configured size in the same order',
$account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Bluesky]);
foreach (range(0, 2) as $minutes) {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'status' => Status::Draft, 'scheduled_at' => now()->addDays(10)->subMinutes($minutes)]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
+ Post::factory()->forAccount($account)->create(['user_id' => $this->user->id, 'status' => Status::Draft, 'scheduled_at' => now()->addDays(10)->subMinutes($minutes)]);
}
$first = $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.index', ['per_page' => 50]))->assertOk()->assertJsonCount(2, 'data')->assertJsonPath('meta.per_page', 2)->assertJsonPath('meta.total', 3);
diff --git a/tests/Feature/Parity/SchedulingParityTest.php b/tests/Feature/Parity/SchedulingParityTest.php
index b6bf968e5..0bb06cad9 100644
--- a/tests/Feature/Parity/SchedulingParityTest.php
+++ b/tests/Feature/Parity/SchedulingParityTest.php
@@ -9,6 +9,7 @@ use App\Actions\Post\UpdatePostRecurrence;
use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Http\Resources\App\ChannelPostingScheduleResource;
use App\Mcp\Servers\TryPostServer;
@@ -48,15 +49,7 @@ function schedulingParitySnapshot(Post $post): array
function schedulingParityDraft(SocialAccount $account, string $workspaceId, string $userId): Post
{
- $post = Post::factory()->draft()->create(['workspace_id' => $workspaceId, 'user_id' => $userId, 'content' => 'Parity draft']);
- $post->postPlatforms()->create([
- 'social_account_id' => $account->id,
- 'platform' => $account->platform->value,
- 'content_type' => 'linkedin_post',
- 'enabled' => true,
- ]);
-
- return $post;
+ return Post::factory()->forAccount($account, ContentType::LinkedInPost)->draft()->create(['workspace_id' => $workspaceId, 'user_id' => $userId, 'content' => 'Parity draft']);
}
beforeEach(function () {
@@ -77,7 +70,7 @@ test('queue next through the api and the mcp batch tool takes the first two free
'content' => 'From the API',
'status' => 'scheduled',
'queue' => 'next',
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, [
@@ -100,14 +93,14 @@ test('queue top through the api and the mcp batch tool puts the new post first',
'content' => 'Next from the API',
'status' => 'scheduled',
'queue' => 'next',
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), [
'content' => 'Top from the API',
'status' => 'scheduled',
'queue' => 'top',
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, [
@@ -130,7 +123,7 @@ test('a custom time scheduled through the api and the mcp batch tool is stored t
'content' => 'Custom time',
'status' => 'scheduled',
'scheduled_at' => $when->toIso8601String(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, [
@@ -154,14 +147,14 @@ test('the single-post mcp create tool queues next like the api', function () {
'content' => 'Queued via API',
'status' => 'scheduled',
'queue' => 'next',
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Queued via MCP',
'status' => 'scheduled',
'queue' => 'next',
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertOk();
$viaApi = Post::query()->where('content', 'Queued via API')->sole();
@@ -180,14 +173,14 @@ test('a custom time scheduled through the api and the single-post mcp create too
'content' => 'Custom via API',
'status' => 'scheduled',
'scheduled_at' => $when->toIso8601String(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, [
'content' => 'Custom via MCP',
'status' => 'scheduled',
'scheduled_at' => $when->toIso8601String(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertOk();
$viaApi = Post::query()->where('content', 'Custom via API')->sole();
@@ -205,7 +198,7 @@ test('queue with a custom time is refused with the same message by the api and t
'status' => 'scheduled',
'queue' => 'next',
'scheduled_at' => Carbon::now()->addDays(3)->toIso8601String(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
@@ -293,7 +286,7 @@ test('queue_slot stores a queue post in that free slot on the api and the mcp to
'content' => 'Slot via API',
'status' => 'scheduled',
'queue_slot' => $slots[2],
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertCreated();
auth()->forgetGuards();
@@ -301,7 +294,7 @@ test('queue_slot stores a queue post in that free slot on the api and the mcp to
'content' => 'Slot via MCP',
'status' => 'scheduled',
'queue_slot' => $slots[4],
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertOk();
$posts = Post::query()->where('workspace_id', $this->workspace->id)->orderBy('scheduled_at')->get();
@@ -313,7 +306,7 @@ test('queue_slot stores a queue post in that free slot on the api and the mcp to
test('queue_slot on a slot already taken is refused with the web message on the api and the mcp tool', function () {
$slot = $this->withHeaders(parityApi($this->token))->getJson(route('api.channels.queue.slots', $this->account))->assertOk()->json('slots.1');
- $payload = ['content' => 'Slot', 'status' => 'scheduled', 'queue_slot' => $slot, 'platforms' => [$this->destination]];
+ $payload = ['content' => 'Slot', 'status' => 'scheduled', 'queue_slot' => $slot, ...$this->destination];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)->assertCreated();
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
@@ -331,7 +324,7 @@ test('queue_slot at an instant that is not a free slot is refused', function ()
'content' => 'Off schedule',
'status' => 'scheduled',
'queue_slot' => now()->addDays(3)->startOfDay()->addHours(11)->toIso8601ZuluString(),
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertUnprocessable()->assertJsonValidationErrors(['queue_slot']);
expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(0);
@@ -341,10 +334,10 @@ test('queue_slot is refused with queue or without status scheduled', function ()
$slot = $this->withHeaders(parityApi($this->token))->getJson(route('api.channels.queue.slots', $this->account))->assertOk()->json('slots.0');
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), [
- 'status' => 'scheduled', 'queue' => 'next', 'queue_slot' => $slot, 'platforms' => [$this->destination],
+ 'status' => 'scheduled', 'queue' => 'next', 'queue_slot' => $slot, ...$this->destination,
])->assertUnprocessable()->assertJsonValidationErrors(['queue_slot']);
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), [
- 'status' => 'draft', 'queue_slot' => $slot, 'platforms' => [$this->destination],
+ 'status' => 'draft', 'queue_slot' => $slot, ...$this->destination,
])->assertUnprocessable()->assertJsonValidationErrors(['queue_slot']);
});
@@ -357,7 +350,7 @@ test('a member who needs approval creating at a queue_slot holds the slot as a p
'content' => 'Needs approval',
'status' => 'scheduled',
'queue_slot' => $slot,
- 'platforms' => [$this->destination],
+ ...$this->destination,
])->assertOk();
$post = Post::query()->where('workspace_id', $this->workspace->id)->sole();
diff --git a/tests/Feature/Parity/ThreadReplyMediaUrlParityTest.php b/tests/Feature/Parity/ThreadReplyMediaUrlParityTest.php
index b95374053..0e2c185e3 100644
--- a/tests/Feature/Parity/ThreadReplyMediaUrlParityTest.php
+++ b/tests/Feature/Parity/ThreadReplyMediaUrlParityTest.php
@@ -9,7 +9,6 @@ use App\Mcp\Tools\Post\CreatePostsTool;
use App\Mcp\Tools\Post\CreatePostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
@@ -30,30 +29,32 @@ function threadReplyUrlMeta(string $url = 'https://example.com/reply.png'): arra
return ['thread_replies' => [['text' => 'Second', 'media' => [['url' => $url]]]]];
}
-function threadReplyStoredMedia(PostPlatform $target): array
+function threadReplyStoredMedia(Post $post): array
{
- return data_get($target->fresh()->meta, 'thread_replies.0.media', []);
+ return data_get($post->fresh()->meta, 'thread_replies.0.media', []);
}
test('a reply media url is hosted on create through api and mcp', function () {
$payload = [
'content' => 'First',
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => ContentType::BlueskyPost->value, 'meta' => threadReplyUrlMeta()]],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => threadReplyUrlMeta(),
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertOk();
- $targets = PostPlatform::query()->with('post')->where('social_account_id', $this->account->id)->get();
+ $posts = Post::query()->where('social_account_id', $this->account->id)->get();
- expect($targets)->toHaveCount(2);
+ expect($posts)->toHaveCount(2);
- foreach ($targets as $target) {
- $media = threadReplyStoredMedia($target);
+ foreach ($posts as $post) {
+ $media = threadReplyStoredMedia($post);
expect($media)->toHaveCount(1)
->and(data_get($media, '0.type'))->toBe('image')
- ->and($target->post->ownedMedia()->count())->toBe(1);
+ ->and($post->ownedMedia()->count())->toBe(1);
}
});
@@ -67,7 +68,7 @@ test('a reply media url is hosted in a batch through api and mcp', function () {
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.batch.store'), $payload)->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, $payload)->assertOk();
- $targets = PostPlatform::query()->where('social_account_id', $this->account->id)->get();
+ $targets = Post::query()->where('social_account_id', $this->account->id)->get();
expect($targets)->toHaveCount(2)
->and(threadReplyStoredMedia($targets[0]))->toHaveCount(1)
@@ -76,34 +77,27 @@ test('a reply media url is hosted in a batch through api and mcp', function () {
test('a reply media url is hosted on update through api and mcp', function () {
$posts = collect([0, 1])->map(function (): Post {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->account->id,
- 'platform' => Platform::Bluesky,
- 'content_type' => ContentType::BlueskyPost,
- 'enabled' => true,
- ]);
-
- return $post;
+ return Post::factory()->forAccount($this->account, ContentType::BlueskyPost)->create(['user_id' => $this->user->id]);
});
$this->withHeaders(parityApi($this->token))->putJson(route('api.posts.update', $posts[0]), ['meta' => threadReplyUrlMeta()])->assertOk();
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, ['post_id' => $posts[1]->id, 'meta' => threadReplyUrlMeta()])->assertOk();
foreach ($posts as $post) {
- expect(threadReplyStoredMedia($post->postPlatforms()->sole()))->toHaveCount(1);
+ expect(threadReplyStoredMedia($post))->toHaveCount(1);
}
});
test('an unreachable reply media url is refused instead of dropped through api and mcp', function () {
$payload = [
'content' => 'First',
- 'platforms' => [['social_account_id' => $this->account->id, 'content_type' => ContentType::BlueskyPost->value, 'meta' => threadReplyUrlMeta('https://example.com/missing.png')]],
+ 'social_account_id' => $this->account->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => threadReplyUrlMeta('https://example.com/missing.png'),
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
- ->assertJsonValidationErrors(['platforms.0.meta.thread_replies.0.media.0.url']);
+ ->assertJsonValidationErrors(['meta.thread_replies.0.media.0.url']);
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertHasErrors();
expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(0);
diff --git a/tests/Feature/Parity/ThreadsParityTest.php b/tests/Feature/Parity/ThreadsParityTest.php
index 1042193c6..035af6c0d 100644
--- a/tests/Feature/Parity/ThreadsParityTest.php
+++ b/tests/Feature/Parity/ThreadsParityTest.php
@@ -12,7 +12,6 @@ use App\Mcp\Tools\Post\GetPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Storage;
@@ -50,14 +49,16 @@ test('thread replies sent as strings are stored as text objects through api and
$payload = [
'content' => 'First post',
'status' => 'draft',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::BlueskyPost->value, 'meta' => ['thread_replies' => ['Second post']]]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::BlueskyPost->value,
+ 'meta' => ['thread_replies' => ['Second post']],
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertOk();
- $replies = PostPlatform::query()->where('social_account_id', $account->id)->get()
- ->map(fn (PostPlatform $platform) => data_get($platform->meta, 'thread_replies'));
+ $replies = Post::query()->where('social_account_id', $account->id)->get()
+ ->map(fn (Post $post) => data_get($post->meta, 'thread_replies'));
expect($replies)->toHaveCount(2)
->and($replies[0])->toEqual($replies[1])
@@ -84,11 +85,11 @@ test('a scheduled thread with text replies is stored the same way on every threa
'destinations' => [['social_account_id' => $account->id, 'content_type' => $contentType, 'meta' => ['thread_replies' => $replies]]],
])->assertOk();
- $stored = PostPlatform::query()->with('post')->where('social_account_id', $account->id)->get();
+ $stored = Post::query()->where('social_account_id', $account->id)->get();
expect($stored)->toHaveCount(2)
- ->and($stored[0]->post->status)->toBe(Status::Scheduled)
- ->and($stored[1]->post->status)->toBe(Status::Scheduled)
+ ->and($stored[0]->status)->toBe(Status::Scheduled)
+ ->and($stored[1]->status)->toBe(Status::Scheduled)
->and($stored[0]->meta['thread_replies'])->toEqual($stored[1]->meta['thread_replies'])
->and($stored[0]->meta['thread_replies'])->toEqual([['text' => 'Two', 'media' => []], ['text' => 'Three', 'media' => []]]);
})->with('thread networks');
@@ -100,20 +101,22 @@ test('a reply keeps its own media owned by the post through api and mcp', functi
$payload = fn (Media $upload): array => [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::XPost->value, 'meta' => ['thread_replies' => [
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => [
['text' => 'Two', 'media' => [['upload_token' => $upload->upload_token]]],
- ]]]],
+ ]],
];
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload($apiUpload))->assertCreated();
TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload($mcpUpload))->assertOk();
foreach ([$apiUpload, $mcpUpload] as $upload) {
- $platform = PostPlatform::query()->with('post')->where('social_account_id', $account->id)->whereHas('post.ownedMedia', fn ($query) => $query->whereKey($upload->id))->sole();
+ $post = Post::query()->where('social_account_id', $account->id)->whereHas('ownedMedia', fn ($query) => $query->whereKey($upload->id))->sole();
- expect($platform->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id)
- ->and($upload->fresh()->post_id)->toBe($platform->post_id)
- ->and($platform->post->media)->toBe([]);
+ expect($post->meta['thread_replies'][0]['media'][0]['id'])->toBe($upload->id)
+ ->and($upload->fresh()->post_id)->toBe($post->id)
+ ->and($post->media)->toBe([]);
}
});
@@ -178,31 +181,29 @@ test('more than 24 replies are rejected on the single create path through api an
$account = threadsParityPlatform(Platform::Mastodon);
$payload = [
'content' => 'Root',
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::MastodonPost->value, 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')]]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::MastodonPost->value,
+ 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')],
];
- $this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
- ->assertUnprocessable()->assertJsonValidationErrors(['platforms.0.meta.thread_replies']);
- TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertHasErrors([__('validation.max.array', ['attribute' => 'platforms.0.meta.thread_replies', 'max' => 24])]);
+ $response = $this->withHeaders(parityApi($this->token))->postJson(route('api.posts.store'), $payload)
+ ->assertUnprocessable()->assertJsonValidationErrors(['meta.thread_replies']);
+ TryPostServer::actingAs($this->user)->tool(CreatePostTool::class, $payload)->assertHasErrors([$response->json('errors')['meta.thread_replies'][0]]);
expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(0);
});
test('thread replies read back as text and media objects through api and mcp', function () {
$account = threadsParityPlatform(Platform::Bluesky);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'status' => Status::Draft]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Bluesky,
- 'content_type' => ContentType::BlueskyPost,
- 'enabled' => true,
+ $post = Post::factory()->forAccount($account, ContentType::BlueskyPost)->create([
+ 'user_id' => $this->user->id,
+ 'status' => Status::Draft,
'meta' => ['thread_replies' => [['text' => 'Two', 'media' => []]]],
]);
- $api = $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.show', $post))->assertOk()->json('platforms.0.meta.thread_replies');
+ $api = $this->withHeaders(parityApi($this->token))->getJson(route('api.posts.show', $post))->assertOk()->json('meta.thread_replies');
TryPostServer::actingAs($this->user)->tool(GetPostTool::class, ['post_id' => $post->id])
- ->assertOk()->assertStructuredContent(fn ($json) => $json->where('platforms.0.meta.thread_replies', $api)->etc());
+ ->assertOk()->assertStructuredContent(fn ($json) => $json->where('meta.thread_replies', $api)->etc());
expect($api)->toEqual([['text' => 'Two', 'media' => []]]);
});
@@ -217,11 +218,11 @@ test('the batch path rejects 25 replies through api and mcp', function () {
$this->withHeaders(parityApi($this->token))->postJson(route('api.posts.batch.store'), $payload)
->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.meta.thread_replies']);
- expect(PostPlatform::query()->where('social_account_id', $account->id)->count())->toBe(0);
+ expect(Post::query()->where('social_account_id', $account->id)->count())->toBe(0);
TryPostServer::actingAs($this->user)->tool(CreatePostsTool::class, $payload)->assertHasErrors([__('validation.max.array', ['attribute' => 'destinations.0.meta.thread_replies', 'max' => 24])]);
- expect(PostPlatform::query()->where('social_account_id', $account->id)->count())->toBe(0);
+ expect(Post::query()->where('social_account_id', $account->id)->count())->toBe(0);
});
test('scheduling replies on a network that cannot chain is rejected through api and mcp', function () {
@@ -246,22 +247,19 @@ test('scheduling replies on a network that cannot chain is rejected through api
])->assertHasErrors([$message]);
});
-function threadsParityDraft(SocialAccount $account, string $contentType): array
+function threadsParityDraft(SocialAccount $account, string $contentType): Post
{
- $post = Post::factory()->draft()->create(['workspace_id' => test()->workspace->id, 'user_id' => test()->user->id, 'content' => 'Root']);
- $platform = PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => $account->platform, 'content_type' => $contentType, 'meta' => []]);
-
- return [$post, $platform];
+ return Post::factory()->forAccount($account, ContentType::from($contentType))->draft()->create(['user_id' => test()->user->id, 'content' => 'Root', 'meta' => []]);
}
test('updating replies on an existing post stores them the same way through api and mcp', function () {
$account = threadsParityPlatform(Platform::Bluesky);
- [$apiPost, $apiPlatform] = threadsParityDraft($account, ContentType::BlueskyPost->value);
- [$mcpPost] = threadsParityDraft($account, ContentType::BlueskyPost->value);
+ $apiPost = threadsParityDraft($account, ContentType::BlueskyPost->value);
+ $mcpPost = threadsParityDraft($account, ContentType::BlueskyPost->value);
$replies = ['Two', ['text' => 'Three']];
$this->withHeaders(parityApi($this->token))
- ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'platforms' => [['id' => $apiPlatform->id, 'meta' => ['thread_replies' => $replies]]]])
+ ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'meta' => ['thread_replies' => $replies]])
->assertOk();
auth()->forgetGuards();
@@ -270,21 +268,21 @@ test('updating replies on an existing post stores them the same way through api
->tool(UpdatePostTool::class, ['post_id' => $mcpPost->id, 'meta' => ['thread_replies' => $replies]])
->assertOk();
- expect($apiPost->postPlatforms()->sole()->meta['thread_replies'])
- ->toEqual($mcpPost->postPlatforms()->sole()->meta['thread_replies'])
+ expect($apiPost->fresh()->meta['thread_replies'])
+ ->toEqual($mcpPost->fresh()->meta['thread_replies'])
->toEqual([['text' => 'Two', 'media' => []], ['text' => 'Three', 'media' => []]]);
});
test('updating a post with more than 24 replies is refused with the same message through api and mcp', function () {
$account = threadsParityPlatform(Platform::Mastodon);
- [$apiPost, $apiPlatform] = threadsParityDraft($account, ContentType::MastodonPost->value);
- [$mcpPost] = threadsParityDraft($account, ContentType::MastodonPost->value);
- $message = __('validation.max.array', ['attribute' => 'platforms.0.meta.thread_replies', 'max' => 24]);
+ $apiPost = threadsParityDraft($account, ContentType::MastodonPost->value);
+ $mcpPost = threadsParityDraft($account, ContentType::MastodonPost->value);
- $this->withHeaders(parityApi($this->token))
- ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'platforms' => [['id' => $apiPlatform->id, 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')]]]])
+ $message = $this->withHeaders(parityApi($this->token))
+ ->putJson(route('api.posts.update', $apiPost), ['status' => 'draft', 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')]])
->assertUnprocessable()
- ->assertJsonValidationErrors(['platforms.0.meta.thread_replies' => $message]);
+ ->assertJsonValidationErrors(['meta.thread_replies'])
+ ->json('errors')['meta.thread_replies'][0];
auth()->forgetGuards();
@@ -292,6 +290,6 @@ test('updating a post with more than 24 replies is refused with the same message
->tool(UpdatePostTool::class, ['post_id' => $mcpPost->id, 'meta' => ['thread_replies' => array_fill(0, 25, 'Reply')]])
->assertHasErrors([$message]);
- expect($apiPost->postPlatforms()->sole()->meta)->toBe([])
- ->and($mcpPost->postPlatforms()->sole()->meta)->toBe([]);
+ expect($apiPost->fresh()->meta)->toBe([])
+ ->and($mcpPost->fresh()->meta)->toBe([]);
});
diff --git a/tests/Feature/Permissions/WorkspaceRolePermissionsTest.php b/tests/Feature/Permissions/WorkspaceRolePermissionsTest.php
index 6aeb65f7c..9572af79e 100644
--- a/tests/Feature/Permissions/WorkspaceRolePermissionsTest.php
+++ b/tests/Feature/Permissions/WorkspaceRolePermissionsTest.php
@@ -95,7 +95,7 @@ test('only admins and above can open the connections screen', function (string $
'requester' => ['requester', false],
]);
-test('opening the dialog does not create platform rows for a member who needs approval', function () {
+test('opening the dialog does not assign a channel for a member who needs approval', function () {
SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]);
@@ -104,10 +104,10 @@ test('opening the dialog does not create platform rows for a member who needs ap
->get(route('app.posts.edit', $this->post))
->assertRedirect(route('app.posts.index', ['edit' => $this->post->id]));
- expect($this->post->postPlatforms()->count())->toBe(0);
+ expect($this->post->fresh()->social_account_id)->toBeNull();
});
-test('opening the dialog does not create platform rows for a member', function () {
+test('opening the dialog does not assign a channel for a member', function () {
SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]);
@@ -116,7 +116,7 @@ test('opening the dialog does not create platform rows for a member', function (
->get(route('app.posts.edit', $this->post))
->assertRedirect(route('app.posts.index', ['edit' => $this->post->id]));
- expect($this->post->postPlatforms()->count())->toBe(0);
+ expect($this->post->fresh()->social_account_id)->toBeNull();
});
test('a member without connected accounts is redirected away from the admin-only accounts screen when creating a post', function () {
diff --git a/tests/Feature/PostControllerTest.php b/tests/Feature/PostControllerTest.php
index 5eadabf34..65d0af24f 100644
--- a/tests/Feature/PostControllerTest.php
+++ b/tests/Feature/PostControllerTest.php
@@ -2,21 +2,16 @@
declare(strict_types=1);
-use App\Enums\Analytics\PublicationContentType;
use App\Enums\Post\CreatedVia;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status;
use App\Enums\SocialAccount\Platform;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\PublishPost;
-use App\Models\AnalyticsPublication;
-use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
use App\Models\PostNote;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -25,7 +20,6 @@ use App\Support\LinkTlds;
use App\Support\PostingSchedule;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Bus;
-use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Route;
@@ -212,28 +206,17 @@ test('posts index exposes each workspace channel separately for filtering', func
->where('filters.channels', []));
});
-test('posts index filters individual accounts and only displays selected targets', function () {
+test('posts index filters individual accounts', function () {
$firstInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$secondInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $sharedPost = Post::factory()->published()->create([
- 'workspace_id' => $this->workspace->id,
+ $sharedPost = Post::factory()->forAccount($firstInstagram)->instagram()->published()->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $sharedPost->id,
- 'social_account_id' => $firstInstagram->id,
- ]);
- PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $sharedPost->id,
- 'social_account_id' => $secondInstagram->id,
- ]);
- $otherPost = Post::factory()->draft()->create([
- 'workspace_id' => $this->workspace->id,
+ Post::factory()->forAccount($secondInstagram)->instagram()->published()->create([
'user_id' => $this->user->id,
]);
- PostPlatform::factory()->instagram()->create([
- 'post_id' => $otherPost->id,
- 'social_account_id' => $secondInstagram->id,
+ Post::factory()->forAccount($secondInstagram)->instagram()->draft()->create([
+ 'user_id' => $this->user->id,
]);
$this->actingAs($this->user)
@@ -245,19 +228,16 @@ test('posts index filters individual accounts and only displays selected targets
->loadDeferredProps(fn ($reload) => $reload
->has('posts.data', 1)
->where('posts.data.0.id', $sharedPost->id)
- ->has('posts.data.0.post_platforms', 1)
- ->where('posts.data.0.post_platforms.0.social_account_id', $firstInstagram->id)));
+ ->where('posts.data.0.social_account_id', $firstInstagram->id)));
});
-test('posts index combines selected channels with OR semantics and ignores disabled targets', function () {
+test('posts index combines selected channels with OR semantics', function () {
$firstInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$secondInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $firstPost = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $secondPost = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $disabledPost = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->instagram()->create(['post_id' => $firstPost->id, 'social_account_id' => $firstInstagram->id]);
- PostPlatform::factory()->instagram()->create(['post_id' => $secondPost->id, 'social_account_id' => $secondInstagram->id]);
- PostPlatform::factory()->instagram()->disabled()->create(['post_id' => $disabledPost->id, 'social_account_id' => $firstInstagram->id]);
+ $thirdInstagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
+ Post::factory()->forAccount($firstInstagram)->instagram()->create(['user_id' => $this->user->id]);
+ Post::factory()->forAccount($secondInstagram)->instagram()->create(['user_id' => $this->user->id]);
+ Post::factory()->forAccount($thirdInstagram)->instagram()->create(['user_id' => $this->user->id]);
$this->actingAs($this->user)
->get(route('app.posts.index', ['channels' => [$firstInstagram->id, $secondInstagram->id], 'tab' => 'drafts']))
@@ -271,8 +251,7 @@ test('posts index combines selected channels with OR semantics and ignores disab
test('posts index does not accept a channel from another workspace', function () {
$otherAccount = SocialAccount::factory()->instagram()->create();
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->socialAccount->id]);
+ Post::factory()->forAccount($this->socialAccount)->create(['user_id' => $this->user->id]);
$this->actingAs($this->user)
->get(route('app.posts.index', ['tab' => 'drafts', 'channels' => [$otherAccount->id]]))
@@ -463,14 +442,13 @@ test('composer data tells whether each channel has posting times', function () {
});
test('posts list and calendar expose the schedule mode', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
'scheduled_at' => now()->addDay(),
'schedule_mode' => ScheduleMode::Queue,
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->socialAccount->id]);
$this->actingAs($this->user)
->get(route('app.posts.index'))
@@ -527,14 +505,14 @@ test('store post creates one independent draft per selected account', function (
])->all(),
])->assertRedirect(route('app.posts.index', ['tab' => 'drafts']));
- $posts = Post::where('workspace_id', $this->workspace->id)->with('postPlatforms')->get();
+ $posts = Post::where('workspace_id', $this->workspace->id)->get();
expect($posts)->toHaveCount(4);
foreach ($posts as $post) {
expect($post->status)->toBe(PostStatus::Draft)
->and($post->content)->toBe('Shared caption')
->and($post->created_via)->toBe(CreatedVia::Web)
->and($post->scheduled_at)->toBeNull()
- ->and($post->postPlatforms)->toHaveCount(1);
+ ->and($post->social_account_id)->not->toBeNull();
}
});
@@ -588,6 +566,25 @@ test('saving a zero-target legacy draft creates independent posts and removes th
->and(Post::where('workspace_id', $this->workspace->id)->where('content', 'Recovered caption')->count())->toBe(2);
});
+test('a draft whose channel is gone opens in the composer and is recovered onto a new channel', function () {
+ $orphaned = Post::factory()->forAccount($this->socialAccount)->create(['user_id' => $this->user->id, 'status' => PostStatus::Draft, 'content' => 'Lost channel']);
+ $orphaned->forceFill(['social_account_id' => null])->save();
+
+ $this->actingAs($this->user)->get(route('app.posts.edit', $orphaned))
+ ->assertRedirect(route('app.posts.index', ['edit' => $orphaned->id]));
+
+ $this->actingAs($this->user)->post(route('app.posts.store'), [
+ 'recover_post_id' => $orphaned->id,
+ 'status' => 'draft',
+ 'content' => 'Lost channel',
+ 'media' => [],
+ 'destinations' => [['social_account_id' => $this->socialAccount->id, 'content_type' => ContentType::LinkedInPost->value, 'meta' => []]],
+ ])->assertSessionHasNoErrors();
+
+ expect(Post::find($orphaned->id))->toBeNull()
+ ->and(Post::where('workspace_id', $this->workspace->id)->where('content', 'Lost channel')->sole()->social_account_id)->toBe($this->socialAccount->id);
+});
+
test('store post rejects invalid schedule format', function () {
$this->actingAs($this->user)
->post(route('app.posts.store'), ['status' => 'scheduled', 'scheduled_at' => 'not-a-date', 'destinations' => [[
@@ -612,17 +609,12 @@ test('edit post requires authentication', function () {
});
test('edit post opens its account in the composer', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->get(route('app.posts.edit', $post));
$response->assertRedirect(route('app.posts.index', ['edit' => $post->id]));
@@ -636,16 +628,14 @@ test('edit post opens its account in the composer', function () {
);
});
-test('edit does not open the composer for a single target without a social account', function () {
+test('edit does not open the composer for a scheduled post whose channel is gone', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => null,
+ 'status' => PostStatus::Scheduled,
+ 'scheduled_at' => now()->addDay(),
+ 'platform' => Platform::LinkedIn,
+ 'content_type' => ContentType::LinkedInPost,
]);
$this->actingAs($this->user)
@@ -654,18 +644,13 @@ test('edit does not open the composer for a single target without a social accou
});
test('edit exposes null scheduled_at for an unscheduled draft', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => null,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)
->get(route('app.posts.index', ['edit' => $post->id]))
->assertOk()
@@ -688,18 +673,13 @@ test('edit post returns 404 for post from different workspace', function () {
});
test('edit redirects to the post details for non-editable statuses', function () {
- foreach ([PostStatus::Published, PostStatus::PartiallyPublished, PostStatus::Publishing, PostStatus::Failed] as $status) {
- $post = Post::factory()->create([
+ foreach ([PostStatus::Published, PostStatus::Publishing, PostStatus::Failed] as $status) {
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => $status,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)
->get(route('app.posts.edit', $post))
->assertRedirect(route('app.posts.index', ['post' => $post->id]));
@@ -708,17 +688,12 @@ test('edit redirects to the post details for non-editable statuses', function ()
test('edit allows draft and scheduled posts', function () {
foreach ([PostStatus::Draft, PostStatus::Scheduled] as $status) {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => $status,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)
->get(route('app.posts.edit', $post))
->assertRedirect(route('app.posts.index', ['edit' => $post->id]));
@@ -726,17 +701,12 @@ test('edit allows draft and scheduled posts', function () {
});
test('edit opens the note an email links to and ignores the old comments tab', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)
->get(route('app.posts.edit', ['post' => $post, 'comment' => 'note-id']))
->assertRedirect(route('app.posts.index', ['notes' => $post->id, 'note' => 'note-id']));
@@ -759,58 +729,38 @@ test('update post requires authentication', function () {
});
test('update post saves changes', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Original content',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Updated content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect();
$post->refresh();
expect($post->content)->toBe('Updated content');
- $postPlatform->refresh();
- expect($postPlatform->content_type)->toBe(ContentType::LinkedInPost);
+ $post->refresh();
+ expect($post->content_type)->toBe(ContentType::LinkedInPost);
});
test('update post cannot update published posts', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Published,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect();
@@ -819,26 +769,16 @@ test('update post cannot update published posts', function () {
test('cannot re-publish a failed post', function () {
Bus::fake();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Failed,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'publishing',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect();
@@ -852,26 +792,16 @@ test('cannot re-publish a failed post', function () {
test('cannot update a post in publishing state', function () {
Bus::fake();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Publishing,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect();
@@ -882,62 +812,19 @@ test('cannot update a post in publishing state', function () {
Bus::assertNotDispatched(PublishPost::class);
});
-test('cannot update a partially published post', function () {
- Bus::fake();
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::PartiallyPublished,
- ]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
- $response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
- 'status' => 'publishing',
- 'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
- ]);
-
- $response->assertRedirect();
- $response->assertSessionHas('flash.bannerStyle', 'danger');
-
- $post->refresh();
- expect($post->status)->toBe(PostStatus::PartiallyPublished);
- Bus::assertNotDispatched(PublishPost::class);
-});
-
test('cannot update a published post', function () {
Bus::fake();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Published,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'publishing',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect();
@@ -952,7 +839,7 @@ test('publish now updates scheduled_at to current time', function () {
Mail::fake();
$this->freezeTime();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -960,20 +847,10 @@ test('publish now updates scheduled_at to current time', function () {
'scheduled_at' => now()->addDays(7),
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'publishing',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect(route('app.posts.index', ['tab' => 'queue']));
@@ -986,7 +863,7 @@ test('publish now is allowed when the draft has no scheduled_at', function () {
Bus::fake();
$this->freezeTime();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -994,20 +871,10 @@ test('publish now is allowed when the draft has no scheduled_at', function () {
'scheduled_at' => null,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'publishing',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertRedirect();
$post->refresh();
@@ -1017,7 +884,7 @@ test('publish now is allowed when the draft has no scheduled_at', function () {
});
test('update rejects scheduled status without a future scheduled_at', function (?string $existingScheduledAt) {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -1025,20 +892,10 @@ test('update rejects scheduled status without a future scheduled_at', function (
'content' => 'Test content',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$payload = [
'status' => 'scheduled',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
];
$this->actingAs($this->user)
@@ -1061,7 +918,7 @@ test('update rejects scheduled status without a future scheduled_at', function (
test('update accepts scheduled status reusing an existing future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -1069,20 +926,10 @@ test('update accepts scheduled status reusing an existing future scheduled_at',
'content' => 'Test content',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'scheduled',
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertRedirect();
$post->refresh();
@@ -1093,7 +940,7 @@ test('update accepts scheduled status reusing an existing future scheduled_at',
test('update schedules an unscheduled draft with an explicit future scheduled_at', function () {
$scheduledAt = now()->addDay()->startOfSecond();
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -1101,21 +948,11 @@ test('update schedules an unscheduled draft with an explicit future scheduled_at
'content' => 'Test content',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'scheduled',
'scheduled_at' => $scheduledAt->toIso8601String(),
'content' => 'Test content',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertRedirect();
$post->refresh();
@@ -1124,7 +961,7 @@ test('update schedules an unscheduled draft with an explicit future scheduled_at
});
test('update keeps an unscheduled draft when saving as draft without scheduled_at', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
@@ -1132,20 +969,10 @@ test('update keeps an unscheduled draft when saving as draft without scheduled_a
'content' => 'Original',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Still a draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
])->assertRedirect();
$post->refresh();
@@ -1182,7 +1009,6 @@ test('destroy keeps a post that already went out or failed', function (PostStatu
})->with([
'publishing' => [PostStatus::Publishing],
'published' => [PostStatus::Published],
- 'partially published' => [PostStatus::PartiallyPublished],
'failed' => [PostStatus::Failed],
]);
@@ -1239,17 +1065,12 @@ test('destroy post returns 404 for post from different workspace', function () {
// Label tests
test('edit post includes workspace labels', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
'name' => 'Marketing',
@@ -1267,29 +1088,19 @@ test('edit post includes workspace labels', function () {
});
test('update post can attach labels', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
]);
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
'label_ids' => [$label->id],
]);
@@ -1301,17 +1112,12 @@ test('update post can attach labels', function () {
});
test('update post can detach labels', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$label = WorkspaceLabel::factory()->create([
'workspace_id' => $this->workspace->id,
]);
@@ -1320,12 +1126,7 @@ test('update post can detach labels', function () {
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
'label_ids' => [],
]);
@@ -1336,17 +1137,12 @@ test('update post can detach labels', function () {
});
test('update post can sync multiple labels', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$label1 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$label2 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$label3 = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
@@ -1357,12 +1153,7 @@ test('update post can sync multiple labels', function () {
// Update with different labels
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
'label_ids' => [$label2->id, $label3->id],
]);
@@ -1373,233 +1164,16 @@ test('update post can sync multiple labels', function () {
expect($post->labels->pluck('id')->toArray())->toEqualCanonicalizing([$label2->id, $label3->id]);
});
-test('platform metrics returns unsupported when post not published', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
-
- $pp = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => Status::Pending,
- ]);
-
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]));
-
- $response->assertOk();
- $response->assertJson(['unsupported' => true, 'reason' => 'not_published']);
-});
-
-test('platform metrics returns 404 for post in another workspace', function () {
- $otherWorkspace = Workspace::factory()->create();
- $otherPost = Post::factory()->create(['workspace_id' => $otherWorkspace->id]);
- $pp = PostPlatform::factory()->create([
- 'post_id' => $otherPost->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
- $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $otherPost->id, 'postPlatform' => $pp->id]))
- ->assertNotFound();
-});
-
-test('platform metrics returns 404 when post platform belongs to different post', function () {
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $otherPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $pp = PostPlatform::factory()->create([
- 'post_id' => $otherPost->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
- $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]))
- ->assertNotFound();
-});
-
-test('platform metrics reads persisted X analytics without a provider request', function () {
- $xAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::X,
- ]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $pp = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $xAccount->id,
- 'platform' => Platform::X,
- 'status' => Status::Published,
- 'platform_post_id' => '1234567890',
- ]);
-
- $publication = AnalyticsPublication::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'social_account_id' => $xAccount->id,
- 'social_account_key' => $xAccount->id,
- 'post_platform_id' => $pp->id,
- 'platform' => Platform::X,
- 'network' => Platform::X->network(),
- 'remote_id' => '1234567890',
- ]);
- AnalyticsPublicationDailySnapshot::factory()->create([
- 'publication_id' => $publication->id,
- 'impressions_count' => 500,
- 'reactions_count' => 42,
- 'metrics' => ['impressions' => ['value' => 500, 'unit' => 'count', 'availability' => 'available']],
- ]);
- Http::fake();
-
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]));
-
- $response->assertOk();
- $response->assertJsonPath('available', true);
- $response->assertJsonPath('metrics.impressions.value', 500);
- $response->assertJsonPath('metrics.impressions.unit', 'count');
- Http::assertNothingSent();
-});
-
-test('platform metrics reads persisted TikTok analytics without a provider request', function () {
- $tiktokAccount = SocialAccount::factory()->tiktok()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => 'tiktoker',
- 'token_expires_at' => now()->addDays(1),
- ]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $pp = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $tiktokAccount->id,
- 'platform' => Platform::TikTok,
- 'status' => Status::Published,
- 'platform_post_id' => '7685359243088103444',
- ]);
-
- $publication = AnalyticsPublication::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'social_account_id' => $tiktokAccount->id,
- 'social_account_key' => $tiktokAccount->id,
- 'post_platform_id' => $pp->id,
- 'platform' => Platform::TikTok,
- 'network' => Platform::TikTok->network(),
- 'remote_id' => '7685359243088103444',
- 'content_type' => PublicationContentType::Video,
- ]);
- AnalyticsPublicationDailySnapshot::factory()->create([
- 'publication_id' => $publication->id,
- 'views_count' => 220,
- 'reactions_count' => 11,
- 'metrics' => ['views' => ['value' => 220, 'unit' => 'count', 'availability' => 'available']],
- ]);
- Http::fake();
-
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]));
-
- $response->assertOk();
- $response->assertJsonPath('available', true);
- $response->assertJsonPath('metrics.views.value', 220);
- $response->assertJsonPath('metrics.views.unit', 'count');
- Http::assertNothingSent();
-});
-
-test('platform metrics excludes LinkedIn profile in V1', function () {
- $linkedinAccount = SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
- 'token_expires_at' => now()->addDay(),
- ]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $pp = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedinAccount->id,
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'status' => Status::Published,
- 'platform_post_id' => 'urn:li:share:7503082467755646976',
- ]);
-
- Http::fake();
-
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]));
-
- $response->assertOk();
- $response->assertJsonPath('unsupported', true);
- $response->assertJsonPath('reason', 'platform_not_supported');
- Http::assertNothingSent();
-});
-
-test('platform metrics excludes LinkedIn Page in V1', function () {
- $pageAccount = SocialAccount::factory()->linkedinPage()->create([
- 'workspace_id' => $this->workspace->id,
- 'token_expires_at' => now()->addDay(),
- 'platform_user_id' => '99920311',
- ]);
-
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $pp = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $pageAccount->id,
- 'platform' => Platform::LinkedInPage,
- 'content_type' => ContentType::LinkedInPagePost,
- 'status' => Status::Published,
- 'platform_post_id' => 'urn:li:ugcPost:7504988143797075969',
- ]);
-
- Http::fake();
-
- $response = $this->actingAs($this->user)
- ->getJson(route('app.posts.platforms.metrics', ['post' => $post->id, 'postPlatform' => $pp->id]));
-
- $response->assertOk();
- $response->assertJsonPath('unsupported', true);
- $response->assertJsonPath('reason', 'platform_not_supported');
- Http::assertNothingSent();
-});
-
test('the standalone post page no longer exists', function () {
expect(Route::has('app.posts.show'))->toBeFalse();
});
test('the post details deep link opens a published post on the sent tab', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Published,
'content' => 'Hello world',
- ]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'enabled' => true,
'platform_url' => 'https://linkedin.com/posts/abc',
]);
@@ -1620,7 +1194,7 @@ test('the post details deep link opens a published post on the sent tab', functi
->loadDeferredProps(fn ($reload) => $reload
->has('posts.data', 1)
->where('posts.data.0.id', $post->id)
- ->has('posts.data.0.post_platforms', 1))
+ ->where('posts.data.0.social_account_id', $this->socialAccount->id))
);
});
@@ -1629,18 +1203,12 @@ test('the post details deep link exposes the content type of the post', function
'workspace_id' => $this->workspace->id,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($facebookAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Published,
- ]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $facebookAccount->id,
'platform' => Platform::Facebook,
'content_type' => ContentType::FacebookReel,
- 'enabled' => true,
]);
$this->actingAs($this->user)
@@ -1648,7 +1216,7 @@ test('the post details deep link exposes the content type of the post', function
->assertInertia(fn ($page) => $page
->component('publish/Index', false)
->loadDeferredProps(fn ($reload) => $reload
- ->where('posts.data.0.post_platforms.0.content_type', ContentType::FacebookReel->value))
+ ->where('posts.data.0.content_type', ContentType::FacebookReel->value))
);
});
@@ -1670,7 +1238,6 @@ test('the post details deep link picks the tab of the post status', function (Po
'scheduled' => [PostStatus::Scheduled, 'queue'],
'pending approval' => [PostStatus::PendingApproval, 'approvals'],
'failed' => [PostStatus::Failed, 'sent'],
- 'partially published' => [PostStatus::PartiallyPublished, 'sent'],
]);
test('a scheduled legacy post without an enabled account opens in the post details', function () {
@@ -1686,7 +1253,7 @@ test('a scheduled legacy post without an enabled account opens in the post detai
});
test('destroy blocks published posts', function () {
- foreach ([PostStatus::Publishing, PostStatus::Published, PostStatus::PartiallyPublished] as $status) {
+ foreach ([PostStatus::Publishing, PostStatus::Published] as $status) {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
@@ -1715,24 +1282,17 @@ test('the post details deep link does not expose a post from another workspace',
});
test('update post goes back to the queue after publishing without opening the post details', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Test',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'publishing',
'content' => 'Test',
- 'platforms' => [
- ['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
]);
$response->assertRedirect(route('app.posts.index', ['tab' => 'queue']));
@@ -1744,18 +1304,13 @@ test('update post rejects scheduling youtube short with image', function () {
'platform' => Platform::YouTube,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($youtubeAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Test',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $youtubeAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
@@ -1768,15 +1323,10 @@ test('update post rejects scheduling youtube short with image', function () {
'mime_type' => 'image/jpeg',
],
],
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::YouTubeShort->value,
- ],
- ],
+ 'content_type' => ContentType::YouTubeShort->value,
]);
- $response->assertSessionHasErrors('platforms.0.content_type');
+ $response->assertSessionHasErrors('content_type');
});
test('update post rejects scheduling instagram reel with no media', function () {
@@ -1785,30 +1335,20 @@ test('update post rejects scheduling instagram reel with no media', function ()
'platform' => Platform::Instagram,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($instagramAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Test',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $instagramAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::InstagramReel->value,
- ],
- ],
+ 'content_type' => ContentType::InstagramReel->value,
]);
- $response->assertSessionHasErrors('platforms.0.content_type');
+ $response->assertSessionHasErrors('content_type');
});
test('update post no longer stores an aspect_ratio meta for facebook or instagram', function (Platform $platform, ContentType $contentType, string $ratio) {
@@ -1817,32 +1357,22 @@ test('update post no longer stores an aspect_ratio meta for facebook or instagra
'platform' => $platform,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($account)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
- ]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
'platform' => $platform,
'meta' => [],
]);
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => $contentType->value,
- 'meta' => ['aspect_ratio' => $ratio],
- ],
- ],
+ 'content_type' => $contentType->value,
+ 'meta' => ['aspect_ratio' => $ratio],
]);
$response->assertSessionHasNoErrors();
- expect(data_get($postPlatform->fresh()->meta, 'aspect_ratio'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'aspect_ratio'))->toBeNull();
})->with([
'instagram 4:5' => [Platform::Instagram, ContentType::InstagramFeed, '4:5'],
'instagram unknown' => [Platform::Instagram, ContentType::InstagramFeed, '2:1'],
@@ -1855,27 +1385,19 @@ test('scheduling without content_type per platform fails', function () {
'platform' => Platform::YouTube,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($youtubeAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'content' => 'Test',
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $youtubeAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- ['id' => $postPlatform->id],
- ],
]);
- $response->assertSessionHasErrors('platforms.0.content_type');
+ $response->assertSessionHasErrors('content_type');
});
test('draft post does not enforce media-vs-content-type compatibility', function () {
@@ -1884,17 +1406,12 @@ test('draft post does not enforce media-vs-content-type compatibility', function
'platform' => Platform::YouTube,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($youtubeAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $youtubeAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
'media' => [
@@ -1906,37 +1423,22 @@ test('draft post does not enforce media-vs-content-type compatibility', function
'mime_type' => 'image/jpeg',
],
],
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::YouTubeShort->value,
- ],
- ],
+ 'content_type' => ContentType::YouTubeShort->value,
]);
- $response->assertSessionDoesntHaveErrors('platforms.0.content_type');
+ $response->assertSessionDoesntHaveErrors('content_type');
});
test('update post validates label_ids exist', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
'label_ids' => ['non-existent-uuid'],
]);
@@ -1944,26 +1446,17 @@ test('update post validates label_ids exist', function () {
});
test('update post rejects a deleted label', function () {
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($this->socialAccount)->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
$label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$label->delete();
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => 'draft',
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
'label_ids' => [$label->id],
])->assertSessionHasErrors('label_ids.0');
@@ -2034,12 +1527,16 @@ test('composer data carries each channel posting schedule', function () {
test('composer data lists the instants already scheduled on each channel', function () {
$other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::X]);
- $taken = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => now()->addDays(2)->startOfMinute()]);
- PostPlatform::factory()->create(['post_id' => $taken->id, 'social_account_id' => $this->socialAccount->id]);
- $draft = Post::factory()->draft()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => now()->addDays(3)]);
- PostPlatform::factory()->create(['post_id' => $draft->id, 'social_account_id' => $this->socialAccount->id]);
- $disabled = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => now()->addDays(4)]);
- PostPlatform::factory()->disabled()->create(['post_id' => $disabled->id, 'social_account_id' => $this->socialAccount->id]);
+ $taken = Post::factory()->forAccount($this->socialAccount)->scheduled()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ 'scheduled_at' => now()->addDays(2)->startOfMinute(),
+ ]);
+ $draft = Post::factory()->forAccount($this->socialAccount)->draft()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
+ 'scheduled_at' => now()->addDays(3),
+ ]);
$takenSlotsOn = fn (SocialAccount $account): array => $this->actingAs($this->user)
->getJson(route('app.posts.composer.taken-slots', ['account' => $account, 'from' => now()->addDays(2)->startOfDay()->toIso8601String(), 'to' => now()->addDays(4)->startOfDay()->toIso8601String()]))
@@ -2076,45 +1573,41 @@ test('composer data tells each channel time zone', function () {
expect($channels[$tokyo->id]['timezone'])->toBe('Asia/Tokyo');
});
-function draftTabPost(mixed $test, array $attributes = []): array
+function draftTabPost(mixed $test, array $attributes = []): Post
{
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount($test->socialAccount)->create([
'workspace_id' => $test->workspace->id,
'user_id' => $test->user->id,
'status' => PostStatus::Draft,
'content' => 'Test',
...$attributes,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $test->socialAccount->id,
- ]);
- return [$post, $postPlatform];
+ return $post;
}
test('saving a draft from the editor on the publish list goes to the drafts tab', function (string $from) {
- [$post, $postPlatform] = draftTabPost($this);
+ $post = draftTabPost($this);
$this->actingAs($this->user)
->from(route('app.posts.index', ['tab' => $from, 'edit' => $post->id]))
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Edited',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertRedirect(route('app.posts.index', ['tab' => 'drafts']));
})->with(['queue', 'drafts', 'sent']);
test('moving a scheduled post to drafts from the editor goes to the drafts tab', function () {
- [$post, $postPlatform] = draftTabPost($this, ['status' => PostStatus::Scheduled, 'scheduled_at' => now()->addDay()]);
+ $post = draftTabPost($this, ['status' => PostStatus::Scheduled, 'scheduled_at' => now()->addDay()]);
$this->actingAs($this->user)
->from(route('app.posts.index', ['tab' => 'queue', 'edit' => $post->id]))
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Test',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertRedirect(route('app.posts.index', ['tab' => 'drafts']));
@@ -2122,20 +1615,20 @@ test('moving a scheduled post to drafts from the editor goes to the drafts tab',
});
test('saving a draft from a channel page goes to that channel drafts tab', function () {
- [$post, $postPlatform] = draftTabPost($this);
+ $post = draftTabPost($this);
$this->actingAs($this->user)
->from(route('app.channels.publish', ['account' => $this->socialAccount, 'tab' => 'queue', 'edit' => $post->id]))
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Edited',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertRedirect(route('app.channels.publish', ['account' => $this->socialAccount, 'tab' => 'drafts']));
});
test('saving a draft from the calendar stays on the calendar', function () {
- [$post, $postPlatform] = draftTabPost($this);
+ $post = draftTabPost($this);
$calendar = route('app.calendar', ['view' => 'month']);
$this->actingAs($this->user)
@@ -2143,7 +1636,7 @@ test('saving a draft from the calendar stays on the calendar', function () {
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Edited',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertRedirect($calendar);
});
@@ -2186,7 +1679,7 @@ test('every way of scheduling from the editor lands on the queue tab', function
]);
test('scheduling an existing post from the editor lands on the queue tab', function () {
- [$post, $postPlatform] = draftTabPost($this);
+ $post = draftTabPost($this);
$this->actingAs($this->user)
->from(route('app.posts.index', ['tab' => 'drafts', 'edit' => $post->id]))
@@ -2194,7 +1687,7 @@ test('scheduling an existing post from the editor lands on the queue tab', funct
'status' => 'scheduled',
'scheduled_at' => '2037-01-01T10:00:00Z',
'content' => 'Test',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertSessionHasNoErrors()
->assertRedirect(route('app.posts.index', ['tab' => 'queue']));
diff --git a/tests/Feature/Posts/ApprovalDecisionEmailTest.php b/tests/Feature/Posts/ApprovalDecisionEmailTest.php
index cbe4f6413..603e45723 100644
--- a/tests/Feature/Posts/ApprovalDecisionEmailTest.php
+++ b/tests/Feature/Posts/ApprovalDecisionEmailTest.php
@@ -7,10 +7,8 @@ use App\Actions\Post\Approval\RejectPost;
use App\Actions\Post\CreatePosts;
use App\Actions\Post\UpdatePost;
use App\Enums\Notification\Type;
-use App\Enums\Post\ApprovalDecision;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Jobs\Post\SendApprovalDecisionEmail;
use App\Jobs\SendNotification;
use App\Mail\PostApproved;
use App\Mail\PostRejected;
@@ -20,13 +18,9 @@ use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
use Carbon\CarbonImmutable;
-use Illuminate\Contracts\Cache\LockTimeoutException;
-use Illuminate\Queue\SyncQueue;
use Illuminate\Support\Collection;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\Exceptions;
+use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;
-use Illuminate\Support\Sleep;
use Illuminate\Validation\ValidationException;
beforeEach(function () {
@@ -61,25 +55,17 @@ function approvalDecisionRequest(object $test): Collection
]);
}
-test('approving every card of a request sends one grouped email', function () {
+test('approving every card of a request sends one email per post', function () {
$posts = approvalDecisionRequest($this);
$posts->each(fn (Post $post) => ApprovePost::execute($post, $this->owner));
- Queue::assertPushed(SendApprovalDecisionEmail::class, 1);
+ $emails = Queue::pushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostApproved);
- $job = Queue::pushed(SendApprovalDecisionEmail::class)->sole();
-
- expect($job->decision)->toBe(ApprovalDecision::Approved)
- ->and($job->requester->is($this->requester))->toBeTrue()
- ->and($job->delay)->not->toBeNull();
-
- $job->handle();
-
- Queue::assertPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->type === Type::Collaboration
- && $notification->mailable instanceof PostApproved
- && $notification->user->is($this->requester)
- && collect($notification->mailable->postIds)->sort()->values()->all() === $posts->pluck('id')->sort()->values()->all());
+ expect($emails)->toHaveCount(2)
+ ->and($emails->every(fn (SendNotification $notification): bool => $notification->type === Type::Collaboration && $notification->user->is($this->requester)))->toBeTrue()
+ ->and($emails->map(fn (SendNotification $notification): string => $notification->mailable->postId)->sort()->values()->all())
+ ->toBe($posts->pluck('id')->sort()->values()->all());
});
test('rejecting sends the rejected email to the author', function () {
@@ -87,35 +73,9 @@ test('rejecting sends the rejected email to the author', function () {
RejectPost::execute($post, $this->owner);
- $job = Queue::pushed(SendApprovalDecisionEmail::class)->sole();
-
- expect($job->decision)->toBe(ApprovalDecision::Rejected);
-
- $job->handle();
-
Queue::assertPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostRejected
&& $notification->user->is($this->requester)
- && $notification->mailable->postIds === [$post->id]);
-});
-
-test('a decision job with nothing collected sends nothing', function () {
- (new SendApprovalDecisionEmail('post-approval-decision:missing:approved:none', $this->requester, $this->owner, ApprovalDecision::Approved))->handle();
-
- Queue::assertNotPushed(SendNotification::class);
-});
-
-test('a decision job for an author who is gone sends nothing', function () {
- $post = approvalDecisionRequest($this)->first();
- Cache::put('post-approval-decision:gone:approved:owner', [$post->id], now()->addDay());
- $job = new SendApprovalDecisionEmail('post-approval-decision:gone:approved:owner', $this->requester, $this->owner, ApprovalDecision::Approved);
-
- $this->requester->delete();
-
- $queue = new SyncQueue;
- $queue->setContainer(app());
- $queue->push($job);
-
- Queue::assertNotPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostApproved);
+ && $notification->mailable->postId === $post->id);
});
test('deciding your own post sends no decision email', function () {
@@ -124,45 +84,18 @@ test('deciding your own post sends no decision email', function () {
RejectPost::execute($post, $this->owner);
- Queue::assertNotPushed(SendApprovalDecisionEmail::class);
+ Queue::assertNotPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostRejected);
});
-test('a decision job waits for the collector lock and sends later', function () {
- Sleep::fake(syncWithCarbon: true);
+test('a decision email whose post was deleted is not sent', function () {
+ Mail::fake();
$post = approvalDecisionRequest($this)->first();
- $key = 'post-approval-decision:locked:approved:owner';
- Cache::put($key, [$post->id], now()->addDay());
- Cache::lock("{$key}:lock", 10)->acquire();
+ $notification = new SendNotification($this->requester, Type::Collaboration, new PostApproved($post->id, $this->owner, $this->requester));
- $job = (new SendApprovalDecisionEmail($key, $this->requester, $this->owner, ApprovalDecision::Approved))->withFakeQueueInteractions();
- $job->handle();
-
- $job->assertReleased();
- expect(Cache::get($key))->toBe([$post->id]);
- Queue::assertNotPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostApproved);
-});
-
-test('a decision job whose posts are all gone sends nothing', function () {
- $post = approvalDecisionRequest($this)->first();
- Cache::put('post-approval-decision:deleted:approved:owner', [$post->id], now()->addDay());
$post->delete();
+ $notification->handle();
- (new SendApprovalDecisionEmail('post-approval-decision:deleted:approved:owner', $this->requester, $this->owner, ApprovalDecision::Approved))->handle();
-
- Queue::assertNotPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostApproved);
-});
-
-test('approving still succeeds when the decision collector is busy', function () {
- Sleep::fake(syncWithCarbon: true);
- Exceptions::fake();
- $post = approvalDecisionRequest($this)->first();
- $group = $post->post_group_id ?? $post->id;
- Cache::lock("post-approval-decision:{$group}:approved:{$this->owner->id}:{$this->requester->id}:lock", 10)->acquire();
-
- ApprovePost::execute($post, $this->owner);
-
- expect($post->refresh()->status)->toBe(PostStatus::Scheduled);
- Exceptions::assertReported(LockTimeoutException::class);
+ Mail::assertNothingSent();
});
/**
@@ -190,12 +123,6 @@ test('approving a post someone else edited emails the member who asked, not the
ApprovePost::execute($post, $this->owner);
- $job = Queue::pushed(SendApprovalDecisionEmail::class)->sole();
-
- expect($job->requester->is($this->requester))->toBeTrue();
-
- $job->handle();
-
Queue::assertPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostApproved
&& $notification->user->is($this->requester));
});
@@ -205,10 +132,8 @@ test('rejecting a post someone else edited emails the member who asked, not the
RejectPost::execute($post, workspaceMember($this->workspace, 'admin'));
- $job = Queue::pushed(SendApprovalDecisionEmail::class)->sole();
-
- expect($job->requester->is($this->requester))->toBeTrue()
- ->and($job->decision)->toBe(ApprovalDecision::Rejected);
+ Queue::assertPushed(SendNotification::class, fn (SendNotification $notification): bool => $notification->mailable instanceof PostRejected
+ && $notification->user->is($this->requester));
});
test('rejecting a post another approver already approved fails and sends no email', function () {
@@ -222,7 +147,7 @@ test('rejecting a post another approver already approved fails and sends no emai
->toThrow(ValidationException::class, __('posts.approvals.errors.not_pending'));
expect($post->refresh()->status)->toBe(PostStatus::Scheduled);
- Queue::assertNotPushed(SendApprovalDecisionEmail::class);
+ Queue::assertNotPushed(SendNotification::class);
});
test('saving a pending post in the composer after it was rejected fails and sends no approval', function () {
@@ -236,5 +161,5 @@ test('saving a pending post in the composer after it was rejected fails and send
->toThrow(ValidationException::class, __('posts.approvals.errors.not_pending'));
expect($post->refresh()->status)->toBe(PostStatus::Draft);
- Queue::assertNotPushed(SendApprovalDecisionEmail::class);
+ Queue::assertNotPushed(SendNotification::class);
});
diff --git a/tests/Feature/Posts/ApprovalRequestEmailTest.php b/tests/Feature/Posts/ApprovalRequestEmailTest.php
index a10cab25c..8aabf60b8 100644
--- a/tests/Feature/Posts/ApprovalRequestEmailTest.php
+++ b/tests/Feature/Posts/ApprovalRequestEmailTest.php
@@ -70,19 +70,25 @@ function approvalEmailRecipients(): array
->all();
}
-test('a multi-channel request sends one email per approver listing every channel', function () {
+test('a multi-channel request sends every approver one email per post', function () {
$this->actingAs($this->requester)
->post(route('app.posts.store'), approvalEmailPayload([$this->linkedin, $this->x]))
->assertSessionHasNoErrors();
- $expected = collect([$this->owner->id, $this->publisher->id])->sort()->values()->all();
+ $postIds = session('created_post_ids');
+ $approvers = collect([$this->owner->id, $this->publisher->id]);
- expect(approvalEmailRecipients())->toBe($expected);
+ expect($postIds)->toHaveCount(2)
+ ->and(approvalEmailRecipients())->toBe($approvers->flatMap(fn (string $id): array => [$id, $id])->sort()->values()->all());
- Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === Type::Collaboration
- && $job->mailable instanceof PostApprovalRequested
- && count($job->mailable->postIds) === 2
- && $job->mailable->requester->is($this->requester));
+ $approvers->each(fn (string $approverId) => collect($postIds)->each(fn (string $postId) => Queue::assertPushed(
+ SendNotification::class,
+ fn (SendNotification $job): bool => $job->type === Type::Collaboration
+ && $job->mailable instanceof PostApprovalRequested
+ && $job->user->id === $approverId
+ && $job->mailable->postId === $postId
+ && $job->mailable->requester->is($this->requester),
+ )));
});
test('a draft or a direct publisher sends no approval email', function () {
@@ -116,14 +122,14 @@ test('the collaboration preference silences the email', function () {
NotificationPreference::factory()->create(['user_id' => $this->owner->id, 'collaboration' => false]);
$post = Post::factory()->pendingApproval()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->requester->id]);
- (new SendNotification($this->owner->fresh(), Type::Collaboration, new PostApprovalRequested([$post->id], $this->requester, $this->owner)))->handle();
+ (new SendNotification($this->owner->fresh(), Type::Collaboration, new PostApprovalRequested($post->id, $this->requester, $this->owner)))->handle();
Mail::assertNothingQueued();
- (new SendNotification($this->publisher->fresh(), Type::Collaboration, new PostApprovalRequested([$post->id], $this->requester, $this->publisher)))->handle();
+ (new SendNotification($this->publisher->fresh(), Type::Collaboration, new PostApprovalRequested($post->id, $this->requester, $this->publisher)))->handle();
Mail::assertQueued(PostApprovalRequested::class);
});
-test('the request email is not sent once none of its posts is still pending', function (string $outcome) {
+test('the request email is not sent once its post is no longer pending', function (string $outcome) {
Mail::fake();
$post = Post::factory()->pendingApproval()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->requester->id]);
@@ -133,17 +139,7 @@ test('the request email is not sent once none of its posts is still pending', fu
'deleted' => $post->delete(),
};
- (new SendNotification($this->owner->fresh(), Type::Collaboration, new PostApprovalRequested([$post->id], $this->requester, $this->owner)))->handle();
+ (new SendNotification($this->owner->fresh(), Type::Collaboration, new PostApprovalRequested($post->id, $this->requester, $this->owner)))->handle();
Mail::assertNothingQueued();
})->with(['approved', 'rejected', 'deleted']);
-
-test('the request email lists only the posts still pending', function () {
- Mail::fake();
- $pending = Post::factory()->pendingApproval()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->requester->id]);
- $approved = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->requester->id]);
-
- (new SendNotification($this->owner->fresh(), Type::Collaboration, new PostApprovalRequested([$pending->id, $approved->id], $this->requester, $this->owner)))->handle();
-
- Mail::assertQueued(PostApprovalRequested::class, fn (PostApprovalRequested $mail): bool => $mail->postIds === [$pending->id]);
-});
diff --git a/tests/Feature/Posts/ApprovalsTabTest.php b/tests/Feature/Posts/ApprovalsTabTest.php
index 3d5919b57..50ab4938d 100644
--- a/tests/Feature/Posts/ApprovalsTabTest.php
+++ b/tests/Feature/Posts/ApprovalsTabTest.php
@@ -9,7 +9,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -35,18 +34,9 @@ beforeEach(function () {
*/
function approvalsTabPost(SocialAccount $channel, User $author, array $attributes = []): Post
{
- $post = Post::factory()->pendingApproval()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->pendingApproval()->create(array_merge([
'user_id' => $author->id,
], $attributes));
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- ]);
-
- return $post;
}
test('approvers count and list every pending post, timed first then unscheduled', function () {
@@ -117,13 +107,7 @@ test('a notes link to a pending post opens the approvals tab', function () {
});
test('a requester sees in approvals the scheduled post they sent back for approval', function () {
- $scheduled = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->owner->id]);
- PostPlatform::factory()->create([
- 'post_id' => $scheduled->id,
- 'social_account_id' => $this->channel->id,
- 'platform' => $this->channel->platform,
- 'content_type' => ContentType::LinkedInPost,
- ]);
+ $scheduled = Post::factory()->forAccount($this->channel, ContentType::LinkedInPost)->scheduled()->create(['user_id' => $this->owner->id]);
UpdatePost::execute($this->workspace, $scheduled, ['status' => 'scheduled', 'content' => 'Typo fixed'], $this->requester);
diff --git a/tests/Feature/Posts/BuildQueueTimelineTest.php b/tests/Feature/Posts/BuildQueueTimelineTest.php
index a0de8aeae..5314918b0 100644
--- a/tests/Feature/Posts/BuildQueueTimelineTest.php
+++ b/tests/Feature/Posts/BuildQueueTimelineTest.php
@@ -6,7 +6,6 @@ use App\Actions\Post\Queue\BuildQueueTimeline;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -40,17 +39,12 @@ function buildTimelineWeekdaySchedule(): PostingSchedule
function buildTimelinePost(SocialAccount $channel, string $at, array $attributes = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $channel->workspace->user_id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => CarbonImmutable::parse($at, 'UTC'),
], $attributes));
-
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id]);
-
- return $post;
}
function buildTimeline(object $test, array $labelIds = [], ?SocialAccount $channel = null, string $timezone = 'UTC'): array
diff --git a/tests/Feature/Posts/CalendarPageTest.php b/tests/Feature/Posts/CalendarPageTest.php
index db814b6f6..ebe76764e 100644
--- a/tests/Feature/Posts/CalendarPageTest.php
+++ b/tests/Feature/Posts/CalendarPageTest.php
@@ -8,7 +8,6 @@ use App\Enums\User\WeekStart;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -33,21 +32,13 @@ beforeEach(function () {
function calendarPost(SocialAccount $account, ?string $scheduledAtUtc, string $content, PostStatus $status = PostStatus::Scheduled, array $attributes = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
+ return Post::factory()->forAccount($account)->create([
'user_id' => $account->workspace->user_id,
'status' => $status,
'scheduled_at' => $scheduledAtUtc ? CarbonImmutable::parse($scheduledAtUtc, 'UTC') : null,
'content' => $content,
...$attributes,
]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- return $post;
}
test('the calendar buckets posts into days of the user time zone by default', function () {
@@ -169,7 +160,7 @@ test('calendar posts carry the timeline card fields', function () {
->where('posts.2026-10-06.0.notes_count', 0)
->where('posts.2026-10-06.0.can_delete', true)
->where('posts.2026-10-06.0.user.name', $this->user->name)
- ->where('posts.2026-10-06.0.post_platforms.0.social_account.has_posting_schedule', false)
+ ->where('posts.2026-10-06.0.social_account.has_posting_schedule', false)
->missing('posts.2026-10-06.0.metrics')
->where('posts.2026-10-05.0.content', 'Sent card')
->has('posts.2026-10-05.0.metrics'));
@@ -187,7 +178,7 @@ test('the calendar filters by channels and ignores ids that are not uuids', func
->has('filterAccounts', 2)
->has('posts.2026-10-06', 1)
->where('posts.2026-10-06.0.content', 'X post')
- ->where('posts.2026-10-06.0.post_platforms.0.social_account_id', $this->x->id));
+ ->where('posts.2026-10-06.0.social_account_id', $this->x->id));
});
test('the calendar filters by labels', function () {
@@ -247,7 +238,6 @@ test('the status filter narrows the calendar to drafts, scheduled or sent posts'
calendarPost($this->linkedin, '2026-10-06 15:00:00', 'Scheduled post');
calendarPost($this->linkedin, '2026-10-06 16:00:00', 'Dated draft', PostStatus::Draft);
calendarPost($this->linkedin, '2026-10-05 09:00:00', 'Published post', PostStatus::Published);
- calendarPost($this->linkedin, '2026-10-05 09:30:00', 'Partial post', PostStatus::PartiallyPublished);
calendarPost($this->linkedin, '2026-10-05 09:45:00', 'Failed post', PostStatus::Failed);
calendarPost($this->linkedin, '2026-10-05 09:55:00', 'Publishing post', PostStatus::Publishing);
@@ -257,11 +247,11 @@ test('the status filter narrows the calendar to drafts, scheduled or sent posts'
$flatten = fn (array $days): array => collect($days)->flatten(1)->pluck('content')->sort()->values()->all();
- expect($flatten($contents(null)))->toHaveCount(6)
+ expect($flatten($contents(null)))->toHaveCount(5)
->and($flatten($contents('drafts')))->toBe(['Dated draft'])
->and($flatten($contents('scheduled')))->toBe(['Publishing post', 'Scheduled post'])
- ->and($flatten($contents('sent')))->toBe(['Failed post', 'Partial post', 'Published post'])
- ->and($flatten($contents('bogus')))->toHaveCount(6);
+ ->and($flatten($contents('sent')))->toBe(['Failed post', 'Published post'])
+ ->and($flatten($contents('bogus')))->toHaveCount(5);
$this->actingAs($this->user)
->get(route('app.calendar', ['view' => 'week', 'status' => 'sent']))
@@ -367,15 +357,9 @@ test('posting slots load only when enabled, cover the visible range and follow t
});
test('an imported post sits on the day it was published', function () {
- $post = Post::factory()->imported()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($this->x)->imported()->create([
'published_at' => CarbonImmutable::parse('2026-10-07 14:20:00', 'UTC'),
]);
- PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->x->id,
- 'platform' => $this->x->platform,
- ]);
$this->actingAs($this->user)
->get(route('app.calendar', ['view' => 'week']))
diff --git a/tests/Feature/Posts/ChannelAltTextTest.php b/tests/Feature/Posts/ChannelAltTextTest.php
index 08a89167e..b660a244d 100644
--- a/tests/Feature/Posts/ChannelAltTextTest.php
+++ b/tests/Feature/Posts/ChannelAltTextTest.php
@@ -51,9 +51,7 @@ function channelAltTextItem(Media $media, array $meta = []): array
function channelAltTextPost(SocialAccount $account): Post
{
- return Post::query()
- ->whereHas('postPlatforms', fn ($query) => $query->where('social_account_id', $account->id))
- ->sole();
+ return Post::query()->where('social_account_id', $account->id)->sole();
}
/**
@@ -130,8 +128,8 @@ test('each publisher sends the alt text of its own channel', function () {
};
});
- (new XPublisher)->publish(channelAltTextPost($this->x)->postPlatforms()->sole());
- (new BlueskyPublisher)->publish(channelAltTextPost($this->bluesky)->postPlatforms()->sole());
+ (new XPublisher)->publish(channelAltTextPost($this->x));
+ (new BlueskyPublisher)->publish(channelAltTextPost($this->bluesky));
Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/media/metadata')
&& data_get($request->data(), 'metadata.alt_text.text') === 'Shared description');
diff --git a/tests/Feature/Posts/ComposerFlowTest.php b/tests/Feature/Posts/ComposerFlowTest.php
index 0e9f09b51..a7eacaf04 100644
--- a/tests/Feature/Posts/ComposerFlowTest.php
+++ b/tests/Feature/Posts/ComposerFlowTest.php
@@ -8,7 +8,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -64,8 +63,7 @@ function composerFlowPayload(array $destinations, array $overrides = []): array
function composerFlowPost(Workspace $workspace, User $author, SocialAccount $account, array $attributes = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ return Post::factory()->forAccount($account, ContentType::LinkedInPost)->create([
'user_id' => $author->id,
'content' => 'Existing caption',
'status' => PostStatus::Scheduled,
@@ -73,21 +71,11 @@ function composerFlowPost(Workspace $workspace, User $author, SocialAccount $acc
'scheduled_at' => now()->addDay(),
...$attributes,
]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => ContentType::LinkedInPost,
- ]);
-
- return $post;
}
test('a user outside the workspace cannot create, edit, duplicate or delete a post', function () {
$outsider = workspaceOutsider($this->workspace);
$post = composerFlowPost($this->workspace, $this->owner, $this->linkedin);
- $postPlatform = $post->postPlatforms()->sole();
$this->actingAs($outsider)
->post(route('app.posts.store'), composerFlowPayload([composerFlowDestination($this->linkedin, ContentType::LinkedInPost)]))
@@ -96,7 +84,7 @@ test('a user outside the workspace cannot create, edit, duplicate or delete a po
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Hijacked',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertForbidden();
$this->actingAs($outsider)->post(route('app.posts.duplicate', $post))->assertForbidden();
@@ -112,13 +100,12 @@ test('a post of another workspace cannot be edited, duplicated or deleted from t
$foreignWorkspace = Workspace::factory()->create(['account_id' => $foreignOwner->account_id, 'user_id' => $foreignOwner->id]);
$foreignAccount = SocialAccount::factory()->create(['workspace_id' => $foreignWorkspace->id, 'platform' => Platform::LinkedIn]);
$post = composerFlowPost($foreignWorkspace, $foreignOwner, $foreignAccount);
- $postPlatform = $post->postPlatforms()->sole();
$this->actingAs($this->owner)
->put(route('app.posts.update', $post), [
'status' => 'draft',
'content' => 'Hijacked',
- 'platforms' => [['id' => $postPlatform->id, 'content_type' => ContentType::LinkedInPost->value]],
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertNotFound();
$this->actingAs($this->owner)->post(route('app.posts.duplicate', $post))->assertNotFound();
@@ -211,11 +198,11 @@ test('each network keeps its own text and settings when the post is customized p
]))
->assertSessionHasNoErrors();
- $linkedinPost = Post::query()->whereHas('postPlatforms', fn ($query) => $query->where('social_account_id', $this->linkedin->id))->sole();
- $xPost = Post::query()->whereHas('postPlatforms', fn ($query) => $query->where('social_account_id', $x->id))->sole();
+ $linkedinPost = Post::query()->where('social_account_id', $this->linkedin->id)->sole();
+ $xPost = Post::query()->where('social_account_id', $x->id)->sole();
expect($linkedinPost->content)->toBe('Long form for LinkedIn')
- ->and($linkedinPost->postPlatforms->sole()->meta)->toEqual(['link_preview' => false])
+ ->and($linkedinPost->meta)->toEqual(['link_preview' => false])
->and($xPost->content)->toBe('Short for X')
->and($xPost->post_group_id)->toBe($linkedinPost->post_group_id)
->and($xPost->scheduled_at->equalTo($linkedinPost->scheduled_at))->toBeTrue();
@@ -295,7 +282,7 @@ test('the mastodon content warning counts against the 500 characters in the comp
))
->assertSessionHasNoErrors();
- expect(Post::query()->where('workspace_id', $this->workspace->id)->sole()->postPlatforms->sole()->meta['spoiler_text'])->toBe('cw');
+ expect(Post::query()->where('workspace_id', $this->workspace->id)->sole()->meta['spoiler_text'])->toBe('cw');
});
test('an x thread from the composer stores its replies as text objects and refuses a reply over the account limit', function () {
@@ -317,7 +304,7 @@ test('an x thread from the composer stores its replies as text objects and refus
))
->assertSessionHasNoErrors();
- expect(Post::query()->sole()->postPlatforms->sole()->meta['thread_replies'])->toEqual([
+ expect(Post::query()->sole()->meta['thread_replies'])->toEqual([
['text' => 'Second', 'media' => []],
['text' => 'Third', 'media' => []],
]);
@@ -325,19 +312,12 @@ test('an x thread from the composer stores its replies as text objects and refus
test('editing an x thread from the composer refuses a reply over the account limit and keeps the stored thread', function () {
$x = SocialAccount::factory()->x()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($x, ContentType::XPost)->create([
'user_id' => $this->owner->id,
'content' => 'Root',
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->addDay(),
- ]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $x->id,
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
'meta' => ['thread_replies' => [['text' => 'Second', 'media' => []]]],
]);
@@ -346,15 +326,12 @@ test('editing an x thread from the composer refuses a reply over the account lim
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'content' => 'Root',
- 'platforms' => [[
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::XPost->value,
- 'meta' => ['thread_replies' => ['Second', str_repeat('a', 281)]],
- ]],
+ 'content_type' => ContentType::XPost->value,
+ 'meta' => ['thread_replies' => ['Second', str_repeat('a', 281)]],
])
->assertSessionHasErrors();
- expect($postPlatform->fresh()->meta['thread_replies'])->toEqual([['text' => 'Second', 'media' => []]]);
+ expect($post->fresh()->meta['thread_replies'])->toEqual([['text' => 'Second', 'media' => []]]);
});
test('a member who needs approval duplicating a scheduled post gets a draft, never a request', function () {
diff --git a/tests/Feature/Posts/ImportExternalPostsTest.php b/tests/Feature/Posts/ImportExternalPostsTest.php
index d1b0dc703..82ade593a 100644
--- a/tests/Feature/Posts/ImportExternalPostsTest.php
+++ b/tests/Feature/Posts/ImportExternalPostsTest.php
@@ -7,17 +7,17 @@ use App\Actions\Post\ImportExternalPosts;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Analytics\PublicationOrigin;
use App\Enums\Post\Origin;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Events\PostCreated;
use App\Events\PostStatusChanged;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
+use App\Jobs\Analytics\SyncTryPostPublication;
use App\Models\AnalyticsPublication;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;
use App\Support\Social\ThreadProgress;
@@ -50,25 +50,18 @@ function externalPublication(SocialAccount $account, array $attributes = []): An
]);
}
-function sentByTryPost(SocialAccount $account, string $platformPostId, string $content, CarbonImmutable $publishedAt, ?ContentType $contentType = null): PostPlatform
+function sentByTryPost(SocialAccount $account, string $platformPostId, string $content, CarbonImmutable $publishedAt, ?ContentType $contentType = null): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $account->workspace_id,
- 'content' => $content,
- 'status' => PostStatus::Published,
- 'origin' => Origin::TryPost,
- 'published_at' => $publishedAt,
- ]);
-
- return PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType ?? ($account->platform === Platform::TikTok ? ContentType::TikTokVideo : ContentType::defaultFor($account->platform)),
- 'platform_post_id' => $platformPostId,
- 'platform_url' => null,
- 'published_at' => $publishedAt,
- ]);
+ return Post::factory()
+ ->forAccount($account, $contentType ?? ($account->platform === Platform::TikTok ? ContentType::TikTokVideo : ContentType::defaultFor($account->platform)))
+ ->published()
+ ->create([
+ 'content' => $content,
+ 'origin' => Origin::TryPost,
+ 'platform_post_id' => $platformPostId,
+ 'platform_url' => null,
+ 'published_at' => $publishedAt,
+ ]);
}
test('a publication becomes a published network post linked to its analytics row', function () {
@@ -84,7 +77,6 @@ test('a publication becomes a published network post linked to its analytics row
$created = ImportExternalPosts::execute($account);
$post = Post::query()->imported()->sole();
- $target = $post->postPlatforms()->sole();
expect($created)->toBe([$post->id])
->and($post->origin)->toBe(Origin::Network)
@@ -98,15 +90,13 @@ test('a publication becomes a published network post linked to its analytics row
->and($post->content)->toBe("First line\nSecond line")
->and($post->media)->toBe([])
->and($post->published_at->toIso8601String())->toBe('2026-09-30T08:15:00+00:00')
- ->and($target->social_account_id)->toBe($account->id)
- ->and($target->platform)->toBe($account->platform)
- ->and($target->status)->toBe(PostPlatformStatus::Published)
- ->and($target->enabled)->toBeTrue()
- ->and($target->content_type)->toBe(ContentType::InstagramReel)
- ->and($target->platform_post_id)->toBe('ig-1')
- ->and($target->platform_url)->toBe('https://www.instagram.com/reel/ig-1/')
- ->and($target->published_at->toIso8601String())->toBe('2026-09-30T08:15:00+00:00')
- ->and($publication->fresh()->post_platform_id)->toBe($target->id);
+ ->and($post->social_account_id)->toBe($account->id)
+ ->and($post->platform)->toBe($account->platform)
+ ->and($post->publish_status)->toBe(PublishStatus::Published)
+ ->and($post->content_type)->toBe(ContentType::InstagramReel)
+ ->and($post->platform_post_id)->toBe('ig-1')
+ ->and($post->platform_url)->toBe('https://www.instagram.com/reel/ig-1/')
+ ->and($publication->fresh()->post_id)->toBe($post->id);
});
test('an image-only publication without text imports with empty content', function () {
@@ -128,7 +118,7 @@ test('only the newest publications up to the limit are imported regardless of in
ImportExternalPosts::execute($account);
- expect(PostPlatform::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['d1', 'd2', 'd3']);
+ expect(Post::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['d1', 'd2', 'd3']);
});
test('stories have their own import limit and never push feed posts out', function () {
@@ -145,7 +135,7 @@ test('stories have their own import limit and never push feed posts out', functi
ImportExternalPosts::execute($account);
- expect(PostPlatform::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['feed-1', 'feed-2', 'story-1', 'story-2']);
+ expect(Post::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['feed-1', 'feed-2', 'story-1', 'story-2']);
});
test('discovery imports newer posts and never removes older imports', function () {
@@ -159,7 +149,7 @@ test('discovery imports newer posts and never removes older imports', function (
externalPublication($account, ['remote_id' => 'new-2', 'provider_published_at' => now()->subDay()]);
ImportExternalPosts::execute($account);
- expect(PostPlatform::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['new-1', 'new-2', 'old-1', 'old-2']);
+ expect(Post::query()->pluck('platform_post_id')->sort()->values()->all())->toBe(['new-1', 'new-2', 'old-1', 'old-2']);
});
test('x imports only publications inside the configured day window', function () {
@@ -169,7 +159,7 @@ test('x imports only publications inside the configured day window', function ()
ImportExternalPosts::execute($account);
- expect(PostPlatform::query()->pluck('platform_post_id')->all())->toBe(['recent']);
+ expect(Post::query()->pluck('platform_post_id')->all())->toBe(['recent']);
});
test('running the import twice creates each post once', function () {
@@ -185,25 +175,21 @@ test('running the import twice creates each post once', function () {
test('a publication trypost already published is linked instead of duplicated', function () {
$account = SocialAccount::factory()->instagram()->create();
- $tryPost = PostPlatform::factory()->instagram()->published()->create([
- 'social_account_id' => $account->id,
+ $tryPost = Post::factory()->forAccount($account)->instagram()->published()->create([
'platform_post_id' => 'shared-1',
]);
- $tryPost->post->update(['workspace_id' => $account->workspace_id]);
$publication = externalPublication($account, ['remote_id' => 'shared-1']);
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($tryPost->id);
+ ->and($publication->fresh()->post_id)->toBe($tryPost->id);
});
test('a facebook post links the trypost video it carries by video id', function () {
$account = SocialAccount::factory()->facebook()->create();
- $tryPost = PostPlatform::factory()->facebookReel()->published()->create([
- 'social_account_id' => $account->id,
+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create([
'platform_post_id' => 'video-9',
]);
- $tryPost->post->update(['workspace_id' => $account->workspace_id]);
$publication = externalPublication($account, [
'remote_id' => 'page_post-1',
'provider_metadata' => ['video_id' => 'video-9'],
@@ -212,17 +198,15 @@ test('a facebook post links the trypost video it carries by video id', function
ImportExternalPosts::execute($account);
expect(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($tryPost->id);
+ ->and($publication->fresh()->post_id)->toBe($tryPost->id);
});
test('a facebook video already tracked by its trypost publication is left unlinked', function () {
$account = SocialAccount::factory()->facebook()->create();
- $tryPost = PostPlatform::factory()->facebookReel()->published()->create([
- 'social_account_id' => $account->id,
+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create([
'platform_post_id' => 'video-9',
]);
- $tryPost->post->update(['workspace_id' => $account->workspace_id]);
- externalPublication($account, ['remote_id' => 'video-9', 'post_platform_id' => $tryPost->id]);
+ externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id]);
$external = externalPublication($account, [
'remote_id' => 'page_post-1',
'provider_metadata' => ['video_id' => 'video-9'],
@@ -231,7 +215,7 @@ test('a facebook video already tracked by its trypost publication is left unlink
ImportExternalPosts::execute($account);
expect(Post::query()->imported()->count())->toBe(0)
- ->and($external->fresh()->post_platform_id)->toBeNull();
+ ->and($external->fresh()->post_id)->toBeNull();
});
test('a facebook photo discovered under its feed post id does not duplicate the original', function (bool $tracked) {
@@ -241,7 +225,7 @@ test('a facebook photo discovered under its feed post id does not duplicate the
if ($tracked) {
externalPublication($account, [
'remote_id' => 'photo-9',
- 'post_platform_id' => $original->id,
+ 'post_id' => $original->id,
'origin' => PublicationOrigin::TryPost,
]);
}
@@ -266,7 +250,7 @@ test('a facebook photo discovered under its feed post id does not duplicate the
expect(ImportExternalPosts::execute($account))->toBe([])
->and(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($tracked ? null : $original->id);
+ ->and($publication->fresh()->post_id)->toBe($tracked ? null : $original->id);
Http::assertSentCount(1);
})->with(['untracked original' => false, 'tracked original' => true]);
@@ -294,8 +278,8 @@ test('a broken publication is reported and the rest of the page still imports',
ImportExternalPosts::execute($account);
- expect(PostPlatform::query()->pluck('platform_post_id')->all())->toBe(['fine'])
- ->and(DB::table('analytics_publications')->where('id', $broken->id)->value('post_platform_id'))->toBeNull();
+ expect(Post::query()->pluck('platform_post_id')->all())->toBe(['fine'])
+ ->and(DB::table('analytics_publications')->where('id', $broken->id)->value('post_id'))->toBeNull();
Exceptions::assertReported(ValueError::class);
});
@@ -318,7 +302,7 @@ test('an account only imports its own workspace publications', function () {
$post = Post::query()->imported()->sole();
expect($post->workspace_id)->toBe($ours->workspace_id)
- ->and($post->postPlatforms()->sole()->platform_post_id)->toBe('ours');
+ ->and($post->platform_post_id)->toBe('ours');
});
test('a reconnected account does not import posts that already exist', function () {
@@ -368,11 +352,32 @@ test('an instagram post trypost published under its container id is linked inste
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($tryPost->id)
+ ->and($publication->fresh()->post_id)->toBe($tryPost->id)
->and($tryPost->fresh()->platform_post_id)->toBe('media-1')
->and($tryPost->fresh()->platform_url)->toBe('https://www.instagram.com/p/media-1/');
});
+test('linking a sent post to its publication moves only the publication clock and queues no sync', function () {
+ Queue::fake();
+ $account = SocialAccount::factory()->instagram()->create();
+ $tryPost = sentByTryPost($account, 'container-2', '<p>Quiet link</p>', now()->subHours(3)->toImmutable());
+ $tryPost->forceFill(['updated_at' => now()->subDays(2)->startOfSecond(), 'publication_updated_at' => now()->subDays(2)->startOfSecond()])->saveQuietly();
+ $updatedAt = $tryPost->fresh()->updated_at;
+ externalPublication($account, [
+ 'remote_id' => 'media-2',
+ 'excerpt' => 'Quiet link',
+ 'provider_published_at' => now()->subHours(3)->addMinutes(2),
+ ]);
+
+ ImportExternalPosts::execute($account);
+
+ expect($tryPost->fresh())
+ ->platform_post_id->toBe('media-2')
+ ->updated_at->toIso8601String()->toBe($updatedAt->toIso8601String())
+ ->and($tryPost->fresh()->publication_updated_at->isAfter(now()->subMinute()))->toBeTrue();
+ Queue::assertNotPushed(SyncTryPostPublication::class);
+});
+
test('a tiktok post still keyed by its publish id is reconciled into the discovered video', function (ContentType $contentType, string $publishId, string $ellipsis) {
$account = SocialAccount::factory()->tiktok()->create();
$tryPost = sentByTryPost($account, $publishId, '<p>A long description that the network cuts short</p>', now()->subHour()->toImmutable(), $contentType);
@@ -383,10 +388,10 @@ test('a tiktok post still keyed by its publish id is reconciled into the discove
'mime_type' => 'image/jpeg',
])->all()
: [['id' => 'video-1', 'url' => 'https://cdn.example/video.mp4', 'mime_type' => 'video/mp4']];
- $tryPost->post->update(['media' => $media]);
+ $tryPost->update(['media' => $media]);
$provisional = externalPublication($account, [
'remote_id' => $publishId,
- 'post_platform_id' => $tryPost->id,
+ 'post_id' => $tryPost->id,
'origin' => PublicationOrigin::TryPost,
'provider_synced_at' => null,
'excerpt' => 'A long description that the network cuts short',
@@ -408,9 +413,9 @@ test('a tiktok post still keyed by its publish id is reconciled into the discove
expect(Post::query()->imported()->count())->toBe(0)
->and($provisional->remote_id)->toBe('7300000000000000001')
- ->and($provisional->post_platform_id)->toBe($tryPost->id)
+ ->and($provisional->post_id)->toBe($tryPost->id)
->and($tryPost->content_type)->toBe($contentType)
- ->and($tryPost->post->media)->toEqual($media)
+ ->and($tryPost->fresh()->media)->toEqual($media)
->and($tryPost->platform_post_id)->toBe('7300000000000000001')
->and($tryPost->platform_url)->toBe('https://www.tiktok.com/@trypost/video/7300000000000000001');
})->with([
@@ -421,7 +426,7 @@ test('a tiktok post still keyed by its publish id is reconciled into the discove
test('a trypost target whose id the network already confirmed is never relinked by text', function () {
$account = SocialAccount::factory()->instagram()->create();
$tryPost = sentByTryPost($account, 'media-0', 'Same caption', now()->subHour()->toImmutable());
- externalPublication($account, ['remote_id' => 'media-0', 'post_platform_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);
+ externalPublication($account, ['remote_id' => 'media-0', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);
externalPublication($account, ['remote_id' => 'media-2', 'excerpt' => 'Same caption', 'provider_published_at' => now()->subHour()]);
ImportExternalPosts::execute($account);
@@ -439,7 +444,7 @@ test('two trypost posts matching the same publication link neither and import no
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and($publication->fresh()->post_id)->toBeNull()
->and($first->fresh()->platform_post_id)->toBe('container-1')
->and($second->fresh()->platform_post_id)->toBe('container-2');
Log::shouldHaveReceived('warning')->once();
@@ -459,7 +464,7 @@ test('a tiktok discovery matching both a photo and video waits instead of claimi
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and($publication->fresh()->post_id)->toBeNull()
->and($photo->fresh()->platform_post_id)->toBe('p_pub_url~123')
->and($video->fresh()->platform_post_id)->toBe('v_pub_url~123');
Log::shouldHaveReceived('warning')->once();
@@ -507,7 +512,7 @@ test('captionless instagram discoveries wait without claiming an unresolved post
expect(ImportExternalPosts::execute($account))->toBe([])
->and(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->refresh()->post_platform_id)->toBeNull()
+ ->and($publication->refresh()->post_id)->toBeNull()
->and($publication->post_dismissed_at)->toBeNull()
->and($tryPost->fresh()->platform_post_id)->toBe('container-1');
})->with([null, '', ' ', "\u{00A0}"]);
@@ -517,7 +522,7 @@ test('a captionless discovery imports once the other instagram post has a confir
$original = sentByTryPost($account, 'media-ours', '', now()->subHour()->toImmutable());
$tracked = externalPublication($account, [
'remote_id' => 'media-ours',
- 'post_platform_id' => $original->id,
+ 'post_id' => $original->id,
'origin' => PublicationOrigin::TryPost,
'provider_synced_at' => null,
]);
@@ -529,7 +534,7 @@ test('a captionless discovery imports once the other instagram post has a confir
expect(ImportExternalPosts::execute($account))->toHaveCount(1)
->and(Post::query()->imported()->count())->toBe(1)
- ->and($native->fresh()->post_platform_id)->not->toBe($original->id)
+ ->and($native->fresh()->post_id)->not->toBe($original->id)
->and($original->fresh()->platform_post_id)->toBe('media-ours');
});
@@ -556,32 +561,34 @@ test('a captionless instagram discovery still links by its exact public id', fun
expect(ImportExternalPosts::execute($account))->toBe([])
->and(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($original->id);
+ ->and($publication->fresh()->post_id)->toBe($original->id);
});
-test('instagram discoveries wait for an in-flight publication without claiming its id', function (PostPlatformStatus $status, string $caption) {
+test('instagram discoveries wait for an in-flight publication without claiming its id', function (PublishStatus $status, string $caption) {
$account = SocialAccount::factory()->instagram()->create();
$target = sentByTryPost($account, 'container-1', $caption, now()->toImmutable());
- $target->update([
- 'status' => $status,
+ $target->forceFill([
+ 'status' => PostStatus::Publishing,
+ 'publish_status' => $status,
+ 'publication_updated_at' => now(),
'platform_post_id' => null,
'published_at' => null,
- 'error_context' => $status === PostPlatformStatus::Retrying
+ 'error_context' => $status === PublishStatus::Retrying
? ['instagram_workflow' => ['stage' => 'final_container', 'container_id' => 'container-1']]
: null,
- ]);
+ ])->save();
$publication = externalPublication($account, ['remote_id' => 'media-1', 'excerpt' => $caption, 'provider_published_at' => now()]);
expect(ImportExternalPosts::execute($account))->toBe([])
- ->and($publication->refresh()->post_platform_id)->toBeNull()
+ ->and($publication->refresh()->post_id)->toBeNull()
->and($target->refresh()->platform_post_id)->toBeNull()
- ->and($target->status)->toBe($status);
+ ->and($target->publish_status)->toBe($status);
- $target->update(['status' => PostPlatformStatus::Failed]);
+ $target->forceFill(['status' => PostStatus::Failed, 'publish_status' => PublishStatus::Failed])->save();
expect(ImportExternalPosts::execute($account))->toHaveCount(1)
- ->and($publication->refresh()->post_platform_id)->not->toBe($target->id);
-})->with([PostPlatformStatus::Publishing, PostPlatformStatus::Retrying])->with(['', 'Our caption']);
+ ->and($publication->refresh()->post_id)->not->toBe($target->id);
+})->with([PublishStatus::Publishing, PublishStatus::Retrying])->with(['', 'Our caption']);
test('an unrelated pending instagram target does not hold a native import', function (string $difference) {
$account = SocialAccount::factory()->instagram()->create();
@@ -589,14 +596,15 @@ test('an unrelated pending instagram target does not hold a native import', func
? SocialAccount::factory()->instagram()->create(['workspace_id' => $account->workspace_id])
: $account;
$target = sentByTryPost($targetAccount, 'container-1', '', now()->toImmutable());
- $target->update([
- 'status' => $difference === 'draft' ? PostPlatformStatus::Pending : PostPlatformStatus::Retrying,
- 'enabled' => $difference !== 'disabled',
+ $target->forceFill([
+ 'status' => $difference === 'draft' ? PostStatus::Draft : PostStatus::Publishing,
+ 'publish_status' => $difference === 'draft' ? PublishStatus::Pending : PublishStatus::Retrying,
+ 'publication_updated_at' => now(),
'content_type' => $difference === 'type' ? ContentType::InstagramStory : ContentType::InstagramFeed,
'platform_post_id' => null,
'published_at' => null,
'error_context' => $difference === 'no container' ? null : ['instagram_workflow' => ['container_id' => 'container-1']],
- ]);
+ ])->save();
externalPublication($account, [
'remote_id' => 'media-1',
'excerpt' => null,
@@ -605,7 +613,7 @@ test('an unrelated pending instagram target does not hold a native import', func
expect(ImportExternalPosts::execute($account))->toHaveCount(1)
->and($target->fresh()->platform_post_id)->toBeNull();
-})->with(['channel', 'time', 'type', 'disabled', 'draft', 'no container']);
+})->with(['channel', 'time', 'type', 'draft', 'no container']);
test('a trypost story is not taken over by a native feed post with the same caption', function () {
$account = SocialAccount::factory()->instagram()->create();
@@ -672,7 +680,7 @@ test('merging into the provisional trypost row keeps the network text and publis
$tryPost = sentByTryPost($account, 'v_pub_url~9', 'A caption that is long enough to match', now()->subHour()->toImmutable());
$provisional = externalPublication($account, [
'remote_id' => 'v_pub_url~9',
- 'post_platform_id' => $tryPost->id,
+ 'post_id' => $tryPost->id,
'origin' => PublicationOrigin::TryPost,
'provider_synced_at' => null,
'excerpt' => 'stale excerpt',
@@ -700,7 +708,7 @@ test('a trypost feed video that instagram reports as a reel is linked', function
ImportExternalPosts::execute($account);
expect(Post::query()->imported()->count())->toBe(0)
- ->and($publication->fresh()->post_platform_id)->toBe($tryPost->id)
+ ->and($publication->fresh()->post_id)->toBe($tryPost->id)
->and($tryPost->fresh()->platform_post_id)->toBe('reel-1');
});
@@ -724,19 +732,14 @@ test('our own thread replies are never imported as external posts', function ()
ImportExternalPosts::execute($account);
- expect(AnalyticsPublication::where('remote_id', 'reply-1')->value('post_platform_id'))->toBeNull()
- ->and(PostPlatform::where('platform_post_id', 'reply-1')->exists())->toBeFalse()
- ->and(PostPlatform::where('platform_post_id', 'other-1')->exists())->toBeTrue();
+ expect(AnalyticsPublication::where('remote_id', 'reply-1')->value('post_id'))->toBeNull()
+ ->and(Post::where('platform_post_id', 'reply-1')->exists())->toBeFalse()
+ ->and(Post::where('platform_post_id', 'other-1')->exists())->toBeTrue();
});
test('the live part of a thread that failed midway is never imported as external posts', function () {
$account = SocialAccount::factory()->bluesky()->create();
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id, 'status' => PostStatus::Failed]);
- PostPlatform::factory()->failed()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => ContentType::BlueskyPost,
+ Post::factory()->forAccount($account, ContentType::BlueskyPost)->failed()->create([
'error_context' => ['category' => 'rate_limit', ThreadProgress::KEY => [
['hash' => 'h0', 'id' => 'root-1', 'uri' => 'at://did/app.bsky.feed.post/root-1', 'cid' => 'c1'],
['hash' => 'h1', 'id' => 'reply-1', 'uri' => 'at://did/app.bsky.feed.post/reply-1', 'cid' => 'c2'],
@@ -749,8 +752,8 @@ test('the live part of a thread that failed midway is never imported as external
ImportExternalPosts::execute($account);
expect(Post::where('origin', Origin::Network)->count())->toBe(1)
- ->and(PostPlatform::where('platform_post_id', 'other-1')->exists())->toBeTrue()
- ->and(AnalyticsPublication::whereIn('remote_id', ['root-1', 'reply-1'])->whereNotNull('post_platform_id')->exists())->toBeFalse();
+ ->and(Post::where('platform_post_id', 'other-1')->exists())->toBeTrue()
+ ->and(AnalyticsPublication::whereIn('remote_id', ['root-1', 'reply-1'])->whereNotNull('post_id')->exists())->toBeFalse();
});
test('captions that differ only after a less-than sign are not linked', function () {
diff --git a/tests/Feature/Posts/ImportedPostActionsTest.php b/tests/Feature/Posts/ImportedPostActionsTest.php
index 3f554bcd7..f1aca431a 100644
--- a/tests/Feature/Posts/ImportedPostActionsTest.php
+++ b/tests/Feature/Posts/ImportedPostActionsTest.php
@@ -12,7 +12,6 @@ use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -73,7 +72,7 @@ test('duplicating an imported post creates a trypost draft with its text', funct
->and($copy->origin)->toBe(Origin::TryPost)
->and($copy->content)->toBe('Straight from the app')
->and($copy->user_id)->toBe($this->user->id)
- ->and($copy->postPlatforms()->sole()->content_type)->toBe(ContentType::InstagramFeed);
+ ->and($copy->content_type)->toBe(ContentType::InstagramFeed);
});
test('a deleted imported post is never imported again', function () {
@@ -84,22 +83,19 @@ test('a deleted imported post is never imported again', function () {
ImportExternalPosts::execute($this->account);
expect($publication->fresh()->post_dismissed_at)->not->toBeNull()
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and($publication->fresh()->post_id)->toBeNull()
->and(Post::query()->imported()->count())->toBe(0);
});
test('a deleted trypost post is never imported back', function () {
- $post = Post::factory()->published()->create(['workspace_id' => $this->workspace->id]);
- $target = PostPlatform::factory()->instagram()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $this->account->id,
+ $post = Post::factory()->forAccount($this->account)->instagram()->published()->create([
'platform_post_id' => 'ig-trypost',
]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $this->workspace->id,
'social_account_id' => $this->account->id,
'social_account_key' => $this->account->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $post->id,
'platform' => $this->account->platform,
'network' => $this->account->platform->network(),
'remote_id' => 'ig-trypost',
@@ -109,7 +105,7 @@ test('a deleted trypost post is never imported back', function () {
ImportExternalPosts::execute($this->account);
expect($publication->fresh()->post_dismissed_at)->not->toBeNull()
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and($publication->fresh()->post_id)->toBeNull()
->and(Post::query()->count())->toBe(0);
});
diff --git a/tests/Feature/Posts/MediaAspectRatioEnforcementTest.php b/tests/Feature/Posts/MediaAspectRatioEnforcementTest.php
index 5dc21fd88..96cba19ed 100644
--- a/tests/Feature/Posts/MediaAspectRatioEnforcementTest.php
+++ b/tests/Feature/Posts/MediaAspectRatioEnforcementTest.php
@@ -10,7 +10,6 @@ use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -89,27 +88,17 @@ function sidewaysJpeg(int $rawWidth, int $rawHeight): string
}
/**
- * @param array<string, mixed> $platformMeta
+ * @param array<string, mixed> $meta
*/
-function aspectTestPost(Workspace $workspace, User $user, SocialAccount $account, Media $asset, ContentType $contentType, array $platformMeta = []): array
+function aspectTestPost(Workspace $workspace, User $user, SocialAccount $account, Media $asset, ContentType $contentType, array $meta = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ return Post::factory()->forAccount($account, $contentType)->create([
'user_id' => $user->id,
'status' => Status::Draft,
'scheduled_at' => null,
'media' => [MediaItem::fromMedia($asset)->toArray()],
+ 'meta' => $meta,
]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'enabled' => true,
- 'meta' => $platformMeta,
- ]);
-
- return [$post, $platform];
}
/**
@@ -133,13 +122,13 @@ function tooWideForInstagramFeed(): string
test('the web schedule rejects an instagram feed image wider than 1.91 with a per-network message', function (string $status) {
$upload = uploadAspectTestImage($this->user, 2000, 1000);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
$response = $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => $status,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'content_type' => ContentType::InstagramFeed->value,
]);
$errors = sessionErrorMessages();
@@ -151,13 +140,13 @@ test('the web schedule rejects an instagram feed image wider than 1.91 with a pe
test('the web schedule accepts a 4:5 instagram feed image', function () {
$upload = uploadAspectTestImage($this->user, 1080, 1350);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'content_type' => ContentType::InstagramFeed->value,
])->assertSessionHasNoErrors();
expect($post->fresh()->status)->toBe(Status::Scheduled);
@@ -165,7 +154,7 @@ test('the web schedule accepts a 4:5 instagram feed image', function () {
test('client-sent dimensions never override the stored row', function () {
$upload = uploadAspectTestImage($this->user, 2000, 1000);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
$item = MediaItem::fromMedia($upload)->toArray();
$item['meta'] = [...($item['meta'] ?? []), 'width' => 1080, 'height' => 1350];
@@ -173,7 +162,7 @@ test('client-sent dimensions never override the stored row', function () {
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [$item],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'content_type' => ContentType::InstagramFeed->value,
]);
expect(sessionErrorMessages())->toContain(tooWideForInstagramFeed())
@@ -182,13 +171,13 @@ test('client-sent dimensions never override the stored row', function () {
test('an instagram story fits any image into the frame', function () {
$upload = uploadAspectTestImage($this->user, 2000, 1000);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramStory);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramStory);
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramStory->value]],
+ 'content_type' => ContentType::InstagramStory->value,
])->assertSessionHasNoErrors();
expect($post->fresh()->status)->toBe(Status::Scheduled);
@@ -202,10 +191,11 @@ test('the rest api rejects a too-wide instagram feed image on create and update'
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [['id' => $wide->id]],
- 'platforms' => [['social_account_id' => $this->instagram->id, 'content_type' => ContentType::InstagramFeed->value]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.content_type' => tooWideForInstagramFeed()]);
+ 'social_account_id' => $this->instagram->id,
+ 'content_type' => ContentType::InstagramFeed->value,
+ ])->assertUnprocessable()->assertJsonValidationErrors(['content_type' => tooWideForInstagramFeed()]);
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
$this->withHeaders($headers)->putJson(route('api.posts.update', $post), [
'status' => 'scheduled',
@@ -223,13 +213,14 @@ test('the rest api accepts a 4:5 instagram feed image', function () {
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [['id' => $portrait->id]],
- 'platforms' => [['social_account_id' => $this->instagram->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'social_account_id' => $this->instagram->id,
+ 'content_type' => ContentType::InstagramFeed->value,
])->assertCreated();
});
test('mcp scheduling and publishing reject the stored too-wide image with the same message', function () {
$wide = aspectTestAsset($this->workspace, 2000, 1000, ['width' => 2000, 'height' => 1000]);
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $post->id,
@@ -245,7 +236,7 @@ test('mcp scheduling and publishing reject the stored too-wide image with the sa
test('the stored-post publish guard rejects the too-wide image', function () {
$wide = aspectTestAsset($this->workspace, 2000, 1000, ['width' => 2000, 'height' => 1000]);
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
expect(fn () => PostStatusRules::assertStoredPostPublishable($post))
->toThrow(ValidationException::class, tooWideForInstagramFeed());
@@ -253,7 +244,7 @@ test('the stored-post publish guard rejects the too-wide image', function () {
test('a row without dimensions is measured from its file and written back', function () {
$wide = aspectTestAsset($this->workspace, 2000, 1000);
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
expect(fn () => PostStatusRules::assertStoredPostPublishable($post))
->toThrow(ValidationException::class, tooWideForInstagramFeed());
@@ -263,7 +254,7 @@ test('a row without dimensions is measured from its file and written back', func
test('an unreadable row skips the dimension check', function () {
$broken = Media::factory()->temporaryUpload($this->workspace)->create(['meta' => []]);
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $broken, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $broken, ContentType::InstagramFeed);
PostStatusRules::assertStoredPostPublishable($post);
@@ -273,7 +264,7 @@ test('an unreadable row skips the dimension check', function () {
test('google business rejects an image under 250 px on its short edge', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
$small = aspectTestAsset($this->workspace, 200, 200, ['width' => 200, 'height' => 200]);
- [$post] = aspectTestPost($this->workspace, $this->user, $account, $small, ContentType::GoogleBusinessPost);
+ $post = aspectTestPost($this->workspace, $this->user, $account, $small, ContentType::GoogleBusinessPost);
$message = trans('posts.form.warnings.image_too_small_dimensions', [
'destination' => ContentType::GoogleBusinessPost->destinationLabel(),
@@ -292,13 +283,14 @@ test('the destination names the network and the post type', function () {
test('a legacy aspect ratio no longer lets a too-wide instagram feed image through on web, api and mcp', function (string $legacyRatio) {
$upload = uploadAspectTestImage($this->user, 2000, 1000);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed, ['aspect_ratio' => $legacyRatio]);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed, ['aspect_ratio' => $legacyRatio]);
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramFeed->value, 'meta' => ['aspect_ratio' => $legacyRatio]]],
+ 'content_type' => ContentType::InstagramFeed->value,
+ 'meta' => ['aspect_ratio' => $legacyRatio],
]);
expect(sessionErrorMessages())->toContain(tooWideForInstagramFeed())
@@ -311,14 +303,12 @@ test('a legacy aspect ratio no longer lets a too-wide instagram feed image throu
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [['id' => $wide->id]],
- 'platforms' => [[
- 'social_account_id' => $this->instagram->id,
- 'content_type' => ContentType::InstagramFeed->value,
- 'meta' => ['aspect_ratio' => $legacyRatio],
- ]],
+ 'social_account_id' => $this->instagram->id,
+ 'content_type' => ContentType::InstagramFeed->value,
+ 'meta' => ['aspect_ratio' => $legacyRatio],
])->assertUnprocessable()->assertJsonFragment([tooWideForInstagramFeed()]);
- [$stored] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed, ['aspect_ratio' => $legacyRatio]);
+ $stored = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed, ['aspect_ratio' => $legacyRatio]);
$this->withHeaders($headers)->putJson(route('api.posts.update', $stored), [
'status' => 'scheduled',
@@ -339,7 +329,7 @@ test('a legacy aspect ratio no longer lets a too-wide instagram feed image throu
test('the web schedule still refuses a ratio-breaking composer item that carries a non-null upload_token', function () {
$upload = aspectTestAsset($this->workspace, 500, 1000, ['width' => 500, 'height' => 1000]);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $upload, ContentType::InstagramFeed);
expect($upload->upload_token)->not->toBeNull();
@@ -347,7 +337,7 @@ test('the web schedule still refuses a ratio-breaking composer item that carries
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [[...MediaItem::fromMedia($upload)->toArray(), 'upload_token' => $upload->upload_token]],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::InstagramFeed->value]],
+ 'content_type' => ContentType::InstagramFeed->value,
]);
expect(implode(' ', sessionErrorMessages()))->toContain('0.50')
@@ -357,13 +347,13 @@ test('the web schedule still refuses a ratio-breaking composer item that carries
test('a facebook post schedules an image of any ratio on web, api and mcp', function (int $width, int $height) {
$facebook = SocialAccount::factory()->facebook()->create(['workspace_id' => $this->workspace->id]);
$upload = uploadAspectTestImage($this->user, $width, $height);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $facebook, $upload, ContentType::FacebookPost);
+ $post = aspectTestPost($this->workspace, $this->user, $facebook, $upload, ContentType::FacebookPost);
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::FacebookPost->value]],
+ 'content_type' => ContentType::FacebookPost->value,
])->assertSessionHasNoErrors();
expect($post->fresh()->status)->toBe(Status::Scheduled);
@@ -376,10 +366,13 @@ test('a facebook post schedules an image of any ratio on web, api and mcp', func
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [['id' => $asset->id]],
- 'platforms' => [['social_account_id' => $facebook->id, 'content_type' => ContentType::FacebookPost->value]],
+ 'social_account_id' => $facebook->id,
+ 'content_type' => ContentType::FacebookPost->value,
])->assertCreated();
- [$mcpPost] = aspectTestPost($this->workspace, $this->user, $facebook, $asset, ContentType::FacebookPost);
+ $mcpAsset = aspectTestAsset($this->workspace, $width, $height, ['width' => $width, 'height' => $height]);
+ $mcpAsset->update(['size' => 500_000]);
+ $mcpPost = aspectTestPost($this->workspace, $this->user, $facebook, $mcpAsset, ContentType::FacebookPost);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $mcpPost->id,
@@ -400,10 +393,10 @@ test('a sideways phone photo is measured as people see it', function () {
expect($tall->meta)->toMatchArray(['width' => 1080, 'height' => 1350])
->and($wide->meta)->toMatchArray(['width' => 2000, 'height' => 1000]);
- [$accepted] = aspectTestPost($this->workspace, $this->user, $this->instagram, $tall, ContentType::InstagramFeed);
+ $accepted = aspectTestPost($this->workspace, $this->user, $this->instagram, $tall, ContentType::InstagramFeed);
PostStatusRules::assertStoredPostPublishable($accepted);
- [$rejected] = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
+ $rejected = aspectTestPost($this->workspace, $this->user, $this->instagram, $wide, ContentType::InstagramFeed);
expect(fn () => PostStatusRules::assertStoredPostPublishable($rejected))
->toThrow(ValidationException::class, tooWideForInstagramFeed());
});
@@ -411,7 +404,7 @@ test('a sideways phone photo is measured as people see it', function () {
test('a row measured on demand applies the exif orientation', function () {
$asset = Media::factory()->temporaryUpload($this->workspace)->create(['meta' => []]);
Storage::put($asset->path, sidewaysJpeg(1000, 2000));
- [$post] = aspectTestPost($this->workspace, $this->user, $this->instagram, $asset, ContentType::InstagramFeed);
+ $post = aspectTestPost($this->workspace, $this->user, $this->instagram, $asset, ContentType::InstagramFeed);
expect(fn () => PostStatusRules::assertStoredPostPublishable($post))
->toThrow(ValidationException::class, tooWideForInstagramFeed());
@@ -435,8 +428,8 @@ test('telegram limits the ratio of photos only', function () {
$strip = aspectTestAsset($this->workspace, 3000, 100, ['width' => 3000, 'height' => 100]);
$video = Media::factory()->video()->temporaryUpload($this->workspace)->create(['meta' => ['width' => 3000, 'height' => 100, 'duration' => 5]]);
- [$photoPost] = aspectTestPost($this->workspace, $this->user, $account, $strip, ContentType::TelegramPost);
- [$videoPost] = aspectTestPost($this->workspace, $this->user, $account, $video, ContentType::TelegramPost);
+ $photoPost = aspectTestPost($this->workspace, $this->user, $account, $strip, ContentType::TelegramPost);
+ $videoPost = aspectTestPost($this->workspace, $this->user, $account, $video, ContentType::TelegramPost);
expect(fn () => PostStatusRules::assertStoredPostPublishable($photoPost))->toThrow(ValidationException::class);
@@ -451,13 +444,13 @@ test('an upload stores the dimensions measured from its bytes', function () {
test('a facebook story schedules an image of any ratio, fitted into the frame at publish', function (int $width, int $height) {
$facebook = SocialAccount::factory()->facebook()->create(['workspace_id' => $this->workspace->id]);
$upload = uploadAspectTestImage($this->user, $width, $height);
- [$post, $platform] = aspectTestPost($this->workspace, $this->user, $facebook, $upload, ContentType::FacebookStory);
+ $post = aspectTestPost($this->workspace, $this->user, $facebook, $upload, ContentType::FacebookStory);
$this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [MediaItem::fromMedia($upload)->toArray()],
- 'platforms' => [['id' => $platform->id, 'content_type' => ContentType::FacebookStory->value]],
+ 'content_type' => ContentType::FacebookStory->value,
])->assertSessionHasNoErrors();
expect($post->fresh()->status)->toBe(Status::Scheduled);
diff --git a/tests/Feature/Posts/MoveChannelPostToQueueSlotTest.php b/tests/Feature/Posts/MoveChannelPostToQueueSlotTest.php
index ad30f1e76..a0ada3002 100644
--- a/tests/Feature/Posts/MoveChannelPostToQueueSlotTest.php
+++ b/tests/Feature/Posts/MoveChannelPostToQueueSlotTest.php
@@ -8,7 +8,6 @@ use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -42,8 +41,7 @@ beforeEach(function () {
function moveToSlotQueuedPost(SocialAccount $channel, User $user): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ $post = Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
@@ -51,8 +49,6 @@ function moveToSlotQueuedPost(SocialAccount $channel, User $user): Post
'scheduled_at' => null,
]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id, 'platform' => $channel->platform]);
-
Cache::lock("queue:{$channel->id}")->forceRelease();
ReflowChannelQueue::handle($channel, $post, QueuePosition::Next);
@@ -64,8 +60,7 @@ function moveToSlotQueuedPost(SocialAccount $channel, User $user): Post
*/
function moveToSlotCustomPost(SocialAccount $channel, User $user, array $attributes = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create([
'user_id' => $user->id,
'content' => 'Custom post',
'status' => PostStatus::Scheduled,
@@ -73,10 +68,6 @@ function moveToSlotCustomPost(SocialAccount $channel, User $user, array $attribu
'scheduled_at' => CarbonImmutable::parse('2026-10-20 15:30:00', 'UTC'),
...$attributes,
]);
-
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id, 'platform' => $channel->platform]);
-
- return $post;
}
test('a custom post dropped on a free slot becomes a queue post at that slot', function () {
@@ -144,18 +135,6 @@ test('a post that does not belong to the channel or is not scheduled is rejected
expect($post->fresh()->only(['status', 'scheduled_at', 'schedule_mode']))->toEqual($before);
})->with(['other channel', 'draft', 'other workspace', 'pending approval', 'published', 'failed', 'due within a minute']);
-test('a post created for several channels at once cannot be moved to a slot', function () {
- $legacy = moveToSlotCustomPost($this->channel, $this->user);
- PostPlatform::factory()->create(['post_id' => $legacy->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $this->workspace->id])->id]);
-
- $this->actingAs($this->user)
- ->put(route('app.channels.queue.slot', $this->channel), ['post_id' => $legacy->id, 'slot_at' => '2026-10-06T12:00:00+00:00'])
- ->assertSessionHasErrors('queue');
-
- expect($legacy->fresh()->schedule_mode)->toBe(ScheduleMode::Custom)
- ->and($legacy->fresh()->scheduled_at->toIso8601String())->toBe('2026-10-20T15:30:00+00:00');
-});
-
test('a member who needs approval cannot move a post to a slot', function () {
$requester = User::factory()->create([
'account_id' => $this->user->account_id,
diff --git a/tests/Feature/Posts/PostApprovalActionsTest.php b/tests/Feature/Posts/PostApprovalActionsTest.php
index 379cc455a..734cfca17 100644
--- a/tests/Feature/Posts/PostApprovalActionsTest.php
+++ b/tests/Feature/Posts/PostApprovalActionsTest.php
@@ -12,7 +12,6 @@ use App\Enums\Webhook\EventType;
use App\Jobs\DispatchWebhook;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -248,19 +247,11 @@ test('approving while another approval holds the post reports the queue as busy'
expect($request->fresh()->status)->toBe(PostStatus::PendingApproval);
});
-test('approving a legacy request that misses required meta keeps it pending', function () {
- $request = Post::factory()->pendingApproval()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->requester->id,
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $request->id,
- 'social_account_id' => $this->channel->id,
- ]);
- PostPlatform::factory()->discord()->create([
- 'post_id' => $request->id,
- 'social_account_id' => SocialAccount::factory()->discord()->create(['workspace_id' => $this->workspace->id])->id,
- ]);
+test('approving a request that misses required meta keeps it pending', function () {
+ $request = Post::factory()
+ ->forAccount(SocialAccount::factory()->discord()->create(['workspace_id' => $this->workspace->id]), ContentType::DiscordMessage)
+ ->pendingApproval()
+ ->create(['user_id' => $this->requester->id]);
$this->actingAs($this->owner)
->put(route('app.posts.approve', $request))
@@ -291,7 +282,7 @@ test('approving from the composer waits for the same approval lock', function ()
Cache::partialMock()->shouldReceive('lock')->with("post-approval:{$request->id}", PostApproval::LOCK_SECONDS)->andReturn($lock);
$this->actingAs($this->owner)
- ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Approved in the composer'])
+ ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Approved in the composer'])
->assertSessionHasErrors(['queue' => __('posts.errors.queue_busy')]);
expect($request->fresh()->status)->toBe(PostStatus::PendingApproval);
@@ -300,7 +291,7 @@ test('approving from the composer waits for the same approval lock', function ()
function approvalActionsEditQueued(object $test, Post $post): void
{
$test->actingAs($test->requester)
- ->put(route('app.posts.update', $post), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited by the member'])
+ ->put(route('app.posts.update', $post), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Edited by the member'])
->assertSessionHasNoErrors();
}
diff --git a/tests/Feature/Posts/PostApprovalGateTest.php b/tests/Feature/Posts/PostApprovalGateTest.php
index 23c107e62..045417737 100644
--- a/tests/Feature/Posts/PostApprovalGateTest.php
+++ b/tests/Feature/Posts/PostApprovalGateTest.php
@@ -18,7 +18,6 @@ use App\Mcp\Tools\Post\CreatePostsTool;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -135,10 +134,8 @@ test('a requester cannot reach the public api, so it can never bypass approval',
->postJson(route('api.posts.store'), [
'status' => 'publishing',
'content' => 'From the API',
- 'platforms' => [[
- 'social_account_id' => $this->channel->id,
- 'content_type' => ContentType::LinkedInPost->value,
- ]],
+ 'social_account_id' => $this->channel->id,
+ 'content_type' => ContentType::LinkedInPost->value,
])
->assertForbidden();
@@ -165,7 +162,7 @@ test('editing an approved queued post returns it to pending and keeps reserving
expect(approvalGateSlot($second))->toBe('Wed 09:00');
$this->actingAs($this->requester)
- ->put(route('app.posts.update', $first), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited by a requester'])
+ ->put(route('app.posts.update', $first), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Edited by a requester'])
->assertSessionHasNoErrors();
$first->refresh();
@@ -183,7 +180,7 @@ test('editing a pending post keeps the original request time', function () {
$this->travel(5)->minutes();
$this->actingAs($this->requester)
- ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'content' => 'Second try'])
+ ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'content' => 'Second try'])
->assertSessionHasNoErrors();
$request->refresh();
@@ -212,7 +209,7 @@ test('a direct publisher saving a pending post approves it', function () {
$request = approvalGateStore($this, $this->requester);
$this->actingAs($this->owner)
- ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Fixed and approved'])
+ ->put(route('app.posts.update', $request), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Fixed and approved'])
->assertSessionHasNoErrors();
$request->refresh();
@@ -297,7 +294,7 @@ test('a requester editing someone else\'s approved post becomes the one who aske
$scheduled = approvalGateStore($this, $this->owner);
$this->actingAs($this->requester)
- ->put(route('app.posts.update', $scheduled), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Typo fixed'])
+ ->put(route('app.posts.update', $scheduled), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Typo fixed'])
->assertSessionHasNoErrors();
$scheduled->refresh();
@@ -324,7 +321,7 @@ test('returning an approved post to approval queues a post.unscheduled webhook',
$scheduled = approvalGateStore($this, $this->owner);
$this->actingAs($this->requester)
- ->put(route('app.posts.update', $scheduled), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited'])
+ ->put(route('app.posts.update', $scheduled), ['status' => 'scheduled', 'content_type' => ContentType::LinkedInPost->value, 'queue' => 'next', 'content' => 'Edited'])
->assertSessionHasNoErrors();
Queue::assertPushed(DispatchWebhook::class, fn (DispatchWebhook $job): bool => $job->eventType === EventType::PostUnscheduled->value
@@ -379,39 +376,25 @@ test('a requester editing an approved post through mcp returns it to approval',
});
/**
- * A legacy post with two enabled targets, scheduled by the owner.
+ * A post scheduled by the owner at a custom time.
*/
-function approvalGateLegacyPost(object $test, PostStatus $status = PostStatus::Scheduled): Post
+function approvalGateCustomPost(object $test, PostStatus $status = PostStatus::Scheduled): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $test->workspace->id,
+ return Post::factory()->forAccount($test->channel, ContentType::LinkedInPost)->create([
'user_id' => $test->owner->id,
'status' => $status,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->addDays(2),
- 'content' => 'Legacy post',
+ 'content' => 'Custom post',
'approval_requested_at' => $status === PostStatus::PendingApproval ? now() : null,
]);
- $x = SocialAccount::factory()->x()->create(['workspace_id' => $test->workspace->id]);
-
- foreach ([$test->channel, $x] as $channel) {
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- 'content_type' => $channel->platform === Platform::X ? ContentType::XPost : ContentType::LinkedInPost,
- 'enabled' => true,
- ]);
- }
-
- return $post;
}
-test('a requester editing a legacy multi-target post returns it to approval', function () {
- $legacy = approvalGateLegacyPost($this);
+test('a requester editing a custom-time post returns it to approval at the same time', function () {
+ $legacy = approvalGateCustomPost($this);
$requestedAt = $legacy->scheduled_at;
- UpdatePost::execute($this->workspace, $legacy, ['status' => 'scheduled', 'content' => 'Legacy edit'], $this->requester);
+ UpdatePost::execute($this->workspace, $legacy, ['status' => 'scheduled', 'content' => 'Edited'], $this->requester);
$legacy->refresh();
@@ -422,8 +405,8 @@ test('a requester editing a legacy multi-target post returns it to approval', fu
Queue::assertNotPushed(PublishPost::class);
});
-test('approving a legacy multi-target request to publish now drops the requested time', function () {
- $legacy = approvalGateLegacyPost($this, PostStatus::PendingApproval);
+test('approving a custom-time request to publish now drops the requested time', function () {
+ $legacy = approvalGateCustomPost($this, PostStatus::PendingApproval);
UpdatePost::execute($this->workspace, $legacy, ['status' => 'publishing'], $this->owner);
diff --git a/tests/Feature/Posts/PostCardPrivacyTest.php b/tests/Feature/Posts/PostCardPrivacyTest.php
index d2d8fa933..4f3f82619 100644
--- a/tests/Feature/Posts/PostCardPrivacyTest.php
+++ b/tests/Feature/Posts/PostCardPrivacyTest.php
@@ -7,7 +7,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -42,22 +41,13 @@ beforeEach(function () {
function privacyPost(SocialAccount $channel, User $author, array $attributes = []): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create([
'user_id' => $author->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->addDay(),
...$attributes,
]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- ]);
-
- return $post;
}
function deferredPublishPayload(object $test, User $viewer, array $query): array
diff --git a/tests/Feature/Posts/PostGroupTest.php b/tests/Feature/Posts/PostGroupTest.php
index a147dfbc7..057049e17 100644
--- a/tests/Feature/Posts/PostGroupTest.php
+++ b/tests/Feature/Posts/PostGroupTest.php
@@ -11,7 +11,6 @@ use App\Mcp\Tools\Post\CreatePostsTool;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -42,8 +41,7 @@ beforeEach(function () {
function groupedPost(SocialAccount $channel, User $user, ?string $groupId, array $attributes = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $user->id,
'post_group_id' => $groupId,
'content' => 'Shared caption',
@@ -51,10 +49,6 @@ function groupedPost(SocialAccount $channel, User $user, ?string $groupId, array
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->addDay(),
], $attributes));
-
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id]);
-
- return $post;
}
function groupDestinations(iterable $channels): array
@@ -160,7 +154,7 @@ test('the group endpoint lists the posts created together, ordered by time then
->getJson(route('app.posts.group.show', $firstChannelLast))
->assertOk()
->assertJsonCount(4)
- ->assertJsonPath('0.post_platforms.0.social_account.id', $this->channels[1]->id)
+ ->assertJsonPath('0.social_account.id', $this->channels[1]->id)
->assertJsonPath('0.can_delete', true)
->assertJsonPath('3.status', PostStatus::Draft->value);
@@ -215,25 +209,18 @@ test('the group endpoint is tenancy scoped', function () {
test('the group endpoint carries the latest metrics of its sent posts', function () {
$groupId = '0190a3b2-0000-7000-8000-000000000010';
$channel = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $sent = Post::factory()->published()->create([
- 'workspace_id' => $this->workspace->id,
+ $sent = Post::factory()->forAccount($channel, ContentType::InstagramFeed)->published()->create([
'user_id' => $this->user->id,
'post_group_id' => $groupId,
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $sent->id,
- 'social_account_id' => $channel->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $this->workspace->id,
'social_account_id' => $channel->id,
'social_account_key' => $channel->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $sent->id,
'platform' => Platform::Instagram,
'network' => Platform::Instagram->network(),
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $sent->platform_post_id,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
@@ -248,8 +235,8 @@ test('the group endpoint carries the latest metrics of its sent posts', function
$posts = collect($response->json())->keyBy('id');
- expect(data_get($posts, "{$sent->id}.metrics.{$target->id}.available"))->toBeTrue()
- ->and(data_get($posts, "{$sent->id}.metrics.{$target->id}.metrics.reactions.value"))->toBe(12)
+ expect(data_get($posts, "{$sent->id}.metrics.available"))->toBeTrue()
+ ->and(data_get($posts, "{$sent->id}.metrics.metrics.reactions.value"))->toBe(12)
->and(data_get($posts, "{$scheduled->id}.metrics"))->toBeNull();
});
@@ -280,25 +267,18 @@ test('the group endpoint runs a fixed number of queries with sent siblings', fun
$groupId = '0190a3b2-0000-7000-8000-00000000000f';
$channel = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
$sentSibling = function () use ($channel, $groupId): void {
- $sent = Post::factory()->published()->create([
- 'workspace_id' => $this->workspace->id,
+ $sent = Post::factory()->forAccount($channel, ContentType::InstagramFeed)->published()->create([
'user_id' => $this->user->id,
'post_group_id' => $groupId,
]);
- $target = PostPlatform::factory()->published()->create([
- 'post_id' => $sent->id,
- 'social_account_id' => $channel->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- ]);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $this->workspace->id,
'social_account_id' => $channel->id,
'social_account_key' => $channel->id,
- 'post_platform_id' => $target->id,
+ 'post_id' => $sent->id,
'platform' => Platform::Instagram,
'network' => Platform::Instagram->network(),
- 'remote_id' => $target->platform_post_id,
+ 'remote_id' => $sent->platform_post_id,
]);
AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publication->id]);
};
diff --git a/tests/Feature/Posts/PostOriginTest.php b/tests/Feature/Posts/PostOriginTest.php
index 46b83f2dc..4380bf55a 100644
--- a/tests/Feature/Posts/PostOriginTest.php
+++ b/tests/Feature/Posts/PostOriginTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Enums\Post\Origin;
use App\Models\AnalyticsPublication;
use App\Models\Post;
-use App\Models\PostPlatform;
test('a post defaults to the trypost origin', function () {
$post = Post::factory()->create();
@@ -25,9 +24,9 @@ test('the origin scopes separate imported posts from trypost posts', function ()
test('a permalink longer than 255 characters is stored whole', function () {
$url = 'https://www.facebook.com/permalink.php?story_fbid='.str_repeat('9', 600);
- $platform = PostPlatform::factory()->published()->create(['platform_url' => $url]);
+ $post = Post::factory()->facebook()->published()->create(['platform_url' => $url]);
- expect($platform->fresh()->platform_url)->toBe($url);
+ expect($post->fresh()->platform_url)->toBe($url);
});
test('a publication records when its imported post was dismissed', function () {
diff --git a/tests/Feature/Posts/PostQueueTest.php b/tests/Feature/Posts/PostQueueTest.php
index 8f6efb503..3f54c52db 100644
--- a/tests/Feature/Posts/PostQueueTest.php
+++ b/tests/Feature/Posts/PostQueueTest.php
@@ -13,7 +13,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -90,8 +89,8 @@ test('storing with queue next gives each channel its own first slot', function (
->assertSessionHasNoErrors()
->assertRedirect(route('app.posts.index', ['tab' => 'queue']));
- $posts = Post::query()->with('postPlatforms')->whereIn('id', session('created_post_ids'))->get()
- ->keyBy(fn (Post $post): string => $post->postPlatforms->first()->social_account_id);
+ $posts = Post::query()->whereIn('id', session('created_post_ids'))->get()
+ ->keyBy(fn (Post $post): string => $post->social_account_id);
expect($posts)->toHaveCount(2)
->and($posts[$this->channel->id]->schedule_mode)->toBe(ScheduleMode::Queue)
@@ -179,7 +178,7 @@ test('updating only the content of a queued post keeps every slot', function ()
$second = postQueueStore($this, $this->channel);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $first), ['status' => 'scheduled', 'content' => 'Edited caption'])
+ ->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'content' => 'Edited caption'])
->assertSessionHasNoErrors();
$first->refresh();
@@ -197,6 +196,7 @@ test('giving a queued post a custom time pins it and the others keep their slots
$this->actingAs($this->user)
->put(route('app.posts.update', $first), [
+ 'content_type' => ContentType::LinkedInPost->value,
'status' => 'scheduled',
'content' => 'Pinned',
'scheduled_at' => $custom->toIso8601String(),
@@ -215,7 +215,7 @@ test('moving a queued post to draft clears its mode and leaves its slot free', f
$second = postQueueStore($this, $this->channel);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $first), ['status' => 'draft', 'content' => 'Back to draft'])
+ ->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'draft', 'content' => 'Back to draft'])
->assertSessionHasNoErrors();
$first->refresh();
@@ -230,7 +230,7 @@ test('publishing a queued post now leaves the others in their slots', function (
$second = postQueueStore($this, $this->channel);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $first), ['status' => 'publishing', 'content' => 'Now'])
+ ->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'publishing', 'content' => 'Now'])
->assertSessionHasNoErrors();
expect($first->refresh()->schedule_mode)->toBeNull()
@@ -247,7 +247,7 @@ test('adding a draft to the queue puts it at the end', function () {
$draft = Post::findOrFail(session('created_post_ids')[0]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $draft), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])
+ ->put(route('app.posts.update', $draft), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])
->assertSessionHasNoErrors();
$draft->refresh();
@@ -265,7 +265,7 @@ test('updating with queue is rejected when the channel has no slots', function (
$draft = Post::sole();
$this->actingAs($this->user)
- ->putJson(route('app.posts.update', $draft), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])
+ ->putJson(route('app.posts.update', $draft), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Joining'])
->assertUnprocessable()
->assertJsonValidationErrors(['queue']);
@@ -277,6 +277,7 @@ test('updating with queue and scheduled_at is rejected', function () {
$this->actingAs($this->user)
->putJson(route('app.posts.update', $post), [
+ 'content_type' => ContentType::LinkedInPost->value,
'status' => 'scheduled',
'queue' => 'next',
'scheduled_at' => now()->addDay()->toIso8601String(),
@@ -285,25 +286,6 @@ test('updating with queue and scheduled_at is rejected', function () {
->assertJsonValidationErrors(['queue']);
});
-test('queueing a legacy multi-target post is rejected', function () {
- $other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- ]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $this->channel->id, 'enabled' => true]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $other->id, 'enabled' => true]);
-
- $this->actingAs($this->user)
- ->putJson(route('app.posts.update', $post), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Legacy'])
- ->assertUnprocessable()
- ->assertJsonValidationErrors(['queue' => __('posts.errors.queue_legacy_post')]);
-
- expect($post->refresh()->status)->toBe(PostStatus::Draft)
- ->and($post->schedule_mode)->toBeNull();
-});
-
test('deleting a queued post leaves its slot free and the others in place', function () {
$first = postQueueStore($this, $this->channel);
$second = postQueueStore($this, $this->channel);
@@ -455,8 +437,7 @@ test('a time zone change moves a pending holder to the first free slot when its
postQueueStoreAtSlot($this, $requester, $this->channel, CarbonImmutable::parse('2026-10-05 09:00', 'America/Sao_Paulo'))
->assertSessionHasNoErrors();
$holder = Post::query()->sole();
- $custom = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => CarbonImmutable::parse('2026-10-05 09:00', 'UTC'), 'schedule_mode' => ScheduleMode::Custom]);
- PostPlatform::factory()->create(['post_id' => $custom->id, 'social_account_id' => $this->channel->id, 'enabled' => true]);
+ $custom = Post::factory()->forAccount($this->channel)->scheduled()->create(['user_id' => $this->user->id, 'scheduled_at' => CarbonImmutable::parse('2026-10-05 09:00', 'UTC'), 'schedule_mode' => ScheduleMode::Custom]);
$this->actingAs($this->user)
->putJson(route('app.channels.posting-schedule.update', $this->channel), [
@@ -476,8 +457,7 @@ test('a time zone change with no slot left turns a pending holder custom at its
postQueueStoreAtSlot($this, $requester, $this->channel, CarbonImmutable::parse('2037-12-30 09:00', 'America/Sao_Paulo'))
->assertSessionHasNoErrors();
$holder = Post::query()->sole();
- $custom = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'scheduled_at' => CarbonImmutable::parse('2037-12-30 09:00', 'UTC'), 'schedule_mode' => ScheduleMode::Custom]);
- PostPlatform::factory()->create(['post_id' => $custom->id, 'social_account_id' => $this->channel->id, 'enabled' => true]);
+ $custom = Post::factory()->forAccount($this->channel)->scheduled()->create(['user_id' => $this->user->id, 'scheduled_at' => CarbonImmutable::parse('2037-12-30 09:00', 'UTC'), 'schedule_mode' => ScheduleMode::Custom]);
$queued = postQueueStore($this, $this->channel);
$at = $holder->refresh()->scheduled_at;
@@ -617,7 +597,7 @@ test('re-sending queue next on a queued post keeps its slot', function () {
$second = postQueueStore($this, $this->channel);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $first), ['status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited'])
+ ->put(route('app.posts.update', $first), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'next', 'content' => 'Edited'])
->assertSessionHasNoErrors();
expect($first->refresh()->content)->toBe('Edited')
@@ -632,7 +612,7 @@ test('queue top on a queued post moves it to the top', function () {
$third = postQueueStore($this, $this->channel);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $second), ['status' => 'scheduled', 'queue' => 'top', 'content' => 'Urgent'])
+ ->put(route('app.posts.update', $second), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'scheduled', 'queue' => 'top', 'content' => 'Urgent'])
->assertSessionHasNoErrors();
expect(postQueueSlot($second))->toBe('Mon 09:00')
diff --git a/tests/Feature/Posts/PostRecurrenceTest.php b/tests/Feature/Posts/PostRecurrenceTest.php
index dbca60fd3..4a894fa39 100644
--- a/tests/Feature/Posts/PostRecurrenceTest.php
+++ b/tests/Feature/Posts/PostRecurrenceTest.php
@@ -4,15 +4,15 @@ declare(strict_types=1);
use App\Actions\Post\FinalizePostPublication;
use App\Actions\Post\UpdatePost;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\RecurrenceFrequency;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
+use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -39,28 +39,19 @@ beforeEach(function () {
function recurringPost(SocialAccount $channel, User $user, array $attributes = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $user->id,
'content' => 'A recurring caption',
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Custom,
'scheduled_at' => now()->addDays(2),
- ], $attributes));
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
'meta' => ['visibility' => 'PUBLIC'],
- ]);
-
- return $post->refresh();
+ ], $attributes))->refresh();
}
-function publishRecurringPost(Post $post, PostPlatformStatus $status = PostPlatformStatus::Published): void
+function publishRecurringPost(Post $post, PublishStatus $status = PublishStatus::Published): void
{
- $post->update(['status' => PostStatus::Publishing]);
- $post->postPlatforms()->update(['status' => $status]);
+ $post->forceFill(['status' => PostStatus::Publishing, 'publish_status' => $status])->save();
app(FinalizePostPublication::class)->handle($post);
}
@@ -70,7 +61,7 @@ function nextOccurrence(Post $post): ?Post
return Post::query()
->where('workspace_id', $post->workspace_id)
->whereKeyNot($post->id)
- ->with('postPlatforms', 'labels')
+ ->with('labels')
->first();
}
@@ -258,9 +249,9 @@ test('publishing a recurring post schedules exactly one next occurrence', functi
->and($next->recurrence_remaining)->toBe(2)
->and($next->post_group_id)->not->toBeNull()
->and($next->post_group_id)->not->toBe($post->post_group_id)
- ->and($next->postPlatforms)->toHaveCount(1)
- ->and($next->postPlatforms->first()->social_account_id)->toBe($this->channel->id)
- ->and($next->postPlatforms->first()->meta)->toEqual(['visibility' => 'PUBLIC'])
+ ->and($next->social_account_id)->toBe($this->channel->id)
+ ->and($next->publish_status)->toBe(PublishStatus::Pending)
+ ->and($next->meta)->toEqual(['visibility' => 'PUBLIC'])
->and($next->labels->pluck('id')->all())->toBe([$label->id]);
})->with([
'day' => [RecurrenceFrequency::Day, '2026-10-05 09:00', '2026-10-06 09:00:00'],
@@ -349,7 +340,7 @@ test('a failed post hands its recurrence to the next occurrence', function () {
'recurrence_remaining' => 5,
]);
- publishRecurringPost($post, PostPlatformStatus::Failed);
+ publishRecurringPost($post, PublishStatus::Failed);
$next = nextOccurrence($post);
@@ -369,7 +360,7 @@ test('retrying a failed occurrence never creates a second next occurrence', func
'recurrence_remaining' => 5,
]);
- publishRecurringPost($post, PostPlatformStatus::Failed);
+ publishRecurringPost($post, PublishStatus::Failed);
publishRecurringPost($post->refresh());
expect($post->refresh()->status)->toBe(PostStatus::Published)
@@ -407,33 +398,6 @@ test('a failure while scheduling the next occurrence keeps the rule for a later
->and(nextOccurrence($post)->recurrence_remaining)->toBe(4);
});
-test('a multi-channel post continues the series on every enabled channel', function () {
- $other = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $disabled = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::LinkedIn]);
- $post = recurringPost($this->channel, $this->user, [
- 'scheduled_at' => now()->subMinute(),
- 'recurrence_interval' => 1,
- 'recurrence_frequency' => RecurrenceFrequency::Day,
- 'recurrence_remaining' => 2,
- ]);
- PostPlatform::factory()->failed()->create(['post_id' => $post->id, 'social_account_id' => $other->id]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $disabled->id, 'enabled' => false]);
- $post->update(['status' => PostStatus::Publishing]);
- $post->postPlatforms()->where('social_account_id', $this->channel->id)->update(['status' => PostPlatformStatus::Published]);
-
- app(FinalizePostPublication::class)->handle($post);
-
- $occurrences = Post::query()->whereKeyNot($post->id)->with('postPlatforms')->get();
-
- expect($post->refresh()->status)->toBe(PostStatus::PartiallyPublished)
- ->and($post->isRecurring())->toBeFalse()
- ->and($occurrences)->toHaveCount(2)
- ->and($occurrences->map(fn (Post $occurrence): string => $occurrence->postPlatforms->sole()->social_account_id)->sort()->values()->all())
- ->toBe(collect([$this->channel->id, $other->id])->sort()->values()->all())
- ->and($occurrences->every(fn (Post $occurrence): bool => $occurrence->recurrence_remaining === 1
- && $occurrence->scheduled_at->equalTo(now()->subMinute()->addDay())))->toBeTrue();
-});
-
test('an anchor in the past catches up and consumes the skipped occurrences', function () {
$post = recurringPost($this->channel, $this->user, [
'scheduled_at' => now()->subDays(17),
@@ -505,7 +469,7 @@ test('publishing now from any entry point keeps the rhythm of the original time'
})->with([
'composer' => [function ($test, Post $post): void {
$test->actingAs($test->user)
- ->put(route('app.posts.update', $post), ['status' => 'publishing', 'content' => 'Now', 'scheduled_at' => null])
+ ->put(route('app.posts.update', $post), ['content_type' => ContentType::LinkedInPost->value, 'status' => 'publishing', 'content' => 'Now', 'scheduled_at' => null])
->assertSessionHasNoErrors();
}],
'mcp' => [function ($test, Post $post): void {
@@ -673,11 +637,11 @@ test('the next occurrence does not inherit the reactions of the published one',
'recurrence_frequency' => RecurrenceFrequency::Day,
'recurrence_remaining' => 2,
]);
- $post->postPlatforms()->sole()->update(['meta' => ['visibility' => 'PUBLIC', 'reactions' => [['type' => '👍', 'count' => 3]]]]);
+ $post->forceFill(['meta' => ['visibility' => 'PUBLIC', 'reactions' => [['type' => '👍', 'count' => 3]]]])->save();
publishRecurringPost($post);
- expect(nextOccurrence($post)->postPlatforms->sole()->meta)->toEqual(['visibility' => 'PUBLIC']);
+ expect(nextOccurrence($post)->meta)->toEqual(['visibility' => 'PUBLIC']);
});
test('an author who left the workspace hands the next occurrence to the workspace owner', function () {
diff --git a/tests/Feature/Posts/PostScheduleActionTest.php b/tests/Feature/Posts/PostScheduleActionTest.php
index 5a07df65c..71ed697f2 100644
--- a/tests/Feature/Posts/PostScheduleActionTest.php
+++ b/tests/Feature/Posts/PostScheduleActionTest.php
@@ -9,7 +9,6 @@ use App\Enums\Post\Status as PostStatus;
use App\Enums\SocialAccount\Platform;
use App\Jobs\PublishPost;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -36,18 +35,13 @@ beforeEach(function () {
function scheduleActionPost(SocialAccount $channel, User $user, array $attributes = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $user->id,
'content' => 'A caption',
'status' => PostStatus::Draft,
'schedule_mode' => null,
'scheduled_at' => null,
- ], $attributes));
-
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id]);
-
- return $post->refresh();
+ ], $attributes))->refresh();
}
function scheduleActionQueued(SocialAccount $channel, User $user): Post
@@ -150,19 +144,18 @@ test('publish now dispatches the publish job', function () {
Queue::assertPushed(PublishPost::class, fn (PublishPost $job): bool => $job->post->is($draft));
});
-test('publish now on a post without enabled platforms is rejected', function () {
+test('publish now on a post without a channel is rejected', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'content' => 'A caption',
'status' => PostStatus::Draft,
]);
- PostPlatform::factory()->disabled()->create(['post_id' => $post->id, 'social_account_id' => $this->channel->id]);
$this->actingAs($this->user)
->put(route('app.posts.schedule.update', $post), ['action' => 'publish_now'])
->assertRedirect()
- ->assertSessionHasErrors('platforms');
+ ->assertSessionHasErrors('social_account_id');
expect($post->fresh()->status)->toBe(PostStatus::Draft);
Queue::assertNotPushed(PublishPost::class);
diff --git a/tests/Feature/Posts/PruneExpiredPostHistoryTest.php b/tests/Feature/Posts/PruneExpiredPostHistoryTest.php
index 9d66e4934..1aadd0f13 100644
--- a/tests/Feature/Posts/PruneExpiredPostHistoryTest.php
+++ b/tests/Feature/Posts/PruneExpiredPostHistoryTest.php
@@ -9,7 +9,6 @@ use App\Models\AnalyticsPublication;
use App\Models\Media;
use App\Models\Post;
use App\Models\PostNote;
-use App\Models\PostPlatform;
use App\Models\WorkspaceLabel;
use App\Support\PostHistoryRetention;
use Illuminate\Console\Scheduling\Schedule;
@@ -38,25 +37,23 @@ test('a post published past the retention is deleted with its media and keeps it
Event::fake([PostDeleted::class]);
$post = pruneHistoryPost();
- $platform = PostPlatform::factory()->published()->create(['post_id' => $post->id]);
$label = WorkspaceLabel::factory()->create(['workspace_id' => $post->workspace_id]);
$post->labels()->attach($label->id);
$note = PostNote::factory()->create(['post_id' => $post->id]);
$medias = collect(range(1, 3))->map(fn () => pruneHistoryStoredMedia($post));
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $post->workspace_id,
- 'post_platform_id' => $platform->id,
+ 'post_id' => $post->id,
]);
$count = PruneExpiredPostHistory::execute(now()->subDays(730));
expect($count)->toBe(1)
->and(Post::query()->find($post->id))->toBeNull()
- ->and(PostPlatform::query()->find($platform->id))->toBeNull()
->and(PostNote::query()->find($note->id))->toBeNull()
->and(DB::table('post_workspace_label')->where('post_id', $post->id)->exists())->toBeFalse()
->and(Media::query()->where('post_id', $post->id)->exists())->toBeFalse()
- ->and($publication->fresh()->post_platform_id)->toBeNull();
+ ->and($publication->fresh()->post_id)->toBeNull();
$medias->each(fn (Media $media) => Storage::assertMissing($media->path));
Event::assertNotDispatched(PostDeleted::class);
@@ -82,12 +79,12 @@ test('recent, unfinished and unrelated posts and media survive', function () {
Storage::assertMissing($expiredFile->path);
});
-test('a partially published post is pruned and a published post without a date is not', function () {
- $partial = pruneHistoryPost(['status' => Status::PartiallyPublished]);
+test('a published post without a date is not pruned', function () {
+ $expired = pruneHistoryPost();
$undated = Post::factory()->create(['status' => Status::Published, 'published_at' => null]);
expect(PruneExpiredPostHistory::execute(now()->subDays(730)))->toBe(1)
- ->and(Post::query()->find($partial->id))->toBeNull()
+ ->and(Post::query()->find($expired->id))->toBeNull()
->and(Post::query()->find($undated->id))->not->toBeNull();
});
diff --git a/tests/Feature/Posts/PublishPageRedirectsTest.php b/tests/Feature/Posts/PublishPageRedirectsTest.php
index a174fbff6..7dfb3cf93 100644
--- a/tests/Feature/Posts/PublishPageRedirectsTest.php
+++ b/tests/Feature/Posts/PublishPageRedirectsTest.php
@@ -7,7 +7,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -27,20 +26,11 @@ beforeEach(function () {
function publishRedirectPost(SocialAccount $channel, PostStatus $status = PostStatus::Draft): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create([
'user_id' => $channel->workspace->user_id,
'status' => $status,
'content' => 'Caption',
]);
-
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- ]);
-
- return $post;
}
/**
@@ -51,9 +41,7 @@ function publishRedirectUpdatePayload(Post $post, string $status): array
return [
'status' => $status,
'content' => 'Edited caption',
- 'platforms' => [
- ['id' => $post->postPlatforms->first()->id, 'content_type' => ContentType::LinkedInPost->value],
- ],
+ 'content_type' => ContentType::LinkedInPost->value,
...($status === 'scheduled' ? ['scheduled_at' => now()->addDay()->toIso8601String()] : []),
];
}
diff --git a/tests/Feature/Posts/PublishPageTest.php b/tests/Feature/Posts/PublishPageTest.php
index 879e0bb14..100ec724f 100644
--- a/tests/Feature/Posts/PublishPageTest.php
+++ b/tests/Feature/Posts/PublishPageTest.php
@@ -4,14 +4,13 @@ declare(strict_types=1);
use App\Actions\Post\BuildPublishPageProps;
use App\Enums\Post\Origin;
+use App\Enums\Post\PublishStatus as PlatformStatus;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\User\WeekStart;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -50,21 +49,12 @@ function publishPageSchedule(): PostingSchedule
return $schedule;
}
-function publishPagePost(SocialAccount $channel, PostStatus $status, array $attributes = [], array $platform = []): Post
+function publishPagePost(SocialAccount $channel, PostStatus $status, array $attributes = [], array $publication = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $channel->workspace->user_id,
'status' => $status,
- ], $attributes));
-
- PostPlatform::factory()->create(array_merge([
- 'post_id' => $post->id,
- 'social_account_id' => $channel->id,
- 'platform' => $channel->platform,
- ], $platform));
-
- return $post;
+ ], $publication, $attributes));
}
/**
@@ -85,7 +75,7 @@ function publishPageQueryCount(object $test, string $tab, int $postsPerStatus):
'approval_requested_at' => now(),
]);
publishPagePost($channel, PostStatus::Published, ['published_at' => now()->subDay()], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => now()->subDay(),
'platform_post_id' => "urn:li:share:{$test->queryCountBatch}{$index}",
]);
@@ -173,19 +163,19 @@ test('the drafts tab returns only drafts and no queue', function () {
->where('posts.data.0.id', $undated->id)
->where('posts.data.1.id', $dated->id)
->where('posts.data.0.can_delete', true)
- ->where('posts.data.0.post_platforms.0.social_account.has_posting_schedule', true)));
+ ->where('posts.data.0.social_account.has_posting_schedule', true)));
});
test('the sent tab returns settled posts newest first with metrics', function () {
$older = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDays(3)], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => now()->subDays(3),
]);
- $partial = publishPagePost($this->channel, PostStatus::PartiallyPublished, ['published_at' => now()->subDay()], [
- 'status' => PlatformStatus::Published,
+ $recent = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDay()], [
+ 'publish_status' => PlatformStatus::Published,
'published_at' => now()->subDay(),
]);
- $failed = publishPagePost($this->channel, PostStatus::Failed, ['published_at' => null, 'scheduled_at' => now()->subDays(5)], ['status' => PlatformStatus::Failed]);
+ $failed = publishPagePost($this->channel, PostStatus::Failed, ['published_at' => null, 'scheduled_at' => now()->subDays(5)], ['publish_status' => PlatformStatus::Failed]);
publishPagePost($this->channel, PostStatus::Draft);
$this->actingAs($this->user)
@@ -196,13 +186,13 @@ test('the sent tab returns settled posts newest first with metrics', function ()
->loadDeferredProps(fn ($reload) => $reload
->missing('queue')
->has('posts.data', 3)
- ->where('posts.data.0.id', $partial->id)
+ ->where('posts.data.0.id', $recent->id)
->where('posts.data.1.id', $older->id)
->where('posts.data.2.id', $failed->id)
->where('posts.data.0.can_delete', false)
->where('posts.data.2.can_delete', false)
- ->has("posts.data.0.metrics.{$partial->postPlatforms->first()->id}")
- ->where("posts.data.2.metrics.{$failed->postPlatforms->first()->id}.reason", 'not_published')));
+ ->has('posts.data.0.metrics')
+ ->where('posts.data.2.metrics.reason', 'not_published')));
});
test('the sent tab places a failed post at the time it was attempted, not when its row was last touched', function () {
@@ -222,9 +212,9 @@ test('the sent tab places a failed post at the time it was attempted, not when i
->where('posts.data.3.id', $unscheduledFailed->id)));
});
-test('the sent tab lists failed and partially published posts with the published ones, never a publishing one', function () {
- $published = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDays(4)]);
- $partial = publishPagePost($this->channel, PostStatus::PartiallyPublished, ['published_at' => now()->subDays(3)]);
+test('the sent tab lists failed posts with the published ones, never a publishing one', function () {
+ $older = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDays(4)]);
+ $published = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDays(3)]);
$failed = publishPagePost($this->channel, PostStatus::Failed, ['scheduled_at' => now()->subDays(2)]);
publishPagePost($this->channel, PostStatus::Publishing, ['scheduled_at' => now()->subMinute()]);
publishPagePost($this->channel, PostStatus::Scheduled, ['scheduled_at' => now()->addDay()]);
@@ -236,7 +226,7 @@ test('the sent tab lists failed and partially published posts with the published
->where('counts.queue', 2)
->loadDeferredProps(fn ($reload) => $reload
->missing('queue')
- ->where('posts.data', fn ($posts) => collect($posts)->pluck('id')->all() === [$failed->id, $partial->id, $published->id])));
+ ->where('posts.data', fn ($posts) => collect($posts)->pluck('id')->all() === [$failed->id, $published->id, $older->id])));
$this->get(route('app.channels.publish', [$this->channel, 'tab' => 'sent']))
->assertInertia(fn (AssertableInertia $page) => $page
@@ -273,7 +263,7 @@ test('a focused publishing post opens the queue tab in its publishing group', fu
test('a publishing post waiting for a network limit carries its retry time to the card', function () {
$retryAt = now()->addHour();
$post = publishPagePost($this->channel, PostStatus::Publishing, ['scheduled_at' => now()->subMinute()], [
- 'status' => PlatformStatus::Retrying,
+ 'publish_status' => PlatformStatus::Retrying,
'retry_at' => $retryAt,
'error_message' => 'LinkedIn rate limit reached. Please try again later.',
]);
@@ -284,8 +274,8 @@ test('a publishing post waiting for a network limit carries its retry time to th
->loadDeferredProps(fn ($reload) => $reload
->has('queue.publishing', 1)
->where('queue.publishing.0.id', $post->id)
- ->where('queue.publishing.0.post_platforms.0.status', PlatformStatus::Retrying->value)
- ->where('queue.publishing.0.post_platforms.0.retry_at', $retryAt->toJSON())));
+ ->where('queue.publishing.0.publish_status', PlatformStatus::Retrying->value)
+ ->where('queue.publishing.0.retry_at', $retryAt->toJSON())));
});
test('a partial reload resolves only the props it asks for', function () {
@@ -333,7 +323,7 @@ test('counts follow the page scope', function () {
publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subDay()]);
publishPagePost($other, PostStatus::Draft);
publishPagePost($other, PostStatus::Failed);
- publishPagePost($other, PostStatus::PartiallyPublished, ['published_at' => now()->subDay()]);
+ publishPagePost($other, PostStatus::Published, ['published_at' => now()->subDay()]);
Post::factory()->create(['status' => PostStatus::Draft]);
$this->actingAs($this->user)
@@ -421,7 +411,7 @@ test('scheduled posts in the queue are sent as paginated cards', function () {
->has('posts.data', 1)
->where('posts.data.0.id', $post->id)
->where('posts.data.0.can_delete', true)
- ->where('posts.data.0.post_platforms.0.social_account.has_posting_schedule', true)));
+ ->where('posts.data.0.social_account.has_posting_schedule', true)));
});
test('an invalid time zone and an oversized queue window fall back safely', function () {
@@ -447,18 +437,13 @@ test("sent this week starts on the viewer's week start in the channel time zone"
$this->user->update(['week_starts_on' => $weekStart]);
publishPagePost($this->channel, PostStatus::Published, [], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => CarbonImmutable::parse('2026-09-28 00:30:00', 'America/Sao_Paulo')->utc(),
]);
publishPagePost($this->channel, PostStatus::Published, [], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => CarbonImmutable::parse('2026-09-27 23:30:00', 'America/Sao_Paulo')->utc(),
]);
- publishPagePost($this->channel, PostStatus::Published, [], [
- 'status' => PlatformStatus::Published,
- 'enabled' => false,
- 'published_at' => CarbonImmutable::parse('2026-09-29 10:00:00', 'America/Sao_Paulo')->utc(),
- ]);
$this->actingAs($this->user)
->get(route('app.channels.publish', $this->channel))
@@ -482,9 +467,6 @@ test('scheduled this week counts the posts still to go out before the week ends
publishPagePost($this->channel, PostStatus::Scheduled, [
'scheduled_at' => CarbonImmutable::parse('2026-10-05 00:30:00', 'America/Sao_Paulo')->utc(),
]);
- publishPagePost($this->channel, PostStatus::Scheduled, [
- 'scheduled_at' => CarbonImmutable::parse('2026-10-03 10:00:00', 'America/Sao_Paulo')->utc(),
- ], ['enabled' => false]);
publishPagePost($this->channel, PostStatus::Draft);
$this->actingAs($this->user)
@@ -827,7 +809,7 @@ test('a label filter without matching scheduled posts shows neither posts nor sl
test('the sent tab lists imported posts by publish time and counts them', function () {
$tryPost = publishPagePost($this->channel, PostStatus::Published, ['published_at' => now()->subHours(2)], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => now()->subHours(2),
]);
$imported = publishPagePost($this->channel, PostStatus::Published, [
@@ -835,7 +817,7 @@ test('the sent tab lists imported posts by publish time and counts them', functi
'user_id' => null,
'published_at' => now()->subHour(),
], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => now()->subHour(),
]);
@@ -855,7 +837,7 @@ test('imported posts count toward the weekly posting goal', function () {
$this->travelTo(CarbonImmutable::parse('2026-09-30 12:00:00', 'UTC'));
publishPagePost($this->channel, PostStatus::Published, ['origin' => Origin::Network, 'user_id' => null], [
- 'status' => PlatformStatus::Published,
+ 'publish_status' => PlatformStatus::Published,
'published_at' => CarbonImmutable::parse('2026-09-29 10:00:00', 'UTC'),
]);
@@ -900,7 +882,7 @@ test('the queue carries the pending queue requests holding a slot, and the slot
->where('queue.pending.0.id', $holder->id)
->where('queue.pending.0.status', PostStatus::PendingApproval->value)
->where('queue.pending.0.scheduled_at', fn ($value) => CarbonImmutable::parse($value)->equalTo($slot))
- ->where('queue.pending.0.post_platforms.0.social_account_id', $this->channel->id)
+ ->where('queue.pending.0.social_account_id', $this->channel->id)
->where('queue.days', fn ($days) => collect($days)->flatMap(fn ($day) => $day['items'])
->where('type', 'slot')
->doesntContain('at', $slot->toIso8601String()))));
diff --git a/tests/Feature/Posts/PurgeImportedPostsTest.php b/tests/Feature/Posts/PurgeImportedPostsTest.php
index 674ce7db1..1e46cd999 100644
--- a/tests/Feature/Posts/PurgeImportedPostsTest.php
+++ b/tests/Feature/Posts/PurgeImportedPostsTest.php
@@ -7,7 +7,6 @@ use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Storage;
@@ -17,9 +16,8 @@ beforeEach(function () {
function purgeImportedPost(array $attributes = []): array
{
- $post = Post::factory()->imported()->create($attributes);
- $target = PostPlatform::factory()->published()->create(['post_id' => $post->id]);
- $publication = AnalyticsPublication::factory()->create(['workspace_id' => $post->workspace_id, 'post_platform_id' => $target->id]);
+ $post = Post::factory()->instagram()->imported()->create($attributes);
+ $publication = AnalyticsPublication::factory()->create(['workspace_id' => $post->workspace_id, 'post_id' => $post->id]);
$snapshot = AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $publication->id]);
$media = Media::factory()->ownedByPost($post)->create();
Storage::put($media->path, 'bytes');
@@ -30,7 +28,7 @@ function purgeImportedPost(array $attributes = []): array
test('purging deletes only network posts and their media and keeps analytics', function () {
Event::fake([PostDeleted::class]);
[$imported, $publication, $snapshot, $media] = purgeImportedPost();
- $ours = Post::factory()->published()->create();
+ $ours = Post::factory()->instagram()->published()->create();
$this->artisan('posts:purge-imported')
->expectsOutputToContain('1 imported post(s) deleted.')
@@ -40,7 +38,7 @@ test('purging deletes only network posts and their media and keeps analytics', f
->and(Post::query()->whereKey($ours->id)->exists())->toBeTrue()
->and(Media::query()->whereKey($media->id)->exists())->toBeFalse()
->and($publication->fresh())->not->toBeNull()
- ->and($publication->fresh()->post_platform_id)->toBeNull()
+ ->and($publication->fresh()->post_id)->toBeNull()
->and($publication->fresh()->post_dismissed_at)->toBeNull()
->and(AnalyticsPublicationDailySnapshot::query()->whereKey($snapshot->id)->exists())->toBeTrue();
@@ -60,7 +58,7 @@ test('purging can be limited to one workspace', function () {
test('a workspace purge keeps that workspace trypost posts and their media', function () {
[$imported] = purgeImportedPost();
- $ours = Post::factory()->published()->create(['workspace_id' => $imported->workspace_id]);
+ $ours = Post::factory()->instagram()->published()->create(['workspace_id' => $imported->workspace_id]);
$ourMedia = Media::factory()->ownedByPost($ours)->create();
Storage::put($ourMedia->path, 'bytes');
diff --git a/tests/Feature/Posts/PurgeOrphanedPostsTest.php b/tests/Feature/Posts/PurgeOrphanedPostsTest.php
deleted file mode 100644
index 3d2eaa36f..000000000
--- a/tests/Feature/Posts/PurgeOrphanedPostsTest.php
+++ /dev/null
@@ -1,87 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\Post\Origin;
-use App\Events\PostDeleted;
-use App\Models\AnalyticsPublication;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use Illuminate\Support\Facades\Event;
-use Illuminate\Support\Facades\Storage;
-
-beforeEach(function () {
- Storage::fake();
-});
-
-/**
- * A post left behind by a disconnect from before posts were deleted with
- * their channel: its target lost the account through the nullOnDelete FK.
- *
- * @return array{0: Post, 1: PostPlatform, 2: Media}
- */
-function orphanedPost(array $attributes = []): array
-{
- $post = Post::factory()->published()->create($attributes);
- $target = PostPlatform::factory()->published()->create(['post_id' => $post->id]);
- $media = Media::factory()->ownedByPost($post)->create();
- Storage::put($media->path, 'bytes');
- SocialAccount::query()->whereKey($target->social_account_id)->delete();
-
- return [$post, $target->fresh(), $media];
-}
-
-test('purging deletes posts left without a channel and their media, and is idempotent', function () {
- Event::fake([PostDeleted::class]);
- [$orphan, $target, $media] = orphanedPost();
- [$importedOrphan] = orphanedPost(['origin' => Origin::Network, 'user_id' => null]);
- $publication = AnalyticsPublication::factory()->create(['workspace_id' => $orphan->workspace_id, 'post_platform_id' => $target->id]);
- $live = PostPlatform::factory()->published()->create();
-
- expect($target->social_account_id)->toBeNull();
-
- $this->artisan('posts:purge-orphaned')
- ->expectsOutputToContain('2 orphaned post(s) deleted, 0 orphaned target(s) removed from posts on other channels.')
- ->assertSuccessful();
-
- expect(Post::query()->whereKey([$orphan->id, $importedOrphan->id])->exists())->toBeFalse()
- ->and(Media::query()->whereKey($media->id)->exists())->toBeFalse()
- ->and($publication->fresh()->post_platform_id)->toBeNull()
- ->and($publication->fresh()->post_dismissed_at)->toBeNull()
- ->and(PostPlatform::query()->whereKey($live->id)->exists())->toBeTrue();
- Storage::assertMissing($media->path);
- Event::assertNotDispatched(PostDeleted::class);
-
- $this->artisan('posts:purge-orphaned')
- ->expectsOutputToContain('0 orphaned post(s) deleted, 0 orphaned target(s) removed from posts on other channels.')
- ->assertSuccessful();
-});
-
-test('a legacy post keeps its live channels and only loses the orphaned target', function () {
- [$post, $orphanTarget] = orphanedPost();
- $live = PostPlatform::factory()->published()->create(['post_id' => $post->id]);
-
- $this->artisan('posts:purge-orphaned')
- ->expectsOutputToContain('0 orphaned post(s) deleted, 1 orphaned target(s) removed from posts on other channels.')
- ->assertSuccessful();
-
- expect($post->fresh())->not->toBeNull()
- ->and($post->postPlatforms()->pluck('id')->all())->toBe([$live->id])
- ->and(PostPlatform::query()->whereKey($orphanTarget->id)->exists())->toBeFalse();
-});
-
-test('purging can be limited to one workspace', function () {
- [$kept] = orphanedPost();
- [$purged] = orphanedPost();
-
- $this->artisan('posts:purge-orphaned', ['--workspace' => $purged->workspace_id])->assertSuccessful();
-
- expect(Post::query()->whereKey($kept->id)->exists())->toBeTrue()
- ->and(Post::query()->whereKey($purged->id)->exists())->toBeFalse();
-});
-
-test('the workspace option must be a uuid', function () {
- $this->artisan('posts:purge-orphaned', ['--workspace' => 'nope'])->assertFailed();
-});
diff --git a/tests/Feature/Posts/ReflowChannelQueueTest.php b/tests/Feature/Posts/ReflowChannelQueueTest.php
index 9795e912f..fff083c50 100644
--- a/tests/Feature/Posts/ReflowChannelQueueTest.php
+++ b/tests/Feature/Posts/ReflowChannelQueueTest.php
@@ -8,7 +8,6 @@ use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Exceptions\Post\QueueBusyException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,16 +30,11 @@ beforeEach(function () {
function makeQueuePost(SocialAccount $channel, array $attributes = []): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ return Post::factory()->forAccount($channel)->create(array_merge([
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => null,
], $attributes));
-
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id]);
-
- return $post;
}
function localSlot(Post $post): string
diff --git a/tests/Feature/Posts/ReorderChannelQueueTest.php b/tests/Feature/Posts/ReorderChannelQueueTest.php
index 387d529b7..9e950978d 100644
--- a/tests/Feature/Posts/ReorderChannelQueueTest.php
+++ b/tests/Feature/Posts/ReorderChannelQueueTest.php
@@ -8,7 +8,6 @@ use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -40,16 +39,13 @@ beforeEach(function () {
function reorderQueuedPost(SocialAccount $channel, User $user, array $attributes = [], bool $enqueue = true): Post
{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $channel->workspace_id,
+ $post = Post::factory()->forAccount($channel)->create(array_merge([
'user_id' => $user->id,
'status' => PostStatus::Scheduled,
'schedule_mode' => ScheduleMode::Queue,
'scheduled_at' => null,
], $attributes));
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $channel->id]);
-
if ($enqueue) {
ReflowChannelQueue::handle($channel, $post, QueuePosition::Next);
}
diff --git a/tests/Feature/Posts/VideoAspectRatioRulesTest.php b/tests/Feature/Posts/VideoAspectRatioRulesTest.php
index 3bf046130..5637563ad 100644
--- a/tests/Feature/Posts/VideoAspectRatioRulesTest.php
+++ b/tests/Feature/Posts/VideoAspectRatioRulesTest.php
@@ -9,7 +9,6 @@ use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -34,29 +33,16 @@ function videoRatioAsset(Workspace $workspace, int $width, int $height): Media
]);
}
-/**
- * @return array{0: Post, 1: PostPlatform}
- */
-function videoRatioDraft(Workspace $workspace, User $user, SocialAccount $account, Media $video, ContentType $contentType): array
+function videoRatioDraft(Workspace $workspace, User $user, SocialAccount $account, Media $video, ContentType $contentType): Post
{
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
+ return Post::factory()->forAccount($account, $contentType)->create([
'user_id' => $user->id,
'status' => Status::Draft,
'scheduled_at' => null,
'content' => 'Video caption',
'media' => [MediaItem::fromMedia($video)->toArray()],
- ]);
- $platform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'content_type' => $contentType,
- 'enabled' => true,
'meta' => $contentType === ContentType::YouTubeShort ? ['title' => 'Video title'] : [],
]);
-
- return [$post, $platform];
}
test('a video ratio the network accepts now schedules on web, api and mcp', function (string $accountState, ContentType $contentType, int $width, int $height) {
@@ -64,13 +50,14 @@ test('a video ratio the network accepts now schedules on web, api and mcp', func
$video = videoRatioAsset($this->workspace, $width, $height);
$scheduledAt = now()->addDay()->toIso8601String();
- [$webPost, $webPlatform] = videoRatioDraft($this->workspace, $this->user, $account, $video, $contentType);
+ $webPost = videoRatioDraft($this->workspace, $this->user, $account, $video, $contentType);
$this->actingAs($this->user)->put(route('app.posts.update', $webPost), [
'status' => Status::Scheduled->value,
'scheduled_at' => $scheduledAt,
'media' => [MediaItem::fromMedia($video)->toArray()],
- 'platforms' => [['id' => $webPlatform->id, 'content_type' => $contentType->value, 'meta' => $webPlatform->meta]],
+ 'content_type' => $contentType->value,
+ 'meta' => $webPost->meta,
])->assertSessionHasNoErrors();
expect($webPost->fresh()->status)->toBe(Status::Scheduled);
@@ -81,14 +68,12 @@ test('a video ratio the network accepts now schedules on web, api and mcp', func
'status' => 'scheduled',
'scheduled_at' => $scheduledAt,
'media' => [['id' => videoRatioAsset($this->workspace, $width, $height)->id]],
- 'platforms' => [[
- 'social_account_id' => $account->id,
- 'content_type' => $contentType->value,
- 'meta' => $webPlatform->meta,
- ]],
+ 'social_account_id' => $account->id,
+ 'content_type' => $contentType->value,
+ 'meta' => $webPost->meta,
])->assertCreated();
- [$mcpPost] = videoRatioDraft($this->workspace, $this->user, $account, videoRatioAsset($this->workspace, $width, $height), $contentType);
+ $mcpPost = videoRatioDraft($this->workspace, $this->user, $account, videoRatioAsset($this->workspace, $width, $height), $contentType);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $mcpPost->id,
@@ -123,10 +108,11 @@ test('a video ratio outside the documented range is still rejected with the per-
'status' => 'scheduled',
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => [['id' => $video->id]],
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => $contentType->value]],
- ])->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.content_type' => $message]);
+ 'social_account_id' => $account->id,
+ 'content_type' => $contentType->value,
+ ])->assertUnprocessable()->assertJsonValidationErrors(['content_type' => $message]);
- [$post] = videoRatioDraft($this->workspace, $this->user, $account, $video, $contentType);
+ $post = videoRatioDraft($this->workspace, $this->user, $account, $video, $contentType);
TryPostServer::actingAs($this->user)->tool(UpdatePostTool::class, [
'post_id' => $post->id,
diff --git a/tests/Feature/Posts/XLongPostTest.php b/tests/Feature/Posts/XLongPostTest.php
index d7d80e988..b81e79802 100644
--- a/tests/Feature/Posts/XLongPostTest.php
+++ b/tests/Feature/Posts/XLongPostTest.php
@@ -3,10 +3,8 @@
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ContentLimitException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -53,13 +51,10 @@ test('a premium x account publishes a long post', function () {
'meta' => ['x_subscription_type' => 'Premium'],
'token_expires_at' => now()->addHours(2),
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => str_repeat('a', 2000)]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::X, 'content_type' => ContentType::XPost,
- ]);
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create(['user_id' => $this->user->id, 'content' => str_repeat('a', 2000)]);
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '99']], 201)]);
- expect((new XPublisher)->publish($postPlatform)['id'])->toBe('99');
+ expect((new XPublisher)->publish($post)['id'])->toBe('99');
Http::assertSent(fn (Request $request): bool => mb_strlen((string) data_get($request->data(), 'text')) === 2000);
});
@@ -69,13 +64,10 @@ test('an account that lost premium fails the long post at publish', function ()
'meta' => ['x_subscription_type' => 'None'],
'token_expires_at' => now()->addHours(2),
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id, 'content' => str_repeat('a', 2000)]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => Platform::X, 'content_type' => ContentType::XPost,
- ]);
+ $post = Post::factory()->forAccount($account, ContentType::XPost)->create(['user_id' => $this->user->id, 'content' => str_repeat('a', 2000)]);
Http::fake();
- expect(fn () => (new XPublisher)->publish($postPlatform))
+ expect(fn () => (new XPublisher)->publish($post))
->toThrow(ContentLimitException::class, __('posts.errors.content_too_long', ['platform' => 'X', 'max' => 280, 'provided' => 2000]));
Http::assertNothingSent();
});
@@ -87,7 +79,8 @@ test('post content accepts up to the long post size on the api', function () {
$this->withHeaders(['Authorization' => "Bearer {$result['plain_token']}"])
->postJson(route('api.posts.store'), [
'content' => str_repeat('a', 20000),
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::XPost->value]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::XPost->value,
])->assertCreated();
});
@@ -108,7 +101,8 @@ test('the post content cap counts the text a reader sees, not the editor markup'
$response = $this->withHeaders(['Authorization' => "Bearer {$result['plain_token']}"])
->postJson(route('api.posts.store'), [
'content' => $content,
- 'platforms' => [['social_account_id' => $account->id, 'content_type' => ContentType::XPost->value]],
+ 'social_account_id' => $account->id,
+ 'content_type' => ContentType::XPost->value,
]);
$accepted ? $response->assertCreated() : $response->assertUnprocessable()->assertJsonValidationErrors(['content']);
diff --git a/tests/Feature/ReleaseTryPost2Test.php b/tests/Feature/ReleaseTryPost2Test.php
deleted file mode 100644
index dcdaf0c83..000000000
--- a/tests/Feature/ReleaseTryPost2Test.php
+++ /dev/null
@@ -1,699 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Actions\Media\AdoptWorkspaceLibrary;
-use App\Console\Commands\Scripts\ReleaseTryPost2;
-use App\Enums\Post\Status;
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
-use App\Enums\SocialAccount\Platform;
-use App\Jobs\Analytics\BackfillTryPostPublications;
-use App\Jobs\Analytics\BootstrapAccountAnalytics;
-use App\Jobs\Analytics\CollectAccountDailySnapshot;
-use App\Jobs\Analytics\DiscoverAccountPublications;
-use App\Jobs\Media\AdoptWorkspaceLibraryJob;
-use App\Jobs\Media\DeleteMediaFiles;
-use App\Models\AnalyticsPublication;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostNote;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use App\Models\WorkspaceLabel;
-use Illuminate\Bus\UniqueLock;
-use Illuminate\Database\Migrations\Migrator;
-use Illuminate\Support\Arr;
-use Illuminate\Support\Facades\Artisan;
-use Illuminate\Support\Facades\Cache;
-use Illuminate\Support\Facades\DB;
-use Illuminate\Support\Facades\File;
-use Illuminate\Support\Facades\Queue;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Sleep;
-use Illuminate\Support\Str;
-use Symfony\Component\Console\Command\Command;
-use Symfony\Component\Console\Output\BufferedOutput;
-
-beforeEach(function () {
- Storage::fake();
- releaseFakeQueue();
-
- $this->workspace = Workspace::factory()->create();
-});
-
-/**
- * Fakes the jobs the release queues; called again after the fixtures so the
- * jobs their observers queue are not counted.
- */
-function releaseFakeQueue(): void
-{
- Queue::fake([BackfillTryPostPublications::class, BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class, DiscoverAccountPublications::class]);
-}
-
-function releaseLibraryAsset(Workspace $workspace): Media
-{
- $asset = Media::factory()->libraryAsset($workspace)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($asset->path, 'library bytes');
-
- return $asset;
-}
-
-/**
- * @return array<string, mixed>
- */
-function releaseLibraryItem(Media $asset): array
-{
- return ['id' => $asset->id, 'path' => $asset->path, 'url' => $asset->url, 'type' => 'image', 'mime_type' => 'image/jpeg'];
-}
-
-/**
- * A legacy scheduled post on two Instagram channels that uses a library file.
- */
-function releaseLegacyPost(Workspace $workspace, Media $asset): Post
-{
- $post = Post::factory()->scheduled()->create(['workspace_id' => $workspace->id, 'media' => [releaseLibraryItem($asset)]]);
- $accounts = SocialAccount::factory()->count(2)->create(['workspace_id' => $workspace->id, 'platform' => Platform::Instagram]);
-
- foreach ($accounts as $account) {
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id, 'platform' => $account->platform]);
- }
-
- return $post;
-}
-
-function releaseOrphanedPost(Workspace $workspace): Post
-{
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- $target = PostPlatform::factory()->published()->create(['post_id' => $post->id]);
- SocialAccount::query()->whereKey($target->social_account_id)->delete();
-
- return $post;
-}
-
-/**
- * The step outputs come from the commands the release calls, so their
- * positions in the output give the order the steps ran in.
- *
- * @param array<string, mixed> $options
- * @return array{0: int, 1: string}
- */
-function runRelease(array $options = []): array
-{
- $output = new BufferedOutput;
- $code = Artisan::call('release:trypost-2', ['--force' => true, ...$options], $output);
-
- return [$code, $output->fetch()];
-}
-
-/**
- * @param list<string> $needles
- */
-function expectInOrder(string $output, array $needles): void
-{
- $positions = array_map(fn (string $needle): int|false => strpos($output, $needle), $needles);
-
- expect($positions)->not->toContain(false);
-
- $sorted = $positions;
- sort($sorted);
-
- expect($positions)->toBe($sorted);
-}
-
-test('pending migrations abort the release before any step runs', function () {
- $directory = storage_path('framework/testing/release-migrations');
- File::ensureDirectoryExists($directory);
- File::put("{$directory}/2099_01_01_000000_release_probe.php", '<?php return new class extends Illuminate\Database\Migrations\Migration { public function up(): void {} };');
- app(Migrator::class)->path($directory);
- $asset = releaseLibraryAsset($this->workspace);
- $post = releaseLegacyPost($this->workspace, $asset);
-
- try {
- [$code, $output] = runRelease();
- } finally {
- File::deleteDirectory($directory);
- }
-
- expect($code)->toBe(Command::FAILURE)
- ->and($output)->toContain('1 pending migration(s)')
- ->and($output)->toContain('2099_01_01_000000_release_probe')
- ->and($output)->not->toContain('[1/8]')
- ->and(Media::query()->whereKey($asset->id)->exists())->toBeTrue()
- ->and($post->postPlatforms()->count())->toBe(2);
-});
-
-test('a dry run prints every step and changes nothing', function () {
- $asset = releaseLibraryAsset($this->workspace);
- $post = releaseLegacyPost($this->workspace, $asset);
- $orphan = releaseOrphanedPost($this->workspace);
-
- releaseFakeQueue();
- $files = Storage::allFiles();
-
- [$code, $output] = runRelease(['--dry-run' => true]);
-
- expect($code)->toBe(Command::SUCCESS)
- ->and(Storage::allFiles())->toBe($files)
- ->and($output)->toMatch('/\| Media library adoption\s+\| dry run\s+\|/')
- ->and($output)->toMatch('/\| Media audit \(read-only\)\s+\| dry run\s+\|/');
- expectInOrder($output, [
- 'Would run: php artisan posts:purge-orphaned',
- 'would delete 1 post(s) and detach 0 target(s)',
- 'Would run: php artisan posts:split-legacy-active',
- 'Editable with multiple enabled targets',
- 'Would run: php artisan posts:bake-aspect-ratio-crops',
- 'would bake the aspect ratio crop of 0 scheduled or in-flight post(s)',
- 'References to copy',
- 'Would run: php artisan analytics:backfill-existing --chunk=100 --delay=0',
- 'Would run: php artisan analytics:dispatch-publication-discovery --platform=instagram --platform=instagram-facebook',
- '| json_drift',
- 'Dry run: nothing was changed.',
- ]);
-
- expect(Media::query()->whereKey($asset->id)->exists())->toBeTrue()
- ->and(Post::query()->count())->toBe(2)
- ->and($post->postPlatforms()->count())->toBe(2)
- ->and(Post::query()->whereKey($orphan->id)->exists())->toBeTrue();
- Queue::assertNothingPushed();
-});
-
-test('a full run executes the steps in order, waits for the queued adoption and is a no-op the second time', function () {
- $asset = releaseLibraryAsset($this->workspace);
- releaseLegacyPost($this->workspace, $asset);
- $orphan = releaseOrphanedPost($this->workspace);
-
- releaseFakeQueue();
-
- [$code, $output] = runRelease(['--include-unsubscribed' => true, '--backfill-chunk' => 10, '--backfill-delay' => 60]);
-
- expect($code)->toBe(Command::SUCCESS);
- expectInOrder($output, [
- '1 orphaned post(s) deleted',
- 'Split 1 original posts and created 1 independent posts.',
- '1/1 workspace(s) done, 0 library row(s) left, 0 stopped',
- 'accounts_dispatched=2',
- '[7/8] Instagram stories discovery',
- '| orphaned_files',
- '0 unexpected',
- 'Release steps done.',
- ]);
-
- expect(Media::query()->whereKey($asset->id)->exists())->toBeFalse()
- ->and(Post::query()->whereKey($orphan->id)->exists())->toBeFalse();
-
- $posts = Post::query()->where('workspace_id', $this->workspace->id)->get();
-
- expect($posts)->toHaveCount(2);
-
- foreach ($posts as $owner) {
- $copy = Media::query()->findOrFail(data_get($owner->media, '0.id'));
-
- expect($copy->post_id)->toBe($owner->id)
- ->and($owner->postPlatforms()->enabled()->count())->toBe(1);
- }
-
- Queue::assertPushed(BootstrapAccountAnalytics::class, 2);
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS);
- expectInOrder($output, [
- '0 orphaned post(s) deleted',
- 'Split 0 original posts and created 0 independent posts.',
- 'No library media to adopt.',
- 'Skipped: already dispatched at',
- '0 expected, 0 unexpected',
- ]);
-
- expect(Post::query()->where('workspace_id', $this->workspace->id)->count())->toBe(2)
- ->and(Media::query()->where('workspace_id', $this->workspace->id)->count())->toBe(2);
- Queue::assertPushed(BootstrapAccountAnalytics::class, 2);
-
- runRelease(['--include-unsubscribed' => true, '--rerun-backfill' => true]);
-
- Queue::assertPushed(BootstrapAccountAnalytics::class, 4);
-});
-
-test('the adoption dispatches one job per workspace on its own queue and waits until every library is adopted', function () {
- $other = Workspace::factory()->create();
- $assets = [releaseLibraryAsset($this->workspace), releaseLibraryAsset($other)];
- Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($assets[0])]]);
- Post::factory()->published()->create(['workspace_id' => $other->id, 'media' => [releaseLibraryItem($assets[1])]]);
- releaseFakeQueue();
- Queue::fake([AdoptWorkspaceLibraryJob::class, BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class, DiscoverAccountPublications::class, BackfillTryPostPublications::class]);
- Sleep::fake(syncWithCarbon: true);
- Sleep::whenFakingSleep(function (): void {
- Queue::pushed(AdoptWorkspaceLibraryJob::class)->each(function (AdoptWorkspaceLibraryJob $job): void {
- $job->handle();
- (new UniqueLock(Cache::store()))->release($job);
- });
- });
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($output)->toContain('0/2 workspace(s) done, 2 library row(s) left, 0 stopped')
- ->and($output)->toContain('2/2 workspace(s) done, 0 library row(s) left, 0 stopped')
- ->and($output)->toContain('2 of 2 workspace(s) adopted')
- ->and(Media::query()->whereKey([$assets[0]->id, $assets[1]->id])->exists())->toBeFalse();
- Queue::assertPushed(AdoptWorkspaceLibraryJob::class, 2);
- Queue::assertPushedOn(AdoptWorkspaceLibraryJob::QUEUE, AdoptWorkspaceLibraryJob::class);
- Sleep::assertSleptTimes(1);
-});
-
-test('a workspace still adopting when the timeout passes is left to its job and the release goes on', function () {
- Sleep::fake(syncWithCarbon: true);
- $asset = releaseLibraryAsset($this->workspace);
- Post::factory()->create(['workspace_id' => $this->workspace->id, 'status' => Status::Publishing, 'media' => [releaseLibraryItem($asset)]]);
-
- [$code, $output] = runRelease(['--adoption-timeout' => 60]);
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($output)->toContain('1 workspace(s) still adopting after 60s')
- ->and($output)->toContain('[7/8] Instagram stories discovery')
- ->and($output)->toContain('| json_drift | 1 | 0 |')
- ->and(Media::query()->whereKey($asset->id)->exists())->toBeTrue();
- Sleep::assertSleptTimes(4);
-});
-
-test('a workspace whose job stops without adopting is reported as failed and the release goes on', function () {
- $healthyAsset = releaseLibraryAsset($this->workspace);
- $healthyPost = Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($healthyAsset)]]);
- $broken = Workspace::factory()->create();
- $brokenAsset = releaseLibraryAsset($broken);
- Storage::delete($brokenAsset->path);
- Post::factory()->published()->create(['workspace_id' => $broken->id, 'media' => [releaseLibraryItem($brokenAsset)]]);
-
- releaseFakeQueue();
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::FAILURE)
- ->and($output)->toContain("1 workspace(s) stopped with library media left: {$broken->id}")
- ->and($output)->toContain('[7/8] Instagram stories discovery')
- ->and($output)->toContain('| Media audit (read-only)')
- ->and($output)->toContain('1 failed step(s)')
- ->and(Media::query()->whereKey($healthyAsset->id)->exists())->toBeFalse()
- ->and(Media::query()->findOrFail(data_get($healthyPost->fresh()->media, '0.id'))->post_id)->toBe($healthyPost->id)
- ->and(Media::query()->whereKey($brokenAsset->id)->exists())->toBeTrue();
-});
-
-test('a legacy instagram post scheduled with two crops on a shared library photo is baked per channel once the release splits it', function () {
- $asset = Media::factory()->libraryAsset($this->workspace)->create(['path' => 'medias/'.Str::uuid().'.jpg', 'meta' => ['width' => 1080, 'height' => 1920]]);
- $image = imagecreatetruecolor(1080, 1920);
- ob_start();
- imagejpeg($image);
- Storage::put($asset->path, (string) ob_get_clean());
- $post = Post::factory()->scheduled()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($asset)]]);
- $ratios = ['4:5' => [1080, 1350], '1:1' => [1080, 1080]];
- $expected = [];
-
- foreach ($ratios as $ratio => $dimensions) {
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- $expected[$account->id] = $dimensions;
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- 'meta' => ['aspect_ratio' => $ratio],
- ]);
- }
-
- releaseFakeQueue();
-
- $this->artisan('posts:bake-aspect-ratio-crops')
- ->expectsOutputToContain('Baked 0 cropped image(s) into 0 post(s)')
- ->expectsOutputToContain("uncropped for now (their media is shared; they keep their aspect ratio until a run after posts:split-legacy-active): {$post->id}")
- ->assertSuccessful();
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output);
- expectInOrder($output, [
- 'Split 1 original posts and created 1 independent posts.',
- 'Baked 2 cropped image(s) into 2 post(s)',
- '1/1 workspace(s) done',
- '0 unexpected',
- ]);
-
- $targets = PostPlatform::query()->with('post')->whereIn('post_id', Post::query()->where('workspace_id', $this->workspace->id)->select('id'))->get();
-
- expect($targets)->toHaveCount(2)
- ->and(Media::query()->whereKey($asset->id)->exists())->toBeFalse();
-
- foreach ($targets as $target) {
- $owner = $target->post;
- $row = Media::query()->findOrFail(data_get($owner->media, '0.id'));
- [$width, $height] = $expected[$target->social_account_id];
-
- expect($target->meta)->toEqual([])
- ->and($row->post_id)->toBe($owner->id)
- ->and(getimagesizefromstring((string) Storage::get($row->path)))->toMatchArray([0 => $width, 1 => $height]);
- }
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($output)->toContain('Baked 0 cropped image(s) into 0 post(s)');
-});
-
-test('a legacy instagram draft on two channels is split without a crop and loses the aspect ratio', function () {
- $asset = Media::factory()->libraryAsset($this->workspace)->create(['path' => 'medias/'.Str::uuid().'.jpg', 'meta' => ['width' => 1080, 'height' => 1920]]);
- $image = imagecreatetruecolor(1080, 1920);
- ob_start();
- imagejpeg($image);
- Storage::put($asset->path, (string) ob_get_clean());
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'status' => Status::Draft, 'media' => [releaseLibraryItem($asset)]]);
-
- foreach (['4:5', '1:1'] as $ratio) {
- $account = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);
- PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- 'meta' => ['aspect_ratio' => $ratio],
- ]);
- }
-
- releaseFakeQueue();
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($output)->toContain('Baked 0 cropped image(s) into 0 post(s)');
-
- $targets = PostPlatform::query()->with('post')->whereIn('post_id', Post::query()->where('workspace_id', $this->workspace->id)->select('id'))->get();
-
- expect($targets)->toHaveCount(2)
- ->and($targets->pluck('post_id')->unique())->toHaveCount(2);
-
- foreach ($targets as $target) {
- $row = Media::query()->findOrFail(data_get($target->post->media, '0.id'));
-
- expect($target->meta)->toEqual([])
- ->and($target->post->status)->toBe(Status::Draft)
- ->and(getimagesizefromstring((string) Storage::get($row->path)))->toMatchArray([0 => 1080, 1 => 1920]);
- }
-});
-
-test('the final audit counts what the release leaves behind on purpose as expected and passes', function () {
- Queue::fake([DeleteMediaFiles::class]);
- $asset = releaseLibraryAsset($this->workspace);
- $other = Workspace::factory()->create();
- Post::factory()->published()->create(['workspace_id' => $other->id, 'media' => [releaseLibraryItem($asset)]]);
- Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [['id' => (string) Str::uuid(), 'path' => 'medias/gone.jpg', 'url' => 'https://cdn.example/gone.jpg', 'type' => 'image']]]);
- $unused = releaseLibraryAsset($this->workspace);
- Storage::put('medias/stray-before-the-release.jpg', 'stray');
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($output)->toContain('| orphaned_files | 2 | 0 |')
- ->and($output)->toContain('| json_drift | 2 | 0 |')
- ->and($output)->toContain('0 unexpected')
- ->and(Media::query()->whereKey($asset->id)->exists())->toBeTrue()
- ->and(Media::query()->whereKey($unused->id)->exists())->toBeFalse();
- Storage::assertExists($unused->path);
-});
-
-test('an audit finding the release did not expect fails it and is listed', function () {
- $asset = releaseLibraryAsset($this->workspace);
- $post = Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($asset)]]);
- Media::created(function (Media $media): void {
- Storage::delete($media->path);
- });
-
- [$code, $output] = runRelease();
-
- $copy = Media::query()->findOrFail(data_get($post->fresh()->media, '0.id'));
-
- expect($code)->toBe(Command::FAILURE)
- ->and($output)->toContain("unexpected missing_files: media_id={$copy->id}")
- ->and($output)->toContain('1 unexpected audit finding(s)');
-});
-
-test('a referenced media row the release deletes by mistake is an unexpected finding', function () {
- $asset = releaseLibraryAsset($this->workspace);
- Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($asset)]]);
- $kept = Post::factory()->published()->create(['workspace_id' => $this->workspace->id]);
- $victim = Media::factory()->ownedByPost($kept)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($victim->path, 'victim bytes');
- $kept->forceFill(['media' => [releaseLibraryItem($victim)]])->saveQuietly();
- Media::created(function () use ($victim): void {
- DB::table('medias')->where('id', $victim->id)->delete();
- });
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::FAILURE)
- ->and($output)->toContain("media_id={$victim->id} problem=json_without_row")
- ->and($output)->toContain('unexpected audit finding(s)');
-});
-
-test('the backfill marker lives in the database cache, so a flushed default cache does not dispatch it again', function () {
- SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'platform' => Platform::Instagram]);
- releaseFakeQueue();
-
- runRelease(['--include-unsubscribed' => true]);
- Cache::flush();
- [, $output] = runRelease(['--include-unsubscribed' => true]);
-
- expect(Cache::store('database')->get(ReleaseTryPost2::BACKFILL_DISPATCHED_KEY))->not->toBeNull()
- ->and($output)->toContain('Skipped: already dispatched at');
- Queue::assertPushed(BootstrapAccountAnalytics::class, 1);
-});
-
-test('a failure while queueing the adoption is reported and the release goes on', function () {
- Sleep::fake();
- $asset = releaseLibraryAsset($this->workspace);
- Post::factory()->published()->create(['workspace_id' => $this->workspace->id, 'media' => [releaseLibraryItem($asset)]]);
- Artisan::command('media:adopt-library {--force} {--dry-run}', function (): void {
- throw new RuntimeException('queue is down');
- });
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::FAILURE)
- ->and($output)->toContain('Could not queue AdoptWorkspaceLibraryJob: queue is down')
- ->and($output)->toContain('[8/8] Media audit')
- ->and($output)->toContain('| Media library adoption')
- ->and(Media::query()->whereKey($asset->id)->exists())->toBeTrue();
- Sleep::assertNeverSlept();
-});
-
-test('a partially published post with a target on a deleted channel ends as one published and one failed post', function () {
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'status' => Status::PartiallyPublished, 'content' => 'Launch video']);
- $youtube = PostPlatform::factory()->youtube()->published()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $this->workspace->id])->id]);
- $instagram = PostPlatform::factory()->instagram()->failed()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $this->workspace->id])->id]);
- $tiktok = PostPlatform::factory()->tiktok()->failed()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $this->workspace->id])->id]);
- $publication = AnalyticsPublication::factory()->create(['workspace_id' => $this->workspace->id, 'post_platform_id' => $youtube->id]);
- $tiktok->socialAccount->delete();
-
- releaseFakeQueue();
-
- [$code, $output] = runRelease();
-
- $posts = Post::query()->where('workspace_id', $this->workspace->id)->with('postPlatforms')->get()->keyBy(fn (Post $split): string => $split->postPlatforms->sole()->id);
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and($posts->keys()->sort()->values()->all())->toBe(collect([$youtube->id, $instagram->id])->sort()->values()->all())
- ->and($posts[$youtube->id]->status)->toBe(Status::Published)
- ->and($posts[$instagram->id]->status)->toBe(Status::Failed)
- ->and($posts[$youtube->id]->post_group_id)->toBe($posts[$instagram->id]->post_group_id)
- ->and($posts->pluck('content')->unique()->all())->toBe(['Launch video'])
- ->and(PostPlatform::query()->whereKey($tiktok->id)->exists())->toBeFalse()
- ->and($publication->fresh()->post_platform_id)->toBe($youtube->id)
- ->and($publication->fresh()->postPlatform->post_id)->toBe($posts[$youtube->id]->id);
-});
-
-/**
- * Everything a second run could change, in a comparable shape.
- *
- * @return array<string, mixed>
- */
-function releaseFingerprint(): array
-{
- return [
- 'posts' => Post::query()->orderBy('id')->get()->map(fn (Post $post): array => [
- $post->id, $post->workspace_id, $post->post_group_id, $post->content, $post->media, $post->status->value, $post->scheduled_at?->toIso8601String(),
- ])->all(),
- 'targets' => PostPlatform::query()->orderBy('id')->get()->map(fn (PostPlatform $target): array => [
- $target->id, $target->post_id, $target->social_account_id, $target->enabled, $target->status->value, $target->meta,
- ])->all(),
- 'media' => Media::query()->orderBy('id')->get()->map(fn (Media $media): array => [
- $media->id, $media->collection, $media->workspace_id, $media->post_id, $media->path,
- ])->all(),
- 'labels' => DB::table('post_workspace_label')->orderBy('post_id')->orderBy('workspace_label_id')->get(['post_id', 'workspace_label_id'])->map(fn (object $row): array => (array) $row)->all(),
- 'notes' => PostNote::query()->orderBy('id')->get(['id', 'post_id', 'body'])->toArray(),
- 'files' => collect(Storage::allFiles())->sort()->values()->all(),
- ];
-}
-
-test('a realistic pre-release workspace keeps every post, target, label, note and file it should after the release, and a second run changes nothing', function (bool $adoptedOnBoot) {
- $workspace = $this->workspace;
- $workspace->owner->forceFill(['timezone' => 'America/Sao_Paulo'])->saveQuietly();
- $accounts = SocialAccount::factory()->count(3)->create(['workspace_id' => $workspace->id]);
- $deadAccount = SocialAccount::factory()->create(['workspace_id' => $workspace->id]);
- [$launch, $promo] = WorkspaceLabel::factory()->count(2)->create(['workspace_id' => $workspace->id])->all();
- $scheduledAt = now()->addDays(3)->startOfSecond();
-
- $shared = releaseLibraryAsset($workspace);
- $draftOnly = releaseLibraryAsset($workspace);
- $orphanOnly = releaseLibraryAsset($workspace);
- $unused = releaseLibraryAsset($workspace);
- $libraryPaths = [$shared->path, $draftOnly->path, $orphanOnly->path, $unused->path];
-
- $target = fn (Post $post, SocialAccount $account, array $attributes = []): PostPlatform => PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'meta' => ['first_comment' => "comment for {$account->id}"],
- ...$attributes,
- ]);
-
- $draft = Post::factory()->draft()->create([
- 'workspace_id' => $workspace->id,
- 'content' => 'Draft caption',
- 'media' => [
- [...releaseLibraryItem($shared), 'meta' => ['alt_text' => 'Shared alt']],
- [...releaseLibraryItem($draftOnly), 'meta' => ['alt_text' => 'Draft alt']],
- ],
- ]);
- $target($draft, $accounts[0]);
- $target($draft, $accounts[1], ['content_type' => ContentType::LinkedInPost]);
- $draft->labels()->attach($launch);
-
- $scheduled = Post::factory()->scheduled()->create([
- 'workspace_id' => $workspace->id,
- 'content' => 'Scheduled caption',
- 'scheduled_at' => $scheduledAt,
- 'media' => [releaseLibraryItem($shared)],
- ]);
- $target($scheduled, $accounts[0]);
- $target($scheduled, $accounts[1]);
- $disabled = PostPlatform::factory()->disabled()->create(['post_id' => $scheduled->id, 'social_account_id' => $accounts[2]->id]);
- $scheduled->labels()->attach([$launch->id, $promo->id]);
- $note = PostNote::factory()->create(['post_id' => $scheduled->id, 'user_id' => $scheduled->user_id]);
-
- $published = Post::factory()->published()->create([
- 'workspace_id' => $workspace->id,
- 'content' => 'Published caption',
- 'media' => [releaseLibraryItem($shared)],
- ]);
- PostPlatform::factory()->published()->create(['post_id' => $published->id, 'social_account_id' => $accounts[0]->id]);
- PostPlatform::factory()->failed()->create(['post_id' => $published->id, 'social_account_id' => $accounts[1]->id]);
-
- $orphan = Post::factory()->published()->create(['workspace_id' => $workspace->id, 'media' => [releaseLibraryItem($orphanOnly)]]);
- PostPlatform::factory()->published()->create(['post_id' => $orphan->id, 'social_account_id' => $deadAccount->id]);
-
- $mixed = Post::factory()->scheduled()->create(['workspace_id' => $workspace->id, 'content' => 'Mixed caption', 'scheduled_at' => $scheduledAt]);
- $deadTarget = $target($mixed, $deadAccount);
- $liveTarget = $target($mixed, $accounts[2]);
-
- $other = Workspace::factory()->create();
- $otherAccount = SocialAccount::factory()->create(['workspace_id' => $other->id]);
- $otherPost = Post::factory()->scheduled()->create(['workspace_id' => $other->id, 'content' => 'Untouched caption']);
- $otherMedia = Media::factory()->ownedByPost($otherPost)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($otherMedia->path, 'owned bytes');
- $otherPost->forceFill(['media' => [releaseLibraryItem($otherMedia)]])->saveQuietly();
- PostPlatform::factory()->create(['post_id' => $otherPost->id, 'social_account_id' => $otherAccount->id]);
-
- $deadAccount->delete();
-
- $originals = collect([$draft, $scheduled, $published, $mixed, $otherPost])->mapWithKeys(fn (Post $post): array => [$post->id => [
- 'content' => $post->content,
- 'status' => $post->status,
- 'scheduled_at' => $post->scheduled_at?->toIso8601String(),
- 'labels' => $post->labels()->pluck('workspace_labels.id')->sort()->values()->all(),
- 'items' => collect($post->fresh()->media)->map(fn (array $item): array => [
- 'fields' => Arr::except($item, ['id', 'path', 'url']),
- 'bytes' => Storage::get($item['path']),
- ])->all(),
- ]]);
- $targets = PostPlatform::query()->whereNotNull('social_account_id')->get()->keyBy('id')
- ->map(fn (PostPlatform $row): array => [$row->post_id, $row->social_account_id, $row->enabled, $row->status, $row->content_type, $row->meta]);
-
- if ($adoptedOnBoot) {
- AdoptWorkspaceLibrary::execute($workspace);
- }
-
- releaseFakeQueue();
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output);
-
- expect(Post::query()->whereKey($orphan->id)->exists())->toBeFalse()
- ->and(PostPlatform::query()->whereKey($deadTarget->id)->exists())->toBeFalse()
- ->and(Post::query()->where('workspace_id', $workspace->id)->count())->toBe(7)
- ->and(Media::query()->where('collection', Media::LIBRARY_COLLECTION)->exists())->toBeFalse();
-
- foreach ($libraryPaths as $path) {
- Storage::assertMissing($path);
- }
-
- foreach ($targets as $id => [$postId, $accountId, $enabled, $status, $contentType, $meta]) {
- $row = PostPlatform::query()->findOrFail($id);
- $original = $originals[$postId];
- $owner = $row->post;
-
- expect([$row->social_account_id, $row->enabled, $row->status, $row->content_type, $row->meta])->toEqual([$accountId, $enabled, $status, $contentType, $meta])
- ->and($owner->content)->toBe($original['content'])
- ->and($owner->status)->toBe($original['status']->isSettled() ? ($status === PostPlatformStatus::Published ? Status::Published : Status::Failed) : $original['status'])
- ->and($owner->scheduled_at?->toIso8601String())->toBe($original['scheduled_at'])
- ->and($owner->labels()->pluck('workspace_labels.id')->sort()->values()->all())->toBe($original['labels']);
-
- foreach ($owner->media as $index => $item) {
- $row = Media::query()->findOrFail($item['id']);
-
- expect(Arr::except($item, ['id', 'path', 'url']))->toEqual($original['items'][$index]['fields'])
- ->and($row->post_id)->toBe($owner->id)
- ->and($row->workspace_id)->toBe($owner->workspace_id)
- ->and($row->path)->toBe($item['path'])
- ->and(Storage::get($item['path']))->toBe($original['items'][$index]['bytes']);
- }
-
- expect($owner->media)->toHaveCount(count($original['items']));
- }
-
- foreach ([$draft, $scheduled] as $legacy) {
- $group = Post::query()->where('post_group_id', $legacy->fresh()->post_group_id)->get();
-
- expect($legacy->fresh()->post_group_id)->not->toBeNull()
- ->and($group)->toHaveCount(2)
- ->and($group->every(fn (Post $post): bool => $post->postPlatforms()->enabled()->count() === 1))->toBeTrue();
- }
-
- expect(PostPlatform::query()->findOrFail($disabled->id)->post_id)->toBe($scheduled->id)
- ->and(PostNote::query()->whereIn('post_id', Post::query()->where('post_group_id', $scheduled->fresh()->post_group_id)->select('id'))->pluck('body')->all())->toBe([$note->body, $note->body])
- ->and($published->fresh()->post_group_id)->not->toBeNull()
- ->and(Post::query()->where('post_group_id', $published->fresh()->post_group_id)->pluck('status')->map->value->sort()->values()->all())->toBe([Status::Failed->value, Status::Published->value])
- ->and(Post::query()->where('status', Status::PartiallyPublished)->exists())->toBeFalse()
- ->and($mixed->fresh()->postPlatforms()->pluck('id')->all())->toBe([$liveTarget->id])
- ->and($otherPost->fresh()->media)->toEqual([releaseLibraryItem($otherMedia)])
- ->and($otherMedia->fresh()->post_id)->toBe($otherPost->id);
- Storage::assertExists($otherMedia->path);
-
- Media::query()->each(fn (Media $media) => Storage::assertExists($media->path));
-
- foreach ($accounts as $account) {
- $account = $account->fresh();
-
- expect($account->timezone)->toBe('America/Sao_Paulo')
- ->and($account->posting_goal)->toBe(3)
- ->and($account->posting_schedule->slotCount())->toBe(3);
- }
-
- $fingerprint = releaseFingerprint();
-
- [$code, $output] = runRelease();
-
- expect($code)->toBe(Command::SUCCESS, $output)
- ->and(releaseFingerprint())->toEqual($fingerprint);
-})->with([
- 'library adopted by the release' => [false],
- 'library already adopted on boot, before the split' => [true],
-]);
diff --git a/tests/Feature/Repurpose/PollingTest.php b/tests/Feature/Repurpose/PollingTest.php
index 239ddd57c..4b3323d3b 100644
--- a/tests/Feature/Repurpose/PollingTest.php
+++ b/tests/Feature/Repurpose/PollingTest.php
@@ -12,7 +12,6 @@ use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\Repurpose\PollRepurposeSource;
use App\Jobs\Repurpose\ProcessRepurposeItem;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -141,8 +140,7 @@ test('media already published through trypost is skipped', function () {
$account = instagramAccount();
$repurpose = activeRepurposeOn($account);
- $post = Post::factory()->create(['workspace_id' => $account->workspace_id]);
- PostPlatform::factory()->for($post)->create(['platform_post_id' => 'known-1']);
+ Post::factory()->instagram()->published()->create(['workspace_id' => $account->workspace_id, 'platform_post_id' => 'known-1']);
poll($account);
@@ -158,8 +156,7 @@ test('another workspace publishing the same media id does not skip ours', functi
$account = instagramAccount();
$repurpose = activeRepurposeOn($account);
- $post = Post::factory()->create(['workspace_id' => Workspace::factory()->create()->id]);
- PostPlatform::factory()->for($post)->create(['platform_post_id' => 'known-1']);
+ Post::factory()->instagram()->published()->create(['workspace_id' => Workspace::factory()->create()->id, 'platform_post_id' => 'known-1']);
poll($account);
@@ -392,8 +389,7 @@ test('a post imported from the network does not count as published through trypo
$account = instagramAccount();
$repurpose = activeRepurposeOn($account);
- $post = Post::factory()->imported()->create(['workspace_id' => $account->workspace_id]);
- PostPlatform::factory()->for($post)->create(['platform_post_id' => 'imported-1']);
+ Post::factory()->instagram()->imported()->create(['workspace_id' => $account->workspace_id, 'platform_post_id' => 'imported-1']);
poll($account);
diff --git a/tests/Feature/Repurpose/ProcessItemTest.php b/tests/Feature/Repurpose/ProcessItemTest.php
index 9d5354f96..451c66683 100644
--- a/tests/Feature/Repurpose/ProcessItemTest.php
+++ b/tests/Feature/Repurpose/ProcessItemTest.php
@@ -25,7 +25,6 @@ use App\Jobs\SendNotification;
use App\Mail\PostApprovalRequested;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -102,7 +101,7 @@ test('it creates one post per destination and publishes each', function () {
->and($post->status)->toBe(PostStatus::Scheduled)
->and($post->schedule_mode)->toBe(ScheduleMode::Custom)
->and($post->media)->toHaveCount(1)
- ->and($post->postPlatforms()->enabled()->count())->toBe(1);
+ ->and($post->social_account_id)->not->toBeNull();
}
expect(Post::query()->due()->whereIn('id', $posts->pluck('id'))->count())->toBe(2);
@@ -127,7 +126,7 @@ test('the video is downloaded once and every post owns its own copy', function (
->and($paths->unique())->toHaveCount(2);
});
-test('destination meta is carried onto the post platform', function () {
+test('destination meta is carried onto the post', function () {
Bus::fake([PublishPost::class]);
fakeVideoDownload();
@@ -135,13 +134,12 @@ test('destination meta is carried onto the post platform', function () {
processItem($item);
- $tiktokPlatform = PostPlatform::query()
- ->enabled()
- ->whereHas('post', fn ($query) => $query->where('repurpose_item_id', $item->id))
+ $tiktokPost = Post::query()
+ ->where('repurpose_item_id', $item->id)
->where('platform', Platform::TikTok)
->sole();
- expect($tiktokPlatform->meta)->toEqual(['privacy_level' => PrivacyLevel::PublicToEveryone->value]);
+ expect($tiktokPost->meta)->toEqual(['privacy_level' => PrivacyLevel::PublicToEveryone->value]);
});
test('a caption over a destination limit is shortened for that post only', function () {
@@ -153,12 +151,10 @@ test('a caption over a destination limit is shortened for that post only', funct
processItem($item, $long);
- $captions = PostPlatform::query()
- ->enabled()
- ->whereHas('post', fn ($query) => $query->where('repurpose_item_id', $item->id))
- ->with('post')
+ $captions = Post::query()
+ ->where('repurpose_item_id', $item->id)
->get()
- ->mapWithKeys(fn (PostPlatform $platform) => [$platform->platform->value => $platform->post->content]);
+ ->mapWithKeys(fn (Post $post) => [$post->platform->value => $post->content]);
expect(Platform::TikTok->contentOverflow($captions[Platform::TikTok->value]))->toBe(0)
->and(Platform::YouTube->contentOverflow($captions[Platform::YouTube->value]))->toBe(0)
@@ -668,11 +664,10 @@ test('a requester repurpose run emails each approver once with every post, never
expect($ownerId)->not->toBeNull()
->and($postIds)->toHaveCount(2)
- ->and($notifications->map(fn (SendNotification $job): string => $job->user->id)->sort()->values()->all())
- ->toBe(collect([$ownerId, $publisher->id])->sort()->values()->all());
+ ->and($notifications->map(fn (SendNotification $job): string => "{$job->user->id}:{$job->mailable->postId}")->sort()->values()->all())
+ ->toBe(collect([$ownerId, $publisher->id])->crossJoin($postIds)->map(fn (array $pair): string => implode(':', $pair))->sort()->values()->all());
$notifications->each(fn (SendNotification $job) => expect($job->type)->toBe(Type::Collaboration)
- ->and(collect($job->mailable->postIds)->sort()->values()->all())->toBe($postIds)
->and($job->mailable->requester->is($requester))->toBeTrue());
expect(Post::whereIn('id', $postIds)->pluck('approval_requested_by')->unique()->values()->all())->toBe([$requester->id]);
});
@@ -696,8 +691,8 @@ test('a retry after the approval request was lost still emails the approvers', f
expect($item->fresh()->status)->toBe(ItemStatus::Published)
->and($postIds)->toHaveCount(2);
- Queue::assertPushed(SendNotification::class, fn (SendNotification $job): bool => $job->mailable instanceof PostApprovalRequested
- && collect($job->mailable->postIds)->sort()->values()->all() === $postIds);
+ expect(Queue::pushed(SendNotification::class, fn (SendNotification $job): bool => $job->mailable instanceof PostApprovalRequested)
+ ->map(fn (SendNotification $job): string => $job->mailable->postId)->unique()->sort()->values()->all())->toBe($postIds);
});
test('a requester repurpose in draft mode sends no approval email', function () {
@@ -730,7 +725,7 @@ test('a stored google business destination is skipped quietly', function () {
processItem($item->fresh());
- $platforms = PostPlatform::query()->whereIn('post_id', Post::where('repurpose_item_id', $item->id)->pluck('id'))->pluck('social_account_id');
+ $platforms = Post::query()->where('repurpose_item_id', $item->id)->pluck('social_account_id');
expect($item->fresh()->status)->toBe(ItemStatus::Published)
->and($platforms)->not->toContain($googleBusiness->id)
diff --git a/tests/Feature/Repurpose/WebTest.php b/tests/Feature/Repurpose/WebTest.php
index f425e97ba..ec315b68d 100644
--- a/tests/Feature/Repurpose/WebTest.php
+++ b/tests/Feature/Repurpose/WebTest.php
@@ -2,8 +2,8 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\Repurpose\PublishMode;
use App\Enums\Repurpose\SourceFormat;
use App\Enums\Repurpose\Status;
@@ -13,7 +13,6 @@ use App\Http\Resources\Api\RepurposeResource as ApiRepurposeResource;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\Repurpose;
use App\Models\RepurposeItem;
use App\Models\SocialAccount;
@@ -506,35 +505,25 @@ test('the activity list exposes each replicated post status', function () {
$item = RepurposeItem::factory()->for($repurpose)->create();
- $published = Post::factory()->create([
+ Post::factory()->mastodon()->published()->create([
'workspace_id' => $this->workspace->id,
'repurpose_item_id' => $item->id,
]);
- PostPlatform::factory()->for($published)->create([
- 'platform' => Platform::Mastodon,
- 'enabled' => true,
- 'status' => PostPlatformStatus::Published,
- ]);
- $failed = Post::factory()->create([
+ Post::factory()->threads()->failed()->create([
'workspace_id' => $this->workspace->id,
'repurpose_item_id' => $item->id,
]);
- PostPlatform::factory()->for($failed)->create([
- 'platform' => Platform::Threads,
- 'enabled' => true,
- 'status' => PostPlatformStatus::Failed,
- ]);
$this->actingAs($this->user)
->get(route('app.repurposes.show', $repurpose))
->assertInertia(fn (AssertableInertia $page) => $page
->has('items.data.0.posts', 2)
->where('items.data.0.posts', fn (Collection $posts): bool => $posts
- ->pluck('platforms.0.status')
+ ->pluck('publish_status')
->sort()
->values()
- ->all() === [PostPlatformStatus::Failed->value, PostPlatformStatus::Published->value]));
+ ->all() === [PublishStatus::Failed->value, PublishStatus::Published->value]));
});
test('google business is never a repurpose destination', function () {
diff --git a/tests/Feature/Services/InstagramPublisherTest.php b/tests/Feature/Services/InstagramPublisherTest.php
index 08bc0ccd5..c992d88ae 100644
--- a/tests/Feature/Services/InstagramPublisherTest.php
+++ b/tests/Feature/Services/InstagramPublisherTest.php
@@ -6,7 +6,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Media\MediaOptimizer;
@@ -22,18 +21,17 @@ beforeEach(function () {
'platform_user_id' => '12345678',
'access_token' => 'test-token',
]);
- $this->post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'content' => 'Test caption']);
- $this->postPlatform = PostPlatform::factory()->instagram()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
+ 'content' => 'Test caption',
'content_type' => ContentType::InstagramFeed,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
});
test('instagram publisher throws exception when no media', function () {
$publisher = new InstagramPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class, 'Instagram requires at least one image or video.');
});
@@ -51,14 +49,14 @@ test('instagram publisher publishes single image', function () {
]]);
$publisher = new InstagramPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('post-123');
expect($result['url'])->toBe('https://instagram.com/p/abc123');
});
test('instagram publisher publishes reel', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel]);
+ $this->post->update(['content_type' => ContentType::InstagramReel]);
Http::fake([
'*/12345678/media' => Http::response(['id' => 'container-123'], 200),
@@ -73,14 +71,14 @@ test('instagram publisher publishes reel', function () {
]]);
$publisher = new InstagramPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('reel-123');
});
test('instagram publisher publishes story', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('fitToCanvas')->once()->with(Mockery::type('string'), 1080, 1920)->andReturnUsing(function (string $tempFile) {
@@ -105,7 +103,7 @@ test('instagram publisher publishes story', function () {
]]);
$publisher = new InstagramPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('story-123');
@@ -137,7 +135,7 @@ test('instagram publisher throws token expired exception on oauth error', functi
$publisher = new InstagramPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -158,6 +156,6 @@ test('instagram publisher throws exception on api error', function () {
$publisher = new InstagramPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class);
});
diff --git a/tests/Feature/Services/Social/BlueskyPublisherTest.php b/tests/Feature/Services/Social/BlueskyPublisherTest.php
index 348b43bd5..6e878156a 100644
--- a/tests/Feature/Services/Social/BlueskyPublisherTest.php
+++ b/tests/Feature/Services/Social/BlueskyPublisherTest.php
@@ -9,7 +9,6 @@ use App\Exceptions\Social\BlueskyPublishException;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -32,18 +31,12 @@ beforeEach(function () {
'username' => 'testuser.bsky.social',
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from Bluesky!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Bluesky,
'content_type' => ContentType::BlueskyPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new BlueskyPublisher;
@@ -62,7 +55,7 @@ test('bluesky publisher can publish text-only post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -85,7 +78,7 @@ test('bluesky publisher parses URLs as facets', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$record = $request['record'];
@@ -106,7 +99,7 @@ test('bluesky publisher parses hashtags as facets', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$record = $request['record'];
@@ -125,7 +118,7 @@ test('bluesky publisher strips trailing punctuation from URL facets', function (
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$link = collect($request['record']['facets'] ?? [])
@@ -147,7 +140,7 @@ test('bluesky publisher keeps a closing paren that has a matching open paren', f
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$link = collect($request['record']['facets'] ?? [])
@@ -168,7 +161,7 @@ test('bluesky publisher computes byte offsets after multibyte characters', funct
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$text = $request['record']['text'];
@@ -198,7 +191,7 @@ test('bluesky publisher resolves mentions to DIDs as facets', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$record = $request->data()['record'] ?? null;
@@ -231,7 +224,7 @@ test('bluesky publisher skips mention facet when handle cannot be resolved', fun
]);
// Post still publishes; the unresolved @handle stays as plain text.
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('3abc123xyz');
@@ -265,7 +258,7 @@ test('bluesky publisher publishes as plain text when handle resolution errors',
});
// A network error resolving the handle must degrade to plain text, not fail the post.
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('3abc123xyz');
@@ -291,7 +284,7 @@ test('bluesky publisher builds the post url from the configured web app host', f
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBe('https://custom.bsky.example/profile/testuser.bsky.social/post/3abc123xyz');
});
@@ -314,7 +307,7 @@ test('bluesky publisher resolves some mentions and skips the unresolvable ones',
], 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$record = $request->data()['record'] ?? null;
@@ -344,7 +337,7 @@ test('bluesky publisher resolves a repeated handle only once', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The same handle appears twice but the per-post cache resolves it once.
$resolveCalls = Http::recorded(fn ($request) => str_contains($request->url(), 'resolveHandle'))->count();
@@ -400,7 +393,7 @@ test('bluesky publisher attaches an uploaded image as an embed', function () {
return Http::response(str_repeat('x', 1024), 200); // media download
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -451,7 +444,7 @@ test('bluesky publisher includes image alt text in the embed', function () {
return Http::response(str_repeat('x', 1024), 200); // media download
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -496,7 +489,7 @@ test('bluesky publisher sends empty-string alt when none is set', function () {
return Http::response(str_repeat('x', 1024), 200); // media download
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -523,7 +516,7 @@ test('bluesky publisher refreshes token when expired', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'refreshSession');
@@ -541,7 +534,7 @@ test('bluesky publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -553,7 +546,7 @@ test('bluesky publisher throws token expired exception on auth error', function
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -604,7 +597,7 @@ test('bluesky publisher optimizes images before upload', function () {
return Http::response(str_repeat('x', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
@unlink($tempFile);
});
@@ -636,7 +629,7 @@ test('bluesky publisher stops publication when an image download fails', functio
return Http::response('Not Found', 404);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -676,7 +669,7 @@ test('bluesky publisher limits images to 4', function () {
return Http::response(str_repeat('x', 1024), 200); // media download
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Six images provided, but Bluesky caps at 4: only 4 blobs upload and the embed carries 4.
$uploads = Http::recorded(fn ($request) => str_contains($request->url(), 'uploadBlob'))->count();
@@ -717,7 +710,7 @@ test('bluesky publisher never publishes a partial image set', function (string $
return Http::response(str_repeat('x', 1024));
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
expect($uploads)->toBe(2);
@@ -799,7 +792,7 @@ test('bluesky publisher uploads a video and embeds it', function () {
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -822,7 +815,7 @@ test('bluesky publisher scopes the upload service-auth to the resolved PDS host'
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Audience for the upload token must be the real PDS host from the DID doc,
// not the bsky.social entryway the account was connected through.
@@ -846,7 +839,7 @@ test('bluesky publisher stops after one upload when the account email is unconfi
]);
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$this->fail('The unconfirmed email must stop publication.');
} catch (BlueskyPublishException $exception) {
expect($exception->category)->toBe(ErrorCategory::Permission)
@@ -876,7 +869,7 @@ test('bluesky publisher preserves video upload retries for other service failure
]),
]);
- expect($this->publisher->publish($this->postPlatform)['id'])->toBe('3retry');
+ expect($this->publisher->publish($this->post)['id'])->toBe('3retry');
expect(Http::recorded(fn ($request) => str_contains($request->url(), '/app.bsky.video.uploadVideo')))->toHaveCount(2);
})->with([
'service token expired' => [['error' => 'ExpiredToken'], 401],
@@ -899,7 +892,7 @@ test('bluesky publisher stops publication when video processing fails', function
fakeBlueskyVideoPipeline('JOB_STATE_FAILED');
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -945,7 +938,7 @@ test('bluesky publisher retries a transient video transcode failure', function (
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect($jobCalls)->toBeGreaterThanOrEqual(2);
Http::assertSent(function ($request) {
@@ -973,7 +966,7 @@ test('bluesky publisher stops publication for an oversized video', function () {
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -991,7 +984,7 @@ test('bluesky publisher stops publication when the video download fails', functi
return Http::response('Not Found', 404);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -1017,7 +1010,7 @@ test('bluesky publisher stops publication when service-auth minting fails', func
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -1050,7 +1043,7 @@ test('bluesky publisher embeds the existing blob when upload returns 409 already
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1092,7 +1085,7 @@ test('bluesky publisher stops publication when upload returns no job id', functi
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -1124,7 +1117,7 @@ test('bluesky publisher stops publication when getJobStatus errors', function ()
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
// A failing getJobStatus bails immediately rather than sleeping to timeout.
@@ -1173,7 +1166,7 @@ test('bluesky publisher backs off while video processing remains pending', funct
return Http::response(str_repeat('v', 2048));
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Sleep::assertSequence([
Sleep::for(2)->seconds(),
@@ -1227,7 +1220,7 @@ test('bluesky publisher caps video poll backoff at the configured maximum', func
return Http::response(str_repeat('v', 2048));
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Sleep::assertSequence([
Sleep::for(10)->seconds(),
@@ -1269,7 +1262,7 @@ test('bluesky publisher retries the upload up to three times before giving up',
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
expect($uploads)->toBe(3);
@@ -1303,7 +1296,7 @@ test('bluesky publisher times out and stops publication when the job never compl
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -1331,7 +1324,7 @@ test('bluesky publisher falls back to the entryway when the DID document is unav
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// With no DID doc, the upload-token audience falls back to the entryway host (bsky.social).
Http::assertSent(function ($request) {
@@ -1364,7 +1357,7 @@ test('bluesky publisher resolves the PDS from a did:web document', function () {
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), 'example.com/.well-known/did.json'));
Http::assertSent(function ($request) {
@@ -1397,7 +1390,7 @@ test('bluesky publisher builds the did:web document url from colon path segments
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// did:web:example.com:user:alice → https://example.com/user/alice/did.json
Http::assertSent(fn ($request) => str_contains($request->url(), 'example.com/user/alice/did.json'));
@@ -1408,7 +1401,7 @@ test('bluesky publisher scopes the status service-auth to the video service', fu
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The getJobStatus token is minted for the video service DID, not the PDS.
Http::assertSent(function ($request) {
@@ -1445,7 +1438,7 @@ test('bluesky publisher picks the PDS entry even when other services come first'
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The upload-token audience is the PDS host, not the labeler listed first.
Http::assertSent(function ($request) {
@@ -1460,7 +1453,7 @@ test('bluesky publisher uploads a webm video with the correct content type', fun
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Bluesky accepts webm natively; send it as webm, not mislabeled mp4.
Http::assertSent(function ($request) {
@@ -1475,7 +1468,7 @@ test('bluesky publisher uploads a mov video with the quicktime content type', fu
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo')
@@ -1489,7 +1482,7 @@ test('bluesky publisher sends an unsupported video format as mp4', function () {
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Unknown formats fall back to mp4 and let the transcoder decide.
Http::assertSent(function ($request) {
@@ -1525,7 +1518,7 @@ test('bluesky publisher polls when a 409 carries an in-flight job without a blob
return Http::response(str_repeat('v', 2048), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The 409 had no blob, so the job is polled and the completed blob is embedded.
Http::assertSent(fn ($request) => str_contains($request->url(), 'xrpc/app.bsky.video.getJobStatus'));
@@ -1565,7 +1558,7 @@ test('bluesky publisher embeds images and skips the video when a post carries bo
return Http::response(str_repeat('x', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Images win; the embed is images and the video service is never touched.
Http::assertSent(function ($request) {
@@ -1600,7 +1593,7 @@ test('bluesky publisher stops publication when only the status token fails', fun
return Http::response(str_repeat('v', 2048), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(BlueskyPublishException::class, 'Media upload to Bluesky failed.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord'));
@@ -1612,7 +1605,7 @@ test('bluesky publisher uploads an mpeg video with the correct content type', fu
fakeBlueskyVideoPipeline();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'xrpc/app.bsky.video.uploadVideo')
@@ -1642,7 +1635,7 @@ test('bluesky publisher uploads a gif without optimizing it', function () {
return Http::response(str_repeat('g', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The GIF is uploaded as-is with its original content type.
Http::assertSent(fn ($request) => str_contains($request->url(), 'uploadBlob')
@@ -1679,7 +1672,7 @@ test('bluesky publisher attaches an external card with a thumb for a bare link',
return Http::response(str_repeat('x', 1024), 200); // og:image download
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1699,7 +1692,7 @@ test('bluesky publisher attaches an external card with a thumb for a bare link',
test('bluesky publisher attaches no external card when the user dropped the link preview', function () {
$this->post->update(['content' => 'read this https://example.com/article']);
- $this->postPlatform->update(['meta' => ['link_preview' => false]]);
+ $this->post->update(['meta' => ['link_preview' => false]]);
$this->mock(LinkCardFetcher::class)->shouldReceive('fetch')->never();
@@ -1707,7 +1700,7 @@ test('bluesky publisher attaches no external card when the user dropped the link
? Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', 'cid' => 'bafyreiabc123'], 200)
: Http::response([], 200));
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord')
&& ! isset($request['record']['embed']));
@@ -1733,7 +1726,7 @@ test('bluesky publisher builds an external card without a thumb when there is no
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1778,7 +1771,7 @@ test('bluesky publisher keeps the card when the thumb upload fails', function ()
return Http::response(str_repeat('x', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1823,7 +1816,7 @@ test('bluesky publisher does not consult the link card fetcher when media is pre
return Http::response(str_repeat('x', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord')
&& ($request['record']['embed']['$type'] ?? null) === 'app.bsky.embed.images');
@@ -1849,7 +1842,7 @@ test('bluesky publisher blocks the thumb download when the card image points at
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1889,7 +1882,7 @@ test('bluesky publisher does not follow a redirect on the card thumb download',
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1931,7 +1924,7 @@ test('bluesky publisher downloads the card thumb through the size-capped fetcher
return Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/3abc123xyz', 'cid' => 'bafyreiabc123'], 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect(data_get($thumbOptions, 'allow_redirects'))->toBeFalse()
->and(data_get($thumbOptions, 'decode_content'))->toBeFalse()
@@ -1961,7 +1954,7 @@ test('bluesky publisher does not attach a card when a non-embeddable media item
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -1988,7 +1981,7 @@ test('bluesky publisher publishes with only a facet when no card is available',
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'createRecord')) {
@@ -2016,21 +2009,21 @@ test('bluesky publisher keeps links intact', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), 'createRecord')
&& $request['record']['text'] === 'New post: https://acme.com/blog');
});
test('a bluesky thread replies with root and parent strong refs', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
$service = data_get($this->socialAccount->meta, 'service');
Http::fake(["{$service}/xrpc/com.atproto.repo.createRecord" => Http::sequence()
->push(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r1', 'cid' => 'c1'])
->push(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r2', 'cid' => 'c2'])
->push(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r3', 'cid' => 'c3'])]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result)->toBe([
'id' => 'r1',
@@ -2054,7 +2047,7 @@ test('a bluesky thread replies with root and parent strong refs', function () {
test('a bluesky thread embeds each reply media in that reply only', function () {
$image = ['id' => 'reply-image', 'path' => 'media/2026-01/photo.jpg', 'url' => 'https://example.com/media/2026-01/photo.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg', 'meta' => ['alt_text' => 'A photo']];
- $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]], 'Three']]]);
+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]], 'Three']]]);
$this->mock(MediaOptimizer::class)
->shouldReceive('optimizeImage')
@@ -2075,7 +2068,7 @@ test('a bluesky thread embeds each reply media in that reply only', function ()
return Http::response(str_repeat('x', 1024), 200);
});
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['r2', 'r3']);
Http::assertSent(fn ($request): bool => str_contains($request->url(), 'createRecord')
@@ -2092,7 +2085,7 @@ test('a bluesky thread embeds each reply media in that reply only', function ()
});
test('a bluesky thread resumes from the stored segments without posting the root again', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
$service = data_get($this->socialAccount->meta, 'service');
$appView = config('trypost.platforms.bluesky.public_appview');
Http::fake([
@@ -2108,9 +2101,9 @@ test('a bluesky thread resumes from the stored segments without posting the root
->push(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r3', 'cid' => 'c3']),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(BlueskyPublishException::class);
+ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(BlueskyPublishException::class);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('r1')->and($result['thread_reply_ids'])->toBe(['r2', 'r3']);
Http::assertSentCount(5);
@@ -2127,7 +2120,7 @@ test('a bluesky thread stops on reply media failure and resumes without repeatin
'mime_type' => 'image/gif',
'original_filename' => 'reply.gif',
];
- $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]]]]]);
+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]]]]]);
$failUpload = true;
$records = 0;
@@ -2151,16 +2144,16 @@ test('a bluesky thread stops on reply media failure and resumes without repeatin
return Http::response(str_repeat('x', 1024));
});
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(BlueskyPublishException::class);
expect($records)->toBe(1)
- ->and(data_get($this->postPlatform->fresh()->error_context, 'thread_progress.0.id'))->toBe('r1');
+ ->and(data_get($this->post->fresh()->error_context, 'thread_progress.0.id'))->toBe('r1');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'createRecord')
&& data_get($request->data(), 'record.text') === 'Two');
$failUpload = false;
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($records)->toBe(2)
->and($result['id'])->toBe('r1')
@@ -2170,9 +2163,9 @@ test('a bluesky thread stops on reply media failure and resumes without repeatin
&& data_get($request->data(), 'record.embed.images.0.image.ref.$link') === 'reply-blob');
});
-function blueskyThreadCheckpoint(PostPlatform $postPlatform): void
+function blueskyThreadCheckpoint(Post $post): void
{
- ThreadProgress::remember($postPlatform, [
+ ThreadProgress::remember($post, [
['hash' => 'root', 'id' => 'r1', 'url' => 'https://bsky.app/profile/testuser.bsky.social/post/r1', 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r1', 'cid' => 'c1'],
['hash' => ThreadProgress::hash('Two'), 'id' => 'r2', 'url' => 'https://bsky.app/profile/testuser.bsky.social/post/r2', 'uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r2', 'cid' => 'c2'],
]);
@@ -2192,8 +2185,8 @@ function blueskyThreadReply(string $did, string $text, string $rkey): array
}
test('a resumed bluesky thread adopts a reply already live instead of posting it again', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
- blueskyThreadCheckpoint($this->postPlatform);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
+ blueskyThreadCheckpoint($this->post);
$service = data_get($this->socialAccount->meta, 'service');
$appView = config('trypost.platforms.bluesky.public_appview');
Http::fake([
@@ -2208,7 +2201,7 @@ test('a resumed bluesky thread adopts a reply already live instead of posting it
"{$service}/xrpc/com.atproto.repo.createRecord" => Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/dup', 'cid' => 'dup']),
]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('r1')->and($result['thread_reply_ids'])->toBe(['r2', 'r3']);
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), 'createRecord'));
@@ -2219,8 +2212,8 @@ test('a resumed bluesky thread adopts a reply already live instead of posting it
});
test('a resumed bluesky thread posts the missing reply when none of ours is live', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
- blueskyThreadCheckpoint($this->postPlatform);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
+ blueskyThreadCheckpoint($this->post);
$service = data_get($this->socialAccount->meta, 'service');
$appView = config('trypost.platforms.bluesky.public_appview');
Http::fake([
@@ -2235,7 +2228,7 @@ test('a resumed bluesky thread posts the missing reply when none of ours is live
"{$service}/xrpc/com.atproto.repo.createRecord" => Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r3', 'cid' => 'c3']),
]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['r2', 'r3']);
Http::assertSent(fn ($request): bool => data_get($request->data(), 'record.text') === 'Three'
@@ -2243,8 +2236,8 @@ test('a resumed bluesky thread posts the missing reply when none of ours is live
});
test('a resumed bluesky thread still posts when the thread lookup fails', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
- blueskyThreadCheckpoint($this->postPlatform);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three']]]);
+ blueskyThreadCheckpoint($this->post);
$service = data_get($this->socialAccount->meta, 'service');
$appView = config('trypost.platforms.bluesky.public_appview');
Http::fake([
@@ -2252,5 +2245,5 @@ test('a resumed bluesky thread still posts when the thread lookup fails', functi
"{$service}/xrpc/com.atproto.repo.createRecord" => Http::response(['uri' => 'at://did:plc:testuser123/app.bsky.feed.post/r3', 'cid' => 'c3']),
]);
- expect($this->publisher->publish($this->postPlatform->fresh())['thread_reply_ids'])->toBe(['r2', 'r3']);
+ expect($this->publisher->publish($this->post->fresh())['thread_reply_ids'])->toBe(['r2', 'r3']);
});
diff --git a/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php b/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php
index 81712ddab..bfc970b70 100644
--- a/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php
+++ b/tests/Feature/Services/Social/Concerns/HasSocialHttpClientTest.php
@@ -6,7 +6,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ContentLimitException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -24,9 +23,9 @@ beforeEach(function () {
return $this->socialHttp()->get($url);
}
- public function callValidateContentLength(PostPlatform $postPlatform): void
+ public function callValidateContentLength(Post $post): void
{
- $this->validateContentLength($postPlatform);
+ $this->validateContentLength($post);
}
};
});
@@ -84,32 +83,26 @@ test('validateContentLength passes when content is within limit', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$socialAccount = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => str_repeat('a', 100)]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $socialAccount->id,
- 'platform' => Platform::LinkedIn,
+ $post = Post::factory()->forAccount($socialAccount)->create([
+ 'user_id' => $user->id,
+ 'content' => str_repeat('a', 100),
'content_type' => ContentType::LinkedInPost,
]);
- expect(fn () => $this->client->callValidateContentLength($postPlatform))->not->toThrow(Exception::class);
+ expect(fn () => $this->client->callValidateContentLength($post))->not->toThrow(Exception::class);
});
test('validateContentLength throws when content exceeds limit', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$socialAccount = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'content' => str_repeat('a', 4000)]);
-
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $socialAccount->id,
- 'platform' => Platform::LinkedIn,
+ $post = Post::factory()->forAccount($socialAccount)->create([
+ 'user_id' => $user->id,
+ 'content' => str_repeat('a', 4000),
'content_type' => ContentType::LinkedInPost,
]);
- expect(fn () => $this->client->callValidateContentLength($postPlatform))
+ expect(fn () => $this->client->callValidateContentLength($post))
->toThrow(ContentLimitException::class, __('posts.errors.content_too_long', [
'platform' => Platform::LinkedIn->label(),
'max' => 3000,
diff --git a/tests/Feature/Services/Social/DiscordPublisherTest.php b/tests/Feature/Services/Social/DiscordPublisherTest.php
index 075d9f53a..0b5b81c01 100644
--- a/tests/Feature/Services/Social/DiscordPublisherTest.php
+++ b/tests/Feature/Services/Social/DiscordPublisherTest.php
@@ -7,7 +7,6 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\DiscordPublishException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,19 +30,12 @@ beforeEach(function () {
'platform_user_id' => '111222333', // guild id
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount, ContentType::DiscordMessage)->create([
'user_id' => $this->user->id,
'content' => 'Hello Discord',
]);
- $this->makePostPlatform = fn (array $meta = ['channel_id' => '444555666']) => PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Discord,
- 'content_type' => ContentType::DiscordMessage,
- 'meta' => $meta,
- ]);
+ $this->postWithMeta = fn (array $meta = ['channel_id' => '444555666']) => tap($this->post)->update(['meta' => $meta]);
$this->publisher = new DiscordPublisher;
});
@@ -66,7 +58,7 @@ function fakeDiscord(array $messageResponse = ['id' => '777'], int $status = 200
test('publishes a text-only message and suppresses accidental pings', function () {
fakeDiscord();
- $result = $this->publisher->publish(($this->makePostPlatform)());
+ $result = $this->publisher->publish(($this->postWithMeta)());
expect($result['id'])->toBe('777');
expect($result['url'])->toBe('https://discord.com/channels/111222333/444555666/777');
@@ -86,7 +78,7 @@ test('publishes a text-only message and suppresses accidental pings', function (
test('builds allowed_mentions from explicit mention chips only', function () {
fakeDiscord();
- $this->publisher->publish(($this->makePostPlatform)([
+ $this->publisher->publish(($this->postWithMeta)([
'channel_id' => '444555666',
'mentions' => [
['token' => '@everyone', 'label' => '@everyone'],
@@ -109,7 +101,7 @@ test('builds allowed_mentions from explicit mention chips only', function () {
test('includes rich embeds with clamped color', function () {
fakeDiscord(['id' => '888']);
- $this->publisher->publish(($this->makePostPlatform)([
+ $this->publisher->publish(($this->postWithMeta)([
'channel_id' => '444555666',
'embeds' => [[
'title' => 'Release v2',
@@ -154,7 +146,7 @@ test('uploads media as a multipart attachment', function () {
config('trypost.platforms.discord.api').'/channels/*/messages' => Http::response(['id' => '901'], 200),
]);
- $result = $this->publisher->publish(($this->makePostPlatform)());
+ $result = $this->publisher->publish(($this->postWithMeta)());
expect($result['id'])->toBe('901');
@@ -194,7 +186,7 @@ test('sets the attachment description from image alt text, capped at the platfor
config('trypost.platforms.discord.api').'/channels/*/messages' => Http::response(['id' => '902'], 200),
]);
- $this->publisher->publish(($this->makePostPlatform)());
+ $this->publisher->publish(($this->postWithMeta)());
$expectedAlt = mb_substr($longAlt, 0, Platform::Discord->altTextMaxLength());
@@ -233,7 +225,7 @@ test('omits the attachment description when the image has no alt text', function
config('trypost.platforms.discord.api').'/channels/*/messages' => Http::response(['id' => '903'], 200),
]);
- $this->publisher->publish(($this->makePostPlatform)());
+ $this->publisher->publish(($this->postWithMeta)());
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/messages')) {
@@ -266,7 +258,7 @@ test('does not set a description on a non-image attachment even if it carries al
config('trypost.platforms.discord.api').'/channels/*/messages' => Http::response(['id' => '904'], 200),
]);
- $this->publisher->publish(($this->makePostPlatform)());
+ $this->publisher->publish(($this->postWithMeta)());
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/messages')) {
@@ -280,14 +272,14 @@ test('does not set a description on a non-image attachment even if it carries al
});
test('throws when no channel is selected', function () {
- expect(fn () => $this->publisher->publish(($this->makePostPlatform)(meta: [])))
+ expect(fn () => $this->publisher->publish(($this->postWithMeta)(meta: [])))
->toThrow(DiscordPublishException::class);
});
test('throws when the channel is not part of the guild', function () {
fakeDiscord();
- expect(fn () => $this->publisher->publish(($this->makePostPlatform)(['channel_id' => '999999999'])))
+ expect(fn () => $this->publisher->publish(($this->postWithMeta)(['channel_id' => '999999999'])))
->toThrow(DiscordPublishException::class);
});
@@ -299,14 +291,14 @@ test('retries (does not permanently fail) when the channel lookup is transiently
// A 5xx on the channel guard must surface as PlatformUnavailableException so
// the publish job reschedules — not a permanent "channel not in server" fail.
- expect(fn () => $this->publisher->publish(($this->makePostPlatform)()))
+ expect(fn () => $this->publisher->publish(($this->postWithMeta)()))
->toThrow(PlatformUnavailableException::class);
});
test('maps a missing-permission error to a publish exception', function () {
fakeDiscord(['code' => 50013, 'message' => 'Missing Permissions'], 403);
- expect(fn () => $this->publisher->publish(($this->makePostPlatform)()))
+ expect(fn () => $this->publisher->publish(($this->postWithMeta)()))
->toThrow(DiscordPublishException::class);
});
@@ -317,7 +309,7 @@ test('discord publisher keeps links intact', function () {
fakeDiscord();
- $this->publisher->publish(($this->makePostPlatform)());
+ $this->publisher->publish(($this->postWithMeta)());
Http::assertSent(fn ($request) => str_contains($request->url(), '/messages')
&& data_get($request->data(), 'content') === 'New post: https://acme.com/blog');
diff --git a/tests/Feature/Services/Social/FacebookPublisherTest.php b/tests/Feature/Services/Social/FacebookPublisherTest.php
index 298c2b017..6d9d0bef9 100644
--- a/tests/Feature/Services/Social/FacebookPublisherTest.php
+++ b/tests/Feature/Services/Social/FacebookPublisherTest.php
@@ -9,7 +9,6 @@ use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\FacebookPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -85,18 +84,12 @@ beforeEach(function () {
],
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Check out this Facebook post!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Facebook,
'content_type' => ContentType::FacebookPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new FacebookPublisher;
});
@@ -108,7 +101,7 @@ test('facebook publisher can publish text only post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -142,7 +135,7 @@ test('facebook publisher can publish single image post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('page_123_photo_post_456');
@@ -177,7 +170,7 @@ test('facebook publisher can publish multi image post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('page_123_multi_post_789');
@@ -207,7 +200,7 @@ test('facebook publisher sends graph api requests as form-urlencoded not json',
'*/page_123/photos' => Http::response(['id' => 'photo_123', 'post_id' => 'post_123'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/photos')
@@ -235,7 +228,7 @@ test('facebook publisher can publish video post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('video_123');
@@ -249,7 +242,7 @@ test('facebook publisher can publish video post', function () {
test('facebook publisher fits an image story to 9:16 and publishes it through photo_stories', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::FacebookStory]);
+ $this->post->update(['content_type' => ContentType::FacebookStory]);
$this->post->update(['media' => [[
'id' => 'test-media-story',
'path' => 'media/2026-01/story.jpg',
@@ -273,7 +266,7 @@ test('facebook publisher fits an image story to 9:16 and publishes it through ph
'*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200, ['Content-Type' => 'image/png']),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toBe([
'id' => 'story_789',
@@ -291,7 +284,7 @@ test('facebook publisher fits an image story to 9:16 and publishes it through ph
test('facebook publisher fails an image story when the photo upload is refused', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::FacebookStory]);
+ $this->post->update(['content_type' => ContentType::FacebookStory]);
$this->post->update(['media' => [[
'id' => 'test-media-story',
'path' => 'media/2026-01/story.jpg',
@@ -314,19 +307,19 @@ test('facebook publisher fails an image story when the photo upload is refused',
'*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200, ['Content-Type' => 'image/png']),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook could not upload the story photo.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), 'photo_stories'));
});
test('facebook publisher rejects a reel without a video', function (array $media) {
- $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);
+ $this->post->update(['content_type' => ContentType::FacebookReel]);
$this->post->update(['media' => $media]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook Reels require a video file.');
Http::assertNothingSent();
@@ -342,24 +335,24 @@ test('facebook publisher rejects a reel without a video', function (array $media
]);
test('facebook publisher rejects a story without media', function () {
- $this->postPlatform->update(['content_type' => ContentType::FacebookStory]);
+ $this->post->update(['content_type' => ContentType::FacebookStory]);
$this->post->update(['media' => []]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook Stories require an image or a video file.');
Http::assertNothingSent();
});
test('facebook publisher can publish reel', function () {
- $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);
+ $this->post->update(['content_type' => ContentType::FacebookReel]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake(facebookVideoUploadFakes('video_reels'));
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('reel_456');
expect($result['url'])->toBe('https://www.facebook.com/reel/reel_456');
@@ -372,12 +365,12 @@ test('facebook publisher can publish reel', function () {
});
test('facebook publisher can publish video story', function () {
- $this->postPlatform->update(['content_type' => ContentType::FacebookStory]);
+ $this->post->update(['content_type' => ContentType::FacebookStory]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake(facebookVideoUploadFakes('video_stories'));
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('story_456');
expect($result['url'])->toBe('https://www.facebook.com/stories/page_123/story_456');
@@ -389,12 +382,12 @@ test('facebook publisher can publish video story', function () {
});
test('facebook publisher hands meta the hosted url and never downloads the video', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake(facebookVideoUploadFakes($edge));
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), config('trypost.platforms.facebook.rupload_host'))) {
@@ -418,7 +411,7 @@ test('facebook publisher hands meta the hosted url and never downloads the video
})->with('facebook resumable video formats');
test('facebook publisher waits for meta to fetch the video before finishing', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -431,7 +424,7 @@ test('facebook publisher waits for meta to fetch the video before finishing', fu
->push(['status' => ['video_status' => 'processing', 'uploading_phase' => ['status' => 'complete']]], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Sleep::assertSleptTimes(2);
Sleep::assertSequence([
@@ -441,7 +434,7 @@ test('facebook publisher waits for meta to fetch the video before finishing', fu
})->with('facebook resumable video formats');
test('facebook publisher retries a rupload failure meta documents as retryable', function (int $status, array $body) {
- $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);
+ $this->post->update(['content_type' => ContentType::FacebookReel]);
$this->post->update(['media' => facebookVideoMedia()]);
$rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');
@@ -451,7 +444,7 @@ test('facebook publisher retries a rupload failure meta documents as retryable',
"{$rupload}/*" => Http::response($body, $status),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class);
Http::assertNotSent(fn ($request) => ($request['upload_phase'] ?? null) === 'finish');
@@ -461,7 +454,7 @@ test('facebook publisher retries a rupload failure meta documents as retryable',
]);
test('facebook publisher fails a rupload error meta flags not retriable by its documented type', function (string $type, string $message, ErrorCategory $category) {
- $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);
+ $this->post->update(['content_type' => ContentType::FacebookReel]);
$this->post->update(['media' => facebookVideoMedia()]);
$rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');
@@ -475,7 +468,7 @@ test('facebook publisher fails a rupload error meta flags not retriable by its d
]], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (FacebookPublishException $exception) => expect($exception->userMessage)
->toBe(__($message, ['platform' => Platform::Facebook->label()]))
->and($exception->category)->toBe($category)
@@ -490,21 +483,21 @@ test('facebook publisher fails a rupload error meta flags not retriable by its d
]);
test('facebook publisher fails when start does not return upload_url', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake([
"*/page_123/{$edge}" => Http::response(['video_id' => 'video_123'], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook did not start the video upload. Please try again.');
Http::assertSentCount(1);
})->with('facebook resumable video formats');
test('facebook publisher rejects an upload_url outside the rupload host', function (ContentType $contentType, string $edge, string $uploadUrl) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake([
@@ -514,7 +507,7 @@ test('facebook publisher rejects an upload_url outside the rupload host', functi
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook returned an invalid upload URL.');
Http::assertSentCount(1);
@@ -528,7 +521,7 @@ test('facebook publisher rejects an upload_url outside the rupload host', functi
test('facebook publisher trusts the rupload host from config', function () {
config()->set('trypost.platforms.facebook.rupload_host', 'rupload.example.test');
- $this->postPlatform->update(['content_type' => ContentType::FacebookStory]);
+ $this->post->update(['content_type' => ContentType::FacebookStory]);
$this->post->update(['media' => facebookVideoMedia()]);
Http::fake([
@@ -536,7 +529,7 @@ test('facebook publisher trusts the rupload host from config', function () {
'https://rupload.example.test/*' => Http::response(['success' => true], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('story_456');
@@ -544,7 +537,7 @@ test('facebook publisher trusts the rupload host from config', function () {
});
test('facebook publisher maps a rupload rejection and does not finish', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');
@@ -554,7 +547,7 @@ test('facebook publisher maps a rupload rejection and does not finish', function
"{$rupload}/*" => Http::response(['error' => ['message' => 'Problem with file', 'code' => 6000]], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Problem with file. Try with another file.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), "/page_123/{$edge}")
@@ -562,7 +555,7 @@ test('facebook publisher maps a rupload rejection and does not finish', function
})->with('facebook resumable video formats');
test('facebook publisher does not finish when rupload does not confirm success', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');
@@ -572,7 +565,7 @@ test('facebook publisher does not finish when rupload does not confirm success',
"{$rupload}/*" => Http::response(['success' => false], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook did not accept the video. Please try again.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), "/page_123/{$edge}")
@@ -580,7 +573,7 @@ test('facebook publisher does not finish when rupload does not confirm success',
})->with('facebook resumable video formats');
test('facebook publisher reschedules when rupload cannot be reached', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$rupload = 'https://'.config('trypost.platforms.facebook.rupload_host');
@@ -590,7 +583,7 @@ test('facebook publisher reschedules when rupload cannot be reached', function (
"{$rupload}/*" => fn () => throw new ConnectionException('cURL error 28: Connection timed out after 10003 milliseconds'),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->retryDelaySeconds)->toBe(60)
->and($exception->getMessage())->toContain('video upload unreachable');
@@ -601,7 +594,7 @@ test('facebook publisher reschedules when rupload cannot be reached', function (
})->with('facebook resumable video formats');
test('facebook publisher reschedules when the status check cannot be reached and keeps the token out of the message', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -611,7 +604,7 @@ test('facebook publisher reschedules when the status check cannot be reached and
"{$graph}/video_123?fields=status*" => fn ($request) => throw new ConnectionException("cURL error 28: Operation timed out for {$request->url()}"),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->getMessage())
->toContain('video status unreachable')
@@ -621,7 +614,7 @@ test('facebook publisher reschedules when the status check cannot be reached and
})->with('facebook resumable video formats');
test('facebook publisher keeps polling the video status through a transient graph error', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -633,13 +626,13 @@ test('facebook publisher keeps polling the video status through a transient grap
->push(['status' => ['video_status' => 'processing', 'uploading_phase' => ['status' => 'complete']]], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Sleep::assertSleptTimes(1);
})->with('facebook resumable video formats');
test('facebook publisher stops polling the video status on a confirmed graph rejection', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -651,7 +644,7 @@ test('facebook publisher stops polling the video status on a confirmed graph rej
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Unsupported get request.');
Sleep::assertNeverSlept();
@@ -661,7 +654,7 @@ test('facebook publisher stops polling the video status on a confirmed graph rej
})->with('facebook resumable video formats');
test('facebook publisher surfaces the video processing error instead of finishing', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -680,7 +673,7 @@ test('facebook publisher surfaces the video processing error instead of finishin
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Resolution too low. Video must have a minimum resolution of 540p.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), "/page_123/{$edge}")
@@ -688,7 +681,7 @@ test('facebook publisher surfaces the video processing error instead of finishin
})->with('facebook resumable video formats');
test('facebook publisher fails when the upload session expires', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -698,12 +691,12 @@ test('facebook publisher fails when the upload session expires', function (Conte
"{$graph}/video_123?fields=status*" => Http::response(['status' => ['video_status' => 'expired']], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook could not process the video. Please try another file.');
})->with('facebook resumable video formats');
test('facebook publisher gives up on a video fetch that never completes', function (ContentType $contentType, string $edge) {
- $this->postPlatform->update(['content_type' => $contentType]);
+ $this->post->update(['content_type' => $contentType]);
$this->post->update(['media' => facebookVideoMedia()]);
$graph = config('trypost.platforms.facebook.graph_api');
@@ -715,7 +708,7 @@ test('facebook publisher gives up on a video fetch that never completes', functi
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook took too long to fetch the video. Please try again.');
Sleep::assertSleptTimes(59);
@@ -729,7 +722,7 @@ test('facebook publisher reschedules a graph post when facebook cannot be reache
'*/page_123/feed' => fn () => throw new ConnectionException('cURL error 28: Connection timed out'),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class);
});
@@ -744,7 +737,7 @@ test('facebook publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -759,7 +752,7 @@ test('facebook publisher throws token expired exception on oauth error', functio
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -775,14 +768,14 @@ test('facebook publisher throws token expired exception on session expired subco
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
test('facebook publisher throws exception for unsupported content type', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramFeed]);
+ $this->post->update(['content_type' => ContentType::InstagramFeed]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Unsupported Facebook content type');
});
@@ -806,7 +799,7 @@ test('facebook publisher throws exception when multi image upload fails', functi
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Failed to upload any images to Facebook');
});
@@ -831,7 +824,7 @@ test('facebook publisher publishes the multi image post with the photos facebook
'*/page_123/feed' => Http::response(['id' => 'page_123_partial_789'], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('page_123_partial_789');
@@ -846,7 +839,7 @@ test('facebook publisher rejects a text post that is only whitespace', function
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Facebook text posts require content');
Http::assertNothingSent();
@@ -865,14 +858,14 @@ test('facebook publisher throws exception for unsupported media type', function
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Unsupported media type for Facebook');
});
test('facebook publisher throws exception for text post with null content', function () {
$this->post->update(['content' => null]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Facebook text posts require content');
});
@@ -897,7 +890,7 @@ test('facebook publisher can publish single image with null content', function (
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-123');
});
@@ -920,7 +913,7 @@ test('single image post without caption omits message from payload', function ()
'*/page_123/photos' => Http::response(['id' => 'photo-123', 'post_id' => 'post-123'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/photos')
@@ -949,7 +942,7 @@ test('multi-image post without caption omits message from payload', function ()
'*/page_123/feed' => Http::response(['id' => 'multi_post_789'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/feed')
@@ -975,7 +968,7 @@ test('video post without description omits description from payload', function (
'*/page_123/videos' => Http::response(['id' => 'video_123'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/videos')
@@ -984,7 +977,7 @@ test('video post without description omits description from payload', function (
});
test('reel post without description omits description from payload (finish phase)', function () {
- $this->postPlatform->update(['content_type' => ContentType::FacebookReel]);
+ $this->post->update(['content_type' => ContentType::FacebookReel]);
$this->post->update([
'content' => null,
@@ -1001,7 +994,7 @@ test('reel post without description omits description from payload (finish phase
Http::fake(facebookVideoUploadFakes('video_reels'));
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/page_123/video_reels')) {
@@ -1018,7 +1011,7 @@ test('reel post without description omits description from payload (finish phase
test('facebook single image post publishes the original image and ignores a legacy aspect ratio', function (?string $legacyRatio) {
Storage::fake();
- $this->postPlatform->update(['meta' => $legacyRatio === null ? [] : ['aspect_ratio' => $legacyRatio]]);
+ $this->post->update(['meta' => $legacyRatio === null ? [] : ['aspect_ratio' => $legacyRatio]]);
$this->post->update([
'media' => [
['id' => 'm1', 'path' => 'media/a.jpg', 'url' => 'https://example.com/media/a.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'a.jpg'],
@@ -1029,7 +1022,7 @@ test('facebook single image post publishes the original image and ignores a lega
'*/page_123/photos' => Http::response(['id' => 'photo_1', 'post_id' => 'post_1'], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post_1')
->and(Storage::allFiles())->toBeEmpty();
@@ -1049,7 +1042,7 @@ test('facebook single image post publishes the original image and ignores a lega
test('facebook multi image post uploads every original image and ignores a legacy aspect ratio', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['aspect_ratio' => '4:5']]);
+ $this->post->update(['meta' => ['aspect_ratio' => '4:5']]);
$this->post->update([
'media' => [
['id' => 'm1', 'path' => 'media/a.jpg', 'url' => 'https://example.com/media/a.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'a.jpg'],
@@ -1064,7 +1057,7 @@ test('facebook multi image post uploads every original image and ignores a legac
'*/page_123/feed' => Http::response(['id' => 'post_1'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect(Storage::allFiles())->toBeEmpty();
@@ -1106,7 +1099,7 @@ test('facebook publisher sends capped alt text on single image post', function (
'*/page_123/photos' => Http::response(['id' => 'photo_123', 'post_id' => 'post_123'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($longAlt, 0, Platform::Facebook->altTextMaxLength());
@@ -1149,7 +1142,7 @@ test('facebook publisher sends capped alt text for each image in multi image pos
'*/page_123/feed' => Http::response(['id' => 'multi_post_alt'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt1 = mb_substr($longAlt1, 0, Platform::Facebook->altTextMaxLength());
$expectedAlt2 = mb_substr($longAlt2, 0, Platform::Facebook->altTextMaxLength());
@@ -1182,7 +1175,7 @@ test('facebook publisher omits alt_text_custom from photos payload when no alt t
'*/page_123/photos' => Http::response(['id' => 'photo_123', 'post_id' => 'post_123'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/page_123/photos')
@@ -1197,7 +1190,7 @@ test('facebook publisher keeps links intact', function () {
Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
&& $request['message'] === 'New post: https://acme.com/blog'
@@ -1206,11 +1199,11 @@ test('facebook publisher keeps links intact', function () {
test('facebook publisher sends no link when the user dropped the link preview', function () {
$this->post->update(['content' => 'New post: https://acme.com/blog']);
- $this->postPlatform->update(['meta' => ['link_preview' => false]]);
+ $this->post->update(['meta' => ['link_preview' => false]]);
Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
&& $request['message'] === 'New post: https://acme.com/blog'
@@ -1226,7 +1219,7 @@ test('facebook publisher retries a text post without the link when the scrape fa
->push(['id' => 'page_123_post_456'], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('page_123_post_456');
@@ -1252,7 +1245,7 @@ test('facebook publisher does not log an error when the rejected link is publish
->push(['id' => 'page_123_post_456'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Log::shouldHaveReceived('warning')->once();
Log::shouldNotHaveReceived('error');
@@ -1269,7 +1262,7 @@ test('facebook publisher logs an error when a text post fails for a reason other
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class);
Log::shouldHaveReceived('error')->once();
@@ -1285,7 +1278,7 @@ test('facebook publisher does not drop the link on an unrelated feed error', fun
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class);
Http::assertSentCount(1);
@@ -1296,7 +1289,7 @@ test('facebook publisher does not send a facebook-owned url as the link', functi
Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('page_123_post_456');
@@ -1319,7 +1312,7 @@ test('facebook publisher uses the first url that facebook can preview', function
Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
&& $request['message'] === 'See https://www.facebook.com/page and https://example.com/post.'
@@ -1331,7 +1324,7 @@ test('facebook publisher still attaches a link on a host that only looks like fa
Http::fake(['*/page_123/feed' => Http::response(['id' => 'page_123_post_456'], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/feed')
&& $request['link'] === 'https://notfacebook.com/post');
@@ -1346,7 +1339,7 @@ test('facebook publisher retries without the link when facebook rejects the url'
->push(['id' => 'page_123_post_456'], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('page_123_post_456');
@@ -1372,7 +1365,7 @@ test('facebook publisher does not drop the link on a permissions error without t
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class);
Http::assertSentCount(1);
@@ -1389,7 +1382,7 @@ test('facebook publisher fails the post when the retry without the link is rejec
->push(['error' => ['message' => 'Duplicate post', 'code' => 506]], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(FacebookPublishException::class, 'Duplicate post detected. Please modify content.');
Http::assertSentCount(2);
@@ -1406,7 +1399,7 @@ test('facebook publisher does not retry a text post with a link when the token i
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
Http::assertSentCount(1);
@@ -1431,7 +1424,7 @@ test('facebook publisher does not attach a link card when the post has media', f
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/page_123/feed'));
Http::assertSent(fn ($request) => str_contains($request->url(), '/page_123/photos')
diff --git a/tests/Feature/Services/Social/GoogleBusinessPublisherTest.php b/tests/Feature/Services/Social/GoogleBusinessPublisherTest.php
index 627f3bb60..fcdb64ab1 100644
--- a/tests/Feature/Services/Social/GoogleBusinessPublisherTest.php
+++ b/tests/Feature/Services/Social/GoogleBusinessPublisherTest.php
@@ -5,11 +5,9 @@ declare(strict_types=1);
use App\Enums\GoogleBusiness\LocalPostState;
use App\Enums\GoogleBusiness\TopicType;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Exceptions\Social\GoogleBusinessPublishException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -29,19 +27,13 @@ beforeEach(function () {
'token_expires_at' => now()->addHour(),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Check out our new arrivals!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::GoogleBusiness,
'content_type' => ContentType::GoogleBusinessPost,
'meta' => ['topic_type' => TopicType::Standard->value],
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new GoogleBusinessPublisher;
});
@@ -50,7 +42,7 @@ test('publish hands Google a JPEG derivative rather than the raw upload', functi
attachPromoPng($this->post);
fakeLocalPostCreate(['state' => LocalPostState::Live->value]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request): bool {
$sourceUrl = (string) data_get($request->data(), 'media.0.sourceUrl');
@@ -67,10 +59,10 @@ test('publish keeps the jpeg while Google is still reviewing', function (string
attachPromoPng($this->post);
fakeLocalPostCreate(['state' => $googleState]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['state'])->toBe($recorded);
- Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($this->postPlatform->id));
+ Storage::assertExists(GoogleBusinessDerivativeCleaner::pathFor($this->post));
})->with([
[LocalPostState::Processing->value, LocalPostState::Processing->value],
[LocalPostState::Scheduled->value, LocalPostState::Scheduled->value],
@@ -82,7 +74,7 @@ test('publish deletes the jpeg once Google is no longer reviewing', function (st
attachPromoPng($this->post);
fakeLocalPostCreate(['state' => $state]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
expect(Storage::allFiles(GoogleBusinessDerivativeCleaner::DIRECTORY))->toBe([]);
})->with([
@@ -99,7 +91,7 @@ test('publish deletes the jpeg when create fails after the derivative is written
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class);
expect(Storage::allFiles(GoogleBusinessDerivativeCleaner::DIRECTORY))->toBe([]);
@@ -111,7 +103,7 @@ test('publish reports the review state Google returned and the real post URL', f
'searchUrl' => 'https://posts.google.com/999',
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['state'])->toBe(LocalPostState::Live->value)
->and($result['url'])->toBe('https://posts.google.com/999');
@@ -121,7 +113,7 @@ test('publishes a standard post with the author locale', function () {
$this->user->update(['locale' => Locale::English]);
fakeLocalPostCreate();
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('accounts/123456789/locations/987654321/localPosts/999');
expect($result['url'])->toBe('https://business.google.com/dashboard/l/u987654321');
@@ -137,9 +129,9 @@ test('publishes a standard post with the author locale', function () {
test('an explicitly null topic_type publishes as STANDARD', function () {
fakeLocalPostCreate();
- $this->postPlatform->update(['meta' => ['topic_type' => null]]);
+ $this->post->update(['meta' => ['topic_type' => null]]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'topicType') === 'STANDARD'
&& ! isset($request['event']));
@@ -149,7 +141,7 @@ test('publish throws when the account has no location', function () {
Http::fake();
$this->socialAccount->update(['meta' => []]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class, __('posts.errors.google_business.no_location'));
Http::assertNothingSent();
@@ -159,7 +151,7 @@ test('publish throws when only one of the location resource names is stored', fu
Http::fake();
$this->socialAccount->update(['meta' => $meta]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class, __('posts.errors.google_business.no_location'));
Http::assertNothingSent();
@@ -170,14 +162,14 @@ test('publish throws when only one of the location resource names is stored', fu
test('a blank offer title throws with the offer-title message', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => '', 'start_date' => '2026-09-01', 'end_date' => '2026-09-02'],
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class, __('posts.form.google_business.offer_title_required'));
Http::assertNothingSent();
@@ -187,7 +179,7 @@ test('a chinese author sends a regional language code', function () {
$this->user->update(['locale' => Locale::Chinese]);
fakeLocalPostCreate();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'languageCode') === 'zh-CN');
});
@@ -196,21 +188,21 @@ test('a post whose author was deleted falls back to the default language code',
$this->post->update(['user_id' => null]);
fakeLocalPostCreate();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'languageCode') === 'en');
});
test('a blank event title throws instead of publishing an untitled event', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'EVENT',
'event' => ['title' => '', 'start_date' => '2026-09-01', 'end_date' => '2026-09-02'],
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class, __('posts.form.google_business.event_title_required'));
Http::assertNothingSent();
@@ -218,14 +210,14 @@ test('a blank event title throws instead of publishing an untitled event', funct
test('a blank event start date throws instead of silently publishing today', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'EVENT',
'event' => ['title' => 'Grand Opening', 'start_date' => '', 'end_date' => '2026-09-02'],
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class);
Http::assertNothingSent();
@@ -233,14 +225,14 @@ test('a blank event start date throws instead of silently publishing today', fun
test('a missing event end date throws instead of silently publishing today', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => null],
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(GoogleBusinessPublishException::class);
Http::assertNothingSent();
@@ -248,47 +240,47 @@ test('a missing event end date throws instead of silently publishing today', fun
test('includes a call to action when configured', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => ['topic_type' => 'STANDARD', 'call_to_action' => ['action_type' => 'BOOK', 'url' => 'https://example.com/book']],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'callToAction') === ['actionType' => 'BOOK', 'url' => 'https://example.com/book']);
});
test('call omits the url even when one is stored', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => ['topic_type' => 'STANDARD', 'call_to_action' => ['action_type' => 'CALL', 'url' => 'https://example.com/should-not-go']],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'callToAction') === ['actionType' => 'CALL']);
});
test('none and deprecated get-offer call to actions are omitted', function (string $action) {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => ['topic_type' => 'STANDARD', 'call_to_action' => ['action_type' => $action, 'url' => 'https://example.com']],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => ! array_key_exists('callToAction', $request->data()));
})->with(['NONE', 'GET_OFFER']);
test('builds an event payload for EVENT topic type', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'EVENT',
'event' => ['title' => 'Grand Opening', 'start_date' => '2026-09-01', 'end_date' => '2026-09-02'],
],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
$event = data_get($request->data(), 'event');
@@ -301,7 +293,7 @@ test('builds an event payload for EVENT topic type', function () {
test('includes event start and end times when they are set', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'EVENT',
'event' => [
@@ -314,7 +306,7 @@ test('includes event start and end times when they are set', function () {
],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
$schedule = data_get($request->data(), 'event.schedule');
@@ -326,7 +318,7 @@ test('includes event start and end times when they are set', function () {
test('builds both an event and an offer payload for OFFER topic type', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => '2026-09-30'],
@@ -334,7 +326,7 @@ test('builds both an event and an offer payload for OFFER topic type', function
],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return data_get($request->data(), 'topicType') === 'OFFER'
@@ -351,7 +343,7 @@ test('builds both an event and an offer payload for OFFER topic type', function
test('omits callToAction on OFFER posts because Google ignores it', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => '2026-09-30'],
@@ -360,7 +352,7 @@ test('omits callToAction on OFFER posts because Google ignores it', function ()
],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'topicType') === 'OFFER'
&& ! array_key_exists('callToAction', $request->data()));
@@ -368,7 +360,7 @@ test('omits callToAction on OFFER posts because Google ignores it', function ()
test('includes offer redeem url and terms when they are set', function () {
fakeLocalPostCreate();
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'topic_type' => 'OFFER',
'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => '2026-09-30'],
@@ -380,7 +372,7 @@ test('includes offer redeem url and terms when they are set', function () {
],
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'offer') === [
'couponCode' => 'SUMMER20',
@@ -400,7 +392,7 @@ test('publish skips a gif and does not send it as a photo', function () {
]]]);
fakeLocalPostCreate(['state' => LocalPostState::Live->value]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => ! isset($request->data()['media']));
});
@@ -415,7 +407,7 @@ test('publish sends the original image url when the jpeg optimizer fails', funct
fakeLocalPostCreate(['state' => LocalPostState::Live->value]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'media.0.sourceUrl') === Storage::url('uploads/promo.png'));
expect(Storage::allFiles(GoogleBusinessDerivativeCleaner::DIRECTORY))->toBe([]);
@@ -431,7 +423,7 @@ test('publish sends the original url when the upload is not on disk', function (
]]]);
fakeLocalPostCreate(['state' => LocalPostState::Live->value]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => data_get($request->data(), 'media.0.sourceUrl') === 'https://cdn.example.com/photo.png');
});
@@ -448,7 +440,7 @@ test('rejects video media for google business posts', function () {
]);
fakeLocalPostCreate();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => ! isset($request['media']) || data_get($request->data(), 'media.0.mediaFormat') !== 'VIDEO');
});
@@ -460,7 +452,7 @@ test('throws a structured exception on API failure', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(GoogleBusinessPublishException::class, 'summary too long');
});
diff --git a/tests/Feature/Services/Social/InstagramPublisherTest.php b/tests/Feature/Services/Social/InstagramPublisherTest.php
index 58ead9d65..dd0a53283 100644
--- a/tests/Feature/Services/Social/InstagramPublisherTest.php
+++ b/tests/Feature/Services/Social/InstagramPublisherTest.php
@@ -2,9 +2,9 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ErrorCategory;
@@ -12,7 +12,6 @@ use App\Exceptions\Social\InstagramPublishException;
use App\Exceptions\TokenExpiredException;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -45,24 +44,18 @@ beforeEach(function () {
'token_expires_at' => now()->addDays(60),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from Instagram!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Instagram,
'content_type' => ContentType::InstagramFeed,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new InstagramPublisher;
});
test('instagram publisher throws exception without media', function () {
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Instagram requires at least one image or video');
});
@@ -94,7 +87,7 @@ test('instagram publisher can publish single image', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -107,7 +100,7 @@ test('instagram publisher can publish single image', function () {
});
test('instagram publisher can publish reel', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel]);
+ $this->post->update(['content_type' => ContentType::InstagramReel]);
$this->post->update([
@@ -138,7 +131,7 @@ test('instagram publisher can publish reel', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('reel-123456789');
expect($result['url'])->toBe('https://www.instagram.com/reel/ABC123/');
@@ -151,7 +144,7 @@ test('instagram publisher can publish reel', function () {
test('instagram publisher fits an image story to 9:16 and posts the hosted copy', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
@@ -192,7 +185,7 @@ test('instagram publisher fits an image story to 9:16 and posts the hosted copy'
'*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200, ['Content-Type' => 'image/png']),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('story-123456789');
@@ -208,7 +201,7 @@ test('instagram publisher fits an image story to 9:16 and posts the hosted copy'
test('instagram publisher fits a real off-ratio story image to a 1080x1920 jpeg', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
@@ -230,7 +223,7 @@ test('instagram publisher fits a real off-ratio story image to a 1080x1920 jpeg'
'https://graph.instagram.com/v25.0/story-123456789*' => Http::response(['permalink' => 'https://www.instagram.com/stories/testuser/123/'], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('story-123456789');
@@ -247,7 +240,7 @@ test('instagram publisher fits a real off-ratio story image to a 1080x1920 jpeg'
test('instagram publisher throws a clean exception when the story image is not decodable', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
@@ -265,13 +258,13 @@ test('instagram publisher throws a clean exception when the story image is not d
'https://example.com/media/story.jpg' => Http::response('<html>error</html>', 200, ['Content-Type' => 'text/html']),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(InstagramPublishException::class, 'Failed to process image for story fitting');
});
test('instagram publisher surfaces a publish exception when the story container fails to create', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
@@ -290,12 +283,12 @@ test('instagram publisher surfaces a publish exception when the story container
'https://graph.instagram.com/v25.0/ig_123456789/media' => Http::response(['error' => ['message' => 'Invalid media', 'code' => 100]], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(InstagramPublishException::class);
});
test('instagram publisher does not leak the fitted temp file when hosting the story image fails', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
@@ -325,14 +318,14 @@ test('instagram publisher does not leak the fitted temp file when hosting the st
Storage::shouldReceive('put')->once()->andThrow(new RuntimeException('disk full'));
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(RuntimeException::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(RuntimeException::class);
expect($fittedPath)->not->toBeNull()
->and(file_exists($fittedPath))->toBeFalse();
});
test('instagram publisher can publish video story', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
@@ -363,7 +356,7 @@ test('instagram publisher can publish video story', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('story-video-123456789');
});
@@ -399,7 +392,7 @@ test('instagram publisher can publish carousel', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('carousel-123456789');
expect($result['url'])->toBe('https://www.instagram.com/p/CAROUSEL123/');
@@ -444,7 +437,7 @@ test('instagram publisher can publish carousel with videos', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('carousel-mix-123456789');
});
@@ -489,7 +482,7 @@ test('instagram publisher resumes a processing carousel child without recreating
]);
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
test()->fail('Expected the processing carousel child to be rescheduled.');
} catch (PlatformUnavailableException $exception) {
expect($exception->context)->toBe([
@@ -502,10 +495,10 @@ test('instagram publisher resumes a processing carousel child without recreating
])->and($exception->retryDelaySeconds)->toBe(60)
->and($exception->maxRetries)->toBe(120);
- $this->postPlatform->update(['error_context' => $exception->context]);
+ $this->post->update(['error_context' => $exception->context]);
}
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('carousel-resumed-123456789')
->and(collect(Http::recorded())->filter(
@@ -536,7 +529,7 @@ test('instagram publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -563,7 +556,7 @@ test('instagram publisher throws token expired exception on oauth error', functi
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -591,12 +584,12 @@ test('instagram publisher throws token expired exception on session expired subc
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
test('instagram publisher throws exception for unsupported content type', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
@@ -610,7 +603,7 @@ test('instagram publisher throws exception for unsupported content type', functi
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Unsupported Instagram content type');
});
@@ -634,7 +627,7 @@ test('instagram publisher throws exception when no container id returned', funct
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'No container ID returned');
});
@@ -661,7 +654,7 @@ test('instagram publisher handles media processing error', function () {
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (InstagramPublishException $exception): void {
expect($exception->getMessage())->toBe(__('posts.errors.instagram.processing_failed'))
->and($exception->category)->toBe(ErrorCategory::Unknown)
@@ -691,7 +684,7 @@ test('instagram publisher explains a container error reported as an error subcod
"{$graph}/container-123*" => Http::response(['status_code' => 'ERROR', 'status' => $status]),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (InstagramPublishException $exception): void {
expect($exception->userMessage)->toBe('Unsupported video format. Please upload MP4 or MOV.')
->and($exception->category)->toBe(ErrorCategory::MediaFormat)
@@ -720,7 +713,7 @@ test('instagram publisher never reads a subcode out of a container status senten
"{$graph}/container-123*" => Http::response(['status_code' => 'ERROR', 'status' => $status]),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (InstagramPublishException $exception) use ($status, $code): void {
expect($exception->userMessage)->toBe(__('posts.errors.instagram.processing_failed'))
->and($exception->userMessage)->not->toContain($status)
@@ -750,7 +743,7 @@ test('instagram publisher says processing failed when the container gives no rea
"{$graph}/container-123*" => Http::response(['status_code' => 'ERROR']),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (InstagramPublishException $exception) => expect($exception->userMessage)
->toBe(__('posts.errors.instagram.processing_failed')));
});
@@ -785,7 +778,7 @@ test('instagram publisher resumes media processing without creating another cont
]);
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
test()->fail('Expected the in-progress container to be rescheduled.');
} catch (PlatformUnavailableException $exception) {
expect($exception->context)->toBe([
@@ -797,13 +790,13 @@ test('instagram publisher resumes media processing without creating another cont
])->and($exception->retryDelaySeconds)->toBe(60)
->and($exception->maxRetries)->toBe(120);
- $this->postPlatform->update(['error_context' => $exception->context]);
+ $this->post->update(['error_context' => $exception->context]);
}
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(PlatformUnavailableException::class);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('media-123456789');
@@ -829,7 +822,7 @@ test('instagram publisher does not publish a container that never finishes proce
'https://graph.instagram.com/v25.0/container-123*' => Http::response(['status_code' => 'IN_PROGRESS']),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
'instagram_workflow' => [
@@ -850,7 +843,7 @@ test('instagram retries long interruptions without abandoning or duplicating the
$availableAt = $startedAt->copy()->addMinutes($minutes);
$workflow = ['stage' => 'final_container', 'container_id' => 'container-123'];
$this->post->update(['status' => PostStatus::Publishing]);
- $this->postPlatform->update(['error_context' => ['instagram_workflow' => $workflow]]);
+ $this->post->update(['error_context' => ['instagram_workflow' => $workflow]]);
Http::fake(function (Request $request) use ($availableAt, $interruption, $recovers) {
$unavailable = ! $recovers || now()->lt($availableAt);
@@ -882,14 +875,14 @@ test('instagram retries long interruptions without abandoning or duplicating the
throw new RuntimeException('Unexpected Instagram request: '.$request->url());
});
- $job = new PublishToSocialPlatform($this->postPlatform);
+ $job = new PublishToSocialPlatform($this->post);
for ($minute = 0; $minute < $minutes; $minute++) {
$job->handle();
- expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($this->postPlatform->error_context['instagram_workflow'])->toBe($workflow)
- ->and($this->postPlatform->error_context['processing_retry_count'])->toBe($minute + 1);
+ expect($this->post->refresh()->publish_status)->toBe(PublishStatus::Retrying)
+ ->and($this->post->error_context['instagram_workflow'])->toBe($workflow)
+ ->and($this->post->error_context['processing_retry_count'])->toBe($minute + 1);
$job = Queue::pushed(PublishToSocialPlatform::class)->last();
@@ -901,7 +894,7 @@ test('instagram retries long interruptions without abandoning or duplicating the
if ($minute >= 59) {
$this->artisan('social:recover-stuck-posts')->assertSuccessful();
- expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)
+ expect($this->post->refresh()->publish_status)->toBe(PublishStatus::Retrying)
->and($this->post->refresh()->status)->toBe(PostStatus::Publishing);
}
}
@@ -909,7 +902,7 @@ test('instagram retries long interruptions without abandoning or duplicating the
expect(now()->equalTo($availableAt))->toBeTrue();
$job->handle();
- expect($this->postPlatform->refresh()->status)->toBe($recovers ? PlatformStatus::Published : PlatformStatus::Failed)
+ expect($this->post->refresh()->publish_status)->toBe($recovers ? PublishStatus::Published : PublishStatus::Failed)
->and($this->post->refresh()->status)->toBe($recovers ? PostStatus::Published : PostStatus::Failed);
Queue::assertPushed(PublishToSocialPlatform::class, $minutes);
Http::assertNotSent(fn (Request $request) => str_ends_with($request->url(), '/media'));
@@ -917,8 +910,8 @@ test('instagram retries long interruptions without abandoning or duplicating the
&& $response->successful()))->toHaveCount($recovers ? 1 : 0);
if (! $recovers) {
- expect($this->postPlatform->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))
- ->and($this->postPlatform->error_context['instagram_workflow'])->toBe($workflow);
+ expect($this->post->error_message)->toBe(__('posts.errors.platform_unavailable_exhausted'))
+ ->and($this->post->error_context['instagram_workflow'])->toBe($workflow);
}
})->with([
'processing for 30 minutes' => [30, 'processing', true],
@@ -950,7 +943,7 @@ test('instagram publisher retries a transient Graph rate-limit on container stat
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(400)
->and($exception->context)->toBe([
@@ -992,7 +985,7 @@ test('instagram publisher retries a transient Graph failure on media_publish', f
], 500),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(500)
->and($exception->context)->toBe([
@@ -1023,7 +1016,7 @@ test('instagram publisher fails at once on a documented rejection sent under a t
'https://graph.instagram.com/v25.0/ig_123456789/media_publish' => $rejection,
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (InstagramPublishException $exception) use ($subcode, $category): void {
expect($exception->platformErrorCode)->toBe((string) $subcode)
->and($exception->category)->toBe($category);
@@ -1048,7 +1041,7 @@ test('instagram publisher still retries a documented server subcode sent under a
'https://graph.instagram.com/v25.0/ig_123456789/media' => Http::response(['error' => ['message' => 'Server error', 'code' => 2, 'error_subcode' => 2207001]], 500),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(PlatformUnavailableException::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(PlatformUnavailableException::class);
});
test('instagram publisher waits for a container media_publish reports as not ready yet', function () {
@@ -1078,7 +1071,7 @@ test('instagram publisher waits for a container media_publish reports as not rea
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(400)
->and($exception->context)->toBe([
@@ -1107,7 +1100,7 @@ test('instagram publisher retries a dropped connection on media_publish', functi
'https://graph.instagram.com/v25.0/ig_123456789/media_publish' => fn () => throw new ConnectionException('cURL error 28: Operation timed out'),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
'instagram_workflow' => [
@@ -1134,7 +1127,7 @@ test('instagram publisher retries a dropped connection on container status', fun
'https://graph.instagram.com/v25.0/container-123*' => fn () => throw new ConnectionException('cURL error 28: Operation timed out'),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
'instagram_workflow' => [
@@ -1162,7 +1155,7 @@ test('instagram publisher retries a dropped connection on container create', fun
'https://graph.instagram.com/v25.0/ig_123456789/media' => fn () => throw new ConnectionException('cURL error 28: Operation timed out'),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->getMessage())->toContain('Instagram API unreachable')
->and($exception->context)->toBe([]);
@@ -1187,12 +1180,12 @@ test('instagram publisher keeps a published media id when the permalink request
'https://graph.instagram.com/v25.0/media-123456789*' => fn () => throw new ConnectionException('cURL error 28: Operation timed out'),
]);
- expect($this->publisher->publish($this->postPlatform))->toBe([
+ expect($this->publisher->publish($this->post))->toBe([
'id' => 'media-123456789',
'url' => null,
]);
- expect($this->postPlatform->fresh()->error_context['instagram_workflow'] ?? null)->toEqual([
+ expect($this->post->fresh()->error_context['instagram_workflow'] ?? null)->toEqual([
'stage' => 'final_container',
'container_id' => 'container-123',
'media_id' => 'media-123456789',
@@ -1200,7 +1193,7 @@ test('instagram publisher keeps a published media id when the permalink request
});
test('instagram publisher does not publish again when a transient media_publish already landed', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -1213,7 +1206,7 @@ test('instagram publisher does not publish again when a transient media_publish
'https://graph.instagram.com/v25.0/container-123*' => Http::response(['status_code' => 'PUBLISHED']),
]);
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'container-123',
'url' => null,
]);
@@ -1243,20 +1236,20 @@ test('instagram publisher fails a confirmed container status rejection', functio
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(InstagramPublishException::class);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/media_publish'));
});
test('instagram publisher rejects an invalid workflow instead of starting over', function (array $workflow) {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['instagram_workflow' => $workflow],
]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(InstagramPublishException::class, 'Instagram publish state is invalid and cannot be resumed.');
Http::assertNothingSent();
@@ -1267,7 +1260,7 @@ test('instagram publisher rejects an invalid workflow instead of starting over',
]);
test('instagram publisher fails a resumed container that reports ERROR', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -1283,7 +1276,7 @@ test('instagram publisher fails a resumed container that reports ERROR', functio
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(function (InstagramPublishException $exception): void {
expect($exception->getMessage())->toBe(__('posts.errors.instagram.processing_failed'))
->and($exception->rawResponse)->toContain('Media download has failed');
@@ -1294,7 +1287,7 @@ test('instagram publisher fails a resumed container that reports ERROR', functio
});
test('instagram publisher fails an expired container instead of retrying it', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -1307,7 +1300,7 @@ test('instagram publisher fails an expired container instead of retrying it', fu
'https://graph.instagram.com/v25.0/container-123*' => Http::response(['status_code' => 'EXPIRED'], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(function (InstagramPublishException $exception): void {
expect($exception->userMessage)->toBe('Media container expired. Please try again in a few minutes.')
->and($exception->category)->toBe(ErrorCategory::ServerError);
@@ -1318,7 +1311,7 @@ test('instagram publisher fails an expired container instead of retrying it', fu
});
test('instagram publisher completes a published container without calling media_publish', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -1344,7 +1337,7 @@ test('instagram publisher completes a published container without calling media_
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'container-123',
'url' => null,
]);
@@ -1355,7 +1348,7 @@ test('instagram publisher completes a published container without calling media_
});
test('instagram publisher does not bind another account post when a published story has no media id', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::InstagramStory,
'error_context' => [
'instagram_workflow' => [
@@ -1391,7 +1384,7 @@ test('instagram publisher does not bind another account post when a published st
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'container-123',
'url' => null,
]);
@@ -1402,7 +1395,7 @@ test('instagram publisher does not bind another account post when a published st
});
test('instagram publisher does not bind another reel from /media when published without a media id', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::InstagramReel,
'error_context' => [
'instagram_workflow' => [
@@ -1429,7 +1422,7 @@ test('instagram publisher does not bind another reel from /media when published
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'container-123',
'url' => null,
]);
@@ -1440,7 +1433,7 @@ test('instagram publisher does not bind another reel from /media when published
});
test('instagram publisher keeps a published carousel parent id without listing /media', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'carousel_children',
@@ -1475,7 +1468,7 @@ test('instagram publisher keeps a published carousel parent id without listing /
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'carousel-parent-123',
'url' => null,
]);
@@ -1486,7 +1479,7 @@ test('instagram publisher keeps a published carousel parent id without listing /
});
test('instagram publisher resumes a checkpointed media id without listing recent media', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'instagram_workflow' => [
'stage' => 'final_container',
@@ -1515,7 +1508,7 @@ test('instagram publisher resumes a checkpointed media id without listing recent
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'media-persisted',
'url' => 'https://www.instagram.com/p/PERSISTED/',
]);
@@ -1543,12 +1536,12 @@ test('instagram publisher checkpoints the media id before fetching the permalink
'https://graph.instagram.com/v25.0/media-123456789*' => Http::response(['error' => ['message' => 'temporarily unavailable']], 500),
]);
- expect($this->publisher->publish($this->postPlatform))->toBe([
+ expect($this->publisher->publish($this->post))->toBe([
'id' => 'media-123456789',
'url' => null,
]);
- expect($this->postPlatform->fresh()->error_context['instagram_workflow'] ?? null)->toEqual([
+ expect($this->post->fresh()->error_context['instagram_workflow'] ?? null)->toEqual([
'stage' => 'final_container',
'container_id' => 'container-123',
'media_id' => 'media-123456789',
@@ -1564,7 +1557,7 @@ test('instagram facebook publisher recovers a published container on graph.faceb
'token_expires_at' => null,
'scopes' => Platform::InstagramFacebook->requiredPublishScopes(),
]);
- $this->postPlatform->update([
+ $this->post->forceFill([
'social_account_id' => $account->id,
'platform' => Platform::InstagramFacebook,
'error_context' => [
@@ -1573,7 +1566,8 @@ test('instagram facebook publisher recovers a published container on graph.faceb
'container_id' => 'container-123',
],
],
- ]);
+ ])->save();
+ $this->post->setRelation('socialAccount', $account);
$graph = (string) config('trypost.platforms.instagram-facebook.graph_api');
@@ -1597,7 +1591,7 @@ test('instagram facebook publisher recovers a published container on graph.faceb
return Http::response(['error' => ['message' => 'unexpected']], 500);
});
- expect($this->publisher->publish($this->postPlatform->fresh()))->toBe([
+ expect($this->publisher->publish($this->post->fresh()))->toBe([
'id' => 'container-123',
'url' => null,
]);
@@ -1623,7 +1617,7 @@ test('instagram publisher retries a 5xx on container status without publishing',
'https://graph.instagram.com/v25.0/container-123*' => Http::response(['error' => ['message' => 'Service temporarily unavailable']], 503),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(503)
->and($exception->context)->toBe([
@@ -1653,7 +1647,7 @@ test('instagram publisher retries a 429 on container status without publishing',
'https://graph.instagram.com/v25.0/container-123*' => Http::response(['error' => ['message' => 'Application request limit reached', 'code' => 4]], 429),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(429)
->and($exception->context)->toBe([
@@ -1687,7 +1681,7 @@ test('instagram publisher throws exception when all carousel items fail', functi
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Failed to create any carousel items');
});
@@ -1720,14 +1714,14 @@ test('instagram publisher can publish single image with null content', function
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('media-null-content');
expect($result['url'])->toBe('https://www.instagram.com/p/NULL123/');
});
test('instagram publisher can publish reel with null content', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel]);
+ $this->post->update(['content_type' => ContentType::InstagramReel]);
$this->post->update([
'content' => null,
'media' => [
@@ -1756,7 +1750,7 @@ test('instagram publisher can publish reel with null content', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('reel-null-content');
});
@@ -1798,7 +1792,7 @@ test('instagram publisher can publish carousel with null content', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('carousel-null-content');
});
@@ -1832,7 +1826,7 @@ test('instagram publisher can publish single image with empty string content', f
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('media-empty-content');
});
@@ -1866,7 +1860,7 @@ test('instagram publisher routes feed video to reel', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('feed-reel-123');
@@ -1906,14 +1900,14 @@ test('instagram publisher handles publish failure', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
test('story image throws when the source image cannot be downloaded for fitting', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [
['id' => 'm1', 'path' => 'media/a.jpg', 'url' => 'https://example.com/media/a.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'a.jpg'],
@@ -1924,14 +1918,14 @@ test('story image throws when the source image cannot be downloaded for fitting'
'https://example.com/media/a.jpg' => Http::response('', 404),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(InstagramPublishException::class, 'Failed to download image for story fitting');
});
test('feed image publishes the original url and ignores a legacy aspect ratio', function (string $legacyRatio) {
Storage::fake();
- $this->postPlatform->update(['meta' => ['aspect_ratio' => $legacyRatio]]);
+ $this->post->update(['meta' => ['aspect_ratio' => $legacyRatio]]);
$this->post->update([
'media' => [
@@ -1952,7 +1946,7 @@ test('feed image publishes the original url and ignores a legacy aspect ratio',
'https://graph.instagram.com/v25.0/media-1*' => Http::response(['permalink' => 'https://www.instagram.com/p/X/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect(Storage::allFiles())->toBeEmpty();
@@ -1974,7 +1968,7 @@ test('feed image publishes the original url and ignores a legacy aspect ratio',
test('carousel images publish their original urls and ignore a legacy aspect ratio', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['aspect_ratio' => '1:1']]);
+ $this->post->update(['meta' => ['aspect_ratio' => '1:1']]);
$this->post->update([
'media' => [
['id' => 'm1', 'path' => 'media/a.jpg', 'url' => 'https://example.com/media/a.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'a.jpg'],
@@ -1992,7 +1986,7 @@ test('carousel images publish their original urls and ignore a legacy aspect rat
'https://graph.instagram.com/v25.0/carousel-1*' => Http::response(['permalink' => 'https://www.instagram.com/p/C1/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$childUrls = collect(Http::recorded())
->map(fn (array $pair) => $pair[0])
@@ -2029,7 +2023,7 @@ test('feed image without aspect_ratio meta uses original URL', function () {
'https://graph.instagram.com/v25.0/media-1*' => Http::response(['permalink' => 'https://www.instagram.com/p/X/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect(Storage::allFiles())->toBeEmpty();
@@ -2065,7 +2059,7 @@ test('instagram publisher sends capped alt text on single image container', func
'*/media-alt-123*' => Http::response(['permalink' => 'https://www.instagram.com/p/ALT123/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($longAlt, 0, Platform::Instagram->altTextMaxLength());
@@ -2096,7 +2090,7 @@ test('instagram publisher omits alt_text from single image container when no alt
'*/media-no-alt-123*' => Http::response(['permalink' => 'https://www.instagram.com/p/NOALT123/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_ends_with($request->url(), '/ig_123456789/media')
@@ -2139,7 +2133,7 @@ test('instagram publisher sends alt text on image carousel children but never on
'*/carousel-alt-123*' => Http::response(['permalink' => 'https://www.instagram.com/p/CAROUSELALT/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($imageAlt, 0, Platform::Instagram->altTextMaxLength());
@@ -2183,7 +2177,7 @@ test('instagram publisher keeps links intact', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/ig_123456789/media')
&& ! str_contains($request->url(), 'media_publish')
@@ -2209,7 +2203,7 @@ test('instagram publisher sends user tags on a single image container', function
'*/media-tags-123*' => Http::response(['permalink' => 'https://www.instagram.com/p/TAGS123/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_ends_with($request->url(), '/ig_123456789/media')
&& json_decode((string) data_get($request->data(), 'user_tags'), true) === [
@@ -2235,7 +2229,7 @@ test('instagram publisher omits user tags when an image has none', function () {
'*/media-no-tags*' => Http::response(['permalink' => 'https://www.instagram.com/p/NOTAGS/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_ends_with($request->url(), '/ig_123456789/media')
&& ! array_key_exists('user_tags', $request->data()));
@@ -2270,7 +2264,7 @@ test('instagram publisher sends user tags on each tagged carousel image', functi
'*/carousel-tags-123*' => Http::response(['permalink' => 'https://www.instagram.com/p/CAROUSELTAGS/'], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains((string) data_get($request->data(), 'image_url'), 'tagged.jpg')
&& ! str_contains((string) data_get($request->data(), 'image_url'), 'untagged.jpg')
@@ -2283,7 +2277,7 @@ test('instagram publisher sends user tags on each tagged carousel image', functi
test('instagram publisher mentions story tags by username only', function () {
Storage::fake();
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
$this->post->update([
'media' => [[
'id' => 'test-media-story',
@@ -2311,14 +2305,14 @@ test('instagram publisher mentions story tags by username only', function () {
'*' => Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200, ['Content-Type' => 'image/png']),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_ends_with($request->url(), '/ig_123456789/media')
&& json_decode((string) data_get($request->data(), 'user_tags'), true) === [['username' => 'paulocastellano']]);
});
test('instagram reel sends the chosen cover frame as thumb_offset in milliseconds', function (?int $coverOffsetMs) {
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel]);
+ $this->post->update(['content_type' => ContentType::InstagramReel]);
$this->post->update([
'media' => [[
'id' => 'test-media-video',
@@ -2338,7 +2332,7 @@ test('instagram reel sends the chosen cover frame as thumb_offset in millisecond
"{$graph}/reel-123*" => Http::response(['permalink' => 'https://www.instagram.com/reel/ABC/']),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn (Request $request): bool => $request->url() === "{$graph}/ig_123456789/media"
&& data_get($request->data(), 'media_type') === 'REELS'
@@ -2381,7 +2375,7 @@ test('instagram carousel video child sends its cover frame as thumb_offset', fun
"{$graph}/carousel-published*" => Http::response(['permalink' => 'https://www.instagram.com/p/CAR/']),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn (Request $request): bool => data_get($request->data(), 'media_type') === 'VIDEO'
&& data_get($request->data(), 'thumb_offset') === 2500);
@@ -2410,7 +2404,7 @@ function instagramVideo(): array
test('instagram reel options reach the container', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::InstagramReel,
'meta' => [
'is_ai_generated' => true,
@@ -2419,7 +2413,7 @@ test('instagram reel options reach the container', function () {
]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'media_type') === 'REELS'
@@ -2429,10 +2423,10 @@ test('instagram reel options reach the container', function () {
test('an instagram reel without options publishes exactly as before', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel, 'meta' => []]);
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'meta' => []]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'share_to_feed') === 'true'
@@ -2441,13 +2435,13 @@ test('an instagram reel without options publishes exactly as before', function (
test('a story sends the ai label and ignores a leftover reel option', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::InstagramStory,
'meta' => ['share_to_feed' => false, 'is_ai_generated' => true],
]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'media_type') === 'STORIES'
@@ -2457,10 +2451,10 @@ test('a story sends the ai label and ignores a leftover reel option', function (
test('a story without the ai label sends none', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory, 'meta' => []]);
+ $this->post->update(['content_type' => ContentType::InstagramStory, 'meta' => []]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'media_type') === 'STORIES'
@@ -2472,7 +2466,7 @@ test('a carousel sends the ai label on the parent only', function () {
['id' => 'a', 'type' => 'image', 'path' => 'media/a.jpg', 'url' => 'https://example.com/a.jpg', 'mime_type' => 'image/jpeg'],
['id' => 'b', 'type' => 'image', 'path' => 'media/b.jpg', 'url' => 'https://example.com/b.jpg', 'mime_type' => 'image/jpeg'],
]]);
- $this->postPlatform->update(['meta' => ['is_ai_generated' => true]]);
+ $this->post->update(['meta' => ['is_ai_generated' => true]]);
$base = config('trypost.platforms.instagram.graph_api');
Http::fake([
'https://example.com/*' => Http::response(fakeJpegBytes()),
@@ -2482,7 +2476,7 @@ test('a carousel sends the ai label on the parent only', function () {
"{$base}/media-2*" => Http::response(['permalink' => 'https://www.instagram.com/p/Y/']),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => data_get($request->data(), 'media_type') === 'CAROUSEL'
&& data_get($request->data(), 'is_ai_generated') === 'true');
@@ -2492,10 +2486,10 @@ test('a carousel sends the ai label on the parent only', function () {
test('an instagram reel sends share_to_feed false when turned off', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update(['content_type' => ContentType::InstagramReel, 'meta' => ['share_to_feed' => false]]);
+ $this->post->update(['content_type' => ContentType::InstagramReel, 'meta' => ['share_to_feed' => false]]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'media_type') === 'REELS'
@@ -2504,13 +2498,13 @@ test('an instagram reel sends share_to_feed false when turned off', function ()
test('a feed video sends the ai label but no reel-only options', function () {
$this->post->update(['media' => instagramVideo()]);
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::InstagramFeed,
'meta' => ['is_ai_generated' => true, 'share_to_feed' => false],
]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media')
&& data_get($request->data(), 'media_type') === 'REELS'
@@ -2520,20 +2514,20 @@ test('a feed video sends the ai label but no reel-only options', function () {
test('instagram publishes a stored caption with more than five hashtags', function (ContentType $type) {
$this->post->update(['content' => 'Launch #a #b #c #d #e #f', 'media' => instagramVideo()]);
- $this->postPlatform->update(['content_type' => $type]);
+ $this->post->update(['content_type' => $type]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media_publish'));
})->with([ContentType::InstagramFeed, ContentType::InstagramReel, ContentType::InstagramStory]);
test('an instagram story is not measured against the caption length', function () {
$this->post->update(['content' => str_repeat('a', 2300), 'media' => instagramVideo()]);
- $this->postPlatform->update(['content_type' => ContentType::InstagramStory]);
+ $this->post->update(['content_type' => ContentType::InstagramStory]);
fakeInstagramReelFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/ig_123456789/media_publish'));
});
diff --git a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
index 43cd85911..71985aed1 100644
--- a/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
+++ b/tests/Feature/Services/Social/LinkedInPagePublisherTest.php
@@ -3,10 +3,8 @@
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,18 +29,12 @@ beforeEach(function () {
],
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from our LinkedIn Page!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::LinkedInPage,
'content_type' => ContentType::LinkedInPagePost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new LinkedInPagePublisher;
});
@@ -54,7 +46,7 @@ test('linkedin page publisher can publish text-only post', function () {
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -76,7 +68,7 @@ test('linkedin page publisher uses organization urn', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request['author'] === 'urn:li:organization:123456';
@@ -87,7 +79,7 @@ test('linkedin page publisher throws exception when organization id missing', fu
Http::fake();
$this->socialAccount->update(['meta' => []]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'LinkedIn Page organization ID not configured');
// Fail-fast: the missing org id must abort before any LinkedIn request.
@@ -101,7 +93,7 @@ test('linkedin page publisher uses correct headers', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request->hasHeader('Authorization')
@@ -119,7 +111,7 @@ test('linkedin page publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -135,7 +127,7 @@ test('linkedin page publisher throws token expired exception on auth error after
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -153,7 +145,7 @@ test('linkedin page publisher refreshes token when expired', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'oauth/v2/accessToken');
@@ -169,7 +161,7 @@ test('linkedin page publisher throws exception when no refresh token available',
'refresh_token' => null,
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available for LinkedIn Page account');
});
@@ -183,7 +175,7 @@ test('linkedin page publisher throws TokenExpiredException when refresh_token is
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'The refresh token is invalid');
});
@@ -196,7 +188,7 @@ test('linkedin page publisher handles empty content', function () {
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:1234567890');
@@ -214,7 +206,7 @@ test('linkedin page publisher builds feed url from the post id regardless of use
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBe('https://www.linkedin.com/feed/update/urn:li:share:1234567890');
})->with([
@@ -227,7 +219,7 @@ test('linkedin page publisher returns a null url when the response has no post i
config('trypost.platforms.linkedin-page.api').'/rest/posts' => Http::response(null, 201),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBeNull();
});
@@ -271,7 +263,7 @@ test('linkedin page publisher can publish post with image using organization urn
return Http::response('fake-image-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:9999999999');
expect($result['url'])->toBe('https://www.linkedin.com/feed/update/urn:li:share:9999999999');
@@ -320,7 +312,7 @@ test('linkedin page publisher publishes a multi-image carousel with image ids un
return Http::response('fake-image-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:orgcarousel');
expect($result['url'])->toBe('https://www.linkedin.com/feed/update/urn:li:share:orgcarousel');
@@ -342,7 +334,7 @@ test('linkedin page publisher publishes a multi-image carousel with image ids un
});
test('linkedin page publisher can publish a document (pdf carousel) using organization urn', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::LinkedInPagePost,
'meta' => ['document_title' => 'Company Deck'],
]);
@@ -387,7 +379,7 @@ test('linkedin page publisher can publish a document (pdf carousel) using organi
return Http::response('fake-pdf-bytes', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:orgdoc999');
expect($result['url'])->toBe('https://www.linkedin.com/feed/update/urn:li:share:orgdoc999');
@@ -405,7 +397,7 @@ test('linkedin page publisher can publish a document (pdf carousel) using organi
});
test('linkedin page publisher throws and does not post when document processing fails', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPagePost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPagePost]);
$this->post->update([
'media' => [[
'id' => 'doc-media-1', 'path' => 'media/2026-01/company-deck.pdf',
@@ -434,7 +426,7 @@ test('linkedin page publisher throws and does not post when document processing
return Http::response('fake-pdf-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'LinkedIn Page document processing failed');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
@@ -453,7 +445,7 @@ test('linkedin page publisher keeps links intact', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& $request['commentary'] === 'New post: https://acme.com/blog');
@@ -478,7 +470,7 @@ test('linkedin page publisher sends the article card under the organization', fu
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& $request['author'] === 'urn:li:organization:123456'
diff --git a/tests/Feature/Services/Social/LinkedInPublisherTest.php b/tests/Feature/Services/Social/LinkedInPublisherTest.php
index 7d89fb1ee..22286a1b8 100644
--- a/tests/Feature/Services/Social/LinkedInPublisherTest.php
+++ b/tests/Feature/Services/Social/LinkedInPublisherTest.php
@@ -4,12 +4,10 @@ declare(strict_types=1);
use App\Enums\Media\Type as MediaType;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\LinkedInPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -30,18 +28,12 @@ beforeEach(function () {
'token_expires_at' => now()->addDays(60),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from LinkedIn!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::LinkedIn,
'content_type' => ContentType::LinkedInPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new LinkedInPublisher;
});
@@ -53,7 +45,7 @@ test('linkedin publisher can publish text-only post', function () {
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -76,7 +68,7 @@ test('linkedin publisher uses correct headers', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request->hasHeader('Authorization')
@@ -94,7 +86,7 @@ test('linkedin publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -110,7 +102,7 @@ test('linkedin publisher throws token expired exception on auth error after retr
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -128,7 +120,7 @@ test('linkedin publisher refreshes token when expired', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'oauth/v2/accessToken');
@@ -144,7 +136,7 @@ test('linkedin publisher throws exception when no refresh token available', func
'refresh_token' => null,
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available for LinkedIn account');
});
@@ -158,7 +150,7 @@ test('linkedin publisher throws TokenExpiredException when refresh_token is reje
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'The refresh token is invalid');
});
@@ -171,7 +163,7 @@ test('linkedin publisher handles empty content', function () {
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:1234567890');
@@ -219,7 +211,7 @@ test('linkedin publisher can publish post with image', function () {
return Http::response('fake-image-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:9876543210');
expect($result['url'])->toContain('linkedin.com/feed/update/urn:li:share:9876543210');
@@ -270,7 +262,7 @@ test('linkedin publisher sends the real alt text on a single image post', functi
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/rest/posts')) {
@@ -321,7 +313,7 @@ test('linkedin publisher omits alt text on a single image post when none is set'
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/rest/posts')) {
@@ -378,7 +370,7 @@ test('linkedin publisher truncates single image alt text to the platform max len
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/rest/posts')) {
@@ -390,7 +382,7 @@ test('linkedin publisher truncates single image alt text to the platform max len
});
test('linkedin publisher can publish carousel with multiple images', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
[
@@ -461,7 +453,7 @@ test('linkedin publisher can publish carousel with multiple images', function ()
return Http::response('fake-image-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:carousel999');
expect($result['url'])->toContain('linkedin.com/feed/update/urn:li:share:carousel999');
@@ -481,7 +473,7 @@ test('linkedin publisher can publish carousel with multiple images', function ()
});
test('linkedin publisher sends per-image alt text on a carousel, not the filename', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
[
@@ -543,7 +535,7 @@ test('linkedin publisher sends per-image alt text on a carousel, not the filenam
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The first image carries the user's real alt text (not the filename); the
// second has no alt_text set, so its `altText` key is omitted entirely.
@@ -601,7 +593,7 @@ test('linkedin publisher caps a carousel at the platform max images', function (
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Only the first 10 images (LinkedIn::maxImages) are uploaded; the extra 2 are dropped.
expect($initCallCount)->toBe(10);
@@ -669,7 +661,7 @@ test('linkedin publisher can publish post with video', function () {
return Http::response(str_repeat('x', 1024), 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:1111111111');
@@ -728,7 +720,7 @@ test('linkedin publisher never sends altText on a single video post even if the
return Http::response(str_repeat('x', 1024), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/rest/posts')) {
@@ -797,7 +789,7 @@ test('linkedin publisher uploads a video across multiple chunks', function () {
return Http::response(str_repeat('x', 4096), 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:multichunk');
expect($chunkPuts)->toBe(3);
@@ -813,7 +805,7 @@ test('linkedin publisher uploads a video across multiple chunks', function () {
});
test('linkedin publisher can publish a document (pdf carousel) with a title', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::LinkedInPost,
'meta' => ['document_title' => 'My Slides'],
]);
@@ -858,7 +850,7 @@ test('linkedin publisher can publish a document (pdf carousel) with a title', fu
return Http::response('fake-pdf-bytes', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:doc999');
expect($result['url'])->toContain('linkedin.com/feed/update/urn:li:share:doc999');
@@ -879,7 +871,7 @@ test('linkedin publisher can publish a document (pdf carousel) with a title', fu
});
test('linkedin publisher document title falls back to the file name', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
[
@@ -916,7 +908,7 @@ test('linkedin publisher document title falls back to the file name', function (
return Http::response('fake-pdf-bytes', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/rest/posts')) {
@@ -928,7 +920,7 @@ test('linkedin publisher document title falls back to the file name', function (
});
test('linkedin publisher waits for document processing before posting', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
[
@@ -965,13 +957,13 @@ test('linkedin publisher waits for document processing before posting', function
return Http::response('fake-pdf-bytes', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/documents/urn'));
});
test('linkedin publisher throws and does not post when document processing fails', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [
[
@@ -1004,14 +996,14 @@ test('linkedin publisher throws and does not post when document processing fails
return Http::response('fake-pdf-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'LinkedIn document processing failed');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
});
test('linkedin publisher throws and does not post when document processing never completes', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [[
'id' => 'doc-media-1', 'path' => 'media/2026-01/deck.pdf',
@@ -1053,14 +1045,14 @@ test('linkedin publisher throws and does not post when document processing never
}
};
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class, 'processing did not complete in time');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
});
test('linkedin publisher throws and does not post when document init fails', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [[
'id' => 'doc-media-1', 'path' => 'media/2026-01/deck.pdf',
@@ -1077,7 +1069,7 @@ test('linkedin publisher throws and does not post when document init fails', fun
return Http::response('fake-pdf-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(Exception::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(Exception::class);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
});
@@ -1099,7 +1091,7 @@ test('linkedin publisher retries a LinkedIn 5xx while uploading media before the
return Http::response('fake-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(500));
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
@@ -1159,7 +1151,7 @@ test('linkedin publisher retries a LinkedIn 5xx after the media upload starts an
return Http::response('fake-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(503));
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
@@ -1171,7 +1163,7 @@ test('linkedin publisher retries a LinkedIn 5xx after the media upload starts an
]);
test('linkedin publisher throws when document init response is missing the urn', function () {
- $this->postPlatform->update(['content_type' => ContentType::LinkedInPost]);
+ $this->post->update(['content_type' => ContentType::LinkedInPost]);
$this->post->update([
'media' => [[
'id' => 'doc-media-1', 'path' => 'media/2026-01/deck.pdf',
@@ -1188,7 +1180,7 @@ test('linkedin publisher throws when document init response is missing the urn',
return Http::response('fake-pdf-bytes', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(LinkedInPublishException::class, 'did not accept the document upload');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/posts'));
@@ -1199,7 +1191,7 @@ test('linkedin publisher treats a 401 response without an error code as a token
config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(['message' => 'Unauthorized'], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -1219,7 +1211,7 @@ test('linkedin publisher does NOT rotate the token when it is only expiring soon
config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201, ['x-restli-id' => 'urn:li:share:soon']),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:soon');
@@ -1234,7 +1226,7 @@ test('linkedin publisher falls back to an empty id and null url when the post id
config('trypost.platforms.linkedin.api').'/rest/posts' => Http::response(null, 201),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('');
expect($result['url'])->toBeNull();
@@ -1253,7 +1245,7 @@ test('linkedin publisher keeps links intact', function () {
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& $request['commentary'] === 'New post: https://trypost.it/blog'
@@ -1279,7 +1271,7 @@ test('linkedin publisher sends an article card for a text post that contains a l
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1295,7 +1287,7 @@ test('linkedin publisher sends an article card for a text post that contains a l
test('linkedin publisher sends no article when the user dropped the link preview', function () {
$this->post->update(['content' => 'Read this https://example.com/article today.']);
- $this->postPlatform->update(['meta' => ['link_preview' => false]]);
+ $this->post->update(['meta' => ['link_preview' => false]]);
$this->mock(LinkCardFetcher::class)->shouldReceive('fetch')->never();
@@ -1305,7 +1297,7 @@ test('linkedin publisher sends no article when the user dropped the link preview
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& $request['commentary'] === 'Read this https://example.com/article today.'
@@ -1331,7 +1323,7 @@ test('linkedin publisher skips the article card when the page has no title', fun
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& ! isset($request['content']));
@@ -1376,7 +1368,7 @@ test('linkedin publisher prefers attached media over a link card', function () {
return Http::response('fake-image-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/rest/posts')
&& isset($request['content']['media']['id'])
@@ -1427,7 +1419,7 @@ test('linkedin publisher uploads the article thumbnail', function () {
return Http::response($jpeg, 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1459,7 +1451,7 @@ test('linkedin publisher still publishes the article when the thumbnail cannot b
return Http::response('', 404);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1496,7 +1488,7 @@ test('linkedin publisher stops downloading an oversized article thumbnail', func
]);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/images'));
Http::assertSent(function ($request) {
@@ -1532,7 +1524,7 @@ test('linkedin publisher downloads the article thumbnail uncompressed and size-c
return Http::response(null, 201, ['x-restli-id' => 'urn:li:share:capped']);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect(data_get($thumb, 'options.decode_content'))->toBeFalse()
->and(data_get($thumb, 'options.allow_redirects'))->toBeFalse()
@@ -1554,7 +1546,7 @@ test('linkedin publisher publishes the text when the link preview lookup fails',
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('urn:li:share:lookupfailed');
@@ -1582,7 +1574,7 @@ test('linkedin publisher blocks the article thumbnail when the image points at a
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1615,7 +1607,7 @@ test('linkedin publisher does not follow a redirect on the article thumbnail', f
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1647,7 +1639,7 @@ test('linkedin publisher trims the article title and description to what the api
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
$article = $request['content']['article'] ?? null;
@@ -1679,7 +1671,7 @@ test('linkedin publisher skips the thumbnail when og:image does not point at an
return Http::response('<html><body>Not an image</body></html>', 200, ['Content-Type' => 'text/html']);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/rest/images'));
Http::assertSent(function ($request) {
@@ -1737,7 +1729,7 @@ test('linkedin publisher refreshes the token when the thumbnail upload is reject
return Http::response($jpeg, 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/oauth/v2/accessToken'));
Http::assertSent(function ($request) {
diff --git a/tests/Feature/Services/Social/MastodonPublisherTest.php b/tests/Feature/Services/Social/MastodonPublisherTest.php
index 53f463076..85926a24c 100644
--- a/tests/Feature/Services/Social/MastodonPublisherTest.php
+++ b/tests/Feature/Services/Social/MastodonPublisherTest.php
@@ -10,7 +10,6 @@ use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\MastodonPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -29,18 +28,12 @@ beforeEach(function () {
'username' => 'testuser',
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from Mastodon!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Mastodon,
'content_type' => ContentType::MastodonPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new MastodonPublisher;
});
@@ -55,7 +48,7 @@ test('mastodon publisher can publish text-only post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -85,7 +78,7 @@ test('mastodon publisher works with custom instance', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toContain('techhub.social');
@@ -129,7 +122,7 @@ test('mastodon publisher uploads media', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')
&& data_get($request->data(), 'media_ids') === ['media-123']);
@@ -190,7 +183,7 @@ test('mastodon publisher sends capped alt text as media description', function (
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedDescription = mb_substr($longAlt, 0, Platform::Mastodon->altTextMaxLength());
@@ -261,7 +254,7 @@ test('mastodon publisher sends no description part when image has no alt text',
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/api/v1/media')) {
@@ -309,7 +302,7 @@ test('mastodon publisher does not send a description for a non-image even if it
return Http::response('fake-video-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/api/v1/media')) {
@@ -328,7 +321,7 @@ test('mastodon publisher includes media ids in post', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/api/v1/statuses')
@@ -343,7 +336,7 @@ test('mastodon publisher throws exception on api error', function () {
], 422),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -354,7 +347,7 @@ test('mastodon publisher throws token expired exception on auth error', function
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -365,7 +358,7 @@ test('mastodon publisher throws permission exception on forbidden', function ()
], 403),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class);
});
@@ -404,7 +397,7 @@ test('mastodon publisher limits media to 4', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSentCount(9);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses')
@@ -421,7 +414,7 @@ test('mastodon publisher handles empty content', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('109876543210');
@@ -438,7 +431,7 @@ test('mastodon publisher uses bearer token authentication', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request->hasHeader('Authorization')
@@ -499,7 +492,7 @@ test('mastodon publisher optimizes images before upload', function () {
return Http::response($minimalJpeg, 200, ['Content-Type' => 'image/jpeg']);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
@unlink($optimizedFile);
});
@@ -528,7 +521,7 @@ test('mastodon publisher retries a media upload server error before creating the
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(500));
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));
@@ -558,7 +551,7 @@ test('mastodon publisher fails with Mastodon\'s message when it refuses the medi
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class, 'Validation failed: File content type is invalid');
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/statuses'));
@@ -578,7 +571,7 @@ test('mastodon publisher fails instead of posting without the media it could not
'https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1'], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(MastodonPublishException::class, __('posts.errors.media_unavailable', ['platform' => 'Mastodon']));
Http::assertNotSent(fn ($request): bool => str_contains($request->url(), '/api/v1/'));
@@ -594,7 +587,7 @@ test('mastodon publisher defaults to mastodon.social if no instance in meta', fu
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'mastodon.social');
@@ -611,17 +604,17 @@ test('mastodon publisher keeps links intact', function () {
'url' => 'https://mastodon.social/@testuser/109876543210',
], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/api/v1/statuses')
&& $request['status'] === 'New post: https://acme.com/blog');
});
test('mastodon content warning reaches the status payload', function () {
- $this->postPlatform->update(['meta' => ['spoiler_text' => 'Spoilers for episode 3']]);
+ $this->post->update(['meta' => ['spoiler_text' => 'Spoilers for episode 3']]);
Http::fake(['https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1', 'url' => 'https://mastodon.social/@t/1'])]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => $request->data() === [
'status' => 'Hello from Mastodon!',
@@ -631,10 +624,10 @@ test('mastodon content warning reaches the status payload', function () {
});
test('mastodon trims unicode space padding from the content warning like the composer does', function () {
- $this->postPlatform->update(['meta' => ['spoiler_text' => "\u{3000}\u{200B}Spoilers\u{00A0}"]]);
+ $this->post->update(['meta' => ['spoiler_text' => "\u{3000}\u{200B}Spoilers\u{00A0}"]]);
Http::fake(['https://mastodon.social/api/v1/statuses' => Http::response(['id' => '1', 'url' => 'https://mastodon.social/@t/1'])]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => data_get($request->data(), 'spoiler_text') === 'Spoilers');
});
@@ -642,10 +635,10 @@ test('mastodon trims unicode space padding from the content warning like the com
test('mastodon refuses a post whose content and content warning exceed the limit before any request', function () {
$limit = Platform::Mastodon->maxContentLength();
$this->post->update(['content' => str_repeat('b', $limit - 9)]);
- $this->postPlatform->update(['meta' => ['spoiler_text' => str_repeat('a', 10)]]);
+ $this->post->update(['meta' => ['spoiler_text' => str_repeat('a', 10)]]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(fn (ContentLimitException $exception) => expect($exception->category)->toBe(ErrorCategory::ContentPolicy)
->and($exception->userMessage)->toBe(__('posts.errors.content_too_long', ['platform' => 'Mastodon', 'max' => $limit, 'provided' => $limit + 1])));
@@ -653,14 +646,14 @@ test('mastodon refuses a post whose content and content warning exceed the limit
});
test('a mastodon thread chains each reply to the previous one with the root content warning', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Two', 'Three'], 'spoiler_text' => 'CW']]);
+ $this->post->update(['meta' => ['thread_replies' => ['Two', 'Three'], 'spoiler_text' => 'CW']]);
$instance = data_get($this->socialAccount->meta, 'instance');
Http::fake(["{$instance}/api/v1/statuses" => Http::sequence()
->push(['id' => '1', 'url' => "{$instance}/@t/1"])
->push(['id' => '2', 'url' => "{$instance}/@t/2"])
->push(['id' => '3', 'url' => "{$instance}/@t/3"])]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result)->toBe(['id' => '1', 'url' => "{$instance}/@t/1", 'thread_reply_ids' => ['2', '3']]);
Http::assertSent(fn ($request): bool => $request->data() === [
@@ -674,12 +667,12 @@ test('a mastodon thread chains each reply to the previous one with the root cont
'visibility' => 'public',
'in_reply_to_id' => '2',
'spoiler_text' => 'CW',
- ] && $request->header('Idempotency-Key') === ["{$this->postPlatform->id}:2:".ThreadProgress::hash('Three')]);
+ ] && $request->header('Idempotency-Key') === ["{$this->post->id}:2:".ThreadProgress::hash('Three')]);
});
test('a mastodon thread attaches each reply media to that reply only', function () {
$image = ['id' => 'reply-image', 'path' => 'media/2026-01/photo.jpg', 'url' => 'https://example.com/media/2026-01/photo.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg'];
- $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]], 'Three']]]);
+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$image]], 'Three']]]);
$instance = data_get($this->socialAccount->meta, 'instance');
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
@@ -700,20 +693,20 @@ test('a mastodon thread attaches each reply media to that reply only', function
->push(['id' => '3', 'url' => "{$instance}/@t/3"]),
]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['2', '3']);
Http::assertSent(fn ($request): bool => str_contains($request->url(), '/statuses') && data_get($request->data(), 'status') === $this->post->content && ! array_key_exists('media_ids', $request->data()));
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Two', 'visibility' => 'public', 'in_reply_to_id' => '1', 'media_ids' => ['media-1']]
- && $request->header('Idempotency-Key') === ["{$this->postPlatform->id}:1:".ThreadProgress::hash('Two', ['reply-image'])]);
+ && $request->header('Idempotency-Key') === ["{$this->post->id}:1:".ThreadProgress::hash('Two', ['reply-image'])]);
Http::assertSent(fn ($request): bool => $request->data() === ['status' => 'Three', 'visibility' => 'public', 'in_reply_to_id' => '2']);
});
test('a mastodon thread with a reply over the limit fails before posting anything', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => [str_repeat('a', 495)], 'spoiler_text' => 'Ten chars!']]);
+ $this->post->update(['meta' => ['thread_replies' => [str_repeat('a', 495)], 'spoiler_text' => 'Ten chars!']]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(ContentLimitException::class, __('posts.form.thread.reply_too_long', ['limit' => 490, 'over' => 5]));
Http::assertNothingSent();
diff --git a/tests/Feature/Services/Social/PinterestPublisherTest.php b/tests/Feature/Services/Social/PinterestPublisherTest.php
index 965297a61..352f700d2 100644
--- a/tests/Feature/Services/Social/PinterestPublisherTest.php
+++ b/tests/Feature/Services/Social/PinterestPublisherTest.php
@@ -8,7 +8,6 @@ use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\PinterestPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -32,19 +31,13 @@ beforeEach(function () {
],
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Check out this pin!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Pinterest,
'content_type' => ContentType::PinterestPin,
'meta' => ['board_id' => 'board_123'],
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new PinterestPublisher;
@@ -80,7 +73,7 @@ test('pinterest publisher can publish image pin', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -93,12 +86,12 @@ test('pinterest publisher can publish image pin', function () {
});
test('pinterest publisher throws exception when no media for pin', function () {
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest requires at least one image');
});
test('pinterest publisher throws exception when no board id', function () {
- $this->postPlatform->update(['meta' => []]);
+ $this->post->update(['meta' => []]);
$this->socialAccount->update(['meta' => []]);
$this->post->update([
@@ -113,12 +106,12 @@ test('pinterest publisher throws exception when no board id', function () {
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest board_id is required');
});
test('pinterest publisher throws exception for carousel when no board id', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::PinterestCarousel,
'meta' => [],
]);
@@ -131,12 +124,12 @@ test('pinterest publisher throws exception for carousel when no board id', funct
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest board_id is required');
});
test('pinterest publisher throws exception for video pin when no board id', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::PinterestVideoPin,
'meta' => [],
]);
@@ -148,12 +141,12 @@ test('pinterest publisher throws exception for video pin when no board id', func
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest board_id is required');
});
test('pinterest publisher uses default board id from account', function () {
- $this->postPlatform->update(['meta' => []]); // No board_id in post meta
+ $this->post->update(['meta' => []]); // No board_id in post meta
$this->post->update([
'media' => [
@@ -174,7 +167,7 @@ test('pinterest publisher uses default board id from account', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -193,7 +186,7 @@ test('pinterest publisher can publish carousel', function () {
'original_filename' => "image{$i}.jpg",
];
}
- $this->postPlatform->update(['content_type' => ContentType::PinterestCarousel]);
+ $this->post->update(['content_type' => ContentType::PinterestCarousel]);
$this->post->update([
@@ -207,7 +200,7 @@ test('pinterest publisher can publish carousel', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('carousel_pin_123');
@@ -218,7 +211,7 @@ test('pinterest publisher can publish carousel', function () {
});
test('pinterest publisher throws exception for carousel with less than 2 images', function () {
- $this->postPlatform->update(['content_type' => ContentType::PinterestCarousel]);
+ $this->post->update(['content_type' => ContentType::PinterestCarousel]);
$this->post->update([
'media' => [
@@ -232,7 +225,7 @@ test('pinterest publisher throws exception for carousel with less than 2 images'
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest carousel requires 2-5 images');
});
@@ -247,7 +240,7 @@ test('pinterest publisher throws exception for carousel with more than 5 images'
'original_filename' => "image{$i}.jpg",
];
}
- $this->postPlatform->update(['content_type' => ContentType::PinterestCarousel]);
+ $this->post->update(['content_type' => ContentType::PinterestCarousel]);
$this->post->update([
@@ -255,7 +248,7 @@ test('pinterest publisher throws exception for carousel with more than 5 images'
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Pinterest carousel requires 2-5 images');
});
@@ -280,7 +273,7 @@ test('pinterest publisher throws exception on api error', function () {
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -305,7 +298,7 @@ test('pinterest publisher throws token expired exception on auth error', functio
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -336,7 +329,7 @@ test('pinterest publisher refreshes token when expired', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'oauth/token');
@@ -368,12 +361,12 @@ test('pinterest publisher throws TokenExpiredException when refresh_token is rej
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'Refresh token expired');
});
test('pinterest publisher includes title and link when provided', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'board_id' => 'board_123',
'title' => 'My Pin Title',
@@ -401,7 +394,7 @@ test('pinterest publisher includes title and link when provided', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -425,7 +418,7 @@ test('pinterest publisher uses post content as description and ignores meta desc
],
]);
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'board_id' => 'board_123',
'description' => 'Stale meta description must be ignored',
@@ -437,7 +430,7 @@ test('pinterest publisher uses post content as description and ignores meta desc
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -464,7 +457,7 @@ test('pinterest publisher omits description when post content is blank', functio
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -475,7 +468,7 @@ test('pinterest publisher omits description when post content is blank', functio
test('pinterest publisher truncates title to 100 characters', function () {
$longTitle = str_repeat('T', 150);
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'board_id' => 'board_123',
'title' => $longTitle,
@@ -500,7 +493,7 @@ test('pinterest publisher truncates title to 100 characters', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -510,7 +503,7 @@ test('pinterest publisher truncates title to 100 characters', function () {
});
test('pinterest publisher omits blank title and link', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'board_id' => 'board_123',
'title' => '',
@@ -536,7 +529,7 @@ test('pinterest publisher omits blank title and link', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
$data = $request->data();
@@ -571,7 +564,7 @@ test('pinterest publisher sends alt text from image meta capped to platform max'
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($longAlt, 0, Platform::Pinterest->altTextMaxLength());
@@ -602,7 +595,7 @@ test('pinterest publisher omits alt_text when image has no alt text set', functi
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -611,7 +604,7 @@ test('pinterest publisher omits alt_text when image has no alt text set', functi
});
test('pinterest publisher ignores postPlatform meta alt_text and only reads image alt', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'board_id' => 'board_123',
'alt_text' => 'legacy per-platform alt text that should be ignored',
@@ -637,7 +630,7 @@ test('pinterest publisher ignores postPlatform meta alt_text and only reads imag
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -721,7 +714,7 @@ test('pinterest publisher stops board pagination on a repeated bookmark', functi
});
test('pinterest publisher can publish video pin', function () {
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
@@ -773,7 +766,7 @@ test('pinterest publisher can publish video pin', function () {
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -786,7 +779,7 @@ test('pinterest publisher can publish video pin', function () {
});
test('pinterest publisher includes title description and link on video pins', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::PinterestVideoPin,
'meta' => [
'board_id' => 'board_123',
@@ -836,7 +829,7 @@ test('pinterest publisher includes title description and link on video pins', fu
return Http::response('fake-video-content', 200);
});
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => $request->url() === config('trypost.platforms.pinterest.api').'/pins'
&& data_get($request->data(), 'title') === 'Video Title'
@@ -857,7 +850,7 @@ test('pinterest publisher includes title description and link on carousels', fun
];
}
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::PinterestCarousel,
'meta' => [
'board_id' => 'board_123',
@@ -875,7 +868,7 @@ test('pinterest publisher includes title description and link on carousels', fun
'*/v5/pins' => Http::response(['id' => 'carousel_pin_123'], 200),
]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(function ($request) {
return str_contains($request->url(), '/v5/pins')
@@ -887,7 +880,7 @@ test('pinterest publisher includes title description and link on carousels', fun
});
test('pinterest video pin sends the chosen cover frame rounded to whole seconds and ignores a stored cover image url', function (?int $coverOffsetMs, int $keyFrameTime) {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::PinterestVideoPin,
'meta' => ['board_id' => 'board_123', 'cover_image_url' => 'https://example.com/cover.jpg'],
]);
@@ -931,7 +924,7 @@ test('pinterest video pin sends the chosen cover frame rounded to whole seconds
return Http::response('fake-video-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => $request->url() === config('trypost.platforms.pinterest.api').'/pins'
&& data_get($request->data(), 'media_source.cover_image_url') === null
@@ -943,7 +936,7 @@ test('pinterest video pin sends the chosen cover frame rounded to whole seconds
]);
test('pinterest publisher throws exception for unsupported content type', function () {
- $this->postPlatform->update(['content_type' => ContentType::InstagramFeed]);
+ $this->post->update(['content_type' => ContentType::InstagramFeed]);
$this->post->update([
'media' => [
@@ -957,14 +950,14 @@ test('pinterest publisher throws exception for unsupported content type', functi
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Unsupported content type');
});
test('pinterest publisher waits through pending video processing before creating the pin', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1009,7 +1002,7 @@ test('pinterest publisher waits through pending video processing before creating
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('video_pin_after_wait')
->and($statusChecks)->toBe(3);
@@ -1020,7 +1013,7 @@ test('pinterest publisher waits through pending video processing before creating
test('pinterest publisher treats video processing timeout as platform unavailable for retry', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1056,7 +1049,7 @@ test('pinterest publisher treats video processing timeout as platform unavailabl
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
@@ -1066,7 +1059,7 @@ test('pinterest publisher treats video processing timeout as platform unavailabl
test('pinterest publisher fails hard when video processing reports failed', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1105,7 +1098,7 @@ test('pinterest publisher fails hard when video processing reports failed', func
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PinterestPublishException::class, 'Pinterest media processing failed: VIDEO_TOO_LONG');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
@@ -1115,7 +1108,7 @@ test('pinterest publisher fails hard when video processing reports failed', func
test('pinterest publisher treats media status 401 as token expired', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1151,7 +1144,7 @@ test('pinterest publisher treats media status 401 as token expired', function ()
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'Access token has expired or been revoked');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
@@ -1161,7 +1154,7 @@ test('pinterest publisher treats media status 401 as token expired', function ()
test('pinterest publisher keeps polling through transient media status http errors', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1208,7 +1201,7 @@ test('pinterest publisher keeps polling through transient media status http erro
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('video_pin_after_5xx')
->and($statusChecks)->toBe(3);
@@ -1219,7 +1212,7 @@ test('pinterest publisher keeps polling through transient media status http erro
test('pinterest publisher treats unknown media status as still processing until timeout', function (string $status) {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1255,7 +1248,7 @@ test('pinterest publisher treats unknown media status as still processing until
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class, 'Pinterest media processing timeout after 60 attempts');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
@@ -1269,7 +1262,7 @@ test('pinterest publisher treats unknown media status as still processing until
test('pinterest publisher treats media status connection errors as platform unavailable', function () {
Sleep::fake();
- $this->postPlatform->update(['content_type' => ContentType::PinterestVideoPin]);
+ $this->post->update(['content_type' => ContentType::PinterestVideoPin]);
$this->post->update([
'media' => [[
@@ -1305,7 +1298,7 @@ test('pinterest publisher treats media status connection errors as platform unav
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class, 'Pinterest media status check connection failed');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/v5/pins'));
@@ -1331,7 +1324,7 @@ test('pinterest publisher keeps links intact', function () {
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/v5/pins')
&& $request['description'] === 'New post: https://acme.com/blog');
diff --git a/tests/Feature/Services/Social/PublishesThreadsTest.php b/tests/Feature/Services/Social/PublishesThreadsTest.php
index c3e48db20..e2baf34b3 100644
--- a/tests/Feature/Services/Social/PublishesThreadsTest.php
+++ b/tests/Feature/Services/Social/PublishesThreadsTest.php
@@ -6,7 +6,7 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\MastodonPublishException;
-use App\Models\PostPlatform;
+use App\Models\Post;
use App\Services\Social\Concerns\PublishesThreads;
use App\Support\Social\ThreadProgress;
use Illuminate\Support\Collection;
@@ -17,17 +17,15 @@ function threadPublisher(): object
{
use PublishesThreads;
- public function run(PostPlatform $postPlatform, callable $postRoot, callable $postReply, ?callable $afterThread = null): array
+ public function run(Post $post, callable $postRoot, callable $postReply, ?callable $afterThread = null): array
{
- return $this->publishThread($postPlatform, ThreadProgress::hash('root'), $postRoot, $postReply, $afterThread);
+ return $this->publishThread($post, ThreadProgress::hash('root'), $postRoot, $postReply, $afterThread);
}
};
}
beforeEach(function () {
- $this->postPlatform = PostPlatform::factory()->create([
- 'platform' => Platform::Mastodon,
- 'content_type' => ContentType::MastodonPost,
+ $this->post = Post::factory()->mastodon()->create([
'meta' => ['thread_replies' => ['two', 'three']],
]);
});
@@ -36,7 +34,7 @@ test('a thread posts root then replies in order, each replying to the previous',
$calls = [];
$result = threadPublisher()->run(
- $this->postPlatform,
+ $this->post,
function () use (&$calls): array {
$calls[] = 'root';
@@ -70,16 +68,16 @@ test('a failed reply keeps the progress and the retry resumes after it', functio
};
try {
- threadPublisher()->run($this->postPlatform, fn (): array => ['id' => 'r'], $reply);
+ threadPublisher()->run($this->post, fn (): array => ['id' => 'r'], $reply);
$this->fail('The thread should not finish.');
} catch (MastodonPublishException $e) {
expect($e)->toBe($failure);
}
- expect(collect($this->postPlatform->fresh()->error_context[ThreadProgress::KEY])->pluck('id')->all())->toBe(['r', 'id-two']);
+ expect(collect($this->post->fresh()->error_context[ThreadProgress::KEY])->pluck('id')->all())->toBe(['r', 'id-two']);
$roots = 0;
- $result = threadPublisher()->run($this->postPlatform->fresh(), function () use (&$roots): array {
+ $result = threadPublisher()->run($this->post->fresh(), function () use (&$roots): array {
$roots++;
return ['id' => 'duplicate'];
@@ -92,13 +90,13 @@ test('a failed reply keeps the progress and the retry resumes after it', functio
});
test('a changed reply is posted again from the first change', function () {
- ThreadProgress::remember($this->postPlatform, [
+ ThreadProgress::remember($this->post, [
['hash' => ThreadProgress::hash('root'), 'id' => 'r'],
['hash' => ThreadProgress::hash('old two'), 'id' => 'old'],
]);
$replies = [];
- $result = threadPublisher()->run($this->postPlatform->fresh(), fn (): array => ['id' => 'duplicate'], function (string $text, Collection $media, array $parent) use (&$replies): array {
+ $result = threadPublisher()->run($this->post->fresh(), fn (): array => ['id' => 'duplicate'], function (string $text, Collection $media, array $parent) use (&$replies): array {
$replies[] = "{$text}>{$parent['id']}";
return ['id' => "id-{$text}"];
@@ -109,13 +107,13 @@ test('a changed reply is posted again from the first change', function () {
});
test('a stored root is trusted on resume even when its text no longer hashes the same', function () {
- ThreadProgress::remember($this->postPlatform, [
+ ThreadProgress::remember($this->post, [
['hash' => ThreadProgress::hash('root before a sanitizer change'), 'id' => 'r', 'url' => 'https://mastodon.social/@a/r'],
['hash' => ThreadProgress::hash('two'), 'id' => 'id-two'],
]);
$calls = [];
- $result = threadPublisher()->run($this->postPlatform->fresh(), function () use (&$calls): array {
+ $result = threadPublisher()->run($this->post->fresh(), function () use (&$calls): array {
$calls[] = 'root';
return ['id' => 'duplicate'];
@@ -130,32 +128,32 @@ test('a stored root is trusted on resume even when its text no longer hashes the
});
test('a post without replies writes no checkpoint', function () {
- $this->postPlatform->update(['meta' => []]);
+ $this->post->update(['meta' => []]);
- $result = threadPublisher()->run($this->postPlatform, fn (): array => ['id' => 'r', 'url' => null], fn (): array => ['id' => 'never']);
+ $result = threadPublisher()->run($this->post, fn (): array => ['id' => 'r', 'url' => null], fn (): array => ['id' => 'never']);
expect($result)->toBe(['id' => 'r', 'url' => null])
- ->and($this->postPlatform->fresh()->error_context)->toBeNull();
+ ->and($this->post->fresh()->error_context)->toBeNull();
});
test('replies on a network without threads are never posted', function () {
- $this->postPlatform->update(['platform' => Platform::Threads, 'content_type' => ContentType::ThreadsPost]);
+ $this->post->update(['platform' => Platform::Threads, 'content_type' => ContentType::ThreadsPost]);
- $result = threadPublisher()->run($this->postPlatform->fresh(), fn (): array => ['id' => 'r'], fn (): array => ['id' => 'never']);
+ $result = threadPublisher()->run($this->post->fresh(), fn (): array => ['id' => 'r'], fn (): array => ['id' => 'never']);
expect($result)->toBe(['id' => 'r', 'url' => null]);
});
test('each reply gets only its own media, and a changed reply media is posted again', function () {
$image = ['id' => 'media-1', 'path' => 'medias/one.jpg', 'url' => 'https://cdn.test/one.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'];
- $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => 'two', 'media' => [$image]], ['text' => 'three', 'media' => []]]]]);
- ThreadProgress::remember($this->postPlatform, [
+ $this->post->update(['meta' => ['thread_replies' => [['text' => 'two', 'media' => [$image]], ['text' => 'three', 'media' => []]]]]);
+ ThreadProgress::remember($this->post, [
['hash' => ThreadProgress::hash('root'), 'id' => 'r'],
['hash' => ThreadProgress::hash('two'), 'id' => 'old'],
]);
$calls = [];
- threadPublisher()->run($this->postPlatform->fresh(), fn (): array => ['id' => 'duplicate'], function (string $text, Collection $media, array $parent) use (&$calls): array {
+ threadPublisher()->run($this->post->fresh(), fn (): array => ['id' => 'duplicate'], function (string $text, Collection $media, array $parent) use (&$calls): array {
$calls[] = [$text, $media->pluck('id')->all(), $parent['id']];
return ['id' => "id-{$text}"];
diff --git a/tests/Feature/Services/Social/TelegramPublisherTest.php b/tests/Feature/Services/Social/TelegramPublisherTest.php
index e03f61f94..7f2a02306 100644
--- a/tests/Feature/Services/Social/TelegramPublisherTest.php
+++ b/tests/Feature/Services/Social/TelegramPublisherTest.php
@@ -3,10 +3,8 @@
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\TelegramPublishException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -23,18 +21,12 @@ beforeEach(function () {
'workspace_id' => $this->workspace->id,
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello world',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Telegram,
'content_type' => ContentType::TelegramPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new TelegramPublisher;
});
@@ -49,7 +41,7 @@ test('telegram publisher sends a text-only message', function () {
'*/botTESTTOKEN/sendMessage' => Http::response(telegramOk(['message_id' => 42]), 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('42');
expect($result['url'])->toBe('https://t.me/mychannel/42');
@@ -78,7 +70,7 @@ test('telegram publisher sends a single image with caption', function () {
'*/botTESTTOKEN/sendPhoto' => Http::response(telegramOk(['message_id' => 7]), 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/sendPhoto')
@@ -104,7 +96,7 @@ test('telegram publisher sends a single video', function () {
'*/botTESTTOKEN/sendVideo' => Http::response(telegramOk(['message_id' => 8]), 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/sendVideo')
@@ -129,7 +121,7 @@ test('telegram publisher sends a non-image, non-video file as a document', funct
'*/botTESTTOKEN/sendDocument' => Http::response(telegramOk(['message_id' => 9]), 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/sendDocument')
@@ -150,7 +142,7 @@ test('telegram publisher sends multiple media as an album', function () {
'*/botTESTTOKEN/sendMediaGroup' => Http::response(telegramOk([['message_id' => 11], ['message_id' => 12]]), 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('11');
@@ -182,7 +174,7 @@ test('telegram publisher sends long text as its own message after media', functi
'*/botTESTTOKEN/sendMessage' => Http::response(telegramOk(['message_id' => 6]), 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Photo carries no caption (too long); the text follows as a separate message.
Http::assertSent(fn ($request) => str_contains($request->url(), '/sendPhoto') && $request['caption'] === '');
@@ -194,7 +186,7 @@ test('telegram publisher rejects content over the 4096 limit', function () {
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(Exception::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(Exception::class);
Http::assertNothingSent();
});
@@ -204,7 +196,7 @@ test('telegram publisher throws on a non-ok response', function () {
'*/botTESTTOKEN/sendMessage' => Http::response(['ok' => false, 'error_code' => 403, 'description' => 'Forbidden: bot is not a member of the channel chat'], 403),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(TelegramPublishException::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(TelegramPublishException::class);
});
test('telegram publisher builds a private-channel url when there is no username', function () {
@@ -214,7 +206,7 @@ test('telegram publisher builds a private-channel url when there is no username'
'*/botTESTTOKEN/sendMessage' => Http::response(telegramOk(['message_id' => 99]), 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBe('https://t.me/c/9876543210/99');
});
@@ -226,7 +218,7 @@ test('telegram publisher keeps links intact', function () {
Http::fake(['*/botTESTTOKEN/sendMessage' => Http::response(telegramOk(['message_id' => 42]), 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/sendMessage')
&& $request['text'] === 'New post: https://acme.com/blog');
diff --git a/tests/Feature/Services/Social/ThreadsPublisherTest.php b/tests/Feature/Services/Social/ThreadsPublisherTest.php
index ba79eb94f..2a283d847 100644
--- a/tests/Feature/Services/Social/ThreadsPublisherTest.php
+++ b/tests/Feature/Services/Social/ThreadsPublisherTest.php
@@ -8,7 +8,6 @@ use App\Exceptions\Social\ThreadsMediaContainerNotFoundException;
use App\Exceptions\Social\ThreadsPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -31,18 +30,12 @@ beforeEach(function () {
'token_expires_at' => now()->addDays(60),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from Threads!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::Threads,
'content_type' => ContentType::ThreadsPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new ThreadsPublisher;
});
@@ -63,7 +56,7 @@ test('threads publisher can publish text-only post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -90,7 +83,7 @@ test('threads publisher keeps the published id when the permalink lookup fails',
},
]);
- expect($this->publisher->publish($this->postPlatform))->toBe([
+ expect($this->publisher->publish($this->post))->toBe([
'id' => 'post-123',
'url' => null,
]);
@@ -127,7 +120,7 @@ test('threads publisher can publish image post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-123456789');
@@ -184,7 +177,7 @@ test('threads publisher recreates a missing image container before retrying publ
], 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-after-retry')
->and($containerCreations)->toBe(2)
@@ -224,7 +217,7 @@ test('threads publisher does not retry a missing media response from container c
], 400);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(ThreadsPublishException::class);
expect($containerCreations)->toBe(1);
@@ -271,7 +264,7 @@ test('threads publisher stops after three missing media containers', function ()
});
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$this->fail('Expected ThreadsPublishException was not thrown.');
} catch (ThreadsPublishException $exception) {
expect($exception)->toBeInstanceOf(ThreadsMediaContainerNotFoundException::class);
@@ -320,7 +313,7 @@ test('threads publisher does not retry unrelated client errors', function () {
return Http::response([], 500);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(ThreadsPublishException::class, 'Invalid parameter');
expect($containerCreations)->toBe(1)
@@ -355,7 +348,7 @@ test('threads publisher can publish video post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-123456789');
@@ -393,7 +386,7 @@ test('threads publisher can publish carousel', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-123456789');
@@ -457,7 +450,7 @@ test('threads publisher waits for the final carousel container before publishing
return Http::response(['permalink' => 'https://www.threads.net/carousel'], 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect($requestOrder)
->toContain('status:carousel-final')
@@ -531,7 +524,7 @@ test('threads publisher recreates the complete carousel after a missing final co
return Http::response(['permalink' => 'https://www.threads.net/carousel'], 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('carousel-post')
->and($childCreations)->toBe(4)
@@ -550,7 +543,7 @@ test('threads publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -565,7 +558,7 @@ test('threads publisher throws token expired exception on auth error', function
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -591,7 +584,7 @@ test('threads publisher refreshes token when expired', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'refresh_access_token');
@@ -610,7 +603,7 @@ test('threads publisher throws TokenExpiredException when refresh_token is rejec
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'Token is invalid');
});
@@ -643,7 +636,7 @@ test('threads publisher waits for media processing', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('post-123456789');
});
@@ -671,14 +664,14 @@ test('threads publisher handles media processing error', function () {
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Threads media processing failed');
});
test('threads publisher throws exception for text post with null content', function () {
$this->post->update(['content' => null]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Threads text posts require content');
});
@@ -711,7 +704,7 @@ test('threads publisher can publish image with null content', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('media-123');
});
@@ -740,7 +733,7 @@ test('threads publisher throws exception when all carousel items fail', function
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'Failed to create any carousel items');
});
@@ -775,7 +768,7 @@ test('threads publisher sends capped alt text on single image container', functi
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($longAlt, 0, Platform::Threads->altTextMaxLength());
@@ -814,7 +807,7 @@ test('threads publisher omits alt_text from single image container when no alt t
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_ends_with($request->url(), '/123456789/threads')
@@ -861,7 +854,7 @@ test('threads publisher sends alt text on image carousel children but never on v
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
$expectedAlt = mb_substr($imageAlt, 0, Platform::Threads->altTextMaxLength());
@@ -911,7 +904,7 @@ test('threads publisher can publish video with null content', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('video-123');
});
@@ -930,7 +923,7 @@ test('threads publisher keeps links intact', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/123456789/threads')
&& ! str_contains($request->url(), 'threads_publish')
@@ -950,13 +943,13 @@ function fakeThreadsContainerFlow(): void
}
test('a ghost post is a text container flagged as ghost and nothing else', function () {
- $this->postPlatform->update([
+ $this->post->update([
'content_type' => ContentType::ThreadsGhostPost,
'meta' => ['topic_tag' => 'laravel'],
]);
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/123456789/threads')
&& data_get($request->data(), 'media_type') === 'TEXT'
@@ -965,28 +958,28 @@ test('a ghost post is a text container flagged as ghost and nothing else', funct
});
test('a ghost post with media fails before calling threads', function () {
- $this->postPlatform->update(['content_type' => ContentType::ThreadsGhostPost]);
+ $this->post->update(['content_type' => ContentType::ThreadsGhostPost]);
$this->post->update(['media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']]]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(ThreadsPublishException::class);
+ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(ThreadsPublishException::class);
Http::assertNothingSent();
});
test('a ghost post without text fails before calling threads', function () {
- $this->postPlatform->update(['content_type' => ContentType::ThreadsGhostPost]);
+ $this->post->update(['content_type' => ContentType::ThreadsGhostPost]);
$this->post->update(['content' => null]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow(ThreadsPublishException::class);
+ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow(ThreadsPublishException::class);
Http::assertNothingSent();
});
test('the threads topic tag reaches the text container without its hash', function () {
- $this->postPlatform->update(['meta' => ['topic_tag' => '#laravel']]);
+ $this->post->update(['meta' => ['topic_tag' => '#laravel']]);
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/123456789/threads')
&& data_get($request->data(), 'topic_tag') === 'laravel'
@@ -995,10 +988,10 @@ test('the threads topic tag reaches the text container without its hash', functi
test('the threads topic tag reaches an image container', function () {
$this->post->update(['media' => [['id' => 'm', 'type' => 'image', 'path' => 'm.jpg', 'url' => 'https://example.com/m.jpg', 'mime_type' => 'image/jpeg']]]);
- $this->postPlatform->update(['meta' => ['topic_tag' => 'laravel']]);
+ $this->post->update(['meta' => ['topic_tag' => 'laravel']]);
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => data_get($request->data(), 'media_type') === 'IMAGE'
&& data_get($request->data(), 'topic_tag') === 'laravel');
@@ -1009,10 +1002,10 @@ test('the threads topic tag reaches the carousel container and never its childre
['id' => 'a', 'type' => 'image', 'path' => 'a.jpg', 'url' => 'https://example.com/a.jpg', 'mime_type' => 'image/jpeg'],
['id' => 'b', 'type' => 'image', 'path' => 'b.jpg', 'url' => 'https://example.com/b.jpg', 'mime_type' => 'image/jpeg'],
]]);
- $this->postPlatform->update(['meta' => ['topic_tag' => 'laravel']]);
+ $this->post->update(['meta' => ['topic_tag' => 'laravel']]);
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => data_get($request->data(), 'media_type') === 'CAROUSEL'
&& data_get($request->data(), 'topic_tag') === 'laravel');
@@ -1023,18 +1016,18 @@ test('the threads topic tag reaches the carousel container and never its childre
test('a threads post without a topic sends only text', function () {
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/123456789/threads')
&& array_keys($request->data()) === ['media_type', 'text', 'access_token']);
});
test('a ghost post with a link is published as a ghost text container', function () {
- $this->postPlatform->update(['content_type' => ContentType::ThreadsGhostPost]);
+ $this->post->update(['content_type' => ContentType::ThreadsGhostPost]);
$this->post->update(['content' => 'Read https://example.com/article']);
fakeThreadsContainerFlow();
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request): bool => str_ends_with($request->url(), '/123456789/threads')
&& data_get($request->data(), 'media_type') === 'TEXT'
@@ -1043,7 +1036,7 @@ test('a ghost post with a link is published as a ghost text container', function
});
test('a text post waits for its container before publishing and recreates it when threads cannot find it', function () {
- $this->postPlatform->update(['content_type' => ContentType::ThreadsGhostPost]);
+ $this->post->update(['content_type' => ContentType::ThreadsGhostPost]);
$base = config('trypost.platforms.threads.graph_api');
$containerCreations = 0;
$publicationAttempts = 0;
@@ -1077,7 +1070,7 @@ test('a text post waits for its container before publishing and recreates it whe
return Http::response(['permalink' => 'https://www.threads.net/@testuser/post/A']);
});
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('post-1')
->and($containerCreations)->toBe(2)
diff --git a/tests/Feature/Services/Social/TikTokAnalyticsTest.php b/tests/Feature/Services/Social/TikTokAnalyticsTest.php
index b93765319..0f312c2da 100644
--- a/tests/Feature/Services/Social/TikTokAnalyticsTest.php
+++ b/tests/Feature/Services/Social/TikTokAnalyticsTest.php
@@ -3,13 +3,11 @@
declare(strict_types=1);
use App\Actions\Analytics\ReadPublicationAnalytics;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
-use App\Enums\SocialAccount\Platform;
+use App\Enums\Post\PublishStatus;
use App\Enums\TikTok\PrivacyLevel;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -20,15 +18,14 @@ use Illuminate\Support\Facades\Http;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
$this->account = SocialAccount::factory()->tiktok()->create([
'workspace_id' => $this->workspace->id,
'username' => 'tiktoker',
'token_expires_at' => now()->addDays(1),
]);
+ $this->post = Post::factory()->forAccount($this->account)->create([
+ 'user_id' => $this->user->id,
+ ]);
$this->api = config('trypost.platforms.tiktok.api');
});
@@ -51,16 +48,13 @@ function tiktokVideoQueryResponse(string $videoId, array $counts = []): array
];
}
-function tiktokPostPlatform(?string $platformPostId = '7685359243088103444'): PostPlatform
+function tiktokPost(?string $platformPostId = '7685359243088103444'): Post
{
- return PostPlatform::factory()->tiktok()->create([
- 'post_id' => test()->post->id,
- 'social_account_id' => test()->account->id,
- 'platform' => Platform::TikTok,
+ return tap(test()->post->forceFill([
'platform_post_id' => $platformPostId,
'platform_url' => 'https://www.tiktok.com/@tiktoker',
'meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value],
- ]);
+ ]))->save();
}
test('tiktok analytics reads post metrics from video query', function () {
@@ -75,7 +69,7 @@ test('tiktok analytics reads post metrics from video query', function () {
])),
]);
- $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPostPlatform($videoId));
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPost($videoId));
expect($metrics)->toBe([
['label' => __('analytics.metrics.views'), 'value' => 1200],
@@ -92,7 +86,7 @@ test('tiktok analytics reads post metrics from video query', function () {
test('tiktok analytics resolves a publish id then persists the public video id', function () {
$publishId = 'v_pub_url~v2-1.7685359243088103444';
$videoId = '7685359243088103444';
- $postPlatform = tiktokPostPlatform($publishId);
+ $post = tiktokPost($publishId);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response([
@@ -110,7 +104,7 @@ test('tiktok analytics resolves a publish id then persists the public video id',
])),
]);
- $metrics = (new TikTokAnalytics)->fetchPostMetrics($postPlatform);
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics($post);
expect($metrics)->toBe([
['label' => __('analytics.metrics.views'), 'value' => 90],
@@ -119,10 +113,10 @@ test('tiktok analytics resolves a publish id then persists the public video id',
['label' => __('analytics.metrics.shares'), 'value' => 0],
]);
- $postPlatform->refresh();
+ $post->refresh();
- expect($postPlatform->platform_post_id)->toBe($videoId)
- ->and($postPlatform->platform_url)->toBe('https://www.tiktok.com/@tiktoker/video/7685359243088103444');
+ expect($post->platform_post_id)->toBe($videoId)
+ ->and($post->platform_url)->toBe('https://www.tiktok.com/@tiktoker/video/7685359243088103444');
Http::assertSent(fn ($request) => str_contains($request->url(), '/post/publish/status/fetch/')
&& $request['publish_id'] === $publishId);
@@ -148,7 +142,7 @@ test('tiktok analytics reports missing_post_id when neither status nor the video
]);
$metrics = (new TikTokAnalytics)->fetchPostMetrics(
- tiktokPostPlatform('v_pub_url~v2-1.still-in-review')
+ tiktokPost('v_pub_url~v2-1.still-in-review')
);
expect($metrics)->toBe(['unsupported' => true, 'reason' => 'missing_post_id']);
@@ -174,11 +168,11 @@ test('tiktok analytics never matches an untitled video from the list', function
]),
]);
- $postPlatform = tiktokPostPlatform('v_pub_url~v2-1.untitled');
+ $post = tiktokPost('v_pub_url~v2-1.untitled');
- expect((new TikTokAnalytics)->fetchPostMetrics($postPlatform))
+ expect((new TikTokAnalytics)->fetchPostMetrics($post))
->toBe(['unsupported' => true, 'reason' => 'missing_post_id'])
- ->and($postPlatform->fresh()->platform_post_id)->toBe('v_pub_url~v2-1.untitled');
+ ->and($post->fresh()->platform_post_id)->toBe('v_pub_url~v2-1.untitled');
});
test('tiktok analytics does not scan the video list for a self only post', function () {
@@ -191,10 +185,10 @@ test('tiktok analytics does not scan the video list for a self only post', funct
]),
]);
- $postPlatform = tiktokPostPlatform('v_pub_url~v2-1.private');
- $postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $post = tiktokPost('v_pub_url~v2-1.private');
+ $post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
- expect((new TikTokAnalytics)->fetchPostMetrics($postPlatform))
+ expect((new TikTokAnalytics)->fetchPostMetrics($post))
->toBe(['unsupported' => true, 'reason' => 'missing_post_id']);
Http::assertSentCount(1);
@@ -207,7 +201,7 @@ test('tiktok analytics matches a publish id to the public video by caption', fun
]);
$videoId = '7682891910226234644';
- $postPlatform = tiktokPostPlatform('v_pub_url~v2-1.7682889326782842900');
+ $post = tiktokPost('v_pub_url~v2-1.7682889326782842900');
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response([
@@ -236,7 +230,7 @@ test('tiktok analytics matches a publish id to the public video by caption', fun
])),
]);
- $metrics = (new TikTokAnalytics)->fetchPostMetrics($postPlatform);
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics($post);
expect($metrics)->toBe([
['label' => __('analytics.metrics.views'), 'value' => 661],
@@ -245,10 +239,10 @@ test('tiktok analytics matches a publish id to the public video by caption', fun
['label' => __('analytics.metrics.shares'), 'value' => 1],
]);
- $postPlatform->refresh();
+ $post->refresh();
- expect($postPlatform->platform_post_id)->toBe($videoId)
- ->and($postPlatform->platform_url)->toBe("https://www.tiktok.com/@tiktoker/video/{$videoId}");
+ expect($post->platform_post_id)->toBe($videoId)
+ ->and($post->platform_url)->toBe("https://www.tiktok.com/@tiktoker/video/{$videoId}");
});
test('tiktok analytics stops scanning at videos older than the publish instead of claiming a same-caption repost', function () {
@@ -273,12 +267,12 @@ test('tiktok analytics stops scanning at videos older than the publish instead o
]),
]);
- $postPlatform = tiktokPostPlatform('v_pub_url~v2-1.repost');
- $postPlatform->update(['published_at' => now()]);
+ $post = tiktokPost('v_pub_url~v2-1.repost');
+ $post->update(['published_at' => now()]);
- expect((new TikTokAnalytics)->fetchPostMetrics($postPlatform))
+ expect((new TikTokAnalytics)->fetchPostMetrics($post))
->toBe(['unsupported' => true, 'reason' => 'missing_post_id'])
- ->and($postPlatform->fresh()->platform_post_id)->toBe('v_pub_url~v2-1.repost');
+ ->and($post->fresh()->platform_post_id)->toBe('v_pub_url~v2-1.repost');
Http::assertSentCount(2);
});
@@ -287,8 +281,8 @@ test('tiktok video matching keeps the one-day cutoff inclusive without changing
$this->post->update(['content' => 'Boundary caption']);
$publishedAt = CarbonImmutable::parse('2026-09-23 12:00:00', 'UTC');
$videoId = '7000000000000000003';
- $postPlatform = tiktokPostPlatform('v_pub_url~v2-1.boundary');
- $postPlatform->update(['published_at' => $publishedAt]);
+ $post = tiktokPost('v_pub_url~v2-1.boundary');
+ $post->update(['published_at' => $publishedAt]);
Http::fake([
$this->api.'/video/list/*' => Http::response([
@@ -304,8 +298,8 @@ test('tiktok video matching keeps the one-day cutoff inclusive without changing
]),
]);
- expect((new TikTokAnalytics)->findVideoIdByCaption($postPlatform))->toBe($expectedVideoId)
- ->and($postPlatform->published_at->toDateTimeString())->toBe('2026-09-23 12:00:00');
+ expect((new TikTokAnalytics)->findVideoIdByCaption($post))->toBe($expectedVideoId)
+ ->and($post->published_at->toDateTimeString())->toBe('2026-09-23 12:00:00');
})->with([
'at cutoff' => [0, '7000000000000000003'],
'before cutoff' => [1, null],
@@ -313,12 +307,12 @@ test('tiktok video matching keeps the one-day cutoff inclusive without changing
test('tiktok post metrics facade returns the saved video url and metrics without provider reads', function () {
$videoId = '7685359243088103444';
- $postPlatform = tiktokPostPlatform($videoId);
- $postPlatform->update([
- 'status' => PostPlatformStatus::Published,
+ $post = tiktokPost($videoId);
+ $post->forceFill([
+ 'publish_status' => PublishStatus::Published,
'platform_url' => "https://www.tiktok.com/@tiktoker/video/{$videoId}",
- ]);
- $publication = AnalyticsPublication::query()->where('post_platform_id', $postPlatform->id)->firstOrFail();
+ ])->save();
+ $publication = AnalyticsPublication::query()->where('post_id', $post->id)->firstOrFail();
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
'views_count' => 5,
@@ -327,12 +321,12 @@ test('tiktok post metrics facade returns the saved video url and metrics without
Http::fake();
- $platforms = app(ReadPublicationAnalytics::class)->forPost($this->post->fresh());
+ $analytics = app(ReadPublicationAnalytics::class)->forPost($this->post->fresh());
- expect($platforms->first())->toMatchArray([
+ expect($analytics)->toMatchArray([
'platform_post_id' => $videoId,
'platform_url' => "https://www.tiktok.com/@tiktoker/video/{$videoId}",
- ])->and($platforms->first()['metrics']['metrics']['views']['value'])->toBe(5);
+ ])->and($analytics['metrics']['metrics']['views']['value'])->toBe(5);
Http::assertNothingSent();
});
@@ -340,7 +334,7 @@ test('tiktok post metrics facade returns the saved video url and metrics without
test('tiktok analytics reports a missing platform post id as unsupported', function () {
Http::fake();
- $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPostPlatform(null));
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPost(null));
expect($metrics)->toBe(['unsupported' => true, 'reason' => 'missing_post_id']);
@@ -354,7 +348,7 @@ test('tiktok analytics reports a query rejection as unsupported', function () {
], 401),
]);
- $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPostPlatform());
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPost());
expect($metrics)->toBe(['unsupported' => true, 'reason' => 'api_error']);
});
@@ -367,7 +361,7 @@ test('tiktok analytics reports an empty video query as unsupported', function ()
]),
]);
- $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPostPlatform());
+ $metrics = (new TikTokAnalytics)->fetchPostMetrics(tiktokPost());
expect($metrics)->toBe(['unsupported' => true, 'reason' => 'api_error']);
});
diff --git a/tests/Feature/Services/Social/TikTokPublisherTest.php b/tests/Feature/Services/Social/TikTokPublisherTest.php
index f1b5d1f05..89532be70 100644
--- a/tests/Feature/Services/Social/TikTokPublisherTest.php
+++ b/tests/Feature/Services/Social/TikTokPublisherTest.php
@@ -9,7 +9,6 @@ use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\TikTokPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -29,18 +28,12 @@ beforeEach(function () {
'token_expires_at' => now()->addDays(1),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->tiktok()->create([
'user_id' => $this->user->id,
'content' => 'Check out this TikTok video!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::TikTok,
'content_type' => ContentType::TikTokVideo,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new TikTokPublisher;
@@ -48,7 +41,7 @@ beforeEach(function () {
});
test('tiktok publisher throws exception when no media', function () {
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'TikTok requires media (video or photos) to publish.');
});
@@ -77,7 +70,7 @@ test('tiktok publisher can publish video', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -90,7 +83,7 @@ test('tiktok publisher can publish video', function () {
});
test('tiktok publisher keeps the public post id returned as an integer or string', function (int|string $postId) {
- $this->postPlatform->update(['error_context' => ['tiktok_publish_id' => 'p_pub_url~123']]);
+ $this->post->update(['error_context' => ['tiktok_publish_id' => 'p_pub_url~123']]);
Http::fake([
$this->api.'/post/publish/status/fetch/' => Http::response([
@@ -101,7 +94,7 @@ test('tiktok publisher keeps the public post id returned as an integer or string
]),
]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('7694308097568836885')
->and($result['url'])->toBe('https://www.tiktok.com/@tiktoker/video/7694308097568836885');
@@ -122,7 +115,7 @@ test('tiktok publisher persists the public video url when status omits the post
'original_filename' => 'test-video.mp4',
]],
]);
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value]]);
Http::fake([
$this->api.'/post/publish/video/init/' => Http::response([
@@ -147,7 +140,7 @@ test('tiktok publisher persists the public video url when status omits the post
]),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('7682891910226234644')
->and($result['url'])->toBe('https://www.tiktok.com/@tiktoker/video/7682891910226234644');
@@ -175,7 +168,7 @@ test('tiktok publisher does not report success before processing completes', fun
$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_DOWNLOAD']]),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
'tiktok_publish_id' => 'pub_processing',
@@ -185,7 +178,7 @@ test('tiktok publisher does not report success before processing completes', fun
->and($exception->maxRetries)->toBe(120);
});
- expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_processing');
+ expect($this->post->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_processing');
Http::assertSentCount(2);
});
@@ -211,16 +204,16 @@ test('tiktok publisher checkpoints a video publish_id when status fetch reports
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
- expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_video_401');
+ expect($this->post->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_video_401');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/content/init/'));
});
test('tiktok publisher checkpoints a photo publish_id before polling status', function () {
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [[
'id' => 'test-media-image',
@@ -237,10 +230,10 @@ test('tiktok publisher checkpoints a photo publish_id before polling status', fu
$this->api.'/post/publish/status/fetch/' => Http::response(['data' => ['status' => 'PROCESSING_DOWNLOAD']]),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class);
- expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_processing');
+ expect($this->post->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_processing');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/video/init/'));
});
@@ -248,7 +241,7 @@ test('tiktok publisher checkpoints a photo publish_id before polling status', fu
test('tiktok publisher checkpoints photo derivatives with the publish_id before polling', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [[
'id' => 'oversized',
@@ -276,10 +269,10 @@ test('tiktok publisher checkpoints photo derivatives with the publish_id before
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(PlatformUnavailableException::class);
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
$paths = $context['tiktok_derivative_paths'] ?? null;
expect($context['tiktok_publish_id'] ?? null)->toBe('pub_photo_deriv')
@@ -294,7 +287,7 @@ test('tiktok publisher checkpoints photo derivatives with the publish_id before
test('tiktok publisher keeps photo derivatives when status fetch reports an expired token', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [[
'id' => 'oversized',
@@ -334,10 +327,10 @@ test('tiktok publisher keeps photo derivatives when status fetch reports an expi
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
- $context = $this->postPlatform->fresh()->error_context;
+ $context = $this->post->fresh()->error_context;
$paths = $context['tiktok_derivative_paths'] ?? null;
expect($context['tiktok_publish_id'] ?? null)->toBe('pub_photo_401')
@@ -348,7 +341,7 @@ test('tiktok publisher keeps photo derivatives when status fetch reports an expi
Storage::assertExists($path);
}
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('video_123');
@@ -363,7 +356,7 @@ test('tiktok publisher keeps photo derivatives when status fetch reports an expi
test('tiktok publisher prunes photo derivatives when TikTok confirms the publish failed', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [[
'id' => 'oversized',
@@ -396,15 +389,15 @@ test('tiktok publisher prunes photo derivatives when TikTok confirms the publish
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
- expect($this->postPlatform->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_failed')
+ expect($this->post->fresh()->error_context['tiktok_publish_id'] ?? null)->toBe('pub_photo_failed')
->and(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
});
test('tiktok publisher resumes an existing publish without creating a duplicate', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
@@ -417,7 +410,7 @@ test('tiktok publisher resumes an existing publish without creating a duplicate'
]),
]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result)->toBe([
'id' => 'video_123',
@@ -429,7 +422,7 @@ test('tiktok publisher resumes an existing publish without creating a duplicate'
});
test('tiktok publisher retries a server-error status fetch without creating a duplicate', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
@@ -437,7 +430,7 @@ test('tiktok publisher retries a server-error status fetch without creating a du
$this->api.'/post/publish/status/fetch/' => Http::response(['error' => ['code' => 'internal_error']], 503),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(503)
->and($exception->context['tiktok_publish_id'] ?? null)->toBe('pub_existing');
@@ -447,7 +440,7 @@ test('tiktok publisher retries a server-error status fetch without creating a du
});
test('tiktok publisher retries a rate-limited status fetch without creating a duplicate', function () {
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => ['tiktok_publish_id' => 'pub_existing'],
]);
@@ -455,7 +448,7 @@ test('tiktok publisher retries a rate-limited status fetch without creating a du
$this->api.'/post/publish/status/fetch/' => Http::response(['error' => ['code' => 'rate_limit']], 429),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->httpStatus)->toBe(429)
->and($exception->context['tiktok_publish_id'] ?? null)->toBe('pub_existing');
@@ -469,7 +462,7 @@ test('tiktok publisher keeps photo derivatives while pending and prunes them on
$derivativePath = 'social-tiktok-photos/123e4567-e89b-12d3-a456-426614174000.jpg';
Storage::put($derivativePath, 'image');
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [
'tiktok_publish_id' => 'pub_existing',
'tiktok_derivative_paths' => [$derivativePath],
@@ -482,14 +475,14 @@ test('tiktok publisher keeps photo derivatives while pending and prunes them on
->push(['data' => ['status' => 'PUBLISH_COMPLETE', 'publicaly_available_post_id' => ['video_123']]]),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(function (PlatformUnavailableException $exception) use ($derivativePath): void {
expect($exception->context['tiktok_derivative_paths'] ?? null)->toBe([$derivativePath]);
});
Storage::assertExists($derivativePath);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('video_123');
Storage::assertMissing($derivativePath);
@@ -522,7 +515,7 @@ test('tiktok publisher can publish photos', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('pub_photo_123');
@@ -560,7 +553,7 @@ test('tiktok publisher throws exception on api error', function () {
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -586,7 +579,7 @@ test('tiktok publisher throws token expired exception on auth error', function (
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -619,7 +612,7 @@ test('tiktok publisher refreshes token when expired', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), 'oauth/token');
@@ -647,7 +640,7 @@ test('tiktok publisher throws exception when no refresh token available', functi
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available for TikTok account');
});
@@ -674,7 +667,7 @@ test('tiktok publisher throws TokenExpiredException when refresh_token is reject
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'Refresh token expired');
});
@@ -691,7 +684,7 @@ test('tiktok publisher throws exception for unsupported media type', function ()
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'TikTok only supports video or image content.');
});
@@ -717,7 +710,7 @@ test('tiktok publisher builds correct profile url when username present', functi
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBe('https://www.tiktok.com/@tiktoker');
});
@@ -746,14 +739,14 @@ test('tiktok publisher returns null url when username missing', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['url'])->toBeNull();
});
test('tiktok publisher publishes with user-selected privacy level even when creator info query fails', function () {
// User has explicitly selected SELF_ONLY in meta. creator_info failure must not block publishing.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
@@ -783,7 +776,7 @@ test('tiktok publisher publishes with user-selected privacy level even when crea
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result['id'])->toBe('pub_fallback_123');
@@ -827,12 +820,12 @@ test('tiktok publisher throws exception when publish fails', function () {
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
});
test('tiktok publisher sends meta settings in video publish request', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'privacy_level' => PrivacyLevel::PublicToEveryone->value,
'allow_comments' => true,
@@ -874,7 +867,7 @@ test('tiktok publisher sends meta settings in video publish request', function (
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
@@ -894,7 +887,7 @@ test('tiktok publisher sends meta settings in video publish request', function (
});
test('tiktok publisher sends auto_add_music for photo posts', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'privacy_level' => PrivacyLevel::SelfOnly->value,
'allow_comments' => true,
@@ -927,7 +920,7 @@ test('tiktok publisher sends auto_add_music for photo posts', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
@@ -946,7 +939,7 @@ test('tiktok publisher sends auto_add_music for photo posts', function () {
});
test('tiktok publisher does not send auto_add_music for video posts', function () {
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'privacy_level' => PrivacyLevel::SelfOnly->value,
'auto_add_music' => true,
@@ -977,7 +970,7 @@ test('tiktok publisher does not send auto_add_music for video posts', function (
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
@@ -992,7 +985,7 @@ test('tiktok publisher does not send auto_add_music for video posts', function (
test('tiktok publisher uses default settings when only privacy_level is set', function () {
// Only privacy_level is set (required); all other meta keys absent — exercise default toggles.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value]]);
$this->post->update([
'media' => [
@@ -1024,7 +1017,7 @@ test('tiktok publisher uses default settings when only privacy_level is set', fu
]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
@@ -1057,7 +1050,7 @@ test('tiktok publisher sends video caption in title field, never description', f
],
'content' => 'My video caption',
]);
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
Http::fake([
$this->api.'/post/publish/creator_info/query/' => Http::response([
@@ -1073,7 +1066,7 @@ test('tiktok publisher sends video caption in title field, never description', f
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/video/init/')) {
@@ -1099,7 +1092,7 @@ test('tiktok publisher throws when meta.privacy_level is missing and user did no
],
]);
// Explicitly clear privacy_level from meta (simulate UI never set it).
- $this->postPlatform->update(['meta' => []]);
+ $this->post->update(['meta' => []]);
Http::fake([
// creator_info returns a healthy response — fallback would have silently picked PUBLIC_TO_EVERYONE.
@@ -1116,7 +1109,7 @@ test('tiktok publisher throws when meta.privacy_level is missing and user did no
], 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
});
@@ -1130,11 +1123,11 @@ test('tiktok publisher throws when meta.privacy_level is not a known option', fu
'original_filename' => 'test-video.mp4',
]],
]);
- $this->postPlatform->update(['meta' => ['privacy_level' => 'EVERYONE']]);
+ $this->post->update(['meta' => ['privacy_level' => 'EVERYONE']]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/post/publish/video/init/'));
@@ -1150,7 +1143,7 @@ test('tiktok publisher throws when self only is combined with branded content',
'original_filename' => 'test-video.mp4',
]],
]);
- $this->postPlatform->update([
+ $this->post->update([
'meta' => [
'privacy_level' => PrivacyLevel::SelfOnly->value,
'brand_content_toggle' => true,
@@ -1159,7 +1152,7 @@ test('tiktok publisher throws when self only is combined with branded content',
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/post/publish/video/init/'));
@@ -1169,7 +1162,7 @@ test('tiktok publisher resizes an oversized photo and pulls a hosted compliant c
Storage::fake();
// TikTok rejects images wider than 1080px; this one is 1254px wide.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1203,7 +1196,7 @@ test('tiktok publisher resizes an oversized photo and pulls a hosted compliant c
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// TikTok must be handed the hosted derivative, never the oversized original.
Http::assertSent(function ($request) {
@@ -1223,7 +1216,7 @@ test('tiktok publisher resizes an oversized photo and pulls a hosted compliant c
test('tiktok publisher passes a compliant photo through without hosting a copy', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1246,7 +1239,7 @@ test('tiktok publisher passes a compliant photo through without hosting a copy',
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// The original URL is published unchanged and nothing is downloaded or hosted.
Http::assertSent(function ($request) {
@@ -1266,7 +1259,7 @@ test('tiktok publisher resizes a photo when its dimensions are unknown', functio
Storage::fake();
// No width/height metadata: fall back to the safe path and host a compliant copy.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1299,7 +1292,7 @@ test('tiktok publisher resizes a photo when its dimensions are unknown', functio
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/post/publish/content/init/')) {
@@ -1318,7 +1311,7 @@ test('tiktok publisher resizes a photo when its dimensions are unknown', functio
test('tiktok publisher fails clearly when an oversized photo cannot be downloaded for resizing', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1342,7 +1335,7 @@ test('tiktok publisher fails clearly when an oversized photo cannot be downloade
'*' => Http::response('not found', 500),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class, 'Failed to download image for TikTok resizing');
// Nothing should be left hosted when resizing never completes.
@@ -1353,7 +1346,7 @@ test('tiktok publisher resizes only the oversized photos in a mixed carousel', f
Storage::fake();
// TikTok carousels can carry many images; here one is oversized, one is compliant.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1396,7 +1389,7 @@ test('tiktok publisher resizes only the oversized photos in a mixed carousel', f
'*' => Http::response('fake-image-content', 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// Order is preserved: oversized -> hosted derivative, compliant -> original URL untouched.
Http::assertSent(function ($request) {
@@ -1422,7 +1415,7 @@ test('tiktok publisher resizes only the oversized photos in a mixed carousel', f
test('tiktok publisher prunes the hosted derivative even when publishing fails', function () {
Storage::fake();
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1455,7 +1448,7 @@ test('tiktok publisher prunes the hosted derivative even when publishing fails',
'*' => Http::response('fake-image-content', 200),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TikTokPublishException::class);
expect(Storage::allFiles('social-tiktok-photos'))->toBeEmpty();
@@ -1464,7 +1457,7 @@ test('tiktok publisher prunes the hosted derivative even when publishing fails',
test('tiktok publisher still reports success when derivative cleanup throws on the storage disk', function () {
// The production default disk (r2) is configured to throw on a failed delete.
// Cleanup must never turn an already-published post into a reported failure.
- $this->postPlatform->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
+ $this->post->update(['meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value]]);
$this->post->update([
'media' => [
[
@@ -1502,7 +1495,7 @@ test('tiktok publisher still reports success when derivative cleanup throws on t
'*' => Http::response('fake-image-content', 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('pub_cleanup_throws_123');
});
@@ -1528,7 +1521,7 @@ test('tiktok publisher keeps links intact', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/video/init/')
&& data_get($request->data(), 'post_info.title') === 'New post: https://acme.com/blog');
@@ -1551,7 +1544,7 @@ test('tiktok video sends the chosen cover frame as video_cover_timestamp_ms', fu
"{$this->api}/post/publish/status/fetch/" => Http::response(['data' => ['status' => 'PUBLISH_COMPLETE', 'publish_id' => 'pub_cover']]),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request): bool => $request->url() === "{$this->api}/post/publish/video/init/"
&& data_get($request->data(), 'post_info.video_cover_timestamp_ms') === $coverOffsetMs
diff --git a/tests/Feature/Services/Social/XPublisherTest.php b/tests/Feature/Services/Social/XPublisherTest.php
index 16c4fed2e..6fb09c0d5 100644
--- a/tests/Feature/Services/Social/XPublisherTest.php
+++ b/tests/Feature/Services/Social/XPublisherTest.php
@@ -2,9 +2,8 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PlatformStatus;
-use App\Enums\SocialAccount\Platform;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\Social\ContentLimitException;
use App\Exceptions\Social\ErrorCategory;
@@ -12,7 +11,6 @@ use App\Exceptions\Social\XPublishException;
use App\Exceptions\TokenExpiredException;
use App\Jobs\PublishToSocialPlatform;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -60,18 +58,12 @@ beforeEach(function () {
'token_expires_at' => now()->addHours(2),
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Hello from X!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::X,
'content_type' => ContentType::XPost,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new XPublisher;
});
@@ -86,7 +78,7 @@ test('x publisher can publish text-only post', function () {
], 200),
]);
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result)->toHaveKey('id');
expect($result)->toHaveKey('url');
@@ -115,7 +107,7 @@ test('x publisher does NOT rotate the token when it is only expiring soon but st
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
// X single-use refresh tokens: a still-valid access_token must NOT be rotated.
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/oauth2/token'));
@@ -133,7 +125,7 @@ test('x publisher uses bearer token authentication', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return $request->hasHeader('Authorization')
@@ -151,7 +143,7 @@ test('x publisher throws exception on api error', function () {
], 403),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -164,7 +156,7 @@ test('x publisher throws token expired exception on auth error', function () {
], 401),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -184,7 +176,7 @@ test('x publisher refreshes token when expired', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), 'oauth2/token')) {
@@ -212,7 +204,7 @@ test('x publisher includes media ids in post when media uploaded', function () {
], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
return str_contains($request->url(), '/2/tweets');
@@ -222,14 +214,14 @@ test('x publisher includes media ids in post when media uploaded', function () {
test('x publisher throws exception with empty content and no media', function () {
$this->post->update(['content' => '']);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'X posts require either text or media');
});
test('x publisher throws exception with null content and no media', function () {
$this->post->update(['content' => null]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'X posts require either text or media');
});
@@ -239,7 +231,7 @@ test('x publisher throws exception when no refresh token available', function ()
'refresh_token' => null,
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available for X account');
});
@@ -253,7 +245,7 @@ test('x publisher throws TokenExpiredException when refresh_token is rejected by
], 400),
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'Value passed for the token was invalid.');
});
@@ -307,7 +299,7 @@ test('x publisher handles gif upload with processing', function () {
return Http::response('fake-gif-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('9999888877776666');
@@ -382,7 +374,7 @@ test('x publisher recovers a missing mime type from the downloaded bytes', funct
);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('1212121212');
Http::assertSent(fn ($request) => str_contains($request->url(), '/media/upload'));
@@ -433,7 +425,7 @@ test('x publisher sends image alt text to the media metadata endpoint', function
);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/media/metadata')) {
@@ -492,7 +484,7 @@ test('x publisher truncates alt text to the platform max length', function () {
);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/media/metadata')) {
@@ -543,7 +535,7 @@ test('x publisher does not call media metadata when no alt text is set', functio
);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/media/metadata'));
});
@@ -593,7 +585,7 @@ test('x publisher still posts the tweet when the alt text metadata call fails',
);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('5551112223');
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets'));
@@ -639,7 +631,7 @@ test('x publisher does not send alt text metadata for a video even if it carries
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('7778889990');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/media/metadata'));
@@ -687,7 +679,7 @@ test('x publisher uploads video via chunked upload', function () {
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('9876543210987654321');
expect($result['url'])->toContain('x.com/testuser/status/9876543210987654321');
@@ -751,7 +743,7 @@ test('x publisher sends JSON object bodies for chunked upload initialize and fin
return Http::response('fake-video-content', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/2/media/upload/initialize')) {
@@ -822,7 +814,7 @@ test('x publisher uploads a large video in sequential 1MB segments', function ()
return Http::response(str_repeat('x', (int) (2.5 * 1024 * 1024)), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
expect($appendCount)->toBeGreaterThan(1);
});
@@ -836,7 +828,7 @@ test('x publisher fails cleanly when media cannot be downloaded', function () {
Http::fake(['cdn.example.com/listing' => Http::response(null, 404)]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'Could not fetch the media to upload to X');
});
@@ -879,7 +871,7 @@ test('x publisher uses simple upload for small images and skips chunked finalize
return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('tweet_simple_1');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/initialize'));
@@ -925,7 +917,7 @@ test('x publisher fails instead of posting without the image when the simple upl
$exception = null;
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
} catch (XPublishException $caught) {
$exception = $caught;
}
@@ -981,7 +973,7 @@ test('x publisher uses chunked upload for images larger than 5MB', function () {
return Http::response('tiny', 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/2/media/upload/initialize')) {
@@ -1035,7 +1027,7 @@ test('x publisher keeps tweet_video category for videos larger than 15MB', funct
return Http::response(str_repeat('v', (15 * 1024 * 1024) + 10), 200);
});
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(function ($request) {
if (! str_contains($request->url(), '/2/media/upload/initialize')) {
@@ -1083,7 +1075,7 @@ test('x publisher fails when chunked finalize is rejected by X', function () {
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'Invalid request. Check your post content.');
});
@@ -1118,7 +1110,7 @@ test('x publisher fails when append is rejected by X', function () {
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class);
});
@@ -1169,7 +1161,7 @@ test('x publisher fails when media processing reports failed', function () {
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'X could not process the uploaded media');
});
@@ -1223,7 +1215,7 @@ test('x publisher reschedules media still processing with its media id as a chec
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_proc_timeout'],
@@ -1270,7 +1262,7 @@ test('x publisher never waits longer than thirty seconds between media status ch
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))->toThrow(PlatformUnavailableException::class);
+ expect(fn () => $this->publisher->publish($this->post))->toThrow(PlatformUnavailableException::class);
Sleep::assertSlept(fn ($duration): bool => $duration->totalSeconds === 30.0, 20);
Sleep::assertSleptTimes(20);
@@ -1318,7 +1310,7 @@ test('x publisher fails once instead of rescheduling when no status check ever s
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'X media processing timed out. Please try again.');
});
@@ -1336,7 +1328,7 @@ test('x publisher resumes checkpointed media without uploading it again', functi
],
],
]);
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']],
]);
@@ -1354,7 +1346,7 @@ test('x publisher resumes checkpointed media without uploading it again', functi
return Http::response('unexpected', 500);
});
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['id'])->toBe('1234567890123456789');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));
@@ -1374,7 +1366,7 @@ test('x status connection failures reschedule and resume the uploaded media', fu
'original_filename' => 'clip.mp4',
]],
]);
- $this->postPlatform->forceFill([
+ $this->post->forceFill([
'scheduled_before_media_checks' => true,
'error_context' => $checkpointed ? [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']] : null,
])->save();
@@ -1404,18 +1396,18 @@ test('x status connection failures reschedule and resume the uploaded media', fu
return Http::response('fake-video-content');
});
- (new PublishToSocialPlatform($this->postPlatform))->handle();
+ (new PublishToSocialPlatform($this->post))->handle();
- expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Retrying)
- ->and($this->postPlatform->error_context[PublishCheckpoint::X_MEDIA])->toBe(['test-media-video' => 'media_ready'])
- ->and($this->postPlatform->error_context['retry_count'])->toBe(1);
- Queue::assertPushed(PublishToSocialPlatform::class, fn ($job) => $job->postPlatform->is($this->postPlatform)
+ expect($this->post->refresh()->publish_status)->toBe(PublishStatus::Retrying)
+ ->and($this->post->error_context[PublishCheckpoint::X_MEDIA])->toBe(['test-media-video' => 'media_ready'])
+ ->and($this->post->error_context['retry_count'])->toBe(1);
+ Queue::assertPushed(PublishToSocialPlatform::class, fn ($job) => $job->post->is($this->post)
&& $job->delay->isFuture());
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/tweets'));
- (new PublishToSocialPlatform($this->postPlatform, 1))->handle();
+ (new PublishToSocialPlatform($this->post, 1))->handle();
- expect($this->postPlatform->refresh()->status)->toBe(PlatformStatus::Published);
+ expect($this->post->refresh()->publish_status)->toBe(PublishStatus::Published);
expect(Http::recorded(fn ($request) => str_contains($request->url(), '/initialize')))->toHaveCount($checkpointed ? 0 : 1);
expect(Http::recorded(fn ($request) => str_contains($request->url(), '/2/tweets')))->toHaveCount(1);
})->with([
@@ -1438,7 +1430,7 @@ test('x publisher uploads again when a checkpointed media id is no longer known
],
],
]);
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_expired']],
]);
@@ -1470,7 +1462,7 @@ test('x publisher uploads again when a checkpointed media id is no longer known
return Http::response('fake-video-content', 200);
});
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets')
@@ -1524,7 +1516,7 @@ test('x publisher fails when tweet rejects invalid media ids', function () {
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'Invalid request. Check your post content.');
});
@@ -1536,7 +1528,7 @@ test('x publisher sends the tweet with links defused', function () {
config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '111']], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets')
&& $request['text'] === 'New post: trypost(.)it/blog');
@@ -1550,7 +1542,7 @@ test('x publisher leaves the tweet untouched when defusing is disabled', functio
config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '111']], 200),
]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => str_contains($request->url(), '/2/tweets')
&& $request['text'] === 'New post: https://trypost.it/blog');
@@ -1562,7 +1554,7 @@ test('x publisher rejects a post that only fits before its links are defused', f
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '1']], 200)]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(fn (ContentLimitException $exception) => expect($exception->category)->toBe(ErrorCategory::ContentPolicy)
->and($exception->userMessage)->toBe(__('posts.errors.content_too_long', ['platform' => 'X', 'max' => 280, 'provided' => 282]))
->and($exception->platform())->toBe('x'));
@@ -1576,7 +1568,7 @@ test('x publisher accepts a post that only fits once its links are defused', fun
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '1']], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => mb_strlen($request['text']) === 276);
});
@@ -1586,19 +1578,19 @@ test('x publisher does not count html markup toward the character limit', functi
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '1']], 200)]);
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
Http::assertSent(fn ($request) => mb_strlen($request['text']) === 275);
});
test('an x thread posts each reply under the previous one', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Second', 'Third']]]);
+ $this->post->update(['meta' => ['thread_replies' => ['Second', 'Third']]]);
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
->push(['data' => ['id' => '100']], 201)
->push(['data' => ['id' => '101']], 201)
->push(['data' => ['id' => '102']], 201)]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result)->toBe(['id' => '100', 'url' => 'https://x.com/testuser/status/100', 'thread_reply_ids' => ['101', '102']]);
Http::assertSent(fn (Request $request): bool => $request->data() === ['text' => 'Second', 'reply' => ['in_reply_to_tweet_id' => '100']]);
@@ -1607,7 +1599,7 @@ test('an x thread posts each reply under the previous one', function () {
test('an x thread uploads each reply media with that reply only', function () {
$image = ['id' => 'reply-image', 'path' => 'media/2026-01/photo.jpg', 'url' => 'https://example.com/media/2026-01/photo.jpg', 'mime_type' => 'image/jpeg', 'original_filename' => 'photo.jpg'];
- $this->postPlatform->update(['meta' => ['thread_replies' => [['text' => '', 'media' => [$image]], ['text' => 'Third', 'media' => []]]]]);
+ $this->post->update(['meta' => ['thread_replies' => [['text' => '', 'media' => [$image]], ['text' => 'Third', 'media' => []]]]]);
$mockOptimizer = Mockery::mock(MediaOptimizer::class);
$mockOptimizer->shouldReceive('optimizeImage')->andReturnUsing(function (string $tempFile) {
@@ -1631,7 +1623,7 @@ test('an x thread uploads each reply media with that reply only', function () {
return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);
});
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['101', '102']);
Http::assertSent(fn (Request $request): bool => str_contains($request->url(), '/2/tweets') && $request->data() === ['text' => 'Hello from X!']);
@@ -1640,14 +1632,14 @@ test('an x thread uploads each reply media with that reply only', function () {
});
test('a retried x thread resumes after the live segments instead of re-posting the root', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => ['Second']]]);
+ $this->post->update(['meta' => ['thread_replies' => ['Second']]]);
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
->push(['data' => ['id' => '100']], 201)
->push(['title' => 'Forbidden', 'detail' => 'Not allowed', 'status' => 403], 403)
->push(['data' => ['id' => '101']], 201)]);
- rescue(fn () => $this->publisher->publish($this->postPlatform->fresh()), report: false);
- $result = (new XPublisher)->publish($this->postPlatform->fresh());
+ rescue(fn () => $this->publisher->publish($this->post->fresh()), report: false);
+ $result = (new XPublisher)->publish($this->post->fresh());
expect($result['id'])->toBe('100')
->and($result['thread_reply_ids'])->toBe(['101']);
@@ -1655,31 +1647,31 @@ test('a retried x thread resumes after the live segments instead of re-posting t
});
test('an x reply over the account limit is rejected before anything is posted', function () {
- $this->postPlatform->update(['meta' => ['thread_replies' => [str_repeat('a', 281)]]]);
+ $this->post->update(['meta' => ['thread_replies' => [str_repeat('a', 281)]]]);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(ContentLimitException::class, __('posts.form.thread.reply_too_long', ['limit' => 280, 'over' => 1]));
Http::assertNothingSent();
});
test('an x account with long posts may thread replies past 280 characters', function () {
$this->socialAccount->update(['meta' => [...(array) $this->socialAccount->meta, 'x_subscription_type' => 'Premium']]);
- $this->postPlatform->update(['meta' => ['thread_replies' => [str_repeat('a', 400)]]]);
+ $this->post->update(['meta' => ['thread_replies' => [str_repeat('a', 400)]]]);
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::sequence()
->push(['data' => ['id' => '100']], 201)
->push(['data' => ['id' => '101']], 201)]);
- $result = $this->publisher->publish($this->postPlatform->fresh());
+ $result = $this->publisher->publish($this->post->fresh());
expect($result['thread_reply_ids'])->toBe(['101']);
});
test('an x post marked as ai generated discloses it with made_with_ai', function (mixed $flag, bool $sent) {
- $this->postPlatform->update(['meta' => ['is_ai_generated' => $flag]]);
+ $this->post->update(['meta' => ['is_ai_generated' => $flag]]);
Http::fake([config('trypost.platforms.x.api').'/tweets' => Http::response(['data' => ['id' => '100']], 201)]);
- $this->publisher->publish($this->postPlatform->fresh());
+ $this->publisher->publish($this->post->fresh());
Http::assertSent(fn (Request $request): bool => str_ends_with($request->url(), '/tweets')
&& array_key_exists('made_with_ai', $request->data()) === $sent
@@ -1701,7 +1693,7 @@ test('x publisher never uploads checkpointed media again when the status check f
'original_filename' => 'clip.mp4',
]],
]);
- $this->postPlatform->update([
+ $this->post->update([
'error_context' => [PublishCheckpoint::X_MEDIA => ['test-media-video' => 'media_ready']],
]);
@@ -1713,7 +1705,7 @@ test('x publisher never uploads checkpointed media again when the status check f
return Http::response('fake-video-content', 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))->toThrow($exception);
+ expect(fn () => $this->publisher->publish($this->post->fresh()))->toThrow($exception);
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/2/media/upload/initialize'));
})->with([
@@ -1801,7 +1793,7 @@ test('x publisher reads processing_info only under data in the status response',
return Http::response('fake-video-content', 200);
});
- $result = $this->publisher->publish($this->postPlatform);
+ $result = $this->publisher->publish($this->post);
expect($result['id'])->toBe('555')
->and(Http::recorded(fn (Request $request): bool => isXMediaUploadStatusRequest($request)))->toHaveCount(1);
@@ -1822,7 +1814,7 @@ test('x publisher reschedules media still processing under its own retry policy'
fakeXVideoUploadStuckWith(['state' => 'in_progress', 'check_after_secs' => 0]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->retryDelaySeconds)->toBe(60)
->and($exception->maxRetries)->toBe(30);
@@ -1862,7 +1854,7 @@ test('x publisher keeps the media uploaded before the one still processing in th
fakeXVideoUploadStuckWith(['state' => 'in_progress', 'check_after_secs' => 0]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(function (PlatformUnavailableException $exception): void {
expect($exception->context)->toBe([
PublishCheckpoint::X_MEDIA => [
@@ -1888,7 +1880,7 @@ test('x publisher treats a processing state that is not a string as unknown', fu
fakeXVideoUploadStuckWith(['state' => ['name' => 'in_progress'], 'check_after_secs' => 0]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'X media processing timed out. Please try again.');
});
@@ -1924,7 +1916,7 @@ test('x publisher fails on a v1-shaped upload response without data.id', functio
return Http::response(file_get_contents(__DIR__.'/../../../fixtures/1x1.png'), 200);
});
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(XPublishException::class, 'X did not accept the media upload. Please try again.');
Http::assertNotSent(fn ($request) => str_contains($request->url(), '/append'));
diff --git a/tests/Feature/Services/Social/YouTubePublisherTest.php b/tests/Feature/Services/Social/YouTubePublisherTest.php
index 2f3a85036..4bc236997 100644
--- a/tests/Feature/Services/Social/YouTubePublisherTest.php
+++ b/tests/Feature/Services/Social/YouTubePublisherTest.php
@@ -9,7 +9,6 @@ use App\Exceptions\Social\ErrorCategory;
use App\Exceptions\Social\YouTubePublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -41,8 +40,8 @@ function fakeYouTubeUpload(array $responses = []): YouTubePublisher
test('youtube description rejects stored invalid data before network work', function (mixed $description, string $key) {
Http::fake();
$this->socialAccount->update(['token_expires_at' => now()->subHour()]);
- $this->postPlatform->update(['meta' => ['description' => $description]]);
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ $this->post->update(['meta' => ['description' => $description]]);
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(YouTubePublishException::class, __($key));
Http::assertNothingSent();
})->with([
@@ -64,7 +63,7 @@ test('youtube description reaches the resumable upload request', function (?stri
'original_filename' => 'video.mp4',
]],
]);
- $this->postPlatform->update(['meta' => ['description' => $description]]);
+ $this->post->update(['meta' => ['description' => $description]]);
$tempFile = null;
$publisher = fakeYouTubeUpload([
'https://example.com/video.mp4' => function (Request $request, array $options) use (&$tempFile) {
@@ -74,7 +73,7 @@ test('youtube description reaches the resumable upload request', function (?stri
},
]);
- $result = $publisher->publish($this->postPlatform->fresh());
+ $result = $publisher->publish($this->post->fresh());
expect($result)->toBe([
'id' => 'short-id',
@@ -111,31 +110,33 @@ test('youtube description reaches the resumable upload request', function (?stri
]);
test('youtube description builds independent upload metadata', function () {
+ $media = [[
+ 'id' => 'video-1',
+ 'type' => 'video',
+ 'path' => 'medias/video.mp4',
+ 'url' => 'https://example.com/video.mp4',
+ 'mime_type' => 'video/mp4',
+ 'original_filename' => 'video.mp4',
+ ]];
$this->post->update([
'content' => 'Short title',
- 'media' => [[
- 'id' => 'video-1',
- 'type' => 'video',
- 'path' => 'medias/video.mp4',
- 'url' => 'https://example.com/video.mp4',
- 'mime_type' => 'video/mp4',
- 'original_filename' => 'video.mp4',
- ]],
+ 'media' => $media,
+ 'meta' => ['description' => 'First channel description'],
]);
- $this->postPlatform->update(['meta' => ['description' => 'First channel description']]);
$secondAccount = SocialAccount::factory()->youtube()->create([
'workspace_id' => $this->workspace->id,
'token_expires_at' => now()->addDays(7),
]);
- $secondPlatform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $secondAccount->id,
+ $secondPost = Post::factory()->forAccount($secondAccount, ContentType::YouTubeShort)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Short title',
+ 'media' => $media,
'meta' => ['description' => 'Second channel description'],
]);
$publisher = fakeYouTubeUpload();
- $publisher->publish($this->postPlatform->fresh());
- $publisher->publish($secondPlatform);
+ $publisher->publish($this->post->fresh());
+ $publisher->publish($secondPost);
foreach (['First channel description', 'Second channel description'] as $description) {
Http::assertSent(function (Request $request) use ($description): bool {
@@ -166,24 +167,18 @@ beforeEach(function () {
],
]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
'user_id' => $this->user->id,
'content' => 'Check out this YouTube Short!',
- ]);
-
- $this->postPlatform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'platform' => Platform::YouTube,
'content_type' => ContentType::YouTubeShort,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
$this->publisher = new YouTubePublisher;
});
test('youtube publisher throws exception when no media', function () {
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'YouTube Shorts requires a video to publish.');
});
@@ -206,7 +201,7 @@ test('youtube publisher cleans up unusable downloads without starting an upload'
},
]);
- expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $publisher->publish($this->post->fresh()))
->toThrow(YouTubePublishException::class, $message);
$this->assertFileDoesNotExist($tempFile);
@@ -231,7 +226,7 @@ test('youtube publisher throws exception for non-video content', function () {
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, 'YouTube Shorts only supports video content.');
});
@@ -260,7 +255,7 @@ test('youtube publisher refreshes token when expired', function () {
]);
try {
- $this->publisher->publish($this->postPlatform);
+ $this->publisher->publish($this->post);
} catch (Exception $e) {
// Expected to fail on upload, but token should be refreshed
}
@@ -291,7 +286,7 @@ test('youtube publisher throws exception when no refresh token available', funct
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available for YouTube account');
});
@@ -324,7 +319,7 @@ test('youtube publisher reports Google upload errors', function (string $url, in
], $status),
]);
- expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $publisher->publish($this->post->fresh()))
->toThrow($exception, $message);
expect(app(Client::class)->shouldDefer())->toBeFalse();
$this->assertFileDoesNotExist($tempFile);
@@ -343,7 +338,7 @@ test('youtube publisher reports Google upload errors', function (string $url, in
]);
test('youtube publisher throws exception with null content', function () {
- $this->postPlatform->update(['meta' => ['description' => 'A valid description is not a title']]);
+ $this->post->update(['meta' => ['description' => 'A valid description is not a title']]);
$this->post->update([
'content' => null,
'media' => [
@@ -357,7 +352,7 @@ test('youtube publisher throws exception with null content', function () {
],
]);
- expect(fn () => $this->publisher->publish($this->postPlatform))
+ expect(fn () => $this->publisher->publish($this->post))
->toThrow(Exception::class, __('posts.form.youtube.title_required'));
});
@@ -400,8 +395,8 @@ function youtubeVideoPost(mixed $test, array $meta): void
'id' => 'video-1', 'type' => 'video', 'path' => 'medias/video.mp4',
'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'video.mp4',
]],
+ 'meta' => $meta,
]);
- $test->postPlatform->update(['meta' => $meta]);
}
test('youtube metadata reaches videos.insert', function () {
@@ -417,7 +412,7 @@ test('youtube metadata reaches videos.insert', function () {
]);
$publisher = fakeYouTubeUpload();
- $publisher->publish($this->postPlatform->fresh());
+ $publisher->publish($this->post->fresh());
Http::assertSent(function (Request $request): bool {
if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
@@ -441,7 +436,7 @@ test('a youtube post without metadata publishes with today defaults', function (
youtubeVideoPost($this, []);
$publisher = fakeYouTubeUpload();
- $publisher->publish($this->postPlatform->fresh());
+ $publisher->publish($this->post->fresh());
Http::assertSent(function (Request $request): bool {
if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
@@ -465,7 +460,7 @@ test('a stored invalid youtube title fails before any upload', function () {
youtubeVideoPost($this, ['title' => 'a <b> title']);
Http::fake();
- expect(fn () => $this->publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $this->publisher->publish($this->post->fresh()))
->toThrow(YouTubePublishException::class, __('posts.form.youtube.title_invalid'));
Http::assertNothingSent();
});
@@ -475,7 +470,7 @@ test('an explicit youtube title publishes a post without content', function () {
$this->post->update(['content' => null]);
$publisher = fakeYouTubeUpload();
- $publisher->publish($this->postPlatform->fresh());
+ $publisher->publish($this->post->fresh());
Http::assertSent(function (Request $request): bool {
if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
@@ -493,7 +488,7 @@ test('a long youtube content becomes the description while the title stays short
$this->post->update(['content' => str_repeat('word ', 400)]);
$publisher = fakeYouTubeUpload();
- $publisher->publish($this->postPlatform->fresh());
+ $publisher->publish($this->post->fresh());
Http::assertSent(function (Request $request): bool {
if (! str_contains($request->url(), '/upload/youtube/v3/videos')) {
@@ -517,7 +512,7 @@ test('a Google server error before the final chunk retries the upload', function
], 503),
]);
- expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $publisher->publish($this->post->fresh()))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBe(503));
Log::shouldNotHaveReceived('error', ['YouTube upload failed', Mockery::any()]);
@@ -542,7 +537,7 @@ test('a Google backendError below 500 retries the upload without an http status'
'id' => 'v', 'url' => 'https://example.com/video.mp4', 'mime_type' => 'video/mp4', 'original_filename' => 'v.mp4',
]]]);
- expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $publisher->publish($this->post->fresh()))
->toThrow(fn (PlatformUnavailableException $exception) => expect($exception->httpStatus)->toBeNull());
});
@@ -556,7 +551,7 @@ test('a Google server error on the final chunk fails without retrying because th
], 503),
]);
- expect(fn () => $publisher->publish($this->postPlatform->fresh()))
+ expect(fn () => $publisher->publish($this->post->fresh()))
->toThrow(function (YouTubePublishException $exception) {
expect($exception->category)->toBe(ErrorCategory::ServerError)
->and($exception->userMessage)->toBe(__('posts.errors.youtube.upload_unconfirmed'))
diff --git a/tests/Feature/Services/WebhookServiceTest.php b/tests/Feature/Services/WebhookServiceTest.php
index b3604c8e6..1f4d0fe2f 100644
--- a/tests/Feature/Services/WebhookServiceTest.php
+++ b/tests/Feature/Services/WebhookServiceTest.php
@@ -12,7 +12,6 @@ use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\DispatchWebhook;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -176,15 +175,34 @@ test('postPayload includes the post lifecycle fields', function () {
],
'labels' => [],
'media' => [],
- 'platforms' => [],
+ 'publish_status' => 'published',
+ 'social_account_id' => null,
+ 'platform' => null,
+ 'content_type' => null,
+ 'platform_post_id' => $post->platform_post_id,
+ 'platform_url' => $post->platform_url,
+ 'error_message' => null,
+ 'display_name' => null,
+ 'display_username' => null,
+ 'display_avatar' => null,
+ 'meta' => [],
+ 'social_account' => null,
]);
});
test('postPayload matches the published webhook example', function () {
- $post = Post::factory()->published()->createQuietly([
- 'workspace_id' => $this->workspace->id,
+ $instagram = SocialAccount::factory()->instagram()->recycle($this->workspace)->create([
+ 'display_name' => 'TryPost',
+ 'username' => 'trypost',
+ 'avatar_url' => 'avatars/ig.jpg',
+ 'access_token' => 'secret-access-token',
+ 'refresh_token' => 'secret-refresh-token',
+ ]);
+
+ $post = Post::factory()->forAccount($instagram, ContentType::InstagramFeed)->published()->createQuietly([
'user_id' => $this->user->id,
'content' => '<p>Launch day. TryPost is live.</p>',
+ 'meta' => ['is_ai_generated' => true],
'created_via' => CreatedVia::Web,
'media' => [
[
@@ -224,42 +242,7 @@ test('postPayload matches the published webhook example', function () {
]);
$post->labels()->attach($label);
- $instagram = SocialAccount::factory()->instagram()->recycle($this->workspace)->create([
- 'display_name' => 'TryPost',
- 'username' => 'trypost',
- 'avatar_url' => 'avatars/ig.jpg',
- 'access_token' => 'secret-access-token',
- 'refresh_token' => 'secret-refresh-token',
- ]);
- $linkedin = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create([
- 'display_name' => 'Paulo Castellano',
- 'username' => 'paulocastellano',
- 'avatar_url' => 'avatars/li.jpg',
- ]);
- $x = SocialAccount::factory()->x()->recycle($this->workspace)->create([
- 'display_name' => 'TryPost',
- 'username' => 'trypost',
- 'avatar_url' => 'avatars/x.jpg',
- ]);
-
- $instagramPlatform = PostPlatform::factory()->published()->recycle($post, $instagram)->create([
- 'platform' => Platform::Instagram,
- 'content_type' => ContentType::InstagramFeed,
- 'meta' => ['is_ai_generated' => true],
- ]);
- $linkedinPlatform = PostPlatform::factory()->published()->recycle($post, $linkedin)->create([
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'meta' => ['document_title' => 'TryPost launch deck'],
- ]);
- $xPlatform = PostPlatform::factory()->published()->recycle($post, $x)->create([
- 'platform' => Platform::X,
- 'content_type' => ContentType::XPost,
- 'meta' => [],
- ]);
-
$payload = $this->service->postPayload($post->fresh());
- $platforms = collect($payload['platforms'])->keyBy('id');
expect($payload)
->toHaveKeys([
@@ -277,7 +260,18 @@ test('postPayload matches the published webhook example', function () {
'workspace',
'labels',
'media',
- 'platforms',
+ 'publish_status',
+ 'social_account_id',
+ 'platform',
+ 'content_type',
+ 'platform_post_id',
+ 'platform_url',
+ 'error_message',
+ 'display_name',
+ 'display_username',
+ 'display_avatar',
+ 'meta',
+ 'social_account',
])
->and($payload['id'])->toBe($post->id)
->and($payload['workspace_id'])->toBe($this->workspace->id)
@@ -333,78 +327,25 @@ test('postPayload matches the published webhook example', function () {
],
],
])
- ->and($payload['platforms'])->toHaveCount(3)
- ->and($platforms[$instagramPlatform->id])->toEqual([
- 'id' => $instagramPlatform->id,
- 'social_account_id' => $instagram->id,
+ ->and($payload)->not->toHaveKey('platforms')
+ ->and($payload)->not->toHaveKey('error_context')
+ ->and($payload['publish_status'])->toBe('published')
+ ->and($payload['social_account_id'])->toBe($instagram->id)
+ ->and($payload['platform'])->toBe(Platform::Instagram->value)
+ ->and($payload['content_type'])->toBe(ContentType::InstagramFeed->value)
+ ->and($payload['platform_post_id'])->toBe($post->platform_post_id)
+ ->and($payload['platform_url'])->toBe($post->platform_url)
+ ->and($payload['error_message'])->toBeNull()
+ ->and($payload['display_name'])->toBe('TryPost')
+ ->and($payload['display_username'])->toBe('trypost')
+ ->and($payload['display_avatar'])->toBe(Storage::url('avatars/ig.jpg'))
+ ->and($payload['meta'])->toEqual(['is_ai_generated' => true])
+ ->and($payload['social_account'])->toEqual([
+ 'id' => $instagram->id,
'platform' => Platform::Instagram->value,
- 'content_type' => ContentType::InstagramFeed->value,
- 'enabled' => true,
- 'status' => 'published',
- 'platform_post_id' => $instagramPlatform->platform_post_id,
- 'platform_url' => $instagramPlatform->platform_url,
- 'published_at' => $instagramPlatform->published_at?->toIso8601String(),
- 'error_message' => null,
- 'error_context' => null,
'display_name' => 'TryPost',
- 'display_username' => 'trypost',
- 'display_avatar' => Storage::url('avatars/ig.jpg'),
- 'meta' => ['is_ai_generated' => true],
- 'social_account' => [
- 'id' => $instagram->id,
- 'platform' => Platform::Instagram->value,
- 'display_name' => 'TryPost',
- 'username' => 'trypost',
- 'status' => 'connected',
- ],
- ])
- ->and($platforms[$linkedinPlatform->id])->toEqual([
- 'id' => $linkedinPlatform->id,
- 'social_account_id' => $linkedin->id,
- 'platform' => Platform::LinkedIn->value,
- 'content_type' => ContentType::LinkedInPost->value,
- 'enabled' => true,
- 'status' => 'published',
- 'platform_post_id' => $linkedinPlatform->platform_post_id,
- 'platform_url' => $linkedinPlatform->platform_url,
- 'published_at' => $linkedinPlatform->published_at?->toIso8601String(),
- 'error_message' => null,
- 'error_context' => null,
- 'display_name' => 'Paulo Castellano',
- 'display_username' => 'paulocastellano',
- 'display_avatar' => Storage::url('avatars/li.jpg'),
- 'meta' => ['document_title' => 'TryPost launch deck'],
- 'social_account' => [
- 'id' => $linkedin->id,
- 'platform' => Platform::LinkedIn->value,
- 'display_name' => 'Paulo Castellano',
- 'username' => 'paulocastellano',
- 'status' => 'connected',
- ],
- ])
- ->and($platforms[$xPlatform->id])->toEqual([
- 'id' => $xPlatform->id,
- 'social_account_id' => $x->id,
- 'platform' => Platform::X->value,
- 'content_type' => ContentType::XPost->value,
- 'enabled' => true,
- 'status' => 'published',
- 'platform_post_id' => $xPlatform->platform_post_id,
- 'platform_url' => $xPlatform->platform_url,
- 'published_at' => $xPlatform->published_at?->toIso8601String(),
- 'error_message' => null,
- 'error_context' => null,
- 'display_name' => 'TryPost',
- 'display_username' => 'trypost',
- 'display_avatar' => Storage::url('avatars/x.jpg'),
- 'meta' => [],
- 'social_account' => [
- 'id' => $x->id,
- 'platform' => Platform::X->value,
- 'display_name' => 'TryPost',
- 'username' => 'trypost',
- 'status' => 'connected',
- ],
+ 'username' => 'trypost',
+ 'status' => 'connected',
])
->and(json_encode($payload))->not->toContain('secret-access-token')
->and(json_encode($payload))->not->toContain('secret-refresh-token')
@@ -412,27 +353,21 @@ test('postPayload matches the published webhook example', function () {
->and(json_encode($payload))->not->toContain('refresh_token');
});
-test('postPayload includes failed platform errors', function () {
- $post = Post::factory()->published()->createQuietly([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
+test('postPayload includes the failed publication error', function () {
$account = SocialAccount::factory()->tiktok()->recycle($this->workspace)->create();
- $platform = PostPlatform::factory()->failed()->recycle($post, $account)->create([
- 'platform' => Platform::TikTok,
- 'content_type' => ContentType::TikTokVideo,
+ $post = Post::factory()->forAccount($account, ContentType::TikTokVideo)->failed()->createQuietly([
+ 'user_id' => $this->user->id,
'meta' => ['privacy_level' => PrivacyLevel::PublicToEveryone->value],
'error_context' => ['retry_count' => 2],
]);
$payload = $this->service->postPayload($post->fresh());
- expect(data_get($payload, 'platforms.0.id'))->toBe($platform->id)
- ->and(data_get($payload, 'platforms.0.status'))->toBe('failed')
- ->and(data_get($payload, 'platforms.0.error_message'))->toBe('Failed to publish')
- ->and(data_get($payload, 'platforms.0.error_context'))->toEqual(['retry_count' => 2])
- ->and(data_get($payload, 'platforms.0.meta.privacy_level'))->toBe(PrivacyLevel::PublicToEveryone->value);
+ expect($payload['social_account_id'])->toBe($account->id)
+ ->and($payload['publish_status'])->toBe('failed')
+ ->and($payload['error_message'])->toBe('Failed to publish')
+ ->and($payload)->not->toHaveKey('error_context')
+ ->and(data_get($payload, 'meta.privacy_level'))->toBe(PrivacyLevel::PublicToEveryone->value);
});
test('postPayload accepts integer media ids from generated attachments', function () {
@@ -472,9 +407,6 @@ test('postPayload keeps display fields when the social account is gone', functio
$post = Post::factory()->published()->createQuietly([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
- ]);
-
- $platform = PostPlatform::factory()->published()->recycle($post)->create([
'social_account_id' => null,
'platform' => Platform::X,
'content_type' => ContentType::XPost,
@@ -485,11 +417,11 @@ test('postPayload keeps display fields when the social account is gone', functio
$payload = $this->service->postPayload($post->fresh());
- expect(data_get($payload, 'platforms.0.id'))->toBe($platform->id)
- ->and(data_get($payload, 'platforms.0.social_account_id'))->toBeNull()
- ->and(data_get($payload, 'platforms.0.social_account'))->toBeNull()
- ->and(data_get($payload, 'platforms.0.display_name'))->toBe('TryPost')
- ->and(data_get($payload, 'platforms.0.display_username'))->toBe('trypost');
+ expect($payload['platform'])->toBe(Platform::X->value)
+ ->and($payload['social_account_id'])->toBeNull()
+ ->and($payload['social_account'])->toBeNull()
+ ->and($payload['display_name'])->toBe('TryPost')
+ ->and($payload['display_username'])->toBe('trypost');
});
function webhookServiceDns(array $answers): void
diff --git a/tests/Feature/Services/XPublisherTest.php b/tests/Feature/Services/XPublisherTest.php
index 13dedfb1b..702225808 100644
--- a/tests/Feature/Services/XPublisherTest.php
+++ b/tests/Feature/Services/XPublisherTest.php
@@ -7,7 +7,6 @@ use App\Enums\SocialAccount\Platform;
use App\Exceptions\Social\XPublishException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Social\XPublisher;
@@ -23,12 +22,8 @@ beforeEach(function () {
'access_token' => 'test-token',
'token_expires_at' => now()->addDays(30),
]);
- $this->post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'content' => 'Test tweet']);
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'content_type' => ContentType::XPost,
- ]);
+ $this->post = Post::factory()->forAccount($this->socialAccount, ContentType::XPost)->create(['content' => 'Test tweet']);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
});
test('x publisher publishes text only tweet', function () {
@@ -39,7 +34,7 @@ test('x publisher publishes text only tweet', function () {
]);
$publisher = new XPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('tweet-123');
expect($result['url'])->toBe('https://x.com/testuser/status/tweet-123');
@@ -55,7 +50,7 @@ test('x publisher throws token expired exception on 401', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -77,7 +72,7 @@ test('x publisher refreshes token when expired', function () {
]);
$publisher = new XPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('tweet-123');
$this->socialAccount->refresh();
@@ -92,7 +87,7 @@ test('x publisher throws exception when no refresh token', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available');
});
@@ -106,7 +101,7 @@ test('x publisher throws exception on api error', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class);
});
@@ -118,7 +113,7 @@ test('x publisher returns unknown id when no id in response', function () {
]);
$publisher = new XPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('unknown');
expect($result['url'])->toBeNull();
@@ -139,7 +134,7 @@ test('x publisher handles token refresh failure', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -162,7 +157,7 @@ test('x publisher does NOT rotate the token when it is only expiring soon but st
]);
$publisher = new XPublisher;
- $result = $publisher->publish($this->postPlatform);
+ $result = $publisher->publish($this->post);
expect($result['id'])->toBe('tweet-123');
@@ -182,7 +177,7 @@ test('x publisher handles 403 error as generic error', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(XPublishException::class);
});
@@ -193,6 +188,6 @@ test('x publisher handles empty error response', function () {
$publisher = new XPublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class);
});
diff --git a/tests/Feature/Services/YouTubePublisherTest.php b/tests/Feature/Services/YouTubePublisherTest.php
index e3098b2cd..38d1577fe 100644
--- a/tests/Feature/Services/YouTubePublisherTest.php
+++ b/tests/Feature/Services/YouTubePublisherTest.php
@@ -6,7 +6,6 @@ use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Social\YouTubePublisher;
@@ -21,18 +20,17 @@ beforeEach(function () {
'access_token' => 'test-token',
'token_expires_at' => now()->addDays(30),
]);
- $this->post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'content' => 'Test YouTube Short description']);
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
+ 'content' => 'Test YouTube Short description',
'content_type' => ContentType::YouTubeShort,
]);
+ $this->post->setRelation('socialAccount', $this->socialAccount);
});
test('youtube publisher throws exception when no media', function () {
$publisher = new YouTubePublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class, 'YouTube Shorts requires a video to publish.');
});
@@ -44,7 +42,7 @@ test('youtube publisher throws exception for non video media', function () {
$publisher = new YouTubePublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(Exception::class, 'YouTube Shorts only supports video content.');
});
@@ -61,7 +59,7 @@ test('youtube publisher throws exception when no refresh token for expired token
$publisher = new YouTubePublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class, 'No refresh token available');
});
@@ -87,7 +85,7 @@ test('youtube publisher throws token expired exception on 401', function () {
'refresh_token' => 'refresh-token',
]);
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -111,7 +109,7 @@ test('youtube publisher throws token expired exception on invalid grant', functi
$publisher = new YouTubePublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
@@ -140,6 +138,6 @@ test('youtube publisher handles auth error reason', function () {
$publisher = new YouTubePublisher;
- expect(fn () => $publisher->publish($this->postPlatform))
+ expect(fn () => $publisher->publish($this->post))
->toThrow(TokenExpiredException::class);
});
diff --git a/tests/Feature/Social/TelegramConnectionTest.php b/tests/Feature/Social/TelegramConnectionTest.php
index f549d29fd..1fc968a1e 100644
--- a/tests/Feature/Social/TelegramConnectionTest.php
+++ b/tests/Feature/Social/TelegramConnectionTest.php
@@ -8,7 +8,6 @@ use App\Events\TelegramConnectFailed;
use App\Exceptions\PlatformUnavailableException;
use App\Exceptions\TokenExpiredException;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -262,14 +261,8 @@ it('consumes the code once so it cannot be replayed for another chat', function
it('stores reaction counts on the matching post from a reaction update', function () {
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->published()->create([
'user_id' => $this->user->id,
- ]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Telegram,
'platform_post_id' => '42',
]);
@@ -288,7 +281,7 @@ it('stores reaction counts on the matching post from a reaction update', functio
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
- expect(data_get($postPlatform->fresh()->meta, 'reactions'))
+ expect(data_get($post->fresh()->meta, 'reactions'))
->toBe([['type' => '👍', 'count' => 12], ['type' => '❤️', 'count' => 5]]);
});
@@ -298,11 +291,8 @@ it('does not store reactions on a post from a different channel with the same me
'platform_user_id' => '-1009999999999',
'meta' => ['chat_id' => '-1009999999999', 'username' => 'other', 'type' => 'channel'],
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $otherAccount->id,
- 'platform' => Platform::Telegram,
+ $post = Post::factory()->forAccount($otherAccount)->published()->create([
+ 'user_id' => $this->user->id,
'platform_post_id' => '42',
]);
@@ -318,16 +308,13 @@ it('does not store reactions on a post from a different channel with the same me
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
- expect(data_get($postPlatform->fresh()->meta, 'reactions'))->toBeNull();
+ expect(data_get($post->fresh()->meta, 'reactions'))->toBeNull();
});
it('labels custom emoji reactions with a fallback', function () {
$account = SocialAccount::factory()->telegram()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id]);
- $postPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => Platform::Telegram,
+ $post = Post::factory()->forAccount($account)->published()->create([
+ 'user_id' => $this->user->id,
'platform_post_id' => '77',
]);
@@ -343,7 +330,7 @@ it('labels custom emoji reactions with a fallback', function () {
->postJson(route('telegram.webhook'), $update)
->assertNoContent();
- expect(data_get($postPlatform->fresh()->meta, 'reactions'))
+ expect(data_get($post->fresh()->meta, 'reactions'))
->toBe([['type' => 'Custom', 'count' => 3]]);
});
diff --git a/tests/Feature/SocialAccount/NetworkUniquenessTest.php b/tests/Feature/SocialAccount/NetworkUniquenessTest.php
index 3314e1975..ab992d2b9 100644
--- a/tests/Feature/SocialAccount/NetworkUniquenessTest.php
+++ b/tests/Feature/SocialAccount/NetworkUniquenessTest.php
@@ -2,15 +2,14 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Enums\PostPlatform\ContentType;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status;
use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Database\QueryException;
@@ -322,7 +321,7 @@ test('connectIdentity releases the lock so the next connect proceeds', function
->and($this->workspace->socialAccounts()->count())->toBe(1);
});
-test('reconnecting through the other variant moves pending targets onto the new platform', function () {
+test('reconnecting through the other variant moves pending posts onto the new platform', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
@@ -330,14 +329,10 @@ test('reconnecting through the other variant moves pending targets onto the new
'scopes' => ['instagram_business_content_publish'],
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $pending = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $pending = Post::factory()->forAccount($account)->create([
'platform' => Platform::Instagram->value,
'content_type' => ContentType::InstagramReel,
- 'status' => PostPlatformStatus::Pending,
+ 'publish_status' => PublishStatus::Pending,
]);
SocialAccount::connectIdentity(
@@ -357,20 +352,16 @@ test('reconnecting through the other variant moves pending targets onto the new
))->toBe([]);
});
-test('a variant move leaves a published target on the platform it really published to', function () {
+test('a variant move leaves a published post on the platform it really published to', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
'platform_user_id' => 'shared-ig-id',
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $published = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $published = Post::factory()->forAccount($account)->create([
'platform' => Platform::Instagram->value,
- 'status' => PostPlatformStatus::Published,
+ 'publish_status' => PublishStatus::Published,
]);
SocialAccount::connectIdentity(
@@ -391,14 +382,10 @@ test('a variant move resets a content type the new platform cannot publish', fun
'platform_user_id' => 'li-same',
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $pending = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $pending = Post::factory()->forAccount($account)->create([
'platform' => Platform::LinkedIn->value,
'content_type' => ContentType::LinkedInPost,
- 'status' => PostPlatformStatus::Pending,
+ 'publish_status' => PublishStatus::Pending,
]);
SocialAccount::connectIdentity(
@@ -413,21 +400,17 @@ test('a variant move resets a content type the new platform cannot publish', fun
->and($pending->fresh()->content_type)->toBe(ContentType::LinkedInPagePost);
});
-test('reconnecting the same variant leaves pending targets untouched', function () {
+test('reconnecting the same variant leaves pending posts untouched', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
'platform_user_id' => 'ig-same',
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $pending = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $pending = Post::factory()->forAccount($account)->create([
'platform' => Platform::Instagram->value,
'content_type' => ContentType::InstagramStory,
- 'status' => PostPlatformStatus::Pending,
+ 'publish_status' => PublishStatus::Pending,
]);
$before = $pending->updated_at;
@@ -445,7 +428,7 @@ test('reconnecting the same variant leaves pending targets untouched', function
->and($pending->fresh()->updated_at->equalTo($before))->toBeTrue();
});
-test('a variant move carries a retrying target, which still has a publish ahead of it', function () {
+test('a variant move carries a retrying post, which still has a publish ahead of it', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
@@ -453,13 +436,9 @@ test('a variant move carries a retrying target, which still has a publish ahead
'scopes' => ['instagram_business_content_publish'],
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $retrying = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $retrying = Post::factory()->forAccount($account)->create([
'platform' => Platform::Instagram->value,
- 'status' => PostPlatformStatus::Retrying,
+ 'publish_status' => PublishStatus::Retrying,
]);
SocialAccount::connectIdentity(
@@ -477,20 +456,16 @@ test('a variant move carries a retrying target, which still has a publish ahead
))->toBe([]);
});
-test('a variant move leaves a failed target on the platform it failed against', function () {
+test('a variant move leaves a failed post on the platform it failed against', function () {
$account = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::Instagram,
'platform_user_id' => 'shared-ig-id',
]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
-
- $failed = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
+ $failed = Post::factory()->forAccount($account)->create([
'platform' => Platform::Instagram->value,
- 'status' => PostPlatformStatus::Failed,
+ 'publish_status' => PublishStatus::Failed,
]);
SocialAccount::connectIdentity(
@@ -503,3 +478,29 @@ test('a variant move leaves a failed target on the platform it failed against',
expect($failed->fresh()->platform)->toBe(Platform::Instagram);
});
+
+test('reconnecting across a network variant moves only the posts still waiting to publish', function () {
+ $account = SocialAccount::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'platform' => Platform::LinkedIn,
+ 'platform_user_id' => 'li-move',
+ ]);
+ $retryAt = now()->addHour()->startOfSecond();
+ $pending = Post::factory()->forAccount($account, ContentType::LinkedInPost)->scheduled()->create();
+ $retrying = Post::factory()->forAccount($account, ContentType::LinkedInPost)->publishing()->create(['publish_status' => PublishStatus::Retrying, 'retry_at' => $retryAt]);
+ $published = Post::factory()->forAccount($account, ContentType::LinkedInPost)->published()->create();
+ $failed = Post::factory()->forAccount($account, ContentType::LinkedInPost)->failed()->create();
+
+ SocialAccount::connectIdentity($this->workspace, Platform::LinkedInPage, 'li-move', ['status' => Status::Connected], $account);
+
+ expect($pending->fresh())
+ ->platform->toBe(Platform::LinkedInPage)
+ ->content_type->toBe(ContentType::LinkedInPagePost)
+ ->and($retrying->fresh())
+ ->platform->toBe(Platform::LinkedInPage)
+ ->retry_at->toIso8601String()->toBe($retryAt->toIso8601String())
+ ->and($published->fresh())
+ ->platform->toBe(Platform::LinkedIn)
+ ->content_type->toBe(ContentType::LinkedInPost)
+ ->and($failed->fresh()->platform)->toBe(Platform::LinkedIn);
+});
diff --git a/tests/Feature/SocialControllerTest.php b/tests/Feature/SocialControllerTest.php
index a344e6d7a..daa888248 100644
--- a/tests/Feature/SocialControllerTest.php
+++ b/tests/Feature/SocialControllerTest.php
@@ -2,12 +2,9 @@
declare(strict_types=1);
-use App\Enums\Post\Status;
-use App\Enums\PostPlatform\Status as PlatformStatus;
use App\Enums\SocialAccount\Platform;
use App\Jobs\SendNotification;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -144,26 +141,11 @@ test('disconnect removes social account', function () {
test('disconnect deletes the channel drafts and published history', function () {
$account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $draftPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $draftPost = Post::factory()->forAccount($account)->draft()->create([
'user_id' => $this->user->id,
- 'status' => Status::Draft,
]);
- $publishedPost = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $publishedPost = Post::factory()->forAccount($account)->published()->create([
'user_id' => $this->user->id,
- 'status' => Status::Published,
- ]);
-
- PostPlatform::factory()->create([
- 'post_id' => $draftPost->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Pending,
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $publishedPost->id,
- 'social_account_id' => $account->id,
- 'status' => PlatformStatus::Published,
]);
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
@@ -176,17 +158,11 @@ test('disconnect deletes a google business post still waiting on the account and
Storage::fake();
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($account)->pendingReview()->create([
'user_id' => $this->user->id,
- 'status' => Status::Publishing,
- ]);
- $target = PostPlatform::factory()->googleBusiness()->pendingReview()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
'platform_post_id' => 'accounts/1/locations/2/localPosts/3',
]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
$this->actingAs($this->user)->delete(route('app.channels.disconnect', $account));
@@ -232,8 +208,7 @@ test('a workspace admin who is not the owner can disconnect a channel that lost
test('a member who needs approval cannot disconnect a channel or its posts', function () {
$member = workspaceMember($this->workspace, 'approval');
$account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
- $post = Post::factory()->create(['workspace_id' => $this->workspace->id, 'user_id' => $member->id, 'status' => Status::Draft]);
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
+ $post = Post::factory()->forAccount($account)->draft()->create(['user_id' => $member->id]);
$this->actingAs($member)->delete(route('app.channels.disconnect', $account))->assertForbidden();
diff --git a/tests/Feature/SplitLegacyActivePostsTest.php b/tests/Feature/SplitLegacyActivePostsTest.php
deleted file mode 100644
index dba1be25c..000000000
--- a/tests/Feature/SplitLegacyActivePostsTest.php
+++ /dev/null
@@ -1,424 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Actions\Media\AdoptWorkspaceLibrary;
-use App\Actions\Media\AuditMedia;
-use App\Actions\Media\DeleteOwnedMedia;
-use App\Actions\Post\UpdatePost;
-use App\Dto\MediaItem;
-use App\Enums\Post\Status;
-use App\Enums\PostPlatform\Status as PostPlatformStatus;
-use App\Events\PostCreated;
-use App\Events\PostStatusChanged;
-use App\Models\AnalyticsPublication;
-use App\Models\Media;
-use App\Models\Post;
-use App\Models\PostNote;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-use App\Models\WorkspaceLabel;
-use Illuminate\Support\Facades\Event;
-use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
-use Illuminate\Validation\ValidationException;
-
-test('split preserves IDs and clones labels, media and notes once', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- 'status' => Status::Scheduled,
- 'scheduled_at' => now()->addDay(),
- 'content' => 'Legacy shared caption',
- 'media' => [['id' => 'media-id', 'path' => 'posts/photo.jpg']],
- ]);
- $accounts = SocialAccount::factory()->count(3)->create(['workspace_id' => $workspace->id]);
- $first = PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $accounts[0]->id]);
- $second = PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $accounts[1]->id]);
- $disabled = PostPlatform::factory()->disabled()->create(['post_id' => $post->id, 'social_account_id' => $accounts[2]->id]);
- $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
- $post->labels()->attach($label);
- $comment = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $user->id]);
- $older = PostNote::factory()->create([
- 'post_id' => $post->id,
- 'user_id' => $user->id,
- 'updated_at' => now()->subDays(3),
- ]);
-
- Event::fake([PostCreated::class]);
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $clone = Post::whereKeyNot($post->id)->sole();
- expect(Post::count())->toBe(2)
- ->and($first->fresh()->post_id)->toBe($post->id)
- ->and($second->fresh()->post_id)->toBe($clone->id)
- ->and($disabled->fresh()->post_id)->toBe($post->id)
- ->and($clone->content)->toBe($post->content)
- ->and($clone->media)->toEqual($post->media)
- ->and($clone->scheduled_at->equalTo($post->scheduled_at))->toBeTrue()
- ->and($clone->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id])
- ->and($clone->notes()->count())->toBe(2)
- ->and($clone->notes()->where('body', $comment->body)->exists())->toBeTrue()
- ->and($clone->notes()->where('body', $older->body)->sole()->updated_at->equalTo($older->updated_at))->toBeTrue();
- Event::assertNotDispatched(PostCreated::class);
-});
-
-test('split leaves in-flight aggregates and settled ones with an unfinished target untouched', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $accounts = SocialAccount::factory()->count(2)->create(['workspace_id' => $workspace->id]);
- $publishing = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'status' => Status::Publishing]);
- $unfinished = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $user->id, 'status' => Status::PartiallyPublished]);
- foreach ($accounts as $account) {
- PostPlatform::factory()->create(['post_id' => $publishing->id, 'social_account_id' => $account->id]);
- }
- PostPlatform::factory()->published()->create(['post_id' => $unfinished->id, 'social_account_id' => $accounts[0]->id]);
- PostPlatform::factory()->create(['post_id' => $unfinished->id, 'social_account_id' => $accounts[1]->id, 'status' => PostPlatformStatus::PendingReview]);
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain('Left 1 settled post(s) with an unfinished target as they are.')
- ->assertSuccessful();
-
- expect(Post::count())->toBe(2)
- ->and(PostPlatform::count())->toBe(4)
- ->and($unfinished->fresh()->status)->toBe(Status::PartiallyPublished);
-});
-
-test('the original post remains editable after a split with a disabled target', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $accounts = SocialAccount::factory()->linkedin()->count(3)->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- 'status' => Status::Draft,
- 'content' => 'Original caption',
- 'media' => [],
- ]);
- $first = PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $accounts[0]->id]);
- $second = PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $accounts[1]->id]);
- $disabled = PostPlatform::factory()->disabled()->create(['post_id' => $post->id, 'social_account_id' => $accounts[2]->id]);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
- UpdatePost::execute($workspace, $post->fresh(), [
- 'status' => Status::Draft->value,
- 'content' => 'Changed caption',
- 'content_type' => $first->content_type->value,
- ]);
-
- expect($post->fresh()->content)->toBe('Changed caption')
- ->and($second->fresh()->post->content)->toBe('Original caption')
- ->and($disabled->fresh()->enabled)->toBeFalse();
-
- expect(fn () => UpdatePost::execute($workspace, $post->fresh(), [
- 'platforms' => [['id' => $disabled->id]],
- ]))->toThrow(ValidationException::class);
- expect($disabled->fresh()->enabled)->toBeFalse();
-});
-
-function legacyAggregatePost(Workspace $workspace, User $user, Status $status, int $targets, array $attributes = []): Post
-{
- $post = Post::factory()->create(array_merge([
- 'workspace_id' => $workspace->id,
- 'user_id' => $user->id,
- 'status' => $status,
- 'scheduled_at' => $status === Status::Scheduled ? now()->addDay() : null,
- ], $attributes));
-
- foreach (SocialAccount::factory()->count($targets)->create(['workspace_id' => $workspace->id]) as $account) {
- PostPlatform::factory()->create(['post_id' => $post->id, 'social_account_id' => $account->id]);
- }
-
- return $post;
-}
-
-test('split posts share one group and a re-run changes nothing', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $post = legacyAggregatePost($workspace, $user, Status::Scheduled, 3);
- $updatedAt = $post->fresh()->updated_at;
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain('Split 1 original posts and created 2 independent posts.')
- ->assertSuccessful();
-
- $groups = Post::query()->pluck('post_group_id', 'id');
- $groupId = $groups->get($post->id);
-
- expect($groups)->toHaveCount(3)
- ->and($groupId)->not->toBeNull()
- ->and($groups->unique()->values()->all())->toBe([$groupId])
- ->and($post->fresh()->updated_at->equalTo($updatedAt))->toBeTrue();
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain('Split 0 original posts and created 0 independent posts.')
- ->expectsOutputToContain('Grouped 0 multi-target posts.')
- ->assertSuccessful();
-
- expect(Post::count())->toBe(3)
- ->and(Post::query()->pluck('post_group_id', 'id')->all())->toEqual($groups->all());
-});
-
-test('split reuses a group the original already has', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $groupId = '0190a3b2-0000-7000-8000-0000000000aa';
- legacyAggregatePost($workspace, $user, Status::Draft, 2, ['post_group_id' => $groupId]);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- expect(Post::query()->pluck('post_group_id')->unique()->all())->toBe([$groupId]);
-});
-
-test('unsplit multi-target history gets its own group and single-target posts stay ungrouped', function () {
- $user = User::factory()->create();
- $workspace = Workspace::factory()->create(['user_id' => $user->id]);
- $published = legacyAggregatePost($workspace, $user, Status::Published, 2);
- $failed = legacyAggregatePost($workspace, $user, Status::Failed, 3);
- $partial = legacyAggregatePost($workspace, $user, Status::PartiallyPublished, 2);
- $single = legacyAggregatePost($workspace, $user, Status::Published, 1);
- $otherWorkspace = Workspace::factory()->create(['user_id' => $user->id]);
- $alreadyGrouped = legacyAggregatePost($otherWorkspace, $user, Status::Published, 2, ['post_group_id' => '0190a3b2-0000-7000-8000-0000000000bb']);
- $otherSingle = legacyAggregatePost($otherWorkspace, $user, Status::Draft, 1);
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain('Grouped 3 multi-target posts.')
- ->assertSuccessful();
-
- $groups = collect([$published, $failed, $partial])->map(fn (Post $post) => $post->fresh()->post_group_id);
-
- expect($groups->filter()->unique())->toHaveCount(3)
- ->and(Post::count())->toBe(6)
- ->and($single->fresh()->post_group_id)->toBeNull()
- ->and($otherSingle->fresh()->post_group_id)->toBeNull()
- ->and($alreadyGrouped->fresh()->post_group_id)->toBe('0190a3b2-0000-7000-8000-0000000000bb');
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain('Grouped 0 multi-target posts.')
- ->assertSuccessful();
-
- expect(collect([$published, $failed, $partial])->map(fn (Post $post) => $post->fresh()->post_group_id)->all())->toBe($groups->all());
-});
-
-/**
- * A legacy post on two channels whose one item points at a post-owned row,
- * as it is once the library was adopted or the post was edited.
- *
- * @return array{0: Post, 1: Media}
- */
-function splitPostWithOwnedMedia(Workspace $workspace, Status $status = Status::Draft): array
-{
- $post = legacyAggregatePost($workspace, $workspace->owner, $status, 2);
- $media = Media::factory()->ownedByPost($post)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($media->path, 'owned bytes');
- $post->forceFill(['media' => [[...MediaItem::fromMedia($media)->toArray(), 'meta' => ['alt_text' => 'Kept alt']]]])->saveQuietly();
-
- return [$post->fresh(), $media];
-}
-
-test('split after the library was adopted gives the copy its own media row and file', function () {
- Storage::fake();
- $workspace = Workspace::factory()->create();
- $asset = Media::factory()->libraryAsset($workspace)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($asset->path, 'library bytes');
- $post = legacyAggregatePost($workspace, $workspace->owner, Status::Scheduled, 2, [
- 'media' => [['id' => $asset->id, 'path' => $asset->path, 'url' => $asset->url, 'type' => 'image', 'mime_type' => 'image/jpeg', 'meta' => ['alt_text' => 'Kept alt']]],
- ]);
- AdoptWorkspaceLibrary::execute($workspace);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $clone = Post::query()->whereKeyNot($post->id)->sole();
- $originalRow = Media::query()->findOrFail(data_get($post->fresh()->media, '0.id'));
- $cloneRow = Media::query()->findOrFail(data_get($clone->media, '0.id'));
-
- expect($originalRow->post_id)->toBe($post->id)
- ->and($cloneRow->post_id)->toBe($clone->id)
- ->and($cloneRow->path)->not->toBe($originalRow->path)
- ->and(data_get($clone->media, '0.path'))->toBe($cloneRow->path)
- ->and(data_get($clone->media, '0.meta.alt_text'))->toBe('Kept alt')
- ->and(Storage::get($cloneRow->path))->toBe('library bytes')
- ->and(collect(AuditMedia::execute())->every(fn (array $findings): bool => $findings === []))->toBeTrue();
-
- DeleteOwnedMedia::forPosts([$clone->id]);
-
- Storage::assertMissing($cloneRow->path);
- Storage::assertExists($originalRow->path);
-});
-
-test('a legacy post edited before the split keeps its media and the copy gets its own', function () {
- Storage::fake();
- $workspace = Workspace::factory()->create();
- [$post, $media] = splitPostWithOwnedMedia($workspace);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $clone = Post::query()->whereKeyNot($post->id)->sole();
- $cloneRow = Media::query()->findOrFail(data_get($clone->media, '0.id'));
-
- expect($post->fresh()->media)->toEqual($post->media)
- ->and($media->fresh()->post_id)->toBe($post->id)
- ->and($cloneRow->post_id)->toBe($clone->id)
- ->and($cloneRow->id)->not->toBe($media->id)
- ->and(Storage::get($cloneRow->path))->toBe('owned bytes')
- ->and(Media::query()->count())->toBe(2)
- ->and(collect(AuditMedia::execute())->every(fn (array $findings): bool => $findings === []))->toBeTrue();
-});
-
-test('a copy whose media file is gone is not split and the run goes on', function () {
- Storage::fake();
- $workspace = Workspace::factory()->create();
- [$broken, $media] = splitPostWithOwnedMedia($workspace);
- Storage::delete($media->path);
- [$healthy] = splitPostWithOwnedMedia($workspace);
-
- $this->artisan('posts:split-legacy-active')
- ->expectsOutputToContain("Post {$broken->id} was not split")
- ->assertSuccessful();
-
- expect($broken->postPlatforms()->count())->toBe(2)
- ->and(Post::query()->count())->toBe(3)
- ->and($healthy->postPlatforms()->count())->toBe(1);
-});
-
-test('every item of the original lands on the copy in order, including items without an id and repeated ones', function () {
- Storage::fake();
- $workspace = Workspace::factory()->create();
- [$post, $owned] = splitPostWithOwnedMedia($workspace);
- $asset = Media::factory()->libraryAsset($workspace)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- $ownedItem = $post->media[0];
- $items = [
- ['url' => 'https://images.example/a.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'],
- ['url' => 'https://images.example/b.jpg', 'type' => 'image', 'mime_type' => 'image/jpeg'],
- $ownedItem,
- [...$ownedItem, 'meta' => ['alt_text' => 'Second use']],
- ['id' => 'legacy-id', 'path' => 'posts/photo.jpg', 'url' => 'https://cdn.example/photo.jpg', 'type' => 'image'],
- ['id' => $asset->id, 'path' => $asset->path, 'url' => $asset->url, 'type' => 'image'],
- ];
- $post->forceFill(['media' => $items])->saveQuietly();
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $clone = Post::query()->whereKeyNot($post->id)->sole();
- $copy = Media::query()->where('post_id', $clone->id)->sole();
- $swap = fn (array $item): array => [...$item, 'id' => $copy->id, 'path' => $copy->path, 'url' => $copy->url];
-
- expect($post->fresh()->media)->toEqual($items)
- ->and($clone->media)->toEqual([$items[0], $items[1], $swap($items[2]), $swap($items[3]), $items[4], $items[5]])
- ->and($owned->fresh()->post_id)->toBe($post->id);
-});
-
-test('a settled multi-target post becomes one post per network with the status of its own target, moving the targets', function () {
- $workspace = Workspace::factory()->create();
- $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => Status::PartiallyPublished,
- 'content' => 'Settled caption',
- 'published_at' => now()->subDay()->startOfSecond(),
- 'created_at' => now()->subDays(2)->startOfSecond(),
- ]);
- $post->labels()->attach($label);
- $note = PostNote::factory()->create(['post_id' => $post->id, 'user_id' => $workspace->user_id]);
- $youtube = PostPlatform::factory()->youtube()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id,
- 'platform_url' => 'https://youtube.com/watch?v=abc',
- ]);
- $instagram = PostPlatform::factory()->instagram()->failed()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id,
- 'error_message' => 'Media rejected',
- ]);
- $disabled = PostPlatform::factory()->disabled()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id]);
- $publication = AnalyticsPublication::factory()->create(['workspace_id' => $workspace->id, 'post_platform_id' => $youtube->id]);
- Event::fake([PostCreated::class, PostStatusChanged::class]);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $youtubePost = $youtube->fresh()->post;
- $instagramPost = $instagram->fresh()->post;
-
- expect(Post::query()->count())->toBe(2)
- ->and(PostPlatform::query()->count())->toBe(3)
- ->and($youtubePost->id)->not->toBe($instagramPost->id)
- ->and([$youtubePost->id, $instagramPost->id])->toContain($post->id)
- ->and($youtubePost->status)->toBe(Status::Published)
- ->and($instagramPost->status)->toBe(Status::Failed)
- ->and($youtubePost->post_group_id)->not->toBeNull()
- ->and($instagramPost->post_group_id)->toBe($youtubePost->post_group_id)
- ->and($youtube->fresh()->platform_url)->toBe('https://youtube.com/watch?v=abc')
- ->and($instagram->fresh()->error_message)->toBe('Media rejected')
- ->and($publication->fresh()->post_platform_id)->toBe($youtube->id)
- ->and($disabled->fresh()->post_id)->toBe($post->id)
- ->and(Post::query()->where('status', Status::PartiallyPublished)->exists())->toBeFalse();
-
- foreach ([$youtubePost, $instagramPost] as $split) {
- expect($split->content)->toBe('Settled caption')
- ->and($split->user_id)->toBe($post->user_id)
- ->and($split->published_at?->toIso8601String())->toBe($split->postPlatforms()->enabled()->sole()->published_at?->toIso8601String())
- ->and($split->created_at->equalTo($post->created_at))->toBeTrue()
- ->and($split->labels()->pluck('workspace_labels.id')->all())->toBe([$label->id])
- ->and($split->notes()->pluck('body')->all())->toBe([$note->body])
- ->and($split->postPlatforms()->enabled()->count())->toBe(1);
- }
-
- Event::assertNotDispatched(PostCreated::class);
- Event::assertNotDispatched(PostStatusChanged::class);
-});
-
-test('a partially published post left with one target takes that target status', function () {
- $workspace = Workspace::factory()->create();
- $post = Post::factory()->create(['workspace_id' => $workspace->id, 'user_id' => $workspace->user_id, 'status' => Status::PartiallyPublished]);
- PostPlatform::factory()->published()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id]);
- PostPlatform::factory()->disabled()->create(['post_id' => $post->id, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id]);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- expect($post->fresh()->status)->toBe(Status::Published)
- ->and(Post::query()->count())->toBe(1);
-});
-
-test('each settled post takes published_at from its own target and keeps the original created_at, scheduled_at and updated_at', function () {
- Storage::fake();
- $workspace = Workspace::factory()->create();
- $publishedAt = now()->subDays(20)->startOfSecond();
- $createdAt = now()->subDays(22)->startOfSecond();
- $updatedAt = now()->subDays(19)->startOfSecond();
- $post = Post::factory()->create([
- 'workspace_id' => $workspace->id,
- 'user_id' => $workspace->user_id,
- 'status' => Status::PartiallyPublished,
- 'scheduled_at' => $publishedAt,
- 'published_at' => $publishedAt,
- ]);
- $media = Media::factory()->ownedByPost($post)->create(['path' => 'medias/'.Str::uuid().'.jpg']);
- Storage::put($media->path, 'bytes');
- $post->forceFill(['media' => [MediaItem::fromMedia($media)->toArray()]])->saveQuietly();
- Post::query()->whereKey($post->id)->toBase()->update(['created_at' => $createdAt, 'updated_at' => $updatedAt]);
- $youtube = PostPlatform::factory()->youtube()->published()->create(['post_id' => $post->id, 'published_at' => $publishedAt, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id]);
- $instagram = PostPlatform::factory()->instagram()->failed()->create(['post_id' => $post->id, 'published_at' => null, 'social_account_id' => SocialAccount::factory()->create(['workspace_id' => $workspace->id])->id]);
-
- $this->artisan('posts:split-legacy-active')->assertSuccessful();
-
- $youtubePost = $youtube->fresh()->post;
- $instagramPost = $instagram->fresh()->post;
-
- expect($youtubePost->published_at->equalTo($publishedAt))->toBeTrue()
- ->and($instagramPost->status)->toBe(Status::Failed)
- ->and($instagramPost->published_at)->toBeNull();
-
- foreach ([$youtubePost, $instagramPost] as $split) {
- expect($split->created_at->equalTo($createdAt))->toBeTrue()
- ->and($split->scheduled_at->equalTo($publishedAt))->toBeTrue()
- ->and($split->updated_at->equalTo($updatedAt))->toBeTrue();
- }
-});
diff --git a/tests/Feature/ThreadRepliesPreviewTest.php b/tests/Feature/ThreadRepliesPreviewTest.php
index e8ef9665c..a80211641 100644
--- a/tests/Feature/ThreadRepliesPreviewTest.php
+++ b/tests/Feature/ThreadRepliesPreviewTest.php
@@ -3,21 +3,15 @@
declare(strict_types=1);
use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
use App\Services\Post\PostPreviewer;
test('previews thread replies with the network sanitizer', function () {
- $post = Post::factory()->create(['content' => 'Root']);
- $account = SocialAccount::factory()->bluesky()->create(['workspace_id' => $post->workspace_id]);
- PostPlatform::factory()->bluesky()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $post = Post::factory()->bluesky()->create([
+ 'content' => 'Root',
'meta' => ['thread_replies' => ['<p>Second</p>', ['text' => '<p>Third</p>', 'media' => [['id' => 'media-1', 'url' => 'https://cdn.test/one.jpg']]]]],
]);
- $preview = app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0];
+ $preview = app(PostPreviewer::class)->forPost($post->fresh());
expect($preview['thread_replies'])->toEqual([
['text' => 'Second', 'media' => []],
@@ -26,14 +20,10 @@ test('previews thread replies with the network sanitizer', function () {
});
test('networks that cannot chain get no thread preview', function () {
- $post = Post::factory()->create(['content' => 'Root']);
- $account = SocialAccount::factory()->threads()->create(['workspace_id' => $post->workspace_id]);
- PostPlatform::factory()->threads()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $post = Post::factory()->threads()->create([
+ 'content' => 'Root',
'meta' => ['thread_replies' => ['Two']],
]);
- expect(app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0])->not->toHaveKey('thread_replies');
+ expect(app(PostPreviewer::class)->forPost($post->fresh()))->not->toHaveKey('thread_replies');
});
diff --git a/tests/Feature/ThreadReplyMediaTest.php b/tests/Feature/ThreadReplyMediaTest.php
index e0cc5cc5c..b3bad8667 100644
--- a/tests/Feature/ThreadReplyMediaTest.php
+++ b/tests/Feature/ThreadReplyMediaTest.php
@@ -15,6 +15,7 @@ use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
+use App\Support\PostCompositionValidator;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
@@ -49,7 +50,7 @@ test('a reply keeps its own media, owned by the post and apart from the root med
'Three',
], [MediaItem::fromMedia($rootImage)->toArray()], 'scheduled');
- $replies = $post->postPlatforms()->sole()->meta['thread_replies'];
+ $replies = $post->fresh()->meta['thread_replies'];
expect(collect($post->fresh()->media)->pluck('id')->all())->toBe([$rootImage->id])
->and($replies[0]['text'])->toBe('Two')
@@ -86,6 +87,49 @@ test('a reply takes the media rules of a post on its network', function () {
}
});
+test('editing a reply with a media that no longer exists fails on that reply item', function () {
+ $post = threadReplyMediaPost($this, ['Two']);
+ $image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ $item = MediaItem::fromMedia($image)->toArray();
+ $image->delete();
+
+ try {
+ UpdatePost::execute($this->workspace, $post->fresh(), [
+ 'status' => 'draft',
+ 'meta' => ['thread_replies' => [['text' => 'Two', 'media' => [$item]]]],
+ ], $this->user);
+ $this->fail('A reply media that was deleted should not save.');
+ } catch (ValidationException $e) {
+ expect($e->errors())->toHaveKey('meta.thread_replies.0.media.0');
+ }
+});
+
+test('a reply media that no longer exists fails on that destination reply in a batch', function () {
+ $image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ $item = MediaItem::fromMedia($image)->toArray();
+ $image->delete();
+
+ try {
+ threadReplyMediaPost($this, [['text' => 'Two', 'media' => [$item]]]);
+ $this->fail('A reply media that was deleted should not save.');
+ } catch (ValidationException $e) {
+ expect($e->errors())->toHaveKey('destinations.0.meta.thread_replies.0.media.0');
+ }
+});
+
+test('a single post keeps the reply media error under its own meta', function () {
+ $image = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
+ $item = MediaItem::fromMedia($image)->toArray();
+ $image->delete();
+
+ try {
+ PostCompositionValidator::forSinglePost(fn (): Post => threadReplyMediaPost($this, [['text' => 'Two', 'media' => [$item]]]));
+ $this->fail('A reply media that was deleted should not save.');
+ } catch (ValidationException $e) {
+ expect($e->errors())->toHaveKey('meta.thread_replies.0.media.0');
+ }
+});
+
test('removing a reply media deletes its row and appending to the root keeps the reply media', function () {
$replyImage = Media::factory()->stored()->temporaryUpload($this->workspace)->create();
$post = threadReplyMediaPost($this, [['text' => 'Two', 'media' => [MediaItem::fromMedia($replyImage)->toArray()]]]);
@@ -94,7 +138,7 @@ test('removing a reply media deletes its row and appending to the root keeps the
AppendPostMedia::execute($post->fresh(), [MediaItem::fromMedia($rootImage)->toArray()], $this->user);
expect(Media::query()->whereKey($replyImage->id)->exists())->toBeTrue()
- ->and($post->postPlatforms()->sole()->meta['thread_replies'][0]['media'][0]['id'])->toBe($replyImage->id);
+ ->and($post->fresh()->meta['thread_replies'][0]['media'][0]['id'])->toBe($replyImage->id);
UpdatePost::execute($this->workspace, $post->fresh(), [
'status' => PostStatus::Draft->value,
@@ -110,7 +154,7 @@ test('a duplicate copies the reply media and deleting the post deletes it', func
$post = threadReplyMediaPost($this, [['text' => 'Two', 'media' => [MediaItem::fromMedia($replyImage)->toArray()]]]);
$copy = DuplicatePost::execute($post->fresh(), $this->user);
- $copiedId = $copy->postPlatforms()->sole()->meta['thread_replies'][0]['media'][0]['id'];
+ $copiedId = $copy->fresh()->meta['thread_replies'][0]['media'][0]['id'];
expect($copiedId)->not->toBe($replyImage->id)
->and(Media::query()->find($copiedId)->post_id)->toBe($copy->id);
diff --git a/tests/Feature/UpdateChannelPostTest.php b/tests/Feature/UpdateChannelPostTest.php
index 3b6f436db..ed183bb97 100644
--- a/tests/Feature/UpdateChannelPostTest.php
+++ b/tests/Feature/UpdateChannelPostTest.php
@@ -9,7 +9,6 @@ use App\Enums\Post\Action as PostAction;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -44,10 +43,10 @@ test('editing one Instagram post changes its type, media and caption without cha
expect($posts[0]->fresh()->content)->toBe('Legenda do Reel')
->and($posts[0]->fresh()->status)->toBe(PostStatus::Scheduled)
- ->and($posts[0]->postPlatforms()->sole()->content_type)->toBe(ContentType::InstagramReel)
- ->and($posts[0]->postPlatforms()->sole()->social_account_id)->toBe($accounts[0]->id)
+ ->and($posts[0]->fresh()->content_type)->toBe(ContentType::InstagramReel)
+ ->and($posts[0]->fresh()->social_account_id)->toBe($accounts[0]->id)
->and($posts[1]->fresh()->content)->toBe('Texto inicial')
- ->and($posts[1]->postPlatforms()->sole()->content_type)->toBe(ContentType::InstagramFeed);
+ ->and($posts[1]->fresh()->content_type)->toBe(ContentType::InstagramFeed);
});
test('an incompatible type and media leaves the edited post unchanged', function () {
@@ -71,7 +70,7 @@ test('an incompatible type and media leaves the edited post unchanged', function
expect($post->fresh()->content)->toBe('Antes')
->and($post->fresh()->status)->toBe(PostStatus::Draft)
- ->and($post->postPlatforms()->sole()->content_type)->toBe(ContentType::InstagramFeed);
+ ->and($post->fresh()->content_type)->toBe(ContentType::InstagramFeed);
});
test('the selected social account cannot change during edit', function () {
@@ -93,33 +92,25 @@ test('the selected social account cannot change during edit', function () {
'platforms' => [['social_account_id' => $accounts[1]->id]],
]))->toThrow(ValidationException::class);
- expect($post->postPlatforms()->sole()->social_account_id)->toBe($accounts[0]->id);
+ expect($post->fresh()->social_account_id)->toBe($accounts[0]->id);
});
-test('settled posts and legacy multi-target posts cannot use the independent editor', function () {
+test('a settled post cannot use the independent editor', function () {
$user = User::factory()->create();
$workspace = Workspace::factory()->create(['user_id' => $user->id]);
$instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
- $xAccount = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);
$post = CreatePosts::execute($workspace, $user, [
'status' => 'draft',
'destinations' => [['social_account_id' => $instagram->id, 'content_type' => ContentType::InstagramFeed->value]],
])->sole();
- PostPlatform::factory()->x()->create(['post_id' => $post->id, 'social_account_id' => $xAccount->id]);
-
- expect(fn () => UpdatePost::execute($workspace, $post, [
- 'status' => PostStatus::Draft->value,
- 'content_type' => ContentType::InstagramStory->value,
- ]))->toThrow(ValidationException::class);
-
- $post->postPlatforms()->where('social_account_id', $xAccount->id)->delete();
$post->update(['status' => PostStatus::Published]);
expect(UpdatePost::execute($workspace, $post, [
'status' => PostStatus::Draft->value,
'content_type' => ContentType::InstagramStory->value,
- ])['action'])->toBe(PostAction::Finalized);
+ ])['action'])->toBe(PostAction::Finalized)
+ ->and($post->fresh()->content_type)->toBe(ContentType::InstagramFeed);
});
test('an edit stores only known meta keys and keeps the system-written ones', function () {
@@ -131,15 +122,14 @@ test('an edit stores only known meta keys and keeps the system-written ones', fu
'content' => 'Caption',
'destinations' => [['social_account_id' => $account->id]],
])->sole();
- $target = $post->postPlatforms()->sole();
- $target->update(['meta' => ['reactions' => [['type' => '👍', 'count' => 3]], 'aspect_ratio' => '4:5']]);
+ $post->forceFill(['meta' => ['reactions' => [['type' => '👍', 'count' => 3]], 'aspect_ratio' => '4:5']])->save();
UpdatePost::execute($workspace, $post, [
'status' => 'draft',
'meta' => ['bogus_key' => 'zzz', 'aspect_ratio' => '1:1', 'is_ai_generated' => true, 'reactions' => []],
]);
- expect($target->fresh()->meta)->toEqual([
+ expect($post->fresh()->meta)->toEqual([
'is_ai_generated' => true,
'reactions' => [['type' => '👍', 'count' => 3]],
]);
diff --git a/tests/Feature/UpdatePostRequestTest.php b/tests/Feature/UpdatePostRequestTest.php
index 6051441f0..e73ea48fd 100644
--- a/tests/Feature/UpdatePostRequestTest.php
+++ b/tests/Feature/UpdatePostRequestTest.php
@@ -8,53 +8,49 @@ use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\TikTok\PrivacyLevel;
+use App\Jobs\Analytics\BootstrapAccountAnalytics;
+use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\PublishPost;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
-use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
test('youtube description checks effective web metadata before scheduling or publishing', function (string $patch, bool $allowed, string $status) {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $this->post->update([
+ $post = Post::factory()->forAccount($account)->youtube()->create([
+ 'user_id' => $this->user->id,
'content' => 'Short title',
'status' => Status::Draft,
'media' => $this->mediaPayload,
- ]);
- $this->postPlatform->update(['enabled' => false]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
'meta' => ['description' => str_repeat('a', 5001)],
]);
$data = [
'status' => $status,
'scheduled_at' => now()->addHour()->toIso8601String(),
'media' => $this->mediaPayload,
+ 'content_type' => ContentType::YouTubeShort->value,
];
if ($patch !== 'omit') {
$data['meta'] = $patch === 'row' ? [] : ['description' => $patch === 'clear' ? null : 'Valid description'];
}
Queue::fake();
- $response = $this->actingAs($this->user)->put(route('app.posts.update', $this->post), $data);
+ $response = $this->actingAs($this->user)->put(route('app.posts.update', $post), $data);
if ($allowed) {
$response->assertSessionHasNoErrors();
- expect($this->post->fresh()->status->value)->toBe($status);
+ expect($post->fresh()->status->value)->toBe($status);
if ($status === Status::Publishing->value) {
Queue::assertPushed(PublishPost::class);
}
} else {
- $response->assertSessionHasErrors('destinations.0.meta.description');
- expect($this->post->fresh()->status)->toBe(Status::Draft);
+ $response->assertSessionHasErrors('meta.description');
+ expect($post->fresh()->status)->toBe(Status::Draft);
Queue::assertNotPushed(PublishPost::class);
}
})->with([
@@ -64,41 +60,27 @@ test('youtube description checks effective web metadata before scheduling or pub
'cleared description' => ['clear', true],
])->with([Status::Scheduled->value, Status::Publishing->value]);
-test('youtube description reports and persists independent selected channel values', function () {
- $platforms = collect(range(1, 2))->map(function () {
- $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+test('youtube description is validated and persisted on a draft', function () {
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($account)->youtube()->create(['user_id' => $this->user->id, 'meta' => []]);
- return PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'meta' => [],
- ]);
- });
- $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Draft->value,
- 'platforms' => [
- ['id' => $platforms[0]->id, 'meta' => ['description' => 'First channel']],
- ['id' => $platforms[1]->id, 'meta' => ['description' => str_repeat('é', 2501)]],
- ],
- ])->assertSessionHasErrors('platforms.1.meta.description')->assertSessionDoesntHaveErrors('platforms.0.meta.description');
- $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ 'meta' => ['description' => str_repeat('é', 2501)],
+ ])->assertSessionHasErrors('meta.description');
+ $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Draft->value,
'content' => 'Short title',
- 'platforms' => [
- ['id' => $platforms[0]->id, 'meta' => ['description' => 'First channel']],
- ['id' => $platforms[1]->id, 'meta' => ['description' => str_repeat('é', 2500)]],
- ],
+ 'meta' => ['description' => str_repeat('é', 2500)],
])->assertSessionHasNoErrors();
- expect(data_get($platforms[0]->fresh()->meta, 'description'))->toBe('First channel')
- ->and(data_get($platforms[1]->fresh()->meta, 'description'))->toBe(str_repeat('é', 2500))
- ->and($this->post->fresh()->content)->toBe('Short title');
+ expect(data_get($post->fresh()->meta, 'description'))->toBe(str_repeat('é', 2500))
+ ->and($post->fresh()->content)->toBe('Short title');
});
test('youtube description update reports one validation message', function (bool $hasSubmittedError) {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->youtube()->create([
+ 'user_id' => $this->user->id,
'meta' => ['description' => str_repeat('a', 5001)],
]);
$data = [
@@ -106,19 +88,16 @@ test('youtube description update reports one validation message', function (bool
'scheduled_at' => now()->addHour()->toIso8601String(),
'content' => 'Short title',
'media' => $this->mediaPayload,
- 'platforms' => [[
- 'id' => $platform->id,
- 'content_type' => ContentType::YouTubeShort->value,
- ]],
+ 'content_type' => ContentType::YouTubeShort->value,
];
- $key = 'platforms.0.meta.description';
if ($hasSubmittedError) {
- $data['platforms'][0]['meta'] = ['description' => str_repeat('é', 2501)];
+ $data['meta'] = ['description' => str_repeat('é', 2501)];
}
- $this->actingAs($this->user)->put(route('app.posts.update', $this->post), $data)
- ->assertSessionHasErrors($key);
+ $response = $this->actingAs($this->user)->put(route('app.posts.update', $post), $data);
+ $key = 'meta.description';
+ $response->assertSessionHasErrors($key);
expect(session('errors')->get($key))->toBe([
__('posts.form.youtube.description_max'),
@@ -128,55 +107,35 @@ test('youtube description update reports one validation message', function (bool
'submitted invalid description' => [true],
]);
-test('youtube description validation keeps submitted channel order and rolls back updates', function () {
+test('youtube description validation rolls back the edit', function () {
$account = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $platform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $post = Post::factory()->forAccount($account)->youtube()->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Original title',
'meta' => ['description' => str_repeat('a', 5001)],
]);
- $secondAccount = SocialAccount::factory()->youtube()->create(['workspace_id' => $this->workspace->id]);
- $secondPlatform = PostPlatform::factory()->youtube()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $secondAccount->id,
- 'enabled' => false,
- 'meta' => ['description' => 'Valid description'],
- ]);
- $this->post->update(['content' => 'Original title']);
- $this->actingAs($this->user)->put(route('app.posts.update', $this->post), [
+ $this->actingAs($this->user)->put(route('app.posts.update', $post), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
'content' => 'Changed title',
'media' => $this->mediaPayload,
- 'platforms' => [
- ['id' => $secondPlatform->id, 'content_type' => ContentType::YouTubeShort->value],
- ['id' => $platform->id, 'content_type' => ContentType::YouTubeShort->value],
- ],
- ])->assertSessionHasErrors('platforms.1.meta.description')
- ->assertSessionDoesntHaveErrors('platforms.0.meta.description');
-
- expect($this->post->fresh()->status)->toBe(Status::Draft)
- ->and($this->post->fresh()->content)->toBe('Original title')
- ->and($this->post->fresh()->scheduled_at)->toBeNull()
- ->and($platform->fresh()->enabled)->toBeTrue()
- ->and($secondPlatform->fresh()->enabled)->toBeFalse()
- ->and($this->postPlatform->fresh()->enabled)->toBeTrue();
+ 'content_type' => ContentType::YouTubeShort->value,
+ ])->assertSessionHasErrors('meta.description');
+
+ expect($post->fresh()->status)->toBe(Status::Draft)
+ ->and($post->fresh()->content)->toBe('Original title')
+ ->and($post->fresh()->scheduled_at)->toBeNull();
});
beforeEach(function () {
Storage::fake();
+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->workspace->members()->attach($this->user->id, membershipPivot('member'));
$this->user->update(['current_workspace_id' => $this->workspace->id]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
// Media payload used by tests that need to satisfy ContentTypeCompatibleWithMedia.
$video = Media::factory()->stored()->video()->temporaryUpload($this->workspace)->create([
'size' => 100_000,
@@ -187,10 +146,8 @@ beforeEach(function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::TikTok,
]);
- $this->postPlatform = PostPlatform::factory()->tiktok()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- // Override factory default so we control privacy_level per test.
+ $this->post = Post::factory()->forAccount($this->socialAccount, ContentType::TikTokVideo)->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
});
@@ -200,16 +157,11 @@ test('publishing a tiktok post without privacy_level is rejected', function () {
->put(route('app.posts.update', $this->post), [
'status' => Status::Publishing->value,
'media' => $this->mediaPayload,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.meta.privacy_level');
+ $response->assertSessionHasErrors('meta.privacy_level');
});
test('publishing a tiktok post with privacy_level passes privacy_level validation', function () {
@@ -217,16 +169,11 @@ test('publishing a tiktok post with privacy_level passes privacy_level validatio
->put(route('app.posts.update', $this->post), [
'status' => Status::Publishing->value,
'media' => $this->mediaPayload,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
- ],
- ],
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => PrivacyLevel::SelfOnly->value],
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.meta.privacy_level']);
+ $response->assertSessionDoesntHaveErrors(['meta.privacy_level']);
});
test('scheduling a bluesky post with a mov video is not rejected on format', function () {
@@ -234,15 +181,14 @@ test('scheduling a bluesky post with a mov video is not rejected on format', fun
'workspace_id' => $this->workspace->id,
'platform' => Platform::Bluesky,
]);
- $blueskyPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $blueskyAccount->id,
+ $blueskyPost = Post::factory()->forAccount($blueskyAccount)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Bluesky,
'content_type' => ContentType::BlueskyPost,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $blueskyPost), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
'media' => [[
@@ -253,12 +199,10 @@ test('scheduling a bluesky post with a mov video is not rejected on format', fun
'mime_type' => 'video/quicktime',
'original_filename' => 'clip.mov',
]],
- 'platforms' => [
- ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],
- ],
+ 'content_type' => ContentType::BlueskyPost->value,
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.content_type']);
+ $response->assertSessionDoesntHaveErrors(['content_type']);
});
test('publishing a bluesky post with an oversized video is rejected server-side', function () {
@@ -266,15 +210,14 @@ test('publishing a bluesky post with an oversized video is rejected server-side'
'workspace_id' => $this->workspace->id,
'platform' => Platform::Bluesky,
]);
- $blueskyPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $blueskyAccount->id,
+ $blueskyPost = Post::factory()->forAccount($blueskyAccount)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Bluesky,
'content_type' => ContentType::BlueskyPost,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $blueskyPost), [
'status' => Status::Publishing->value,
'media' => [[
'id' => 'test-media-big',
@@ -285,14 +228,12 @@ test('publishing a bluesky post with an oversized video is rejected server-side'
'original_filename' => 'big.mp4',
'size' => 300_000_001,
]],
- 'platforms' => [
- ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],
- ],
+ 'content_type' => ContentType::BlueskyPost->value,
]);
// Bluesky's cap is decimal, so both numbers render in decimal units.
$response->assertSessionHasErrors([
- 'platforms.0.content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '300.0 MB']),
+ 'content_type' => trans('posts.form.warnings.video_too_large', ['max' => '300 MB', 'current' => '300.0 MB']),
]);
});
@@ -301,15 +242,14 @@ test('publishing a bluesky post with a video over the duration cap is rejected s
'workspace_id' => $this->workspace->id,
'platform' => Platform::Bluesky,
]);
- $blueskyPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $blueskyAccount->id,
+ $blueskyPost = Post::factory()->forAccount($blueskyAccount)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Bluesky,
'content_type' => ContentType::BlueskyPost,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $blueskyPost), [
'status' => Status::Publishing->value,
'media' => [[
'id' => 'test-media-long',
@@ -321,12 +261,10 @@ test('publishing a bluesky post with a video over the duration cap is rejected s
'size' => 50_000_000,
'meta' => ['duration' => 601.5],
]],
- 'platforms' => [
- ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],
- ],
+ 'content_type' => ContentType::BlueskyPost->value,
]);
- $response->assertSessionHasErrors(['platforms.0.content_type' => 'Video is 10min 2s long, but this post type allows up to 10min.']);
+ $response->assertSessionHasErrors(['content_type' => 'Video is 10min 2s long, but this post type allows up to 10min.']);
});
test('saving a draft does not enforce media compatibility', function () {
@@ -334,15 +272,14 @@ test('saving a draft does not enforce media compatibility', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Bluesky,
]);
- $blueskyPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $blueskyAccount->id,
+ $blueskyPost = Post::factory()->forAccount($blueskyAccount)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Bluesky,
'content_type' => ContentType::BlueskyPost,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $blueskyPost), [
'status' => Status::Draft->value,
'media' => [[
'id' => 'test-media-mov',
@@ -352,12 +289,10 @@ test('saving a draft does not enforce media compatibility', function () {
'mime_type' => 'video/quicktime',
'original_filename' => 'clip.mov',
]],
- 'platforms' => [
- ['id' => $blueskyPlatform->id, 'content_type' => ContentType::BlueskyPost->value],
- ],
+ 'content_type' => ContentType::BlueskyPost->value,
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.content_type']);
+ $response->assertSessionDoesntHaveErrors(['content_type']);
});
test('publishing a pinterest post without board_id is rejected', function () {
@@ -365,9 +300,8 @@ test('publishing a pinterest post without board_id is rejected', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
@@ -383,19 +317,14 @@ test('publishing a pinterest post without board_id is rejected', function () {
];
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Publishing->value,
'media' => $mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.meta.board_id');
+ $response->assertSessionHasErrors('meta.board_id');
});
test('publishing a pinterest post with board_id passes board validation', function () {
@@ -403,9 +332,8 @@ test('publishing a pinterest post with board_id passes board validation', functi
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
@@ -421,19 +349,14 @@ test('publishing a pinterest post with board_id passes board validation', functi
];
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Publishing->value,
'media' => $mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => ['board_id' => '123456789'],
- ],
- ],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => ['board_id' => '123456789'],
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.meta.board_id']);
+ $response->assertSessionDoesntHaveErrors(['meta.board_id']);
});
test('scheduling a pinterest post without board_id is rejected', function () {
@@ -441,9 +364,8 @@ test('scheduling a pinterest post without board_id is rejected', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
@@ -459,20 +381,15 @@ test('scheduling a pinterest post without board_id is rejected', function () {
];
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'media' => $mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.meta.board_id');
+ $response->assertSessionHasErrors('meta.board_id');
});
test('publishing a pinterest carousel without board_id is rejected', function () {
@@ -480,9 +397,8 @@ test('publishing a pinterest carousel without board_id is rejected', function ()
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterestCarousel()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterestCarousel()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
@@ -506,19 +422,14 @@ test('publishing a pinterest carousel without board_id is rejected', function ()
];
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Publishing->value,
'media' => $mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestCarousel->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::PinterestCarousel->value,
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.meta.board_id');
+ $response->assertSessionHasErrors('meta.board_id');
});
test('publishing a pinterest video pin without board_id is rejected', function () {
@@ -526,82 +437,20 @@ test('publishing a pinterest video pin without board_id is rejected', function (
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterestVideoPin()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterestVideoPin()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Publishing->value,
'media' => $this->mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestVideoPin->value,
- 'meta' => [],
- ],
- ],
- ]);
-
- $response->assertSessionHasErrors('platforms.0.meta.board_id');
-});
-
-test('pinterest board error does not block other platforms in multi-platform publish', function () {
- $pinterestAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::Pinterest,
- ]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
- 'meta' => [],
- ]);
-
- $linkedinAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::LinkedIn,
- ]);
- $linkedinPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $linkedinAccount->id,
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'meta' => [],
- ]);
-
- $mediaPayload = [
- [
- 'id' => 'test-image',
- 'path' => 'media/2026-01/pin.jpg',
- 'url' => 'https://example.com/media/2026-01/pin.jpg',
- 'type' => 'image',
- 'mime_type' => 'image/jpeg',
- 'original_filename' => 'pin.jpg',
- ],
- ];
-
- $response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
- 'status' => Status::Publishing->value,
- 'media' => $mediaPayload,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [],
- ],
- [
- 'id' => $linkedinPlatform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::PinterestVideoPin->value,
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.meta.board_id');
- $response->assertSessionDoesntHaveErrors(['platforms.1.meta.board_id']);
+ $response->assertSessionHasErrors('meta.board_id');
});
test('saving a pinterest post as draft without board_id skips the board rule', function () {
@@ -609,25 +458,19 @@ test('saving a pinterest post as draft without board_id skips the board rule', f
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Draft->value,
- 'platforms' => [
- [
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [],
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.meta.board_id']);
+ $response->assertSessionDoesntHaveErrors(['meta.board_id']);
});
test('publishing a tiktok post with an unknown privacy_level is rejected', function () {
@@ -635,16 +478,11 @@ test('publishing a tiktok post with an unknown privacy_level is rejected', funct
->put(route('app.posts.update', $this->post), [
'status' => Status::Publishing->value,
'media' => $this->mediaPayload,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => ['privacy_level' => 'EVERYONE'],
- ],
- ],
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => ['privacy_level' => 'EVERYONE'],
]);
- $response->assertSessionHasErrors('platforms.0.meta.privacy_level');
+ $response->assertSessionHasErrors('meta.privacy_level');
});
test('publishing a tiktok post as self only branded content is rejected', function () {
@@ -652,35 +490,25 @@ test('publishing a tiktok post as self only branded content is rejected', functi
->put(route('app.posts.update', $this->post), [
'status' => Status::Publishing->value,
'media' => $this->mediaPayload,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => [
- 'privacy_level' => PrivacyLevel::SelfOnly->value,
- 'brand_content_toggle' => true,
- ],
- ],
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => [
+ 'privacy_level' => PrivacyLevel::SelfOnly->value,
+ 'brand_content_toggle' => true,
],
]);
- $response->assertSessionHasErrors(['platforms.0.meta.privacy_level' => trans('posts.form.tiktok.privacy.private_disabled_branded')]);
+ $response->assertSessionHasErrors(['meta.privacy_level' => trans('posts.form.tiktok.privacy.private_disabled_branded')]);
});
test('saving a tiktok post as draft without privacy_level skips the privacy_level rule', function () {
$response = $this->actingAs($this->user)
->put(route('app.posts.update', $this->post), [
'status' => Status::Draft->value,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => ContentType::TikTokVideo->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::TikTokVideo->value,
+ 'meta' => [],
]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.meta.privacy_level']);
+ $response->assertSessionDoesntHaveErrors(['meta.privacy_level']);
});
test('scheduling a threads post over 500 chars is rejected with the platform name', function () {
@@ -688,23 +516,17 @@ test('scheduling a threads post over 500 chars is rejected with the platform nam
'workspace_id' => $this->workspace->id,
'platform' => Platform::Threads,
]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $threadsAccount->id,
+ $threadsPost = Post::factory()->forAccount($threadsAccount)->threads()->create([
+ 'user_id' => $this->user->id,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $threadsPost), [
'status' => Status::Scheduled->value,
'content' => str_repeat('a', 537),
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- [
- 'id' => $threadsPlatform->id,
- 'content_type' => ContentType::ThreadsPost->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => [],
]);
$response->assertSessionHasErrors('content');
@@ -719,23 +541,17 @@ test('scheduling a threads post within 500 chars passes content-length validatio
'workspace_id' => $this->workspace->id,
'platform' => Platform::Threads,
]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $threadsAccount->id,
+ $threadsPost = Post::factory()->forAccount($threadsAccount)->threads()->create([
+ 'user_id' => $this->user->id,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $threadsPost), [
'status' => Status::Scheduled->value,
'content' => str_repeat('a', 500),
'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- [
- 'id' => $threadsPlatform->id,
- 'content_type' => ContentType::ThreadsPost->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => [],
]);
$response->assertSessionDoesntHaveErrors('content');
@@ -746,70 +562,21 @@ test('saving an over-limit threads post as draft skips the content-length rule',
'workspace_id' => $this->workspace->id,
'platform' => Platform::Threads,
]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $threadsAccount->id,
+ $threadsPost = Post::factory()->forAccount($threadsAccount)->threads()->create([
+ 'user_id' => $this->user->id,
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $threadsPost), [
'status' => Status::Draft->value,
'content' => str_repeat('a', 1000),
- 'platforms' => [
- [
- 'id' => $threadsPlatform->id,
- 'content_type' => ContentType::ThreadsPost->value,
- 'meta' => [],
- ],
- ],
+ 'content_type' => ContentType::ThreadsPost->value,
+ 'meta' => [],
]);
$response->assertSessionDoesntHaveErrors('content');
});
-test('scheduling across multiple platforms enforces the strictest content-length cap', function () {
- $facebookAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::Facebook,
- ]);
- $facebookPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $facebookAccount->id,
- ]);
-
- $threadsAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'platform' => Platform::Threads,
- ]);
- $threadsPlatform = PostPlatform::factory()->threads()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $threadsAccount->id,
- ]);
-
- // 600 chars: fine for Facebook (63206 cap), over for Threads (500 cap).
- $response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
- 'status' => Status::Scheduled->value,
- 'content' => str_repeat('a', 600),
- 'scheduled_at' => now()->addDay()->toIso8601String(),
- 'platforms' => [
- [
- 'id' => $facebookPlatform->id,
- 'content_type' => ContentType::FacebookPost->value,
- 'meta' => [],
- ],
- [
- 'id' => $threadsPlatform->id,
- 'content_type' => ContentType::ThreadsPost->value,
- 'meta' => [],
- ],
- ],
- ]);
-
- $response->assertSessionHasErrors('content');
- expect(session('errors')->get('content')[0])->toContain('Threads');
-});
-
test('draft save accepts media source metadata for ai regeneration', function () {
$asset = Media::factory()->stored()->temporaryUpload($this->workspace)->create([
'path' => 'ai-images/generated.webp',
@@ -834,7 +601,6 @@ test('draft save accepts media source metadata for ai regeneration', function ()
->put(route('app.posts.update', $this->post), [
'status' => Status::Draft->value,
'media' => $payload,
- 'platforms' => [['id' => $this->postPlatform->id]],
]);
$response->assertSessionDoesntHaveErrors();
@@ -846,7 +612,7 @@ test('draft save accepts media source metadata for ai regeneration', function ()
test('the web update accepts a compatible type change for the fixed account', function () {
$this->socialAccount->update(['platform' => Platform::Instagram]);
- $this->postPlatform->update([
+ $this->post->update([
'platform' => Platform::Instagram,
'content_type' => ContentType::InstagramFeed,
]);
@@ -862,7 +628,7 @@ test('the web update accepts a compatible type change for the fixed account', fu
]);
$response->assertSessionDoesntHaveErrors();
- expect($this->postPlatform->fresh()->content_type)->toBe(ContentType::InstagramReel)
+ expect($this->post->fresh()->content_type)->toBe(ContentType::InstagramReel)
->and($this->post->fresh()->content)->toBe('Reel atualizado');
});
@@ -870,60 +636,47 @@ test('instagram_carousel is rejected as a content_type — carousel is a feed po
$response = $this->actingAs($this->user)
->put(route('app.posts.update', $this->post), [
'status' => Status::Draft->value,
- 'platforms' => [
- [
- 'id' => $this->postPlatform->id,
- 'content_type' => 'instagram_carousel',
- 'meta' => [],
- ],
- ],
+ 'content_type' => 'instagram_carousel',
+ 'meta' => [],
]);
- $response->assertSessionHasErrors('platforms.0.content_type');
+ $response->assertSessionHasErrors('content_type');
});
test('publishing a discord post without a channel is rejected', function () {
$account = SocialAccount::factory()->discord()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Discord,
'content_type' => ContentType::DiscordMessage,
'meta' => [],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [[
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::DiscordMessage->value,
- 'meta' => [],
- ]],
+ 'content_type' => ContentType::DiscordMessage->value,
+ 'meta' => [],
])
- ->assertSessionHasErrors('platforms.0.meta.channel_id');
+ ->assertSessionHasErrors('meta.channel_id');
});
test('saving a discord draft without a channel is allowed', function () {
$account = SocialAccount::factory()->discord()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
'platform' => Platform::Discord,
'content_type' => ContentType::DiscordMessage,
'meta' => [],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Draft->value,
- 'platforms' => [[
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::DiscordMessage->value,
- 'meta' => [],
- ]],
+ 'content_type' => ContentType::DiscordMessage->value,
+ 'meta' => [],
])
- ->assertSessionDoesntHaveErrors('platforms.0.meta.channel_id');
+ ->assertSessionDoesntHaveErrors('meta.channel_id');
});
test('saving a pinterest draft persists title and link meta', function () {
@@ -931,29 +684,25 @@ test('saving a pinterest draft persists title and link meta', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => ['board_id' => 'board-1'],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Draft->value,
'content' => 'Shared caption',
- 'platforms' => [[
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'title' => 'Pin Title',
- 'link' => 'https://example.com/product',
- ],
- ]],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'title' => 'Pin Title',
+ 'link' => 'https://example.com/product',
+ ],
])
->assertSessionDoesntHaveErrors();
- $meta = $pinterestPlatform->fresh()->meta;
+ $meta = $pinterestPost->fresh()->meta;
expect(data_get($meta, 'title'))->toBe('Pin Title')
->and(data_get($meta, 'link'))->toBe('https://example.com/product')
@@ -965,9 +714,8 @@ test('clearing pinterest title and link removes the meta keys', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [
'board_id' => 'board-1',
'title' => 'Keep me gone',
@@ -976,21 +724,18 @@ test('clearing pinterest title and link removes the meta keys', function () {
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Draft->value,
- 'platforms' => [[
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'title' => null,
- 'link' => null,
- ],
- ]],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'title' => null,
+ 'link' => null,
+ ],
])
->assertSessionDoesntHaveErrors();
- $meta = $pinterestPlatform->fresh()->meta;
+ $meta = $pinterestPost->fresh()->meta;
expect(data_get($meta, 'board_id'))->toBe('board-1')
->and(array_key_exists('title', $meta))->toBeFalse()
@@ -1002,9 +747,8 @@ test('pinterest rejects invalid link when scheduling', function () {
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => ['board_id' => 'board-1'],
]);
@@ -1020,22 +764,19 @@ test('pinterest rejects invalid link when scheduling', function () {
];
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Scheduled->value,
'scheduled_at' => now()->addHour()->toIso8601String(),
'content' => 'Ready to schedule',
'media' => $mediaPayload,
- 'platforms' => [[
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'board_id' => 'board-1',
- 'link' => 'not-a-url',
- ],
- ]],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'board_id' => 'board-1',
+ 'link' => 'not-a-url',
+ ],
])
->assertSessionHasErrors([
- 'platforms.0.meta.link' => __('posts.form.pinterest.link_invalid'),
+ 'meta.link' => __('posts.form.pinterest.link_invalid'),
]);
});
@@ -1044,131 +785,108 @@ test('pinterest meta title and link validation bounds are enforced', function ()
'workspace_id' => $this->workspace->id,
'platform' => Platform::Pinterest,
]);
- $pinterestPlatform = PostPlatform::factory()->pinterest()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $pinterestAccount->id,
+ $pinterestPost = Post::factory()->forAccount($pinterestAccount)->pinterest()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $pinterestPost), [
'status' => Status::Draft->value,
- 'platforms' => [[
- 'id' => $pinterestPlatform->id,
- 'content_type' => ContentType::PinterestPin->value,
- 'meta' => [
- 'title' => str_repeat('t', 101),
- 'link' => 'not-a-url',
- ],
- ]],
+ 'content_type' => ContentType::PinterestPin->value,
+ 'meta' => [
+ 'title' => str_repeat('t', 101),
+ 'link' => 'not-a-url',
+ ],
])
->assertSessionHasErrors([
- 'platforms.0.meta.title' => __('posts.form.pinterest.title_max'),
- 'platforms.0.meta.link' => __('posts.form.pinterest.link_invalid'),
+ 'meta.title' => __('posts.form.pinterest.title_max'),
+ 'meta.link' => __('posts.form.pinterest.link_invalid'),
]);
});
test('saving a google business event title over the api length is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Draft->value,
- 'platforms' => [[
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1)],
- ],
- ]],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1)],
+ ],
])
->assertSessionHasErrors([
- 'platforms.0.meta.event.title' => __('posts.form.google_business.title_max'),
+ 'meta.event.title' => __('posts.form.google_business.title_max'),
]);
});
test('saving a google business coupon longer than the event title cap is accepted', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Draft->value,
- 'platforms' => [[
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'offer' => ['coupon_code' => str_repeat('C', TopicType::TITLE_MAX_LENGTH + 20)],
- ],
- ]],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'offer' => ['coupon_code' => str_repeat('C', TopicType::TITLE_MAX_LENGTH + 20)],
+ ],
])
->assertSessionDoesntHaveErrors();
- expect(data_get($postPlatform->fresh()->meta, 'offer.coupon_code'))
+ expect(data_get($post->fresh()->meta, 'offer.coupon_code'))
->toBe(str_repeat('C', TopicType::TITLE_MAX_LENGTH + 20));
});
test('publishing a google business event post without event fields is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => ['topic_type' => 'EVENT'],
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => ['topic_type' => 'EVENT'],
]);
- $response->assertSessionHasErrors('platforms.0.meta.event.title');
+ $response->assertSessionHasErrors('meta.event.title');
});
test('publishing a google business offer post round-trips topic_type and offer meta', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => '2026-09-30'],
- 'offer' => ['coupon_code' => 'SAVE10'],
- ],
- ],
+ 'content' => 'Visit us',
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'event' => ['title' => 'Summer Sale', 'start_date' => '2026-09-01', 'end_date' => '2026-09-30'],
+ 'offer' => ['coupon_code' => 'SAVE10'],
],
]);
$response->assertSessionDoesntHaveErrors();
- $meta = $postPlatform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'topic_type'))->toBe('OFFER')
->and(data_get($meta, 'event.title'))->toBe('Summer Sale')
@@ -1177,274 +895,163 @@ test('publishing a google business offer post round-trips topic_type and offer m
test('publishing a google business offer post requires the event title', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'offer' => ['coupon_code' => 'SAVE10'],
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'offer' => ['coupon_code' => 'SAVE10'],
],
]);
$response->assertSessionHasErrors([
- 'platforms.0.meta.event.title' => __('posts.form.google_business.offer_title_required'),
+ 'meta.event.title' => __('posts.form.google_business.offer_title_required'),
]);
});
test('publishing a google business offer post without dates is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'OFFER',
- 'event' => ['title' => 'Summer Sale'],
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'OFFER',
+ 'event' => ['title' => 'Summer Sale'],
],
]);
- $response->assertSessionHasErrors('platforms.0.meta.event.start_date');
+ $response->assertSessionHasErrors('meta.event.start_date');
});
test('publishing a google business event with the end date before the start is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => ['title' => 'Sale', 'start_date' => '2026-09-10', 'end_date' => '2026-09-01'],
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => ['title' => 'Sale', 'start_date' => '2026-09-10', 'end_date' => '2026-09-01'],
],
]);
- $response->assertSessionHasErrors('platforms.0.meta.event.end_date');
+ $response->assertSessionHasErrors('meta.event.end_date');
});
test('publishing a google business event with a same-day end time before start is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => 'Sale',
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-01',
- 'start_time' => '18:00',
- 'end_time' => '09:00',
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => 'Sale',
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-01',
+ 'start_time' => '18:00',
+ 'end_time' => '09:00',
],
],
]);
$response->assertSessionHasErrors([
- 'platforms.0.meta.event.end_time' => __('posts.form.google_business.event_end_time_before_start'),
+ 'meta.event.end_time' => __('posts.form.google_business.event_end_time_before_start'),
]);
});
test('publishing a google business event persists start and end times', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => [
- 'title' => 'Grand Opening',
- 'start_date' => '2026-09-01',
- 'end_date' => '2026-09-02',
- 'start_time' => '09:30',
- 'end_time' => '17:00',
- ],
- ],
+ 'content' => 'Visit us',
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'EVENT',
+ 'event' => [
+ 'title' => 'Grand Opening',
+ 'start_date' => '2026-09-01',
+ 'end_date' => '2026-09-02',
+ 'start_time' => '09:30',
+ 'end_time' => '17:00',
],
],
]);
$response->assertSessionDoesntHaveErrors();
- $meta = $postPlatform->fresh()->meta;
+ $meta = $post->fresh()->meta;
expect(data_get($meta, 'event.start_time'))->toBe('09:30')
->and(data_get($meta, 'event.end_time'))->toBe('17:00');
});
-test('saving two google business events scopes end-before-start to the inverted one', function () {
- $firstAccount = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $secondAccount = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $validEvent = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $firstAccount->id,
- 'meta' => [],
- ]);
- $invertedEvent = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $secondAccount->id,
- 'meta' => [],
- ]);
-
- $response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
- 'status' => Status::Draft->value,
- 'platforms' => [
- [
- 'id' => $validEvent->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => ['title' => 'Valid', 'start_date' => '2026-09-01', 'end_date' => '2026-09-10'],
- ],
- ],
- [
- 'id' => $invertedEvent->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'EVENT',
- 'event' => ['title' => 'Inverted', 'start_date' => '2026-09-10', 'end_date' => '2026-09-01'],
- ],
- ],
- ],
- ]);
-
- $response->assertSessionHasErrors([
- 'platforms.1.meta.event.end_date' => __('posts.form.google_business.event_end_date_before_start'),
- ]);
- $response->assertSessionDoesntHaveErrors(['platforms.0.meta.event.end_date']);
-});
-
-test('publishing two google business posts scopes event errors to the missing one', function () {
- $firstAccount = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $secondAccount = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $missingEvent = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $firstAccount->id,
- 'meta' => [],
- ]);
- $completeStandard = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $secondAccount->id,
- 'meta' => [],
- ]);
-
- $response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
- 'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $missingEvent->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => ['topic_type' => 'EVENT'],
- ],
- [
- 'id' => $completeStandard->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => ['topic_type' => 'STANDARD'],
- ],
- ],
- ]);
-
- $response->assertSessionHasErrors('platforms.0.meta.event.title');
- $response->assertSessionDoesntHaveErrors(['platforms.1.meta.event.title']);
-});
-
test('publishing a google business post with a url-needing cta and no url is rejected', function () {
$account = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $this->workspace->id]);
- $postPlatform = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
+ $post = Post::factory()->forAccount($account)->googleBusiness()->create([
+ 'user_id' => $this->user->id,
'meta' => [],
]);
$response = $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), [
+ ->put(route('app.posts.update', $post), [
'status' => Status::Publishing->value,
- 'platforms' => [
- [
- 'id' => $postPlatform->id,
- 'content_type' => ContentType::GoogleBusinessPost->value,
- 'meta' => [
- 'topic_type' => 'STANDARD',
- 'call_to_action' => ['action_type' => 'BOOK'],
- ],
- ],
+ 'content_type' => ContentType::GoogleBusinessPost->value,
+ 'meta' => [
+ 'topic_type' => 'STANDARD',
+ 'call_to_action' => ['action_type' => 'BOOK'],
],
]);
- $response->assertSessionHasErrors('platforms.0.meta.call_to_action.url');
+ $response->assertSessionHasErrors('meta.call_to_action.url');
});
-test('a legacy giphy media source blocks the edit until the migration clears it', function () {
- $item = [...$this->mediaPayload[0], 'source' => 'giphy', 'source_meta' => ['attribution' => 'GIPHY']];
- $this->post->update(['media' => [$item]]);
- $payload = fn (array $media): array => ['status' => Status::Draft->value, 'media' => $media];
-
- $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), $payload($this->post->fresh()->media))
- ->assertSessionHasErrors('media.0.source');
-
- $migration = require database_path('migrations/2026_10_06_111329_clear_giphy_source_from_stored_media.php');
- $migration->up();
+test('scheduling a channel post without content_type keeps its stored type', function () {
+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);
+ $post = Post::factory()->forAccount($account)->create([
+ 'user_id' => $this->user->id,
+ 'content' => 'Ready',
+ 'status' => Status::Draft,
+ ]);
+ $scheduledAt = now()->addDay()->startOfMinute();
- expect(DB::table('posts')->where('id', $this->post->id)->exists())->toBeTrue();
+ $this->actingAs($this->user)->put(route('app.posts.update', $post), [
+ 'status' => Status::Scheduled->value,
+ 'content' => 'Ready to go',
+ 'scheduled_at' => $scheduledAt->toIso8601String(),
+ ])->assertSessionHasNoErrors();
- $this->actingAs($this->user)
- ->put(route('app.posts.update', $this->post), $payload($this->post->fresh()->media))
- ->assertSessionDoesntHaveErrors('media.0.source');
+ expect($post->fresh())
+ ->status->toBe(Status::Scheduled)
+ ->content_type->toBe(ContentType::LinkedInPost)
+ ->content->toBe('Ready to go');
});
diff --git a/tests/Feature/Webhook/DispatchWebhookTest.php b/tests/Feature/Webhook/DispatchWebhookTest.php
index c9358a085..725c1fed5 100644
--- a/tests/Feature/Webhook/DispatchWebhookTest.php
+++ b/tests/Feature/Webhook/DispatchWebhookTest.php
@@ -4,6 +4,7 @@ declare(strict_types=1);
use App\Actions\Post\UpdatePost;
use App\Enums\Post\CreatedVia;
+use App\Enums\Post\PublishStatus;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
@@ -13,7 +14,6 @@ use App\Events\Webhook\LogUpdated;
use App\Jobs\DispatchWebhook;
use App\Mail\WebhookPausedMail;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -184,9 +184,14 @@ test('dispatch webhook job sends the published post payload as data', function (
'example.com/webhook' => Http::response('OK', 200),
]);
- $post = Post::factory()->published()->createQuietly([
- 'workspace_id' => $this->workspace->id,
+ $account = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create([
+ 'display_name' => 'Paulo Castellano',
+ 'username' => 'paulocastellano',
+ 'avatar_url' => 'avatars/li.jpg',
+ ]);
+ $post = Post::factory()->forAccount($account, ContentType::LinkedInPost)->published()->createQuietly([
'user_id' => $this->user->id,
+ 'meta' => ['document_title' => 'TryPost launch deck'],
'content' => '<p>Launch day. TryPost is live.</p>',
'created_via' => CreatedVia::Web,
'media' => [
@@ -208,17 +213,6 @@ test('dispatch webhook job sends the published post payload as data', function (
]);
$post->labels()->attach($label);
- $account = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create([
- 'display_name' => 'Paulo Castellano',
- 'username' => 'paulocastellano',
- 'avatar_url' => 'avatars/li.jpg',
- ]);
- PostPlatform::factory()->published()->recycle($post, $account)->create([
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'meta' => ['document_title' => 'TryPost launch deck'],
- ]);
-
$payload = app(WebhookService::class)->postPayload($post->fresh());
$job = new DispatchWebhook(
@@ -229,7 +223,7 @@ test('dispatch webhook job sends the published post payload as data', function (
app()->call([$job, 'handle']);
- Http::assertSent(function ($request) use ($job, $payload) {
+ Http::assertSent(function ($request) use ($job, $payload, $account) {
$body = $request->data();
return $body['id'] === $job->logId
@@ -242,9 +236,13 @@ test('dispatch webhook job sends the published post payload as data', function (
&& data_get($body, 'data.workspace.name') === $this->workspace->name
&& data_get($body, 'data.labels.0.name') === 'Launch'
&& data_get($body, 'data.media.0.type') === 'image'
- && data_get($body, 'data.platforms.0.platform') === Platform::LinkedIn->value
- && data_get($body, 'data.platforms.0.meta.document_title') === 'TryPost launch deck'
- && ! array_key_exists('access_token', data_get($body, 'data.platforms.0.social_account', []));
+ && data_get($body, 'data.platform') === Platform::LinkedIn->value
+ && data_get($body, 'data.social_account_id') === $account->id
+ && data_get($body, 'data.publish_status') === PublishStatus::Published->value
+ && data_get($body, 'data.meta.document_title') === 'TryPost launch deck'
+ && ! array_key_exists('platforms', data_get($body, 'data', []))
+ && ! array_key_exists('error_context', data_get($body, 'data', []))
+ && ! array_key_exists('access_token', data_get($body, 'data.social_account', []));
});
});
@@ -283,7 +281,7 @@ test('unscheduling a post delivers the log id on the webhook envelope', function
'events' => [WebhookEvent::PostUnscheduled->value],
]);
- $post = Post::factory()->scheduled()->createQuietly([
+ $post = Post::factory()->linkedin()->scheduled()->createQuietly([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'content' => 'Was scheduled',
diff --git a/tests/Feature/Webhook/WebhookListenersTest.php b/tests/Feature/Webhook/WebhookListenersTest.php
index 133321700..f2d1c9f06 100644
--- a/tests/Feature/Webhook/WebhookListenersTest.php
+++ b/tests/Feature/Webhook/WebhookListenersTest.php
@@ -86,7 +86,6 @@ test('SendPostStatusWebhook dispatches for known post statuses', function (PostS
})->with([
[PostStatus::Scheduled, EventType::PostScheduled],
[PostStatus::Published, EventType::PostPublished],
- [PostStatus::PartiallyPublished, EventType::PostPartiallyPublished],
[PostStatus::Failed, EventType::PostFailed],
]);
diff --git a/tests/Feature/Webhook/WebhookPostLifecycleTest.php b/tests/Feature/Webhook/WebhookPostLifecycleTest.php
index ed0eac541..081d57f8d 100644
--- a/tests/Feature/Webhook/WebhookPostLifecycleTest.php
+++ b/tests/Feature/Webhook/WebhookPostLifecycleTest.php
@@ -18,7 +18,6 @@ use App\Listeners\Webhook\SendPostCreatedWebhook;
use App\Listeners\Webhook\SendPostDeletedWebhook;
use App\Listeners\Webhook\SendPostStatusWebhook;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Webhook;
@@ -49,7 +48,7 @@ function subscribeToWebhook(Workspace $workspace, array $events): Webhook
/** @param array<string, mixed> $data */
function createWebhookPost(Workspace $workspace, User $user, array $data): Post
{
- $destination = $data['platforms'][0] ?? null;
+ $destination = $data['destination'] ?? null;
if ($destination === null) {
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
$destination = [
@@ -91,7 +90,7 @@ test('creating a channel post queues a post.created webhook', function () {
});
});
-test('creating a channel post includes labels and platforms in the payload', function () {
+test('creating a channel post includes labels and its channel in the payload', function () {
subscribeToWebhook($this->workspace, [EventType::PostCreated]);
$label = WorkspaceLabel::factory()->recycle($this->workspace)->create([
@@ -107,11 +106,11 @@ test('creating a channel post includes labels and platforms in the payload', fun
'content' => 'Hello from webhooks',
'created_via' => CreatedVia::Web,
'label_ids' => [$label->id],
- 'platforms' => [[
+ 'destination' => [
'social_account_id' => $account->id,
'content_type' => ContentType::LinkedInPost->value,
'meta' => ['document_title' => 'TryPost launch deck'],
- ]],
+ ],
]);
Queue::assertPushed(DispatchWebhook::class, function (DispatchWebhook $job) use ($post, $label, $account) {
@@ -119,31 +118,24 @@ test('creating a channel post includes labels and platforms in the payload', fun
&& data_get($job->payload, 'id') === $post->id
&& data_get($job->payload, 'labels.0.id') === $label->id
&& data_get($job->payload, 'labels.0.name') === 'Launch'
- && data_get($job->payload, 'platforms.0.social_account_id') === $account->id
- && data_get($job->payload, 'platforms.0.enabled') === true
- && data_get($job->payload, 'platforms.0.meta.document_title') === 'TryPost launch deck';
+ && data_get($job->payload, 'social_account_id') === $account->id
+ && data_get($job->payload, 'platform') === Platform::LinkedIn->value
+ && data_get($job->payload, 'meta.document_title') === 'TryPost launch deck';
});
});
-test('scheduling a post through UpdatePost includes labels and platforms from the same save', function () {
+test('scheduling a post through UpdatePost includes labels and meta from the same save', function () {
subscribeToWebhook($this->workspace, [EventType::PostScheduled]);
- $post = Post::factory()->createQuietly([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Draft,
- 'content' => 'Ready to schedule',
- ]);
-
$label = WorkspaceLabel::factory()->recycle($this->workspace)->create([
'name' => 'Launch',
'color' => '#7C3AED',
]);
$account = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create();
- $platform = PostPlatform::factory()->recycle($post, $account)->create([
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'enabled' => false,
+ $post = Post::factory()->forAccount($account, ContentType::LinkedInPost)->createQuietly([
+ 'user_id' => $this->user->id,
+ 'status' => PostStatus::Draft,
+ 'content' => 'Ready to schedule',
'meta' => [],
]);
@@ -151,22 +143,18 @@ test('scheduling a post through UpdatePost includes labels and platforms from th
'status' => PostStatus::Scheduled->value,
'scheduled_at' => now()->addDay()->toIso8601String(),
'label_ids' => [$label->id],
- 'platforms' => [[
- 'id' => $platform->id,
- 'content_type' => ContentType::LinkedInPost->value,
- 'meta' => ['document_title' => 'TryPost launch deck'],
- ]],
+ 'content_type' => ContentType::LinkedInPost->value,
+ 'meta' => ['document_title' => 'TryPost launch deck'],
]);
- Queue::assertPushed(DispatchWebhook::class, function (DispatchWebhook $job) use ($post, $label, $platform) {
+ Queue::assertPushed(DispatchWebhook::class, function (DispatchWebhook $job) use ($post, $label, $account) {
return $job->eventType === EventType::PostScheduled->value
&& data_get($job->payload, 'id') === $post->id
&& data_get($job->payload, 'status') === PostStatus::Scheduled->value
&& data_get($job->payload, 'labels.0.id') === $label->id
&& data_get($job->payload, 'labels.0.name') === 'Launch'
- && data_get($job->payload, 'platforms.0.id') === $platform->id
- && data_get($job->payload, 'platforms.0.enabled') === true
- && data_get($job->payload, 'platforms.0.meta.document_title') === 'TryPost launch deck';
+ && data_get($job->payload, 'social_account_id') === $account->id
+ && data_get($job->payload, 'meta.document_title') === 'TryPost launch deck';
});
});
@@ -185,7 +173,7 @@ test('creating a draft does not queue status webhooks', function () {
test('unscheduling a post through UpdatePost queues a post.unscheduled webhook', function () {
subscribeToWebhook($this->workspace, [EventType::PostUnscheduled]);
- $post = Post::factory()->createQuietly([
+ $post = Post::factory()->linkedin()->createQuietly([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Scheduled,
@@ -250,7 +238,6 @@ test('changing post status through the observer queues the matching webhook', fu
'scheduled_at' => now()->addDay(),
]),
PostStatus::Published => $post->markAsPublished(),
- PostStatus::PartiallyPublished => $post->markAsPartiallyPublished(),
PostStatus::Failed => $post->markAsFailed(),
default => $post->update(['status' => $status]),
};
@@ -262,22 +249,27 @@ test('changing post status through the observer queues the matching webhook', fu
&& data_get($job->payload, 'workspace.id') === $this->workspace->id
&& array_key_exists('labels', $job->payload)
&& array_key_exists('media', $job->payload)
- && array_key_exists('platforms', $job->payload);
+ && array_key_exists('publish_status', $job->payload)
+ && ! array_key_exists('platforms', $job->payload);
});
})->with([
[PostStatus::Scheduled, EventType::PostScheduled],
[PostStatus::Published, EventType::PostPublished],
- [PostStatus::PartiallyPublished, EventType::PostPartiallyPublished],
[PostStatus::Failed, EventType::PostFailed],
]);
test('publishing a post queues the full webhook payload', function () {
subscribeToWebhook($this->workspace, [EventType::PostPublished]);
- $post = Post::factory()->createQuietly([
- 'workspace_id' => $this->workspace->id,
+ $account = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create([
+ 'display_name' => 'Paulo Castellano',
+ 'username' => 'paulocastellano',
+ 'avatar_url' => 'avatars/li.jpg',
+ ]);
+ $post = Post::factory()->forAccount($account, ContentType::LinkedInPost)->published()->createQuietly([
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
+ 'meta' => ['document_title' => 'TryPost launch deck'],
'content' => '<p>Launch day. TryPost is live.</p>',
'created_via' => CreatedVia::Web,
'media' => [
@@ -299,22 +291,11 @@ test('publishing a post queues the full webhook payload', function () {
]);
$post->labels()->attach($label);
- $account = SocialAccount::factory()->linkedin()->recycle($this->workspace)->create([
- 'display_name' => 'Paulo Castellano',
- 'username' => 'paulocastellano',
- 'avatar_url' => 'avatars/li.jpg',
- ]);
- $platform = PostPlatform::factory()->published()->recycle($post, $account)->create([
- 'platform' => Platform::LinkedIn,
- 'content_type' => ContentType::LinkedInPost,
- 'meta' => ['document_title' => 'TryPost launch deck'],
- ]);
-
$post->markAsPublished();
$expected = app(WebhookService::class)->postPayload($post->fresh());
- Queue::assertPushed(DispatchWebhook::class, function (DispatchWebhook $job) use ($expected, $platform) {
+ Queue::assertPushed(DispatchWebhook::class, function (DispatchWebhook $job) use ($expected, $account) {
return $job->eventType === EventType::PostPublished->value
&& $job->payload['id'] === $expected['id']
&& $job->payload['status'] === PostStatus::Published->value
@@ -322,8 +303,12 @@ test('publishing a post queues the full webhook payload', function () {
&& $job->payload['workspace'] === $expected['workspace']
&& $job->payload['labels'] === $expected['labels']
&& $job->payload['media'] === $expected['media']
- && $job->payload['platforms'] === $expected['platforms']
- && data_get($job->payload, 'platforms.0.id') === $platform->id;
+ && $job->payload['social_account'] === $expected['social_account']
+ && $job->payload['meta'] === ['document_title' => 'TryPost launch deck']
+ && $job->payload['publish_status'] === $expected['publish_status']
+ && $job->payload['platform_post_id'] === $expected['platform_post_id']
+ && $job->payload['social_account_id'] === $account->id
+ && ! array_key_exists('error_context', $job->payload);
});
});
diff --git a/tests/Feature/YouTubeDescriptionPreviewTest.php b/tests/Feature/YouTubeDescriptionPreviewTest.php
index 90cd0ffc4..a3cbd8618 100644
--- a/tests/Feature/YouTubeDescriptionPreviewTest.php
+++ b/tests/Feature/YouTubeDescriptionPreviewTest.php
@@ -5,22 +5,17 @@ declare(strict_types=1);
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\PreviewPostTool;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Services\Post\PostPreviewer;
use Illuminate\Testing\Fluent\AssertableJson;
test('youtube description preview includes effective bytes and the description length limit', function (mixed $description, string $expected) {
- $post = Post::factory()->create(['content' => 'Title']);
- $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $post->workspace_id]);
- PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $post = Post::factory()->youtube()->create([
+ 'content' => 'Title',
'meta' => ['description' => $description],
]);
- $preview = app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0];
+ $preview = app(PostPreviewer::class)->forPost($post->fresh());
expect($preview['description'])->toBe($expected)
->and($preview['description_length_bytes'])->toBe(strlen($expected))
@@ -36,70 +31,49 @@ test('youtube description preview includes effective bytes and the description l
]);
test('other networks do not gain youtube description preview fields', function () {
- $post = Post::factory()->create(['content' => 'Title']);
- PostPlatform::factory()->create(['post_id' => $post->id, 'enabled' => true]);
+ $post = Post::factory()->linkedin()->create(['content' => 'Title']);
- $preview = app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0];
+ $preview = app(PostPreviewer::class)->forPost($post->fresh());
expect($preview)->not->toHaveKeys(['description', 'description_length_bytes']);
});
-test('API and MCP previews expose independent YouTube descriptions', function () {
+test('API and MCP previews expose the YouTube description', function () {
$token = createApiTestToken();
- $post = Post::factory()->create([
- 'workspace_id' => $token['workspace']->id,
+ $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $token['workspace']->id]);
+ $post = Post::factory()->forAccount($account)->create([
'user_id' => $token['user']->id,
'content' => 'Short title',
+ 'meta' => ['description' => 'Channel description'],
]);
- $platforms = collect(['First channel', 'Second channel'])->map(function (string $description) use ($post) {
- $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $post->workspace_id]);
-
- return PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
- 'meta' => ['description' => $description],
- ]);
- });
$response = $this->withToken($token['plain_token'])
->getJson(route('api.posts.preview', $post))
->assertOk();
- foreach ($platforms as $platform) {
- $preview = collect($response->json('platforms'))->firstWhere('post_platform_id', $platform->id);
-
- expect($preview['description'])->toBe($platform->meta['description'])
- ->and($preview['description_length_bytes'])->toBe(strlen($platform->meta['description']))
- ->and($preview['sanitized_content'])->toBe('Short title');
- }
+ expect($response->json('description'))->toBe('Channel description')
+ ->and($response->json('description_length_bytes'))->toBe(strlen('Channel description'))
+ ->and($response->json('sanitized_content'))->toBe('Short title');
TryPostServer::actingAs($token['user'])->tool(PreviewPostTool::class, ['post_id' => $post->id])
->assertOk()
- ->assertStructuredContent(function (AssertableJson $json) use ($platforms) {
+ ->assertStructuredContent(function (AssertableJson $json) {
$json->etc();
+ $preview = $json->toArray();
- foreach ($platforms as $platform) {
- $preview = collect($json->toArray()['platforms'])->firstWhere('post_platform_id', $platform->id);
-
- expect($preview['description'])->toBe($platform->meta['description'])
- ->and($preview['description_length_bytes'])->toBe(strlen($platform->meta['description']))
- ->and($preview['sanitized_content'])->toBe('Short title');
- }
+ expect($preview['description'])->toBe('Channel description')
+ ->and($preview['description_length_bytes'])->toBe(strlen('Channel description'))
+ ->and($preview['sanitized_content'])->toBe('Short title');
});
});
test('youtube preview shows the explicit title or the derived one', function (array $meta, string $expected) {
- $post = Post::factory()->create(['content' => 'First sentence. Second']);
- $account = SocialAccount::factory()->youtube()->create(['workspace_id' => $post->workspace_id]);
- PostPlatform::factory()->youtube()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'enabled' => true,
+ $post = Post::factory()->youtube()->create([
+ 'content' => 'First sentence. Second',
'meta' => $meta,
]);
- expect(app(PostPreviewer::class)->forPost($post->fresh())['platforms'][0]['title'])->toBe($expected);
+ expect(app(PostPreviewer::class)->forPost($post->fresh())['title'])->toBe($expected);
})->with([
'explicit title' => [['title' => 'My title'], 'My title'],
'derived title' => [[], 'First sentence. Second'],
diff --git a/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php b/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php
index 1f717dcac..bd8f7d99b 100644
--- a/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php
+++ b/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php
@@ -5,7 +5,6 @@ declare(strict_types=1);
use App\Actions\Workspace\PurgeWorkspace;
use App\Models\Media;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -48,17 +47,12 @@ test('purge workspace prunes google business jpegs before the cascade', function
'account_id' => $owner->account_id,
'user_id' => $owner->id,
]);
- $post = Post::factory()->create([
+ $post = Post::factory()->forAccount(SocialAccount::factory()->googleBusiness()->create([
'workspace_id' => $workspace->id,
+ ]))->create([
'user_id' => $owner->id,
]);
- $target = PostPlatform::factory()->googleBusiness()->create([
- 'post_id' => $post->id,
- 'social_account_id' => SocialAccount::factory()->googleBusiness()->create([
- 'workspace_id' => $workspace->id,
- ])->id,
- ]);
- $path = GoogleBusinessDerivativeCleaner::pathFor($target->id);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
PurgeWorkspace::execute($workspace);
diff --git a/tests/Unit/Enums/Post/PublishStatusTest.php b/tests/Unit/Enums/Post/PublishStatusTest.php
new file mode 100644
index 000000000..0b8ca731c
--- /dev/null
+++ b/tests/Unit/Enums/Post/PublishStatusTest.php
@@ -0,0 +1,41 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\PublishStatus;
+
+test('a finished publication settles the post', function (PublishStatus $status, bool $finished) {
+ expect($status->isFinished())->toBe($finished);
+})->with([
+ [PublishStatus::Published, true],
+ [PublishStatus::Failed, true],
+ [PublishStatus::Rejected, true],
+ [PublishStatus::PendingReview, false],
+ [PublishStatus::Pending, false],
+ [PublishStatus::Publishing, false],
+ [PublishStatus::Retrying, false],
+]);
+
+test('a closed publication must not be published again', function (PublishStatus $status, bool $closed) {
+ expect($status->isClosed())->toBe($closed);
+})->with([
+ [PublishStatus::Published, true],
+ [PublishStatus::Failed, true],
+ [PublishStatus::Rejected, true],
+ [PublishStatus::PendingReview, true],
+ [PublishStatus::Pending, false],
+ [PublishStatus::Publishing, false],
+ [PublishStatus::Retrying, false],
+]);
+
+test('a pending, publishing or retrying publication is in flight', function (PublishStatus $status, bool $inFlight) {
+ expect($status->isInFlight())->toBe($inFlight);
+})->with([
+ [PublishStatus::Pending, true],
+ [PublishStatus::Publishing, true],
+ [PublishStatus::Retrying, true],
+ [PublishStatus::PendingReview, false],
+ [PublishStatus::Published, false],
+ [PublishStatus::Failed, false],
+ [PublishStatus::Rejected, false],
+]);
diff --git a/tests/Unit/Enums/PostPlatform/StatusTest.php b/tests/Unit/Enums/PostPlatform/StatusTest.php
deleted file mode 100644
index edae7e868..000000000
--- a/tests/Unit/Enums/PostPlatform/StatusTest.php
+++ /dev/null
@@ -1,29 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\PostPlatform\Status;
-
-test('a finished target counts toward settling the parent post', function (Status $status, bool $finished) {
- expect($status->isFinished())->toBe($finished);
-})->with([
- [Status::Published, true],
- [Status::Failed, true],
- [Status::Rejected, true],
- [Status::PendingReview, false],
- [Status::Pending, false],
- [Status::Publishing, false],
- [Status::Retrying, false],
-]);
-
-test('a closed target must not be published again', function (Status $status, bool $closed) {
- expect($status->isClosed())->toBe($closed);
-})->with([
- [Status::Published, true],
- [Status::Failed, true],
- [Status::Rejected, true],
- [Status::PendingReview, true],
- [Status::Pending, false],
- [Status::Publishing, false],
- [Status::Retrying, false],
-]);
diff --git a/tests/Unit/Enums/PostStatusTest.php b/tests/Unit/Enums/PostStatusTest.php
index 3ac05aeb5..883b2feb6 100644
--- a/tests/Unit/Enums/PostStatusTest.php
+++ b/tests/Unit/Enums/PostStatusTest.php
@@ -9,7 +9,6 @@ test('post status has correct values', function () {
expect(Status::Scheduled->value)->toBe('scheduled');
expect(Status::Publishing->value)->toBe('publishing');
expect(Status::Published->value)->toBe('published');
- expect(Status::PartiallyPublished->value)->toBe('partially_published');
expect(Status::Failed->value)->toBe('failed');
});
@@ -18,7 +17,6 @@ test('post status has labels', function () {
expect(Status::Scheduled->label())->toBe('Scheduled');
expect(Status::Publishing->label())->toBe('Publishing');
expect(Status::Published->label())->toBe('Published');
- expect(Status::PartiallyPublished->label())->toBe('Partially Published');
expect(Status::Failed->label())->toBe('Failed');
});
@@ -27,7 +25,6 @@ test('settled statuses are the ones finalize must not rewrite', function () {
expect(Status::Scheduled->isSettled())->toBeFalse();
expect(Status::Publishing->isSettled())->toBeFalse();
expect(Status::Published->isSettled())->toBeTrue();
- expect(Status::PartiallyPublished->isSettled())->toBeTrue();
expect(Status::Failed->isSettled())->toBeTrue();
});
@@ -36,6 +33,5 @@ test('post status has colors', function () {
expect(Status::Scheduled->color())->toBe('blue');
expect(Status::Publishing->color())->toBe('yellow');
expect(Status::Published->color())->toBe('green');
- expect(Status::PartiallyPublished->color())->toBe('orange');
expect(Status::Failed->color())->toBe('red');
});
diff --git a/tests/Unit/Enums/WebhookEventTypeTest.php b/tests/Unit/Enums/WebhookEventTypeTest.php
index c3e83b783..f34526ae0 100644
--- a/tests/Unit/Enums/WebhookEventTypeTest.php
+++ b/tests/Unit/Enums/WebhookEventTypeTest.php
@@ -12,7 +12,6 @@ test('every webhook event has the expected value', function (EventType $event, s
[EventType::PostScheduled, 'post.scheduled'],
[EventType::PostUnscheduled, 'post.unscheduled'],
[EventType::PostPublished, 'post.published'],
- [EventType::PostPartiallyPublished, 'post.partially_published'],
[EventType::PostFailed, 'post.failed'],
[EventType::PostDeleted, 'post.deleted'],
]);
@@ -22,7 +21,6 @@ test('fromPostStatus maps publishable statuses and ignores the rest', function (
})->with([
[PostStatus::Scheduled, EventType::PostScheduled],
[PostStatus::Published, EventType::PostPublished],
- [PostStatus::PartiallyPublished, EventType::PostPartiallyPublished],
[PostStatus::Failed, EventType::PostFailed],
[PostStatus::Draft, null],
[PostStatus::Draft, EventType::PostUnscheduled, PostStatus::Scheduled],
diff --git a/tests/Unit/Events/PostPlatformStatusUpdatedTest.php b/tests/Unit/Events/PostPlatformStatusUpdatedTest.php
deleted file mode 100644
index c753e0e21..000000000
--- a/tests/Unit/Events/PostPlatformStatusUpdatedTest.php
+++ /dev/null
@@ -1,52 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\Post\Status as PostStatus;
-use App\Events\PostPlatformStatusUpdated;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-use Illuminate\Broadcasting\PrivateChannel;
-
-beforeEach(function () {
- $this->user = User::factory()->create();
- $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
- $this->socialAccount = SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
- ]);
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- 'status' => PostStatus::Scheduled,
- ]);
- $this->postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-});
-
-test('event broadcasts on the per-post and per-workspace channels', function () {
- $event = new PostPlatformStatusUpdated($this->postPlatform);
- $channels = $event->broadcastOn();
-
- expect($channels)->toHaveCount(2);
- expect($channels[0])->toBeInstanceOf(PrivateChannel::class);
- expect($channels[0]->name)->toBe("private-post.{$this->post->id}");
- expect($channels[1])->toBeInstanceOf(PrivateChannel::class);
- expect($channels[1]->name)->toBe("private-workspace.{$this->workspace->id}");
-});
-
-test('event broadcasts with the post id', function () {
- $event = new PostPlatformStatusUpdated($this->postPlatform);
-
- expect($event->broadcastWith())->toBe(['post_id' => $this->post->id]);
-});
-
-test('event broadcasts as a stable name', function () {
- $event = new PostPlatformStatusUpdated($this->postPlatform);
-
- expect($event->broadcastAs())->toBe('post.platform.status.updated');
-});
diff --git a/tests/Unit/Events/PostStatusUpdatedTest.php b/tests/Unit/Events/PostStatusUpdatedTest.php
new file mode 100644
index 000000000..56639a7ef
--- /dev/null
+++ b/tests/Unit/Events/PostStatusUpdatedTest.php
@@ -0,0 +1,37 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Events\PostStatusUpdated;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+use Illuminate\Broadcasting\PrivateChannel;
+
+beforeEach(function () {
+ $this->user = User::factory()->create();
+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+ $this->socialAccount = SocialAccount::factory()->linkedin()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+ $this->post = Post::factory()->forAccount($this->socialAccount)->scheduled()->create([
+ 'user_id' => $this->user->id,
+ ]);
+});
+
+test('event broadcasts on the workspace channel only', function () {
+ $channels = (new PostStatusUpdated($this->post))->broadcastOn();
+
+ expect($channels)->toHaveCount(1)
+ ->and($channels[0])->toBeInstanceOf(PrivateChannel::class)
+ ->and($channels[0]->name)->toBe("private-workspace.{$this->workspace->id}");
+});
+
+test('event broadcasts with the post id', function () {
+ expect((new PostStatusUpdated($this->post))->broadcastWith())->toBe(['post_id' => $this->post->id]);
+});
+
+test('event broadcasts as a stable name', function () {
+ expect((new PostStatusUpdated($this->post))->broadcastAs())->toBe('post.platform.status.updated');
+});
diff --git a/tests/Unit/Mail/PostPublishFailedTest.php b/tests/Unit/Mail/PostPublishFailedTest.php
index 58ed2f048..780b84b2a 100644
--- a/tests/Unit/Mail/PostPublishFailedTest.php
+++ b/tests/Unit/Mail/PostPublishFailedTest.php
@@ -2,9 +2,9 @@
declare(strict_types=1);
+use App\Enums\Post\PublishStatus;
use App\Mail\PostPublishFailed;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
@@ -15,12 +15,7 @@ test('failed email falls back to the page display name when facebook has no user
'username' => null,
'display_name' => 'InboxPlacement.io',
]);
- $post = Post::factory()->failed()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->facebook()->failed()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
+ $post = Post::factory()->forAccount($account)->failed()->create();
$mail = new PostPublishFailed($post);
@@ -30,10 +25,23 @@ test('failed email falls back to the page display name when facebook has no user
});
test('failed email links to the post in the sent tab', function () {
- $post = Post::factory()->failed()->create();
+ $post = Post::factory()->forAccount(SocialAccount::factory()->linkedin()->create())->failed()->create();
$mail = new PostPublishFailed($post);
$mail->assertSeeInHtml(route('app.posts.index', ['tab' => 'sent', 'post' => $post->id]));
$mail->assertDontSeeInHtml(route('app.posts.edit', $post), false);
});
+
+test('failed email shows the account and the reason when google rejects a post in review', function () {
+ $account = SocialAccount::factory()->googleBusiness()->create(['display_name' => 'Acme Bakery']);
+ $post = Post::factory()->forAccount($account)->failed()->create([
+ 'publish_status' => PublishStatus::Rejected,
+ 'error_message' => 'Google rejected this post in review.',
+ ]);
+
+ $mail = new PostPublishFailed($post);
+
+ $mail->assertSeeInHtml('Acme Bakery');
+ $mail->assertSeeInHtml('Google rejected this post in review.');
+});
diff --git a/tests/Unit/Mail/PostPublishedTest.php b/tests/Unit/Mail/PostPublishedTest.php
index 2cc87485a..125d748ce 100644
--- a/tests/Unit/Mail/PostPublishedTest.php
+++ b/tests/Unit/Mail/PostPublishedTest.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
use App\Mail\PostPublished;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
@@ -15,11 +14,7 @@ test('published email falls back to the page display name when facebook has no u
'username' => null,
'display_name' => 'InboxPlacement.io',
]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
+ $post = Post::factory()->forAccount($account)->published()->create([
'platform_url' => 'https://www.facebook.com/permalink.php?story_fbid=pfbid0&id=61592851040951',
]);
@@ -38,12 +33,7 @@ test('published email uses the username when the display name is empty', functio
'username' => 'inboxplacementio.bsky.social',
'display_name' => '',
]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->bluesky()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create();
$mail = new PostPublished($post);
@@ -59,12 +49,7 @@ test('published email omits empty parentheses when both identifiers are missing'
'username' => null,
'display_name' => '',
]);
- $post = Post::factory()->published()->create(['workspace_id' => $workspace->id]);
- PostPlatform::factory()->facebook()->published()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
+ $post = Post::factory()->forAccount($account)->published()->create();
$mail = new PostPublished($post);
diff --git a/tests/Unit/Models/PostTest.php b/tests/Unit/Models/PostTest.php
index f15bb33bc..92c142406 100644
--- a/tests/Unit/Models/PostTest.php
+++ b/tests/Unit/Models/PostTest.php
@@ -4,7 +4,6 @@ declare(strict_types=1);
use App\Enums\Post\Status as PostStatus;
use App\Models\Post;
-use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
@@ -32,23 +31,28 @@ test('post belongs to user', function () {
expect($post->user->id)->toBe($this->user->id);
});
-test('post has many post platforms', function () {
- $post = Post::factory()->create([
+test('post belongs to its channel', function () {
+ $socialAccount = SocialAccount::factory()->linkedin()->create([
'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
]);
- $socialAccount = SocialAccount::factory()->linkedin()->create([
- 'workspace_id' => $this->workspace->id,
+ $post = Post::factory()->forAccount($socialAccount)->create([
+ 'user_id' => $this->user->id,
]);
- $postPlatform = PostPlatform::factory()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $socialAccount->id,
+ expect($post->socialAccount->id)->toBe($socialAccount->id)
+ ->and($post->hasChannel())->toBeTrue()
+ ->and($post->hasDestination())->toBeTrue();
+});
+
+test('a draft without a channel has no destination', function () {
+ $post = Post::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'user_id' => $this->user->id,
]);
- expect($post->postPlatforms)->toHaveCount(1);
- expect($post->postPlatforms->first()->id)->toBe($postPlatform->id);
+ expect($post->hasChannel())->toBeFalse()
+ ->and($post->hasDestination())->toBeFalse();
});
test('post can be marked as publishing', function () {
@@ -74,18 +78,6 @@ test('post can be marked as published', function () {
expect($post->fresh()->published_at)->not->toBeNull();
});
-test('post can be marked as partially published', function () {
- $post = Post::factory()->scheduled()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $post->markAsPartiallyPublished();
-
- expect($post->fresh()->status)->toBe(PostStatus::PartiallyPublished);
- expect($post->fresh()->published_at)->not->toBeNull();
-});
-
test('post can be marked as failed', function () {
$post = Post::factory()->scheduled()->create([
'workspace_id' => $this->workspace->id,
diff --git a/tests/Unit/PostPlatformMetaRulesTest.php b/tests/Unit/PostPlatformMetaRulesTest.php
index b308549d0..d7bbee8a3 100644
--- a/tests/Unit/PostPlatformMetaRulesTest.php
+++ b/tests/Unit/PostPlatformMetaRulesTest.php
@@ -11,28 +11,28 @@ use Illuminate\Support\Facades\Validator;
test('custom meta messages only cover pinterest title and link', function () {
expect(PostPlatformMetaRules::messages())->toBe([
- 'platforms.*.meta.link.url' => __('posts.form.pinterest.link_invalid'),
- 'platforms.*.meta.link.max' => __('posts.form.pinterest.link_max'),
- 'platforms.*.meta.title.max' => __('posts.form.pinterest.title_max'),
- 'platforms.*.meta.event.end_date.after_or_equal' => __('posts.form.google_business.event_end_date_before_start'),
- 'platforms.*.meta.event.title.max' => __('posts.form.google_business.title_max'),
+ 'meta.link.url' => __('posts.form.pinterest.link_invalid'),
+ 'meta.link.max' => __('posts.form.pinterest.link_max'),
+ 'meta.title.max' => __('posts.form.pinterest.title_max'),
+ 'meta.event.end_date.after_or_equal' => __('posts.form.google_business.event_end_date_before_start'),
+ 'meta.event.title.max' => __('posts.form.google_business.title_max'),
]);
});
test('custom meta attributes use translated field names', function () {
expect(PostPlatformMetaRules::attributes())->toBe([
- 'platforms.*.meta.title' => __('posts.form.pinterest.title'),
- 'platforms.*.meta.description' => __('posts.form.youtube.description'),
- 'platforms.*.meta.link' => __('posts.form.pinterest.link'),
- 'platforms.*.meta.event.title' => __('posts.form.google_business.event_title'),
- 'platforms.*.meta.call_to_action.url' => __('posts.form.google_business.cta_url'),
+ 'meta.title' => __('posts.form.pinterest.title'),
+ 'meta.description' => __('posts.form.youtube.description'),
+ 'meta.link' => __('posts.form.pinterest.link'),
+ 'meta.event.title' => __('posts.form.google_business.event_title'),
+ 'meta.call_to_action.url' => __('posts.form.google_business.cta_url'),
]);
});
test('shared description validation rejects multibyte overflow', function () {
- $validator = Validator::make(['platforms' => [['meta' => ['description' => str_repeat('é', 2501)]]]], PostPlatformMetaRules::rules());
+ $validator = Validator::make(['meta' => ['description' => str_repeat('é', 2501)]], PostPlatformMetaRules::rules());
expect($validator->fails())->toBeTrue()
- ->and($validator->errors()->has('platforms.0.meta.description'))->toBeTrue();
+ ->and($validator->errors()->has('meta.description'))->toBeTrue();
});
test('stored youtube description is checked without requiring it for other networks', function () {
@@ -45,13 +45,13 @@ test('stored youtube description is checked without requiring it for other netwo
test('shared meta rules still include non-pinterest platform fields', function () {
$rules = PostPlatformMetaRules::rules();
- expect($rules)->not->toHaveKey('platforms.*.meta.aspect_ratio')
+ expect($rules)->not->toHaveKey('meta.aspect_ratio')
->and($rules)->toHaveKeys([
- 'platforms.*.meta.privacy_level',
- 'platforms.*.meta.board_id',
- 'platforms.*.meta.channel_id',
- 'platforms.*.meta.title',
- 'platforms.*.meta.link',
+ 'meta.privacy_level',
+ 'meta.board_id',
+ 'meta.channel_id',
+ 'meta.title',
+ 'meta.link',
]);
});
@@ -159,42 +159,42 @@ test('google business offer topic type with all event fields present has no viol
test('google business meta rules validate topic_type and call_to_action shape', function () {
$rules = PostPlatformMetaRules::rules();
- expect($rules)->toHaveKey('platforms.*.meta.topic_type');
- expect($rules)->toHaveKey('platforms.*.meta.call_to_action.action_type');
- expect($rules)->toHaveKey('platforms.*.meta.call_to_action.url');
- expect($rules)->toHaveKey('platforms.*.meta.event.title');
- expect($rules)->toHaveKey('platforms.*.meta.offer.coupon_code');
+ expect($rules)->toHaveKey('meta.topic_type');
+ expect($rules)->toHaveKey('meta.call_to_action.action_type');
+ expect($rules)->toHaveKey('meta.call_to_action.url');
+ expect($rules)->toHaveKey('meta.event.title');
+ expect($rules)->toHaveKey('meta.offer.coupon_code');
});
test('google business event title is capped at the api length and coupon is not', function () {
$rules = PostPlatformMetaRules::rules();
- expect($rules['platforms.*.meta.event.title'])->toBe([
+ expect($rules['meta.event.title'])->toBe([
'sometimes',
'nullable',
'string',
'max:'.TopicType::TITLE_MAX_LENGTH,
])
- ->and($rules['platforms.*.meta.offer.coupon_code'])->toBe(['sometimes', 'nullable', 'string']);
+ ->and($rules['meta.offer.coupon_code'])->toBe(['sometimes', 'nullable', 'string']);
$tooLong = Validator::make(
- ['platforms' => [['meta' => ['event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1)]]]]],
+ ['meta' => ['event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH + 1)]]],
PostPlatformMetaRules::rules(),
PostPlatformMetaRules::messages(),
);
$atLimit = Validator::make(
- ['platforms' => [['meta' => ['event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH)]]]]],
+ ['meta' => ['event' => ['title' => str_repeat('t', TopicType::TITLE_MAX_LENGTH)]]],
PostPlatformMetaRules::rules(),
PostPlatformMetaRules::messages(),
);
$longCoupon = Validator::make(
- ['platforms' => [['meta' => ['offer' => ['coupon_code' => str_repeat('C', TopicType::TITLE_MAX_LENGTH + 20)]]]]],
+ ['meta' => ['offer' => ['coupon_code' => str_repeat('C', TopicType::TITLE_MAX_LENGTH + 20)]]],
PostPlatformMetaRules::rules(),
PostPlatformMetaRules::messages(),
);
expect($tooLong->fails())->toBeTrue()
- ->and($tooLong->errors()->first('platforms.0.meta.event.title'))->toBe(__('posts.form.google_business.title_max'))
+ ->and($tooLong->errors()->first('meta.event.title'))->toBe(__('posts.form.google_business.title_max'))
->and($atLimit->fails())->toBeFalse()
->and($longCoupon->fails())->toBeFalse();
});
@@ -202,17 +202,17 @@ test('google business event title is capped at the api length and coupon is not'
test('google business call_to_action.url rule is unconditional, not required_unless', function () {
$rules = PostPlatformMetaRules::rules();
- expect($rules['platforms.*.meta.call_to_action.url'])->toBe(['sometimes', 'nullable', 'url:http,https', 'max:2048']);
+ expect($rules['meta.call_to_action.url'])->toBe(['sometimes', 'nullable', 'url:http,https', 'max:2048']);
});
test('google business call_to_action action types reject get offer', function () {
$validator = Validator::make(
- ['platforms' => [['meta' => ['call_to_action' => ['action_type' => 'GET_OFFER']]]]],
+ ['meta' => ['call_to_action' => ['action_type' => 'GET_OFFER']]],
PostPlatformMetaRules::rules(),
);
expect($validator->fails())->toBeTrue()
- ->and($validator->errors()->has('platforms.0.meta.call_to_action.action_type'))->toBeTrue();
+ ->and($validator->errors()->has('meta.call_to_action.action_type'))->toBeTrue();
});
test('google business same-day end time before start time is a required-meta violation', function () {
@@ -371,22 +371,22 @@ test('youtube title is checked only for youtube', function () {
});
test('youtube enum keys reject unknown values', function () {
- $validator = Validator::make(['platforms' => [['meta' => [
+ $validator = Validator::make(['meta' => [
'privacy_status' => 'friends',
'license' => 'mine',
'category_id' => 'music',
- ]]]], PostPlatformMetaRules::rules());
+ ]], PostPlatformMetaRules::rules());
expect($validator->errors()->keys())->toEqualCanonicalizing([
- 'platforms.0.meta.privacy_status',
- 'platforms.0.meta.license',
- 'platforms.0.meta.category_id',
+ 'meta.privacy_status',
+ 'meta.license',
+ 'meta.category_id',
]);
});
test('youtube category accepts only the fixed category ids', function () {
$validate = fn (string $categoryId): bool => Validator::make(
- ['platforms' => [['meta' => ['category_id' => $categoryId]]]],
+ ['meta' => ['category_id' => $categoryId]],
PostPlatformMetaRules::rules(),
)->passes();
@@ -401,9 +401,9 @@ test('the meta documentation names every youtube key', function () {
});
test('youtube category accepts numeric ids', function () {
- $validator = Validator::make(['platforms' => [['meta' => [
+ $validator = Validator::make(['meta' => [
'category_id' => 27,
- ]]]], PostPlatformMetaRules::rules());
+ ]], PostPlatformMetaRules::rules());
expect($validator->passes())->toBeTrue()
->and(PostPlatformMetaRules::normalize(['category_id' => 27, 'title' => 'x']))->toBe(['category_id' => '27', 'title' => 'x'])
diff --git a/tests/Unit/PostPlatformTest.php b/tests/Unit/PostPlatformTest.php
deleted file mode 100644
index c3a1efb51..000000000
--- a/tests/Unit/PostPlatformTest.php
+++ /dev/null
@@ -1,178 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\PostPlatform\Status;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\User;
-use App\Models\Workspace;
-
-beforeEach(function () {
- $this->user = User::factory()->create();
- $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
-
- $this->post = Post::factory()->create([
- 'workspace_id' => $this->workspace->id,
- 'user_id' => $this->user->id,
- ]);
-
- $this->socialAccount = SocialAccount::factory()->create([
- 'workspace_id' => $this->workspace->id,
- ]);
-
- $this->postPlatform = PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
-});
-
-test('markAsPublished clears stale error_message and error_context', function () {
- $this->postPlatform->update([
- 'status' => Status::Failed,
- 'error_message' => 'The post is empty. Please enter a message to share.',
- 'error_context' => ['platform_error_code' => 197, 'content_length' => 0],
- ]);
-
- $this->postPlatform->markAsPublished('platform_post_abc', 'https://www.facebook.com/platform_post_abc');
-
- $this->postPlatform->refresh();
-
- expect($this->postPlatform->status)->toBe(Status::Published)
- ->and($this->postPlatform->platform_post_id)->toBe('platform_post_abc')
- ->and($this->postPlatform->error_message)->toBeNull()
- ->and($this->postPlatform->error_context)->toBeNull();
-});
-
-test('published scope only includes published platforms', function () {
- $publishedPostPlatform = PostPlatform::factory()->published()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- ]);
- PostPlatform::factory()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $this->socialAccount->id,
- 'status' => Status::Failed,
- ]);
-
- $publishedPlatforms = PostPlatform::query()->published()->get();
-
- expect($publishedPlatforms)->toHaveCount(1)
- ->and($publishedPlatforms->first()->is($publishedPostPlatform))->toBeTrue();
-});
-
-test('display_name falls back to the account username when display_name is not set', function () {
- $this->socialAccount->update(['display_name' => null, 'username' => 'acme_handle']);
-
- expect($this->postPlatform->fresh()->display_name)->toBe('acme_handle');
-});
-
-test('display_name falls back to the platform label when the live account has neither name set', function () {
- $this->socialAccount->update(['display_name' => null, 'username' => null]);
-
- expect($this->postPlatform->fresh()->display_name)->toBe($this->socialAccount->platform->label());
-});
-
-test('display_name falls back to the platform_name snapshot when the account has been deleted', function () {
- $this->postPlatform->update(['platform_name' => 'Snapshot Name']);
- $this->socialAccount->delete();
-
- expect($this->postPlatform->fresh()->display_name)->toBe('Snapshot Name');
-});
-
-test('notificationLabel prefers username over display name', function () {
- $account = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => 'myfbpage',
- 'display_name' => 'InboxPlacement.io',
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- expect($postPlatform->notificationLabel())->toBe('Facebook Page (@myfbpage)');
-});
-
-test('notificationLabel falls back to display name when username is empty', function () {
- $account = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => null,
- 'display_name' => 'InboxPlacement.io',
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- expect($postPlatform->notificationLabel())->toBe('Facebook Page (@InboxPlacement.io)');
-});
-
-test('notificationLabel uses username when display name is empty', function () {
- $account = SocialAccount::factory()->bluesky()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => 'inboxplacementio.bsky.social',
- 'display_name' => '',
- ]);
- $postPlatform = PostPlatform::factory()->bluesky()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- expect($postPlatform->notificationLabel())->toBe('Bluesky (@inboxplacementio.bsky.social)');
-});
-
-test('notificationLabel omits empty parentheses when both identifiers are missing', function () {
- $account = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => null,
- 'display_name' => '',
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- ]);
-
- expect($postPlatform->notificationLabel())->toBe('Facebook Page');
-});
-
-test('notificationLabel uses the snapshot when the account has been deleted', function () {
- $account = SocialAccount::factory()->facebook()->create([
- 'workspace_id' => $this->workspace->id,
- 'username' => null,
- 'display_name' => 'InboxPlacement.io',
- ]);
- $postPlatform = PostPlatform::factory()->facebook()->create([
- 'post_id' => $this->post->id,
- 'social_account_id' => $account->id,
- 'platform' => $account->platform,
- 'platform_name' => 'InboxPlacement.io',
- ]);
-
- $account->delete();
-
- expect($postPlatform->fresh()->notificationLabel())->toBe('Facebook Page (@InboxPlacement.io)');
-});
-
-test('markAsFailed clears stale platform_post_id and platform_url', function () {
- $this->postPlatform->update([
- 'status' => Status::Published,
- 'platform_post_id' => 'old_post_id',
- 'platform_url' => 'https://www.facebook.com/old_post_id',
- 'published_at' => now(),
- ]);
-
- $this->postPlatform->markAsFailed('Something went wrong.', ['platform_error_code' => 500]);
-
- $this->postPlatform->refresh();
-
- expect($this->postPlatform->status)->toBe(Status::Failed)
- ->and($this->postPlatform->error_message)->toBe('Something went wrong.')
- ->and($this->postPlatform->platform_post_id)->toBeNull()
- ->and($this->postPlatform->platform_url)->toBeNull();
-});
diff --git a/tests/Unit/PostPublicationTest.php b/tests/Unit/PostPublicationTest.php
new file mode 100644
index 000000000..bef8d9848
--- /dev/null
+++ b/tests/Unit/PostPublicationTest.php
@@ -0,0 +1,178 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\Post\PublishStatus;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Models\User;
+use App\Models\Workspace;
+
+beforeEach(function () {
+ $this->user = User::factory()->create();
+ $this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
+
+ $this->socialAccount = SocialAccount::factory()->create([
+ 'workspace_id' => $this->workspace->id,
+ ]);
+
+ $this->post = Post::factory()->forAccount($this->socialAccount)->create([
+ 'user_id' => $this->user->id,
+ ]);
+});
+
+test('markPublicationPublished clears stale error_message and error_context', function () {
+ $this->post->forceFill([
+ 'publish_status' => PublishStatus::Failed,
+ 'error_message' => 'The post is empty. Please enter a message to share.',
+ 'error_context' => ['platform_error_code' => 197, 'content_length' => 0],
+ ])->save();
+
+ $this->post->markPublicationPublished('platform_post_abc', 'https://www.facebook.com/platform_post_abc');
+
+ $this->post->refresh();
+
+ expect($this->post->publish_status)->toBe(PublishStatus::Published)
+ ->and($this->post->platform_post_id)->toBe('platform_post_abc')
+ ->and($this->post->error_message)->toBeNull()
+ ->and($this->post->error_context)->toBeNull();
+});
+
+test('markPublicationPublished does not move updated_at', function () {
+ $this->post->forceFill(['updated_at' => now()->subDay()])->saveQuietly();
+ $updatedAt = $this->post->fresh()->updated_at;
+
+ $this->post->markPublicationPublished('platform_post_abc');
+
+ expect($this->post->fresh()->updated_at->equalTo($updatedAt))->toBeTrue()
+ ->and($this->post->fresh()->publication_updated_at)->not->toBeNull();
+});
+
+test('publicationPublished scope only includes published posts', function () {
+ $published = Post::factory()->forAccount($this->socialAccount)->published()->create();
+ Post::factory()->forAccount($this->socialAccount)->failed()->create();
+
+ $publishedPosts = Post::query()->publicationPublished()->get();
+
+ expect($publishedPosts)->toHaveCount(1)
+ ->and($publishedPosts->first()->is($published))->toBeTrue();
+});
+
+test('display_name falls back to the account username when display_name is not set', function () {
+ $this->socialAccount->update(['display_name' => null, 'username' => 'acme_handle']);
+
+ expect($this->post->fresh()->display_name)->toBe('acme_handle');
+});
+
+test('display_name falls back to the platform label when the live account has neither name set', function () {
+ $this->socialAccount->update(['display_name' => null, 'username' => null]);
+
+ expect($this->post->fresh()->display_name)->toBe($this->socialAccount->platform->label());
+});
+
+test('display_name falls back to the platform_name snapshot when the account has been deleted', function () {
+ $this->post->update(['platform_name' => 'Snapshot Name']);
+ $this->socialAccount->delete();
+
+ expect($this->post->fresh()->display_name)->toBe('Snapshot Name');
+});
+
+test('display_username falls back to the platform_username snapshot when the account has been deleted', function () {
+ $this->post->update(['platform_username' => 'snapshot_handle']);
+ $this->socialAccount->delete();
+
+ expect($this->post->fresh()->display_username)->toBe('snapshot_handle');
+});
+
+test('notificationLabel prefers username over display name', function () {
+ $account = SocialAccount::factory()->facebook()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => 'myfbpage',
+ 'display_name' => 'InboxPlacement.io',
+ ]);
+ $post = Post::factory()->forAccount($account)->create();
+
+ expect($post->notificationLabel())->toBe('Facebook Page (@myfbpage)');
+});
+
+test('notificationLabel falls back to display name when username is empty', function () {
+ $account = SocialAccount::factory()->facebook()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => null,
+ 'display_name' => 'InboxPlacement.io',
+ ]);
+ $post = Post::factory()->forAccount($account)->create();
+
+ expect($post->notificationLabel())->toBe('Facebook Page (@InboxPlacement.io)');
+});
+
+test('notificationLabel uses username when display name is empty', function () {
+ $account = SocialAccount::factory()->bluesky()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => 'inboxplacementio.bsky.social',
+ 'display_name' => '',
+ ]);
+ $post = Post::factory()->forAccount($account)->create();
+
+ expect($post->notificationLabel())->toBe('Bluesky (@inboxplacementio.bsky.social)');
+});
+
+test('notificationLabel omits empty parentheses when both identifiers are missing', function () {
+ $account = SocialAccount::factory()->facebook()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => null,
+ 'display_name' => '',
+ ]);
+ $post = Post::factory()->forAccount($account)->create();
+
+ expect($post->notificationLabel())->toBe('Facebook Page');
+});
+
+test('notificationLabel uses the snapshot when the account has been deleted', function () {
+ $account = SocialAccount::factory()->facebook()->create([
+ 'workspace_id' => $this->workspace->id,
+ 'username' => null,
+ 'display_name' => 'InboxPlacement.io',
+ ]);
+ $post = Post::factory()->forAccount($account)->create([
+ 'platform_name' => 'InboxPlacement.io',
+ ]);
+
+ $account->delete();
+
+ expect($post->fresh()->notificationLabel())->toBe('Facebook Page (@InboxPlacement.io)');
+});
+
+test('notificationLabel is empty for a draft without a channel', function () {
+ $post = Post::factory()->create(['workspace_id' => $this->workspace->id]);
+
+ expect($post->notificationLabel())->toBe('');
+});
+
+test('attachesLinkPreview is false only when the card was dropped', function (?array $meta, bool $expected) {
+ $post = Post::factory()->forAccount($this->socialAccount)->make(['meta' => $meta]);
+
+ expect($post->attachesLinkPreview())->toBe($expected);
+})->with([
+ 'no meta' => [null, true],
+ 'card kept' => [['link_preview' => true], true],
+ 'card dropped' => [['link_preview' => false], false],
+]);
+
+test('markPublicationFailed clears stale platform_post_id and platform_url', function () {
+ $this->post->forceFill([
+ 'publish_status' => PublishStatus::Published,
+ 'platform_post_id' => 'old_post_id',
+ 'platform_url' => 'https://www.facebook.com/old_post_id',
+ 'published_at' => now(),
+ ])->save();
+
+ $this->post->markPublicationFailed('Something went wrong.', ['platform_error_code' => 500]);
+
+ $this->post->refresh();
+
+ expect($this->post->publish_status)->toBe(PublishStatus::Failed)
+ ->and($this->post->error_message)->toBe('Something went wrong.')
+ ->and($this->post->platform_post_id)->toBeNull()
+ ->and($this->post->platform_url)->toBeNull();
+});
diff --git a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
index 7a02361ef..e64169918 100644
--- a/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
+++ b/tests/Unit/Rules/ContentTypeCompatibleWithMediaTest.php
@@ -10,7 +10,7 @@ function runMediaRule(string $contentType, array $media): array
{
$errors = [];
$rule = (new ContentTypeCompatibleWithMedia)->setData(['media' => $media]);
- $rule->validate('platforms.0.content_type', $contentType, function (string $message) use (&$errors): void {
+ $rule->validate('content_type', $contentType, function (string $message) use (&$errors): void {
$errors[] = $message;
});
@@ -362,7 +362,7 @@ test('falls back to stored media when the request omits the media key', function
$errors = [];
(new ContentTypeCompatibleWithMedia([['type' => 'document', 'mime_type' => 'application/pdf']]))
->setData([]) // no 'media' key in the request -> use the fallback
- ->validate('platforms.0.content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void {
+ ->validate('content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void {
$errors[] = $message;
});
@@ -372,7 +372,7 @@ test('falls back to stored media when the request omits the media key', function
$xErrors = [];
(new ContentTypeCompatibleWithMedia([['type' => 'document', 'mime_type' => 'application/pdf']]))
->setData([])
- ->validate('platforms.0.content_type', ContentType::XPost->value, function (string $message) use (&$xErrors): void {
+ ->validate('content_type', ContentType::XPost->value, function (string $message) use (&$xErrors): void {
$xErrors[] = $message;
});
@@ -389,7 +389,7 @@ test('request media takes precedence over the stored fallback', function () {
['type' => 'document', 'mime_type' => 'application/pdf'],
['type' => 'image', 'mime_type' => 'image/jpeg'],
]])
- ->validate('platforms.0.content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void {
+ ->validate('content_type', ContentType::LinkedInPost->value, function (string $message) use (&$errors): void {
$errors[] = $message;
});
diff --git a/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php b/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php
index e5a6dedda..4886f4006 100644
--- a/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php
+++ b/tests/Unit/Rules/ContentTypeMatchesPlatformTest.php
@@ -8,19 +8,21 @@ use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Rules\ContentTypeMatchesPlatform;
use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Str;
uses(RefreshDatabase::class);
function runMatchesPlatformRule(string $contentType, ?string $accountId, array $extraData = []): array
{
$errors = [];
- $rule = (new ContentTypeMatchesPlatform)->setData(array_merge([
- 'platforms' => [
+ $workspaceId = $accountId !== null && Str::isUuid($accountId) ? SocialAccount::query()->find($accountId)?->workspace_id : null;
+ $rule = (new ContentTypeMatchesPlatform($workspaceId))->setData(array_merge([
+ 'destinations' => [
['social_account_id' => $accountId, 'content_type' => $contentType],
],
], $extraData));
- $rule->validate('platforms.0.content_type', $contentType, function (string $message) use (&$errors): void {
+ $rule->validate('destinations.0.content_type', $contentType, function (string $message) use (&$errors): void {
$errors[] = $message;
});
@@ -86,3 +88,30 @@ test('skips validation when content_type is not a known enum value', function ()
// intentionally no-ops so it doesn't double-report.
expect(runMatchesPlatformRule('completely_made_up', $linkedin->id))->toBe([]);
});
+
+test('reads the top-level account next to a top-level content type', function () {
+ $linkedin = SocialAccount::factory()->create(['platform' => Platform::LinkedIn]);
+ $errors = [];
+
+ (new ContentTypeMatchesPlatform($linkedin->workspace_id))
+ ->setData(['social_account_id' => $linkedin->id, 'content_type' => ContentType::XPost->value])
+ ->validate('content_type', ContentType::XPost->value, function (string $message) use (&$errors): void {
+ $errors[] = $message;
+ });
+
+ expect($errors)->toHaveCount(1)
+ ->and($errors[0])->toContain('not compatible');
+});
+
+test('says nothing about an account from another workspace', function () {
+ $linkedin = SocialAccount::factory()->create(['platform' => Platform::LinkedIn]);
+ $errors = [];
+
+ (new ContentTypeMatchesPlatform(Workspace::factory()->create()->id))
+ ->setData(['social_account_id' => $linkedin->id, 'content_type' => ContentType::XPost->value])
+ ->validate('content_type', ContentType::XPost->value, function (string $message) use (&$errors): void {
+ $errors[] = $message;
+ });
+
+ expect($errors)->toBe([]);
+});
diff --git a/tests/Unit/Rules/ContentTypeMatchesPostChannelTest.php b/tests/Unit/Rules/ContentTypeMatchesPostChannelTest.php
new file mode 100644
index 000000000..1554ecbad
--- /dev/null
+++ b/tests/Unit/Rules/ContentTypeMatchesPostChannelTest.php
@@ -0,0 +1,47 @@
+<?php
+
+declare(strict_types=1);
+
+use App\Enums\PostPlatform\ContentType;
+use App\Models\Post;
+use App\Models\SocialAccount;
+use App\Rules\ContentTypeMatchesPostChannel;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+
+uses(RefreshDatabase::class);
+
+function runMatchesPostChannelRule(Post $post, string $contentType): array
+{
+ $errors = [];
+
+ (new ContentTypeMatchesPostChannel($post))->validate('content_type', $contentType, function (string $message) use (&$errors): void {
+ $errors[] = $message;
+ });
+
+ return $errors;
+}
+
+test('passes when content_type matches the post channel', function () {
+ $post = Post::factory()->forAccount(SocialAccount::factory()->linkedin()->create())->create();
+
+ expect(runMatchesPostChannelRule($post, ContentType::LinkedInPost->value))->toBe([]);
+});
+
+test('fails when content_type belongs to a different platform than the post channel', function () {
+ $post = Post::factory()->forAccount(SocialAccount::factory()->linkedin()->create())->create();
+
+ $errors = runMatchesPostChannelRule($post, ContentType::XPost->value);
+
+ expect($errors)->toHaveCount(1)
+ ->and($errors[0])->toContain('not compatible');
+});
+
+test('skips validation for a post without a channel', function () {
+ expect(runMatchesPostChannelRule(Post::factory()->create(), ContentType::XPost->value))->toBe([]);
+});
+
+test('skips validation for an unknown content type', function () {
+ $post = Post::factory()->forAccount(SocialAccount::factory()->linkedin()->create())->create();
+
+ expect(runMatchesPostChannelRule($post, 'not_a_type'))->toBe([]);
+});
diff --git a/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php b/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php
deleted file mode 100644
index 0c0396c05..000000000
--- a/tests/Unit/Rules/ContentTypeMatchesPostPlatformTest.php
+++ /dev/null
@@ -1,74 +0,0 @@
-<?php
-
-declare(strict_types=1);
-
-use App\Enums\PostPlatform\ContentType;
-use App\Enums\SocialAccount\Platform;
-use App\Models\Post;
-use App\Models\PostPlatform;
-use App\Models\SocialAccount;
-use App\Models\Workspace;
-use App\Rules\ContentTypeMatchesPostPlatform;
-use Illuminate\Foundation\Testing\RefreshDatabase;
-
-uses(RefreshDatabase::class);
-
-function runMatchesPostPlatformRule(string $contentType, ?string $postPlatformId): array
-{
- $errors = [];
- $rule = (new ContentTypeMatchesPostPlatform)->setData([
- 'platforms' => [
- ['id' => $postPlatformId, 'content_type' => $contentType],
- ],
- ]);
-
- $rule->validate('platforms.0.content_type', $contentType, function (string $message) use (&$errors): void {
- $errors[] = $message;
- });
-
- return $errors;
-}
-
-test('passes when content_type matches the post_platform social account', function () {
- $workspace = Workspace::factory()->create();
- $linkedin = SocialAccount::factory()->create([
- 'workspace_id' => $workspace->id,
- 'platform' => Platform::LinkedIn,
- ]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedin->id,
- ]);
-
- expect(runMatchesPostPlatformRule(ContentType::LinkedInPost->value, $postPlatform->id))->toBe([]);
-});
-
-test('fails when content_type belongs to a different platform than the post_platform', function () {
- $workspace = Workspace::factory()->create();
- $linkedin = SocialAccount::factory()->create([
- 'workspace_id' => $workspace->id,
- 'platform' => Platform::LinkedIn,
- ]);
- $post = Post::factory()->create(['workspace_id' => $workspace->id]);
- $postPlatform = PostPlatform::factory()->linkedin()->create([
- 'post_id' => $post->id,
- 'social_account_id' => $linkedin->id,
- ]);
-
- $errors = runMatchesPostPlatformRule(ContentType::XPost->value, $postPlatform->id);
-
- expect($errors)->toHaveCount(1);
- expect($errors[0])->toContain('not compatible');
-});
-
-test('skips validation when platform id is missing', function () {
- expect(runMatchesPostPlatformRule(ContentType::XPost->value, null))->toBe([]);
-});
-
-test('skips validation when post_platform does not exist', function () {
- // Valid-format UUID that does not exist in the database. The rule
- // intentionally no-ops so the missing-resource error is reported by
- // the surrounding Rule::exists check rather than this rule.
- expect(runMatchesPostPlatformRule(ContentType::XPost->value, '00000000-0000-0000-0000-000000000000'))->toBe([]);
-});
diff --git a/tests/Unit/Support/PostStatusRulesTest.php b/tests/Unit/Support/PostStatusRulesTest.php
index 515bd9333..6bb7b08b0 100644
--- a/tests/Unit/Support/PostStatusRulesTest.php
+++ b/tests/Unit/Support/PostStatusRulesTest.php
@@ -13,7 +13,6 @@ test('blocks editing for terminal statuses', function (PostStatus $status) {
})->with([
PostStatus::Publishing,
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
]);
@@ -33,7 +32,6 @@ test('blocks deletion for sent and failed statuses', function (PostStatus $statu
})->with([
PostStatus::Publishing,
PostStatus::Published,
- PostStatus::PartiallyPublished,
PostStatus::Failed,
]);
diff --git a/tests/Unit/Support/Social/GoogleBusinessDerivativeCleanerTest.php b/tests/Unit/Support/Social/GoogleBusinessDerivativeCleanerTest.php
index 692211ec3..916d2a036 100644
--- a/tests/Unit/Support/Social/GoogleBusinessDerivativeCleanerTest.php
+++ b/tests/Unit/Support/Social/GoogleBusinessDerivativeCleanerTest.php
@@ -2,18 +2,20 @@
declare(strict_types=1);
+use App\Models\Post;
use App\Support\Social\GoogleBusinessDerivativeCleaner;
use Illuminate\Support\Facades\Storage;
-test('it deletes the managed google business jpeg for a post platform', function () {
+test('it deletes the managed google business jpeg for a post', function () {
Storage::fake();
- $postPlatformId = '123e4567-e89b-12d3-a456-426614174000';
- $path = GoogleBusinessDerivativeCleaner::pathFor($postPlatformId);
+ $post = Post::factory()->make(['id' => '123e4567-e89b-12d3-a456-426614174000']);
+ $path = GoogleBusinessDerivativeCleaner::pathFor($post);
Storage::put($path, 'image');
Storage::put('uploads/keep.jpg', 'keep');
- app(GoogleBusinessDerivativeCleaner::class)->cleanup($postPlatformId);
+ app(GoogleBusinessDerivativeCleaner::class)->cleanup($post);
+ expect($path)->toEndWith('/123e4567-e89b-12d3-a456-426614174000.jpg');
Storage::assertMissing($path);
Storage::assertExists('uploads/keep.jpg');
});
@@ -21,7 +23,7 @@ test('it deletes the managed google business jpeg for a post platform', function
test('it no-ops when the derivative is already gone', function () {
Storage::fake();
- app(GoogleBusinessDerivativeCleaner::class)->cleanup('123e4567-e89b-12d3-a456-426614174000');
+ app(GoogleBusinessDerivativeCleaner::class)->cleanup(Post::factory()->make(['id' => '123e4567-e89b-12d3-a456-426614174000']));
expect(Storage::allFiles())->toBe([]);
});
diff --git a/tests/Unit/ThreadRepliesTest.php b/tests/Unit/ThreadRepliesTest.php
index 40f8bf0dc..cb9c9cc7f 100644
--- a/tests/Unit/ThreadRepliesTest.php
+++ b/tests/Unit/ThreadRepliesTest.php
@@ -48,7 +48,7 @@ test('resume keeps the longest matching prefix', function () {
});
test('thread_replies has a rule so validated() keeps it', function () {
- expect(PostPlatformMetaRules::rules())->toHaveKeys(['platforms.*.meta.thread_replies', 'platforms.*.meta.thread_replies.*'])
+ expect(PostPlatformMetaRules::rules())->toHaveKeys(['meta.thread_replies', 'meta.thread_replies.*'])
->and(ThreadReplies::supports(Platform::X))->toBeTrue()
->and(ThreadReplies::supports(Platform::Mastodon))->toBeTrue()
->and(ThreadReplies::supports(Platform::Bluesky))->toBeTrue()
diff --git a/tests/fixtures/single-line-copy.php b/tests/fixtures/single-line-copy.php
index 312cdd5a9..c9883f316 100644
--- a/tests/fixtures/single-line-copy.php
+++ b/tests/fixtures/single-line-copy.php
@@ -101,6 +101,7 @@ return [
'posts.form.youtube.visibility' => 13,
'posts.list_view' => 6,
'posts.publish.actions.add_to_queue' => 28,
+ 'posts.publish.in_google_review' => 28,
'settings.api_keys.description' => 42,
'settings.members.access.admin_description' => 41,
'settings.members.access.needs_approval' => 25,
@@ -131,7 +132,6 @@ return [
'webhooks.event_descriptions.post_created' => 41,
'webhooks.event_descriptions.post_deleted' => 36,
'webhooks.event_descriptions.post_failed' => 50,
- 'webhooks.event_descriptions.post_partially_published' => 55,
'webhooks.event_descriptions.post_published' => 48,
'webhooks.event_descriptions.post_scheduled' => 51,
'webhooks.event_descriptions.post_unscheduled' => 54,