Skip to content

refactor: single-domain routing, actions, policies, Google login, PostHog, full test coverage - #10

Merged
paulocastellano merged 91 commits into
mainfrom
refactor/actions-subdomain-routes
Apr 1, 2026
Merged

paulocastellano merged 91 commits into
mainfrom
refactor/actions-subdomain-routes

Conversation

@paulocastellano

@paulocastellano paulocastellano commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Single-domain routing: Remove subdomain architecture (app./api./mcp.), use path prefixes instead (/api, /mcp/trypost). Self-hosted users only configure APP_URL
  • Actions pattern: Extract business logic into Action classes (CreateUser, CreatePost, UpdatePost, ToggleSocialAccount, etc.)
  • Policy refactor: Use pivot role instead of workspace.user_id, add manageBilling (owner-only), fix API key authorization
  • Google OAuth login/signup: SocialLoginController with separate google-auth driver, CreateUser shared action, SignupSuccess page
  • PostHog + GTM: Backend service + job, frontend tracking composable, all env-configurable (graceful when keys missing)
  • Notification system: Bell panel, mark read/archive, email preferences, SendNotification job
  • Social account toggle: Action + API endpoint + MCP tool with full test coverage
  • Scroll pagination: Posts, hashtags, labels use Inertia scroll with InfiniteScroll
  • Code quality: All data_get(), all enums (Role, PostStatus, PostAction, ApiToken\Status), User::SUBSCRIPTION_NAME constant, no hardcoded strings
  • Frontend: Arrow functions only, no required HTML attrs, no new Date(), no hardcoded URLs, 0 TypeScript errors, 0 ESLint errors

Test coverage

  • 896 tests, 2321 assertions
  • 31 app controllers: all tested
  • 19 API endpoints: all tested (happy path + validation + cross-workspace + auth)
  • 18 MCP tools: all tested (CRUD + validation + cross-workspace + error handling)
  • 11 social publishers: all tested
  • Role-based authorization: owner/admin/member tested for every feature

Test plan

  • All 896 tests pass
  • Pint: 0 formatting issues
  • TypeScript: 0 errors
  • ESLint: 0 errors
  • No pending migrations

- Extract business logic from controllers into Action classes:
  Post/, Workspace/, Hashtag/, Label/, Invite/, ApiKey/
- Create subdomain routing: app.trypost.test (Inertia dashboard),
  api.trypost.test (REST API with token auth)
- Add ApiToken model with tp_ prefix, token_lookup/hash auth
- Add AuthenticateApiToken middleware for API authentication
- Create Api controllers with JSON Resources for all entities
- Create App controllers that use Actions + Inertia responses
- Organize Form Requests into Api/ and App/ directories
- Add api_tokens migration
- Update all route names with app. prefix
- Update all tests to use new route names (684 passing)
Update all Vue components and TypeScript files to import from the new
Wayfinder-generated paths under @/routes/app/ and @/actions/App/Http/Controllers/App/.
- Remove old root-level controllers (moved to App/ namespace)
- Remove old routes/settings.php (merged into routes/app.php)
- Add routes/mcp.php placeholder for future MCP server
- Add settings/ApiKeys.vue page with create/delete/copy token
- Add API Keys nav item to settings layout
- Add 26 API endpoint tests (auth, hashtags, labels, api-keys, workspace)
- Add ApiToken factory
- All 710 tests passing
…hardening

- Add API rate limiting (60/min per workspace) in AppServiceProvider
- Add throttle:api middleware to all API routes
- Add rate limit exception rendering for JSON responses
- Add middleware priority list (AuthenticateApiToken before ThrottleRequests)
- Add ApiKeyControllerTest (6 tests for App dashboard CRUD)
- Remove duplicate test files (Controllers/ dir duplicates)
- Remove old controllers and routes/settings.php
- Add routes/mcp.php placeholder
- Add API Keys nav item to settings layout
- Fix LazilyRefreshDatabase conflict in API tests
- 698 tests passing
- Create TryPostServer MCP server with 17 tools:
  Post (List, Get, Create, Delete), Hashtag (List, Create, Update, Delete),
  Label (List, Create, Update, Delete), Workspace (Get),
  ApiKey (List, Create, Delete)
- Create AuthenticateMcpToken middleware (logs in workspace owner)
- Register mcp.auth middleware alias in bootstrap/app.php
- Create routes/ai.php with mcp.trypost.test subdomain
- Add PostApiTest with 6 tests (list, show, create, delete, isolation)
- Fix PostApiTest assertions for pagination/resource wrapping
- 704 tests passing, frontend build passing
…es, fix auth routes

- Move middleware to App/ subdir (HandleInertiaRequests, HandleAppearance,
  EnsureSubscribed, EnsureUserSetupIsComplete) matching Sendkit pattern
- Move all Form Requests into organized subdirs (App/Post, App/Workspace,
  App/Media, App/Invite, App/Settings, App/Auth)
- Create AuthUserResource and AuthWorkspaceResource for HandleInertiaRequests
  shared data (role inside currentWorkspace, matching Sendkit pattern)
- Split auth.php into 3 route groups (no middleware, guest, auth) matching
  Sendkit pattern exactly
- Fix UserFactory to include all nullable attributes (current_workspace_id,
  stripe_id, pm_type, pm_last_four, trial_ends_at)
- Fix SocialAccountResource (display_name not name)
- Update frontend for new auth prop structure
- 702 tests passing (2 pre-existing Mastodon failures)
- Workspace switcher in sidebar header (dropdown with team list)
- NavMain component with label and activePattern support
- User menu in sidebar footer via NavUser component
- UserMenuContent with theme switcher submenu (light/dark/system)
- UserInfo component with avatar fallback and customizable classes
- AppSidebarLayout using SidebarProvider/SidebarInset directly
- AppSidebarHeader with right slot for header actions
- AppLayout with fullWidth and header-right slot support
- Remove workspace/user/theme/language from header dropdown
- 702 tests passing, build passing
…orkspace logo upload

- Fix useActiveUrl to use prefix matching (matching Sendkit pattern) so
  sidebar and settings nav tabs properly highlight the active page
- Make user reactive (computed) in Profile.vue and NavUser.vue so photo
  upload/delete reflects immediately without page reload
- Update Avatar component to use simple v-if/v-else instead of Reka UI
  AvatarImage/AvatarFallback which cached internal loading state
- Remove rounded="full" from PhotoUpload usage to match Sendkit (rounded-lg)
- Add workspace logo upload/delete routes and controller methods
- Replace workspace logo attribute (array) with has_logo/logo_url accessors
- Pass logo_url in AuthWorkspaceResource so sidebar shows workspace logo
@paulocastellano
paulocastellano marked this pull request as draft March 30, 2026 02:02
…trict_types

Settings pages:
- Redesign layout to match Sendkit (max-w-4xl, space-y-12, Separator sections)
- Merge Members page into Workspace settings with Table, invite Dialog, ConfirmDeleteModal
- Add workspace logo upload/delete routes and controller methods
- Translate all hardcoded strings in Workspace.vue modals

Language system:
- Drop languages table, replace language_id FK with locale string column on users
- Create config/languages.php for available languages and default locale
- Add Spanish (es) translations (13 files)
- Simplify HandleInertiaRequests, ProfileController, RegisteredUserController

Code quality:
- Add declare(strict_types=1) to all PHP files
- Fix MastodonPublisher using wrong attribute (filename -> original_filename)
- Fix HasMediaTest for new has_photo/photo_url accessors
- Fix PublishToSocialPlatformTest type error revealed by strict_types
- Remove orphaned Language model from AppServiceProvider morph map
- Update User TypeScript interface (has_photo, photo_url, locale)
- Eager load media relation on workspaces to prevent N+1
- Add 8 new tests for workspace logo upload/delete
- Update workspace settings test to assert members/invitations props

All 710 tests passing.
…okie locale

Auth pages:
- Create AuthSplitLayout with animated feature slides (6 slides, 3 languages)
- All auth pages use split layout (form left, visual right)
- Add show/hide password toggle with tooltip on Register
- Legal footer only shown on Register via showLegal prop

Subscribe page:
- Redesign to match auth card pattern (centered, clean)
- Platform icons, feature checklist, dynamic trial days (trialDays - 1)
- Add "Switch workspace" link
- Full i18n (en, es, pt-BR)

Onboarding:
- Rename URLs: step1 -> role, step2 -> connect
- Add enforceStep() to prevent skipping/going back steps
- Redirect /onboarding to /onboarding/role
- Redesign Step2 with AuthSplitLayout and compact platform list
- 21 tests covering all step enforcement scenarios

Workspaces page:
- Redesign with AuthSplitLayout (list with avatars, current badge)

Language system:
- Move locale from DB to cookie (forever, unencrypted, session.domain)
- Create SetLocale middleware (sets cookie if missing, validates against config)
- Rename lang/pt-br to lang/pt-BR
- Add dayjs es locale

Other:
- Copy utils.ts from sendkit (formatNumber, formatMoney, copyToClipboard)
- ConfirmDeleteModal with text confirmation (sendkit pattern)
- i18n for ConfirmDeleteModal internal strings (common.php)
- EmptyState component for posts index
- Exact match for "All" posts in sidebar
- Posts breadcrumbs show current status filter
- DialogFooter buttons aligned left
- API Keys page redesign with Table, DropdownMenu, EmptyState
- Extract CreateApiKeyDialog and InviteMemberDialog to components
- Remove API Keys from sidebar
- DropdownMenuItem destructive variant for Remove action
- Add subscription check to AuthenticateApiToken and AuthenticateMcpToken
  middlewares (returns 402 Payment Required if no active subscription)
- Skip subscription check in self-hosted mode
- Remove temporary OAuth debug log from SocialController
- Run composer dump-autoload to fix email_asset() helper autoloading
- Add 4 new tests for API subscription enforcement

All 728 tests passing.
i18n (all 3 languages - EN, ES, PT-BR):
- ApiKeys page + CreateApiKeyDialog: 26 strings
- billing/Processing page: 8 strings
- onboarding/Step1 + Step2: 10 strings (new onboarding.php)
- UserMenuContent: 7 strings (Account, Theme, Language, Log out)
- PhotoUpload: 4 strings (Upload, Remove, hint)
- TimezoneCombobox: 3 strings
- DatePicker: 1 string
- workspaces/Create + Index: full i18n (new workspaces.php)

Toast system:
- Unify Toast.vue with Sonner (copied from sendkit)
- Flash messages + JS toasts use same system
- Icon colors via CSS (success/error/warning/info)
- Position bottom-right

UI improvements:
- Posts Edit: move trash/schedule/publish to header-right slot
- Posts Edit: labels/hashtags/datepicker stay in top bar with platforms
- Posts Edit: delete post requires typing DELETE to confirm
- Posts Edit: Labels button with icon+text, always visible
- DatePicker: w-full by default, w-auto via class override
- Fix "Etiquetas" -> "Etiqueta" (remove plural)
- Posts breadcrumbs: /posts shows "Posts > All Posts"
- Calendar breadcrumbs: "Posts > Calendar"
- Edit breadcrumbs: "Posts > Edit Post"
- Remove unused AppHeader.vue and AppHeaderLayout.vue

All 728 tests passing.
Critical:
- Fix EnsureUserSetupIsComplete middleware route name prefixes and
  redirect Subscription step to subscribe page (not onboarding)
- Fix MCP session pollution: Auth::setUser() instead of Auth::login()
- Remove dead BillingController::addWorkspace/removeWorkspace methods
- Remove broken Workspace::pendingInvites() method

Security (IDOR):
- MediaController: add workspace ownership verification on all endpoints
- UpdatePostRequest: scope label_ids validation to current workspace
- UpdatePostRequest: scope platform IDs validation to current post

Security (other):
- Fix open redirect in login and registration (validate internal URLs)
- Add validation to API PostController store/update (was $request->all())
- Prevent Owner role assignment via updateRole endpoint
- Fix API post author attribution to use workspace owner

Authorization:
- PostController: use createPost policy instead of view for store/update/destroy

Logic:
- Post Status enum labels now use translation system instead of hardcoded Portuguese
- Workspace deletion cleans up current_workspace_id for all affected members
- StoreWorkspaceInviteRequest: replace Portuguese validation messages with __()

Rename onboarding:
- Step1.vue -> Role.vue, Step2.vue -> Connect.vue
- Controller methods: step1->role, storeStep1->storeRole, step2->connect, storeStep2->storeConnect

All 728 tests passing.
Publishing improvements:
- Create PostPlatformStatus enum (Pending, Publishing, Published, Failed)
- Update PostPlatform model, jobs, factories to use enum
- Add PostPublishFailed email notification when post fails to publish
- Maizzle template + blade for failure email with platform details
- PublishPost job: add $tries=3, $backoff=30, failed() method
- Fix broadcast event to serialize enum status value

Security:
- Add rate limiting (throttle:6,1) on social connect endpoints
- Fix MediaController::reorder IDOR vulnerability
- Fix Connect.vue broken import (storeStep2 -> storeConnect)
- Fix UpdatePost data_get() consistency

Database:
- Add composite index on post_platforms (post_id, enabled)
- Add index on post_platforms (social_account_id)

Tests:
- Add 3 tests for profile photo upload/delete
- Add 2 tests for media reorder (including IDOR check)
- Fix publish tests for PostPlatformStatus enum
- Add Mail::fake() to publish tests

Cleanup:
- Remove unused AppHeader.vue and AppHeaderLayout.vue
- Remove dead BillingController methods

All 733 tests passing.
Backend:
- Create notifications table (user_id, workspace_id, type, channel,
  title, body, data JSON, read_at, archived_at)
- Create Notification model with Type enum (post_failed,
  account_disconnected, invite_received, member_joined, member_removed)
  and Channel enum (email, in_app, both)
- Create SendNotification job: isolated from publish flow, handles
  saving in-app notification and sending email independently
- NotificationController: index (excludes archived, scoped to workspace),
  markAsRead, markAllAsRead, archiveAll
- Integrate with PublishToSocialPlatform (post failed/partial)
- Integrate with VerifyWorkspaceConnections (batch disconnection)
- Integrate with SocialAccount::markAsDisconnected (single disconnection)
- All use SendNotification::dispatch() instead of direct Mail::to()

Frontend:
- NotificationBell component in sidebar footer with unread badge
- Dialog with notification list, mark as read, mark all read, archive all
- Click navigates to relevant page (post edit, accounts)
- i18n for notifications UI (en, es, pt-BR)

Tests:
- 8 tests for NotificationController (auth, CRUD, workspace scoping)
- 4 tests for SendNotification job (channels, email, data storage)

All 745 tests passing.
- Create PostPublished mail + maizzle template for success notifications
- Add PostPublished type to Notification enum
- Notify owner on publish success (email + in-app via SendNotification job)
- Rename AppSidebarHeader to AppHeader with left/right slots
- Fix layout: header fixed, content scrolls (flex h-screen pattern)
- Fix fullWidth pages (calendar, editor) to fill available height
- Fix NotificationBell icon size to match sidebar items
- Fix SocialAccountsGrid buttons to use shadcn Button ghost
- Add pending status i18n key for PostPlatform

All 745 tests passing.
… polish

Notification preferences:
- Create notification_preferences table (post_published, post_failed,
  account_disconnected booleans per user)
- NotificationPreferenceController with firstOrCreate on first visit
- SendNotification job respects email preferences before sending
- Settings page with toggle switches, i18n in 3 languages
- 8 new tests for preferences (controller + wantsEmailFor + job integration)

Post published notification:
- PostPublished mail + maizzle template
- Notify owner on successful publish via SendNotification job
- PostPublished type added to notification enum

Header & Layout:
- Rename AppSidebarHeader to AppHeader with left/center/right slots
- showSidebarTrigger prop to hide sidebar toggle
- Calendar: controls in header (left: nav, center: date, right: tabs + new post)
- Fixed header with scrollable content (flex h-screen pattern)
- fullWidth pages use overflow-y-auto (fixes month view scroll)

UI improvements:
- Action buttons moved to header-right: posts, hashtags, labels
- Settings breadcrumbs: "Settings > Profile" pattern
- Calendar: remove duplicate New Post button from day view
- Remove size="sm" from Schedule/Publish buttons
- Remove bg-background from header (inherits from SidebarInset)
- Add Cancel button to labels and hashtags create/edit dialogs
- Add common.cancel i18n key
- Clean up orphaned Calendar breadcrumbs
- Fix SocialAccountsGrid buttons to use shadcn Button ghost

All 753 tests passing.
…polish

Sidebar:
- Fix double active state: "All" uses excludeActive to skip filter paths
- Add excludeActive option to urlIsActive composable and NavItem type
- Move notification bell next to user menu (icon only, no text)
- Remove Discord from sidebar footer
- Rename "Docs" to "Documentation" in EN

Phone mockup:
- Increase size from 270x585 to 360x780 for better preview

Header & Layout:
- Add center slot to AppHeader (used by Calendar for date title)
- Calendar controls split: left (nav), center (date), right (tabs + new post)
- Remove duplicate New Post button from day view
- Fix month view scroll (remove overflow-hidden)

UI:
- Move action buttons to header-right: posts, hashtags, labels
- Settings breadcrumbs: "Settings > Profile" pattern for all pages
- Add Cancel button to hashtags create/edit dialogs
- Add common.cancel i18n key for reuse
- Social accounts grid: use shadcn Button ghost for actions

All 753 tests passing.
- Refactor WorkspacePolicy to use pivot role instead of workspace.user_id
- Add manageBilling policy (owner only) to BillingController
- Fix ApiKeyController authorization (view → manageTeam for store/destroy)
- Fix WorkspaceInviteController using workspace.user_id for owner checks
- Fix WorkspaceController settings is_owner using workspace.user_id
- Create PostAction enum for UpdatePost/PostController action strings
- Create ApiToken\Status enum
- Add User::SUBSCRIPTION_NAME constant, replace all hardcoded 'default'
- Convert wantsEmailFor to accept NotificationType enum
- Convert all $data[] to data_get() across publishers, controllers, jobs
- Fix SocialLoginController callback missing try/catch
- Fix SocialController::toggleActive missing workspace null check
- Fix UpdatePost NPE on meta merge when postPlatform not found
- Remove HTML5 required attributes from form inputs
- Convert function declarations to arrow functions in Vue components
- Replace hardcoded URLs with Wayfinder route helpers
- Replace new Date() with dayjs
- Add 16 new test files covering policies, authorization, publishing
- Extract ToggleSocialAccount action from SocialController
- Add API endpoints: GET /social-accounts, PUT /social-accounts/{id}/toggle
- Add MCP tools: ListSocialAccountsTool, ToggleSocialAccountTool
- Fix all MCP tools: findOrFail → find + Response::error for graceful errors
- Fix MCP tools using $request->validated() without validate() call
- Fix return types to Response|ResponseFactory for error paths
- Add SocialAccountResource is_active/status fields (no tokens exposed)
- Add 43 MCP tests covering all 18 tools (CRUD, validation, cross-workspace)
- Add API response structure tests for posts, hashtags, labels, workspace
- Add API validation tests for post create/update, api-key expiry, label color
- Add API cross-workspace delete tests for hashtags and labels
- Add app validation tests for hashtag/label update, invite fields, password
- Add auth required tests for notifications, profile delete, api-keys index
- Add media reorder validation tests
- Fix Auth type: add currentWorkspace, workspaces, FlashData
- Fix User.id type: number → string (UUID)
- Fix trans() number params: wrap with String()
- Fix debounce NodeJS.Timeout → ReturnType<typeof setTimeout>
- Fix DatePicker name prop: required → optional
- Fix DatePicker emit typing
- Fix storeStep1 → storeRole import in onboarding/Role
- Fix duplicate id in AcceptInvite interface
- Fix formatDate → formatDateTime in ApiKeys
- Add @unovis/vue and @unovis/ts type declarations
- Install @unovis/vue @unovis/ts dev dependencies
- Add type casts for Inertia/Reka UI component props
- Remove unused imports (trans, postsIndex, BreadcrumbItemType, workspaceSettings)
- Remove unused variables (pageDescription, selectedLabels, _progress, props)
- Fix duplicate key: rename preferences import to preferencesRoute
- Remove @unovis ambient declarations (packages now installed)
- Fix import order in Wayfinder-generated routes
…, stuck recovery

- Add ContentSanitizer: strips HTML, converts bold/underline to Unicode for LinkedIn
- Add backend content length validation in all 11 publishers via HasSocialHttpClient trait
- Add scope verification before publishing — checks required scopes per platform
- Add RecoverStuckPosts command (every 30min) — recovers posts stuck in publishing > 1h
- Add requiredPublishScopes() to Platform enum
- Update SocialAccount factory with correct scopes per platform state
…eckSocialConnections includes TokenExpired
… frontend, duplicate notifications, chunked mime validation
…ublishPost tries:1, TokenExpired allows publish, API validation scoping
…ed as token error — now only code 190 triggers TokenExpiredException
… — binary upload was breaking the transfer phase
@paulocastellano
paulocastellano marked this pull request as ready for review April 1, 2026 18:20
@paulocastellano
paulocastellano merged commit 6e86b83 into main Apr 1, 2026
@paulocastellano
paulocastellano deleted the refactor/actions-subdomain-routes branch April 1, 2026 18:20
paulocastellano pushed a commit to mrbeandev/trypost that referenced this pull request Nov 9, 2026
Graph answers a deleted Page post's own node with trypostit#10, which also means a missing permission, so the deletion was never confirmed. Its insights edge answers 100/33 (checked against a real deleted post).
paulocastellano pushed a commit that referenced this pull request Nov 9, 2026
…come back (#464)

* Mark Instagram and Facebook posts deleted on the network

Graph answers code 100, subcode 33 when a post was deleted on Instagram or
Facebook after publishing, but the Meta error mapping filed it as a generic
malformed read, so the publication stayed available and the post card kept
showing it as published with a link to a post that no longer exists.

The Instagram and Facebook metric collectors now read the post itself when a
metrics read fails as malformed. If Graph says the post does not exist while
the account's own node still reads with the same token, the post is gone and
the publication is marked deleted. The same subcode also means "missing
permission", so a token that cannot read the account is never treated as a
deletion. Threads is unchanged.

A published post whose publication is deleted gets a Deleted badge, a note,
Delete and Repost buttons on its card, and may be deleted in TryPost.

Refs #228

* Mark posts deleted on the network through publish_status, and cover Threads

- Add PublishStatus::Deleted. When the metrics read finds a published post
  gone (YouTube, or Facebook, Instagram and Threads), the post moves to
  publish_status deleted (status stays published) and can be deleted in
  TryPost. A discovery that lists it again restores it.
- Move the Meta deletion check into AbstractMetaPublicationMetricsCollector
  for all three networks. Instagram Login and Threads read `me`; Instagram
  through Facebook reads the Instagram account, not the Page; Facebook reads
  the Page. A story older than a day is never reported as deleted.
- Stop loading the analytics publication on every card (it sent the whole
  row to the browser); the deletion rule reads publish_status only.
- Hide the network link on the card, the card menu and the details dialog.
  Drop the duplicate Delete and Repost buttons: the card menu already has
  Delete and Duplicate. Move the strings to posts.publish.deleted_on_network.
- Tests: config URLs in fakes, no fixed dates, Threads and Instagram Login
  cases, web/API/MCP deletion parity, sent tab props, a browser test of the
  card, and the badge's single-line budget.

* Address the review of deleted-on-network posts

- Only a deletion the collector confirms moves the post: YouTube, or Meta
  through AnalyticsCollectionException::deletedOnNetwork(). A bare 404 or 410
  from other networks only marks the analytics publication, as before.
- Meta checks the account's posts edge (published_posts, media, threads), the
  one discovery reads, instead of the public account node. Stories are never
  checked, since they expire on their own.
- Restoring a post no longer reruns the "just published" side effects.
- A post still publishing can't be deleted; a deleted post finalizes as
  published; the posting goal, lifecycle and PostHog activity keep counting it
  (Post::scopeWentOut()).
- Front end: isDeletedOnNetwork() and postCardPermalink() in
  usePostCardActions guard the card, menu, details dialog and share/copy; the
  details dialog shows the Deleted badge; the repurpose list labels the state
  instead of showing a raw key; the badge is subtle and the hint skips Delete
  for members who can't delete.
- Translations follow each locale's menu words (fr, el, es, nl, uk).
- Tests for every guard, each checked to fail without it.
- Remove the outdated DEPLOYMENT.md (#454).

* Remove the outdated MEDIA_INTEGRATIONS_SETUP.md

* Drop the env comments pointing at the removed media setup doc

* Explain a post deleted on the network in a popover on its badge

The note under the post moves into a popover on the Deleted badge, like the
failure popover. The details dialog shows Deleted in place of Published, so a
post shows one status.

* Keep the deleted-on-network rule on the post, and trim its popover

Post::isDeletedOnNetwork() replaces PostStatusRules::deletedOnNetwork() and the
check in ReadPublicationAnalytics. The popover drops the account line: the card
already shows which channel it is.

* Make the deleted-on-network popover a title and a consequence

The title says where the post was deleted; the text says what that changes
(no link, no insights) instead of repeating it.

* Address the second review of deleted-on-network posts

- The details dialog's channel rail shows a deleted sibling as deleted.
- YouTube reads its statistics cache once, so an entry expiring between two
  reads can no longer look like a deleted video.
- Meta checks whether a post was deleted only after a read answered "object
  does not exist", saving a Graph request on live posts whose metrics are
  refused for another reason.
- The metrics job marks a publication and its post deleted under the row
  lock, and not when a sync saw the post while it was being checked.
- PublishStatus::wentOut() is the one definition of "published or deleted",
  used by the scope and by FinalizePostPublication.
- PostDeletedOnNetworkBadge is shared by the popover and the details dialog;
  RepurposeItemList uses transform(); Italian uses "insight".
- post.md and AGENTS.md describe the final rules.

* Address the third review of deleted-on-network posts

- YouTube uses the statistics it just fetched, so a cache that drops the
  entry can no longer make a live video look deleted.
- Facebook still checks a deleted post on a Page that never granted insights.
- PublishStatus::wentOut() uses match and wentOutCases() a collection; the
  job compares the stored last_seen_at strictly.
- The details dialog computes the rail statuses once and tags the icon.
- Russian badge agrees with the post's gender.
- Tests: the metrics reason on the API and MCP, the lifecycle and PostHog
  activity counting a deleted post, YouTube without a cache, Facebook without
  insights, and the browser test asserts the live link and the closed popover.

* Address the fourth review of deleted-on-network posts

- YouTube caches only the statistics it found, so a video missing from
  another video's batch is read again before it is reported deleted.
- One recordRefusal() keeps the refusals and the "object does not exist"
  flag together for every Meta collector.
- The details dialog types its rail statuses instead of casting.
- The PostHog and lifecycle test lives with the PostHog activity tests; the
  parity test builds its posts with count().
- AGENTS.md names every read that stays on live posts only.

* Detect posts deleted on X, Bluesky, Mastodon and Pinterest

Each confirms a deletion from the metrics read it already makes, with an
account-level read (the list its discovery reads) proving the token still
works:

- X: the documented resource-not-found problem for the post, in a 200's
  errors or a 404's body, with no extra request.
- Bluesky: getPosts leaves the post out and its repository answers
  RecordNotFound while listRecords still reads.
- Mastodon: a 404 on an owner read, while the account's statuses still read.
- Pinterest: a 404 on the Pin analytics and on the Pin, while the Pins list
  still reads.

TikTok cannot tell a deleted video from a private one, and LinkedIn, Google
Business, Telegram and Discord have no read after publishing (#481).

* Address the fifth review of deleted-on-network posts

- A deletion check that fails only for now (rate limit, server error) is
  rethrown, so the job retries instead of settling the publication as gone
  without a confirmation (Mastodon and Pinterest lost the detection for good).
- readsMissing() and stillReads() on AbstractPublicationMetricsCollector are
  the one confirmation flow for Meta, Bluesky, Mastodon and Pinterest.
- X flags the 404 in successfulResponse() and decides once in collect(); the
  problem must name this post (resource_id required, also in a 404).
- Bluesky only handles RecordNotFound and leaves the rest to the parent;
  SocialAccount::blueskyService() replaces two copies of the PDS lookup.
- YouTube caches the batch in a plain loop.
- AGENTS.md says which networks need an account read and renders correctly.
- Tests: transient checks retried, X thread root and edge problems, Bluesky
  read once when present and on a self-hosted PDS, Mastodon 410 / 500 / 403
  and the exact authenticated list read, Pinterest Pin refused and the exact
  list read, and the job moving the post for X, Bluesky, Mastodon and
  Pinterest.

* Address the sixth review of deleted-on-network posts

- A Facebook Page without insights keeps its permission refusal when the
  deletion is not confirmed, instead of turning malformed.
- readUnlessDeleted() is the one "read, or report the post deleted" flow for
  Meta, X, Mastodon and Pinterest; the confirmation helpers are named
  confirmsDeletion().
- PostFactory::deletedOnNetwork() replaces the repeated published state.
- AGENTS.md: 404 or 410 for Mastodon and Pinterest, and the shared helpers.
- Tests: a temporary failure is retried on every confirming read (Meta post
  and posts reads, Pinterest Pin, Bluesky record), Meta only checks after a
  malformed read and forgets refusals between posts, Bluesky on a fixed
  self-hosted PDS, a publication removed during the check, the copy link and
  the live rail label, a publishing post never shown as deleted, and the
  repurpose Google review label; test helpers deduplicated and the dynamic
  factory call replaced by a dataset of closures.

* Keep the deleted-on-network popover off the screen edge on phones

* Send webhooks when a post is deleted on or back on its network

Adds the post.deleted_on_network and post.restored webhook events, guards a
deletion against a discovery that saw the post meanwhile (seen_generation),
confirms a Facebook video refused for permission by reading the video instead
of probing on every read, and writes the network presence transitions in a
transaction so their webhook never reads the post without its timestamps.

* Send no network presence webhook for posts imported from the network

* Guard a deletion with last_seen_at instead of a seen_generation column

* Cover the hidden link and the calendar mark of posts deleted on the network

* Confirm a Facebook video deletion only after its reads were refused

* Type visiblePermalink by the enum and convert raw rows where they are read

* Read a channel's server through accessors and decide network presence events in EventType

* Keep the visible permalink rule on PublicationAvailability

* Type the details rail from getPostStatusConfig's return instead of exporting its config

* Read a publication's post on discovery only when it was marked deleted

* Drop the trailing slash of third-party URLs once, in config/trypost.php

Every URL in the config goes through one $url closure that removes a
trailing slash, so readers append their path to (string) config(...) and
no longer trim it (17 reads in app/, 41 in tests).

Closes #484

* Put the environment back as it was after loading the config in tests

* Cover reading a channel's server from the account or the config

* Read config URLs without casts or trims, and simplify PostObserver::updated

The $url closure guarantees a string without a trailing slash, so readers
drop the (string) casts on those keys and the account server accessors no
longer trim. PostObserver::updated returns early when publish_status did not
change and leaves the deleted-origin check to EventType::fromPublishStatus.
The webhook dialog browser test counts the events from EventType instead of
a fixed six.

* Read the Meta Graph API through Platform::graphApiUrl

One enum method returns the Graph API of Facebook, Instagram (both
connections) and Threads, replacing instagramGraphBaseUrl and the abstract
graphBaseUrl/baseUrl hooks of the metrics collectors and the carousel
resolvers. The Instagram and Threads resolvers were the same class with a
different base URL, so they become one MetaCarouselResolver.

* Fall back to the config when an account server is stored as null

data_get() only uses its default when the key is missing, so an account
with "service": null or "instance": null made the accessors return null and
throw; the publishers' earlier ?? covered it. Also names the network in the
deleted-on-network message from Platform::label(), and locks a post's
publications by id only.

* Read a post listed again even when it is past its metrics window

The read queued when a discovery restores a post ran as a regular read, so
a post past its metrics window was skipped and a stale discovery could leave
it published for good. It now runs as a baseline read like the daily
dispatch and the page queue do, and refreshes a read already done today.
The Bluesky deletion test reads the account's stored PDS instead of a
literal host.

* Build Bluesky XRPC and Telegram bot URLs in one place each

BlueskyLexicon::xrpc() joins a server and a method, and TelegramApi::botUrl() builds the bot link, so call sites no longer concatenate them by hand.

* Build Mastodon API URLs through MastodonApi::url

The /api/v1 prefix lives in one place instead of every call site.

* Confirm a deleted Facebook Page post on its insights edge

Graph answers a deleted Page post's own node with #10, which also means a missing permission, so the deletion was never confirmed. Its insights edge answers 100/33 (checked against a real deleted post).

* Open the details of a publication the network deleted, without its link

Insights list deleted publications, but their details answered 404 when no TryPost post was linked. Web, API and MCP now return them with a null permalink, and the dialog shows the deleted-on-network badge.

* Name why metrics are unavailable with MetricsUnavailableReason

The four reasons were string literals across ReadPublicationAnalytics; the enum holds them, and the front end types the union.

* Remove the empty enum generated under app/Enums/Enums

* Read X's deleted-post problem in successfulResponse for every status

A 200 with the resource-not-found problem now goes through readUnlessDeleted like a 404, so the lookup no longer carries its errors back to collect().

* Move post publication helpers to lib and read a post's status in one place

isDeletedOnNetwork() and postPermalink() are pure helpers, so they live in lib/postPublication.ts instead of the card actions composable. getPostCardStatusConfig() gives the status a post shows, deleted on the network included, which the details rail and the deleted badge now use.

* Rename lib/postPublication.ts to lib/postNetwork.ts

* Confirm a deleted X post inside the lookup that read it

X answers a deleted post with a 200 whose errors name it, single and batch lookups alike (checked against a real deleted post). The lookups check it where the post id is known, so the collector keeps no post id state, needs no successfulResponse override and no readUnlessDeleted wrapper.

* Name X's resource-not-found problem with the ProblemType enum

The X collector reads the problem type through App\Enums\X\ProblemType and keeps the rule for a deleted post in namesDeletedPost().

* Read X problem types through ProblemType in XPublishException

fromApiResponse() and isConfirmedDeadToken() match the enum cases instead of basename() and string literals; an unknown type keeps its full type URI as the platform error code.

* Name X problem types by their ProblemType case in comments

---------

Co-authored-by: Paulo Castellano <paulo@castellanos.llc>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant