Merge pull request #14 from trypost-it/feature/mcp-rest-create-publish-posts

feat: complete create + publish post flow via MCP and REST API
This commit is contained in:
Paulo Castellano 2026-05-04 15:47:14 -03:00 committed by GitHub
commit 99179b65af
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
87 changed files with 3317 additions and 4268 deletions

View file

@ -18,6 +18,12 @@ ### Creating Tests
All tests must be written using Pest. Use `php artisan make:test --pest {name}`.
The `{name}` argument should include only the path and test name, but should not include the test suite.
- Incorrect: `php artisan make:test --pest Feature/SomeFeatureTest` will generate `tests/Feature/Feature/SomeFeatureTest.php`
- Correct: `php artisan make:test --pest SomeControllerTest` will generate `tests/Feature/SomeControllerTest.php`
- Incorrect: `php artisan make:test --pest --unit Unit/SomeServiceTest` will generate `tests/Unit/Unit/SomeServiceTest.php`
- Correct: `php artisan make:test --pest --unit SomeServiceTest` will generate `tests/Unit/SomeServiceTest.php`
### Test Organization
- Unit/Feature tests: `tests/Feature` and `tests/Unit` directories.
@ -156,4 +162,5 @@ ## Common Pitfalls
- Using `assertStatus(200)` instead of `assertSuccessful()`
- Forgetting datasets for repetitive validation tests
- Deleting tests without approval
- Forgetting `assertNoJavaScriptErrors()` in browser tests
- Forgetting `assertNoJavaScriptErrors()` in browser tests
- Prefixing `Feature/` or `Unit/` in `{name}` when using `make:test`

View file

@ -89,6 +89,9 @@ jobs:
DB_PORT: ${{ job.services.postgres.ports['5432'] }}
REDIS_PORT: ${{ job.services.redis.ports['6379'] }}
- name: Generate Passport keys
run: php artisan passport:keys --force
- name: Run tests
run: php artisan test --compact
env:

View file

@ -41,21 +41,7 @@ ## Foundational Context
## Skills Activation
This project has domain-specific skills available. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
- `ai-sdk-development` — TRIGGER when working with ai-sdk which is Laravel official first-party AI SDK. Activate when building, editing AI agents, chatbots, text generation, image generation, audio/TTS, transcription/STT, embeddings, RAG, vector stores, reranking, structured output, streaming, conversation memory, tools, queueing, broadcasting, and provider failover across OpenAI, Anthropic, Gemini, Azure, Groq, xAI, DeepSeek, Mistral, Ollama, ElevenLabs, Cohere, Jina, and VoyageAI. Invoke when the user references ai-sdk, the `Laravel\Ai\` namespace, or this project's AI features — not for Prism PHP or other AI packages used directly.
- `cashier-stripe-development` — Handles Laravel Cashier Stripe integration including subscriptions, webhooks, Stripe Checkout, invoices, charges, refunds, trials, coupons, metered billing, and payment failure handling. Triggered when a user mentions Cashier, Billable, IncompletePayment, stripe_id, newSubscription, Stripe subscriptions, or billing. Also applies when setting up webhooks, handling SCA/3DS payment failures, testing with Stripe test cards, or troubleshooting incomplete subscriptions, CSRF webhook errors, or migration publish issues.
- `laravel-best-practices` — Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns.
- `configuring-horizon` — Use this skill whenever the user mentions Horizon by name in a Laravel context. Covers the full Horizon lifecycle: installing Horizon (horizon:install, Sail setup), configuring config/horizon.php (supervisor blocks, queue assignments, balancing strategies, minProcesses/maxProcesses), fixing the dashboard (authorization via Gate::define viewHorizon, blank metrics, horizon:snapshot scheduling), and troubleshooting production issues (worker crashes, timeout chain ordering, LongWaitDetected notifications, waits config). Also covers job tagging and silencing. Do not use for generic Laravel queues without Horizon, SQS or database drivers, standalone Redis setup, Linux supervisord, Telescope, or job batching.
- `mcp-development` — Use this skill for Laravel MCP development only. Trigger when creating or editing MCP tools, resources, prompts, or servers in Laravel projects. Covers: artisan make:mcp-* generators, mcp:inspector, routes/ai.php, Tool/Resource/Prompt classes, schema validation, shouldRegister(), OAuth setup, URI templates, read-only attributes, and MCP debugging. Do not use for non-Laravel MCP projects or generic AI features without MCP.
- `configure-nightwatch` — Configures Laravel Nightwatch data collection, sampling rates, filtering rules, and redaction policies. Use when setting up Nightwatch, managing data volume, protecting sensitive data (PII), or optimizing event collection for production workloads.
- `passport-development` — Develops OAuth2 API authentication with Laravel Passport. Activates when installing or configuring Passport; setting up OAuth2 grants (authorization code, client credentials, personal access tokens, device authorization); managing OAuth clients; protecting API routes with token authentication; defining or checking token scopes; configuring SPA cookie authentication; handling token lifetimes and refresh tokens; or when the user mentions Passport, OAuth2, API tokens, bearer tokens, or API authentication. Make sure to use this skill whenever the user works with OAuth2, API tokens, or third-party API access, even if they don't explicitly mention Passport.
- `pennant-development` — Use when working with Laravel Pennant the official Laravel feature flag package. Trigger whenever the query mentions Pennant by name or involves feature flags or feature toggles in a Laravel project. Tasks include defining feature flags checking whether features are active creating class based features in `app/Features` using Blade `@feature` directives scoping flags to users or teams building custom Pennant storage drivers protecting routes with feature flags testing feature flags with Pest or PHPUnit and implementing A B testing or gradual rollouts with feature flags. Do not trigger for generic Laravel configuration authorization policies authentication or non Pennant feature management systems.
- `socialite-development` — Manages OAuth social authentication with Laravel Socialite. Activate when adding social login providers; configuring OAuth redirect/callback flows; retrieving authenticated user details; customizing scopes or parameters; setting up community providers; testing with Socialite fakes; or when the user mentions social login, OAuth, Socialite, or third-party authentication.
- `wayfinder-development` — Use this skill for Laravel Wayfinder which auto-generates typed functions for Laravel controllers and routes. ALWAYS use this skill when frontend code needs to call backend routes or controller actions. Trigger when: connecting any React/Vue/Svelte/Inertia frontend to Laravel controllers, routes, building end-to-end features with both frontend and backend, wiring up forms or links to backend endpoints, fixing route-related TypeScript errors, importing from @/actions or @/routes, or running wayfinder:generate. Use Wayfinder route functions instead of hardcoded URLs. Covers: wayfinder() vite plugin, .url()/.get()/.post()/.form(), query params, route model binding, tree-shaking. Do not use for backend-only task
- `pest-testing` — Use this skill for Pest PHP testing in Laravel projects only. Trigger whenever any test is being written, edited, fixed, or refactored — including fixing tests that broke after a code change, adding assertions, converting PHPUnit to Pest, adding datasets, and TDD workflows. Always activate when the user asks how to write something in Pest, mentions test files or directories (tests/Feature, tests/Unit, tests/Browser), or needs browser testing, smoke testing multiple pages for JS errors, or architecture tests. Covers: test()/it()/expect() syntax, datasets, mocking, browser testing (visit/click/fill), smoke testing, arch(), Livewire component tests, RefreshDatabase, and all Pest 4 features. Do not use for factories, seeders, migrations, controllers, models, or non-test PHP code.
- `inertia-vue-development` — Develops Inertia.js v3 Vue client-side applications. Activates when creating Vue pages, forms, or navigation; using <Link>, <Form>, useForm, useHttp, setLayoutProps, or router; working with deferred props, prefetching, optimistic updates, instant visits, or polling; or when user mentions Vue with Inertia, Vue pages, Vue forms, or Vue navigation.
- `tailwindcss-development` — Always invoke when the user's message includes 'tailwind' in any form. Also invoke for: building responsive grid layouts (multi-column card grids, product grids), flex/grid page structures (dashboards with sidebars, fixed topbars, mobile-toggle navs), styling UI components (cards, tables, navbars, pricing sections, forms, inputs, badges), adding dark mode variants, fixing spacing or typography, and Tailwind v3/v4 work. The core use case: writing or fixing Tailwind utility classes in HTML templates (Blade, JSX, Vue). Skip for backend PHP logic, database queries, API routes, JavaScript with no HTML/CSS component, CSS file audits, build tool configuration, and vanilla CSS.
This project has domain-specific skills available in `**/skills/**`. You MUST activate the relevant skill whenever you work in that domain—don't wait until you're stuck.
## Conventions
@ -130,10 +116,16 @@ # PHP
- Always use curly braces for control structures, even for single-line bodies.
- Use PHP 8 constructor property promotion: `public function __construct(public GitHub $github) { }`. Do not leave empty zero-parameter `__construct()` methods unless the constructor is private.
- Use explicit return type declarations and type hints for all method parameters: `function isAccessible(User $user, ?string $path = null): bool`
- Follow existing application Enum naming conventions.
- Use TitleCase for Enum keys: `FavoritePerson`, `BestLake`, `Monthly`.
- Prefer PHPDoc blocks over inline comments. Only add inline comments for exceptionally complex logic.
- Use array shape type definitions in PHPDoc blocks.
=== deployments rules ===
# Deployment
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
=== herd rules ===
# Laravel Herd
@ -201,10 +193,6 @@ ## Vite Error
- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.
## Deployment
- Laravel can be deployed using [Laravel Cloud](https://cloud.laravel.com/), which is the fastest way to deploy and scale production Laravel applications.
=== wayfinder/core rules ===
# Laravel Wayfinder
@ -223,6 +211,7 @@ # Laravel Pint Code Formatter
## Pest
- This project uses Pest for testing. Create tests: `php artisan make:test --pest {name}`.
- The `{name}` argument should not include the test suite directory. Use `php artisan make:test --pest SomeFeatureTest` instead of `php artisan make:test --pest Feature/SomeFeatureTest`.
- Run tests: `php artisan test --compact` or filter: `php artisan test --compact --filter=testName`.
- Do NOT delete tests without approval.

View file

@ -1,65 +1,235 @@
# TryPost License
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
## Functional Source License, Version 1.1, MIT
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
### Licensor
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
TryPost
Preamble
### Software
The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
TryPost - Social Media Scheduling Platform
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
### Use Limitation
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
You may not use the Software to provide a commercial service that allows third parties to schedule, manage, or publish content to social media platforms, where such service competes with or substitutes for TryPost or any product or service provided by Licensor.
Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
### License Grant
A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public.
Licensor hereby grants you the right to copy, modify, create derivative works, redistribute, and make non-production use of the Software. If your use of the Software does not violate the Use Limitation, Licensor hereby grants you the right to make production use of the Software.
The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version.
### Permitted Uses
An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license.
The following uses are expressly permitted:
The precise terms and conditions for copying, distribution and modification follow.
1. **Personal Use**: Using TryPost for your own personal social media management
2. **Internal Business Use**: Using TryPost within your organization to manage your company's social media accounts
3. **Educational Use**: Using TryPost for learning, teaching, or research purposes
4. **Development**: Modifying, studying, or contributing to the TryPost codebase
5. **Self-Hosting**: Deploying TryPost on your own infrastructure for personal or internal business use
TERMS AND CONDITIONS
### Prohibited Uses
0. Definitions.
The following uses are expressly prohibited:
"This License" refers to version 3 of the GNU Affero General Public License.
1. **Competing SaaS**: Offering TryPost (or a modified version) as a hosted service to third parties
2. **White-Label Services**: Rebranding and selling TryPost as your own product
3. **Managed Service Provider**: Operating TryPost as a service for multiple clients or customers
"Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
### Corollary
"The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
For clarity, the Use Limitation does not prohibit:
To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
- Using TryPost to manage social media for your own business or clients (as a social media manager)
- Integrating TryPost into internal tools that are not offered as a competing service
- Contributing improvements back to the TryPost project
A "covered work" means either the unmodified Program or a work based on the Program.
### Notice
To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
You must ensure that anyone who receives a copy of any part of the Software from you also receives a copy of this License.
To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
### No Other Rights
An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
These terms do not grant you any right in any trademark or logo of Licensor or its affiliates.
1. Source Code.
The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
### Patent
A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
To the extent your use qualifies as a Permitted Use, Licensor grants you a license under any patent claims it can license that are necessarily infringed by the Software, to make, use, and distribute the Software.
The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
### Disclaimer
The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those
subprograms and other parts of the work.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
---
The Corresponding Source for a work in source code form is that same work.
Copyright (c) 2025 TryPost
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
"Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.

139
README.md
View file

@ -3,22 +3,23 @@
</p>
<p align="center">
<strong>The open-source social media scheduling platform</strong>
<strong>The open-source alternative to Buffer, Hootsuite, and Later.</strong>
</p>
<p align="center">
Schedule, manage, and publish content to all your social media accounts from one place.
<br />
Self-hosted. Privacy-focused. No limits.
Schedule, write, and publish to every social network from one place.<br/>
Self-hosted. Built for teams, agencies, and creators who own their data.
</p>
<p align="center">
<a href="https://github.com/trypost-it/trypost/stargazers"><img src="https://img.shields.io/github/stars/trypost-it/trypost" alt="Stars"></a>
<a href="https://github.com/trypost-it/trypost/blob/main/LICENSE.md"><img src="https://img.shields.io/badge/license-FSL-blue" alt="License"></a>
<a href="https://github.com/trypost-it/trypost/releases"><img src="https://img.shields.io/github/v/release/trypost-it/trypost" alt="Release"></a>
<a href="https://github.com/trypost-it/trypost/stargazers"><img src="https://img.shields.io/github/stars/trypost-it/trypost?style=flat-square&color=4f46e5" alt="Stars"></a>
<a href="https://github.com/trypost-it/trypost/blob/main/LICENSE.md"><img src="https://img.shields.io/badge/license-AGPL--3.0-4f46e5?style=flat-square" alt="License"></a>
<a href="https://github.com/trypost-it/trypost/releases"><img src="https://img.shields.io/github/v/release/trypost-it/trypost?style=flat-square&color=4f46e5" alt="Release"></a>
<a href="https://github.com/trypost-it/trypost/discussions"><img src="https://img.shields.io/github/discussions/trypost-it/trypost?style=flat-square&color=4f46e5" alt="Discussions"></a>
</p>
<p align="center">
<a href="https://trypost.it">Cloud</a> &bull;
<a href="https://trypost.it/docs">Documentation</a> &bull;
<a href="https://github.com/orgs/trypost-it/projects/1">Roadmap</a> &bull;
<a href="https://github.com/trypost-it/trypost/discussions">Community</a>
@ -26,31 +27,50 @@
---
## Why TryPost?
## TryPost 1.0 is here
Tired of paying expensive monthly fees for social media scheduling tools? Want full control over your data? TryPost is the solution.
A massive release that turns TryPost into a complete open-source social media platform.
| | |
| ----------------------- | ---------------------------------------------------- |
| **100% Open Source** | Inspect the code, contribute, make it yours |
| **Self-Hosted** | Your data stays on your servers |
| **No Limits** | Schedule unlimited posts, connect unlimited accounts |
| **Privacy First** | No tracking, no analytics, no data selling |
- **MCP Server** — connect Claude, Cursor, ChatGPT, and any MCP client. Schedule, publish, and pull metrics with natural language.
- **REST API** — Personal Access Tokens, every workflow you can do in the dashboard, available over HTTP.
- **Workspaces &amp; Teams** — manage multiple brands or clients in isolated environments. Invite team members with role-based permissions.
- **AI Carousel Generator** — type a prompt, get a multi-slide LinkedIn / Instagram carousel back, with images and copy on-brand.
- **Brand Profile** — set tone, voice, language, and colors once. Every AI generation respects them automatically.
- **Analytics** — per-account engagement metrics from every platform that exposes them, in a single dashboard.
Read the [release notes &rarr;](https://github.com/trypost-it/trypost/releases/latest)
---
## Why TryPost
Tired of paying $30–$200/month per user for a scheduler? Tired of your content sitting on someone else's database?
| | |
| ---------------------------- | ---------------------------------------------------------- |
| **Self-hosted, your data** | Your posts, drafts, and metrics never leave your server |
| **No artificial limits** | Unlimited posts, unlimited connected accounts, unlimited workspaces |
| **AI built in** | Captions, carousels, on-brand voice — using your own keys |
| **Multi-tenant ready** | Workspaces + roles for agencies managing many clients |
| **API + MCP first-class** | Automate everything; your AI assistant can post for you |
| **AGPL-licensed** | Inspect every line, fork it, ship it — forever free |
## Features
| | |
| ----------------------------- | ------------------------------------------------------- |
| **Visual Calendar** | Drag and drop posts across your content calendar |
| **Post Composer** | Create and preview posts for multiple platforms at once |
| **Media Library** | Upload images and videos with automatic optimization |
| **Team Collaboration** | Invite team members with role-based permissions (Owner, Admin, Member) |
| **Workspaces** | Manage multiple brands or clients separately |
| **REST API** | Full API with Bearer token authentication |
| **MCP Server** | AI-ready with Model Context Protocol support |
| **Google Login** | Sign up and log in with Google OAuth |
| **Notifications** | In-app and email notifications for post status |
| **i18n** | Available in English, Spanish, and Portuguese |
| | |
| ------------------------------ | ---------------------------------------------------------------------- |
| **Visual Calendar** | See every scheduled post at a glance, switch between month/week/day |
| **Multi-Platform Composer** | One draft &rarr; preview &amp; tweak for every network in parallel |
| **AI Generate / Review** | Draft from a prompt, get inline feedback before you publish |
| **AI Carousel Builder** | Prompt &rarr; multi-slide carousel with images, on-brand |
| **Brand Profile** | Tone, voice, language, colors — applied to every AI call |
| **Asset Library** | Reusable workspace media + Unsplash &amp; Giphy search built in |
| **Signatures &amp; Labels** | Reusable text blocks (hashtags, CTAs) and color-coded post tags |
| **Team Collaboration** | Owner / Admin / Member roles, comments with @mentions on drafts |
| **Workspaces** | Isolate brands, clients, or projects in their own spaces |
| **REST API + MCP** | Full programmatic control; AI assistants integrate natively |
| **Analytics** | Per-account engagement metrics across every supported platform |
| **Multi-language** | English, Spanish, Portuguese |
## Supported Platforms
@ -71,75 +91,26 @@ ## Supported Platforms
</tr>
</table>
## Tech Stack
| Layer | Technology |
| ----- | ---------- |
| **Backend** | Laravel 13, PHP 8.4 |
| **Frontend** | Vue 3, Inertia.js v3, Tailwind CSS v4 |
| **Database** | PostgreSQL |
| **Queue** | Redis + Laravel Horizon |
| **WebSockets** | Laravel Reverb |
| **API** | REST with Bearer token auth |
| **MCP** | Laravel MCP for AI integrations |
| **Payments** | Laravel Cashier (Stripe) |
## Getting Started
Get TryPost running in minutes:
## Get Started
| | |
| --- | --- |
| [Installation Guide](https://trypost.it/docs/getting-started/installation) | Step-by-step setup |
| [Docker Setup](https://trypost.it/docs/self-hosting/docker) | Run with Laravel Sail |
| [Configuration](https://trypost.it/docs/getting-started/configuration) | Environment setup |
| [Platform Setup](https://trypost.it/docs/platforms/) | Connect your social accounts |
### Quick Start
```bash
git clone https://github.com/trypost-it/trypost.git
cd trypost
cp .env.example .env
composer install
npm install
php artisan key:generate
php artisan migrate
npm run build
```
## API
TryPost includes a REST API for programmatic access. All endpoints are under `/api` and require a Bearer token.
```bash
curl -H "Authorization: Bearer tp_your_token" \
https://your-domain.com/api/posts
```
See the [API documentation](https://trypost.it/docs/api) for all available endpoints.
## MCP Server
TryPost ships with a Model Context Protocol (MCP) server at `/mcp/trypost`, enabling AI assistants to manage your social media directly.
| **Try it on Cloud** | The fastest way. [Sign up at trypost.it](https://trypost.it) |
| **Self-host** | Free forever. [Installation guide &rarr;](https://trypost.it/docs/getting-started/installation) |
| **Run with AI assistants** | [Connect Claude / Cursor / ChatGPT via MCP &rarr;](https://trypost.it/docs/mcp) |
## Contributing
We love contributions! Check the [issues](https://github.com/trypost-it/trypost/issues) for open tasks.
We love contributions, no matter how small. Pick an [issue](https://github.com/trypost-it/trypost/issues), say hi in [Discussions](https://github.com/trypost-it/trypost/discussions), or just open a PR with what you'd like to see.
- [Discussions](https://github.com/trypost-it/trypost/discussions) - Ask questions, share ideas
- [Issues](https://github.com/trypost-it/trypost/issues) - Report bugs, request features
If TryPost is useful to you, **a star helps more people find it.** That's the most valuable contribution if you're short on time.
## License
TryPost is licensed under the [Functional Source License (FSL)](LICENSE.md).
**You can:** Use for personal or business use, self-host, modify and contribute.
**You cannot:** Offer as a competing SaaS, white-label and resell.
[GNU Affero General Public License v3.0](LICENSE.md) — use, modify, fork, self-host, and redistribute, including commercially. If you run a modified version as a network service, you need to make your changes available to its users (AGPL §13).
---
<p align="center">
<strong>If TryPost helps you, please give us a star</strong>
Built openly by the community. <a href="https://github.com/trypost-it/trypost/stargazers">Star us on GitHub</a> and tell a friend.
</p>

View file

@ -1,333 +0,0 @@
# TikTok Direct Post API — Review Video Script
Script for re-submitting trypost to TikTok's Direct Post API audit after the initial rejection. Based on https://developers.tiktok.com/doc/content-sharing-guidelines/
Goal: in ~2–3 minutes of screen recording, prove **every** compliance requirement visually. Narration in English (reviewers are in English-speaking teams).
---
## 0. Pre-recording checklist
Before hitting record, set up the state so you can flow through the script without pauses.
### Account / environment
- [ ] A **real TikTok account** connected to trypost (use your personal, not a test stub)
- [ ] Post log in production (`app.trypost.it`) — **not** localhost. Reviewers distrust `.test` domains
- [ ] `npm run build` deployed. Browser cache cleared (hard reload)
- [ ] Dev Tools closed, clean Chrome profile (no extensions bar visible)
### Content to upload
- [ ] One short vertical video (15–30s, 720p+) — original content. **Not** reposted from another platform
- [ ] A caption draft written (avoid preset auto-text — reviewer must see it's editable)
- [ ] Optional: a long video (>max duration of your account) to demonstrate the duration warning
### Workspace state
- [ ] Have a **second TikTok account** also connected — the video should demonstrate multi-account support (each collapse is per-account)
- [ ] Confirm `creator_info` is actually loading (watch Network tab once before recording)
### Recording tool
- Mac: QuickTime > File > New Screen Recording (record cursor + microphone)
- Resolution: 1440p minimum, browser window at 80% scale
- Narration: headset mic, quiet room
---
## 1. Opening shot (0:00–0:10)
**Screen:** trypost dashboard home (`/calendar` or `/posts`).
**Narration:**
> "Hi TikTok team. I'm demonstrating the trypost Direct Post integration. trypost is a social media scheduler for authentic creators. Let me walk you through the posting flow for TikTok."
**Why:** establishes you're not copying from another platform and the app is a scheduler for original content (addresses "Intended Use Requirements" in the doc).
---
## 2. TikTok authorization flow (0:10–0:30)
**Required by the submission form: "User flow of TikTok authorization page".**
**Screen:** navigate to `/accounts` with no TikTok account connected yet.
**Action:**
1. Click "Connect TikTok" button
2. Wait for TikTok's consent screen to load
3. Show the scopes list on TikTok's page
4. Click "Authorize"
5. Return to trypost with the account now connected (avatar + @handle visible)
**Narration:**
> "To use trypost with TikTok, the creator first authorizes our app. Clicking Connect TikTok takes me to TikTok's official consent page, where I can see the exact scopes we request: user profile, basic info, stats, and video publishing permissions. Once I authorize, I'm returned to trypost and my TikTok account is connected."
**What MUST be visible:**
- trypost's Connect TikTok button
- TikTok's native authorization page (not a clone — the real `open-api.tiktok.com/platform/oauth/connect/` screen)
- The scope list on TikTok's page
- Return redirect back to trypost with the account populated
## 3. Open post editor — creator_info fetched (0:30–0:45)
**Screen:** click "Create post" or open an existing draft.
**Action:** just wait 1–2s for the editor to render.
**Narration:**
> "Now I'll open the post editor. When it loads, trypost automatically fetches the latest creator_info for my TikTok account, so all visibility options and interaction settings you'll see reflect my current account state."
**What MUST be visible:**
- The post editor with the TikTok account nickname visible
- Optional: DevTools Network tab briefly showing the `post/publish/creator_info/query/` call
---
## 3. Compose + media upload (0:25–0:40)
**Screen:** post composer.
**Action:**
1. Type a caption manually (e.g. "Testing the TikTok Direct Post integration")
2. Upload the video
**Narration:**
> "I'll write my caption here — notice the caption field is fully editable; trypost does not inject any preset text or hashtags. Now I'll add my video, which I recorded myself."
**What MUST be visible:**
- Caption is user-typed (no auto-fill)
- Media upload visible
- No watermarks or promotional logos added anywhere by trypost
---
## 4. Open the Schedule tab + show creator nickname (0:40–0:55)
**Screen:** right sidebar, click "Schedule" tab.
**Action:** click on the TikTok platform in "Publish to" to select it.
**Narration:**
> "I'll select my TikTok account to publish to. Notice the creator's nickname is displayed here so I know exactly which TikTok account this will post to."
**What MUST be visible:**
- The TikTok platform card with **avatar + nickname visible** (not hidden in tooltip)
- Account visibly selected (primary ring)
---
## 5. Expand TikTok Settings — walk through each compliance field (0:55–1:45)
**Screen:** click to expand "TikTok Settings" collapse.
**Narration (go slowly here — this is the compliance core):**
### 5.1 Creator identity
> "Inside the settings, I see again which account I'm posting to: my nickname and handle."
### 5.2 Privacy level
**Action:** click the "Who can see this video?" dropdown — reveal it's empty with "Select visibility" placeholder.
> "Privacy is required — there is no default value. The user must explicitly choose a visibility. The options listed come directly from TikTok's creator_info API response, so only the visibility levels that my account can actually use are shown."
**Key moment:** hover the dropdown open so the reviewer sees the options list.
### 5.3 Interaction checkboxes
> "Next, the interaction settings — Comments, Duet, and Stitch. None of them are checked by default; I opt in to each."
**Key moment:** if any of them are greyed out on your account (because you disabled them in TikTok app settings), hover over one and show the tooltip *"Disabled by your TikTok account settings"*.
> "If any of these are disabled on my TikTok account itself, trypost respects that — the checkbox is greyed out and I cannot enable it."
### 5.4 Video made with AI
> "There's an independent toggle to declare if the video was made with AI — off by default."
### 5.5 Disclose video content toggle (CRITICAL SECTION)
**Action:** click the "Disclose video content" checkbox.
> "This is the commercial content disclosure toggle. It starts OFF by default, as required. I'll turn it on to demonstrate."
**What happens when ON:** sub-toggles "Your brand" and "Branded content" appear; a reminder text says *"You need to indicate if your content promotes yourself, a third party, or both"*.
**Action:** scroll up to the top of the page — point at the **disabled** Schedule/Post now button.
> "Right now, with the disclosure toggle on but no sub-option selected, the publish button is disabled, matching TikTok's requirement."
**Action:** back to the settings, click "Your brand" sub-toggle.
> "If I select Your brand, TikTok will classify this as Brand Organic. The disclosure reads: 'Your photo or video will be labeled as Promotional content'. Notice the agreement text below: 'By posting, you agree to TikTok's Music Usage Confirmation'."
**Action:** un-select "Your brand", click "Branded content" instead.
> "If I switch to Branded content, the label changes to 'Paid partnership', and the agreement now includes TikTok's Branded Content Policy, as required."
**Action:** open the privacy dropdown again.
> "And because branded content cannot be posted privately, the 'Only me' option is no longer available. If I had already picked 'Only me' before, trypost automatically clears the selection to force me to pick a valid one."
### 5.6 Duration warning (skip if not applicable)
If you set up the long-video scenario: show the red warning *"Video is Xs long but this account can only post videos up to Ys"*.
---
## 6. Preview tab (1:45–2:00)
**Screen:** click the "Preview" tab.
**Narration:**
> "Before posting, I can preview exactly how my post will look. This is the explicit consent step — I only publish after reviewing the content here."
**What MUST be visible:**
- The preview shows the actual video + caption
- Clear that this happens before the upload
---
## 7. Publish + processing notification (2:00–2:20)
**Screen:** back to the composer / schedule view.
**Action:**
1. Select a valid privacy level (e.g. Public)
2. Make sure disclose is OFF or one sub-toggle is picked
3. Click "Post now"
**Narration:**
> "I'll set privacy to public and publish. After I hit post, trypost shows me a notification saying the content may take a few minutes to process and appear on my TikTok profile — exactly what TikTok's guideline specifies."
**What MUST be visible:**
- Flash banner: *"Post is being published! It may take a few minutes to process and appear on each platform."*
- Button disables / spinner while submitting
---
## 8. Verify on TikTok (2:20–2:40)
**Action:** open tiktok.com in a new tab, navigate to your profile.
**Narration:**
> "And here's the post on my TikTok profile, with the correct visibility, the interaction settings I chose, and — because I had Branded Content disclosed — the 'Paid partnership' label is applied by TikTok automatically."
**What MUST be visible:**
- The exact video just uploaded, live on the TikTok profile
- If branded content was enabled: the "Paid partnership" label
---
## 9. Bonus (optional, strong signal): multi-account support (2:40–3:00)
**Screen:** go back to the post editor (or create a new post).
**Action:** select a **second** TikTok account. Show that a second, independent "TikTok Settings" collapse appears for that account.
**Narration:**
> "trypost supports posting to multiple TikTok accounts simultaneously. Each selected account gets its own settings panel with its own creator_info — so each account's privacy options and interaction rules are respected independently."
**Why this helps:** shows you understand the per-creator nature of the compliance, which matches "creator-specific restrictions" in the doc.
---
## 10. Closing (3:00 end)
**Narration:**
> "That's the trypost Direct Post flow — fully aligned with TikTok's Content Sharing Guidelines. Thanks for reviewing."
**Screen:** end on the TikTok profile showing the freshly-posted video.
---
## Final checklist before uploading the video
Use this as a last gate. **Every** item must be true or the rejection comes back.
### Compliance items demonstrated
- [ ] Creator nickname visible on the upload page
- [ ] Preview of content before publishing
- [ ] Privacy dropdown uses API values (not a static preset)
- [ ] Privacy has no default — user selects
- [ ] Comment / Duet / Stitch all unchecked by default
- [ ] Greyed-out interaction (shown at least once if your account has it)
- [ ] Commercial disclosure toggle default OFF
- [ ] "Your brand" sub-toggle revealed, label "Promotional content"
- [ ] "Branded content" sub-toggle, label "Paid partnership"
- [ ] "Music Usage Confirmation" text + link visible (hover the link)
- [ ] "Branded Content Policy" text + link (when branded content)
- [ ] Publish button disabled while disclose ON + no sub-toggle picked
- [ ] SELF_ONLY (Only me) removed when Branded Content is on
- [ ] Caption/title fully user-editable, no auto-presets
- [ ] Post-publish "may take a few minutes to process" notification
- [ ] Content is original (recorded by you, not reposted)
### What NOT to show
- [ ] No localhost or `.test` domain in the URL bar
- [ ] No dev tools consoles open (unless briefly for the creator_info call)
- [ ] No watermarks/promotional overlays added by trypost
- [ ] No reposted content from other platforms
- [ ] No "Other Apps / tools we compete with" references
- [ ] No preset hashtags or AI-generated caption that the user didn't edit
### Technical
- [ ] Video resolution ≥ 1080p
- [ ] Clear, slow narration in English
- [ ] Cursor visible at each click
- [ ] Total length 2–4 minutes
- [ ] Exported as mp4, < 100MB
---
## Why the last submission was rejected (so you know what changed)
Based on the doc, the previous build likely violated:
1. Privacy level had a default (`SELF_ONLY`)
2. Comments checkbox was pre-checked
3. No "Paid partnership" label when branded content selected
4. No block on SELF_ONLY + branded content
5. Publish button not disabled when disclose ON without sub-toggle
6. No creator_info fetched — interactions & privacy options were static
7. No max-duration check
8. No processing-time notification
All addressed in this build. The video above deliberately demonstrates each of these fixes in order.
---
## Submission notes
When submitting on TikTok's developer portal for the **Direct Post API audit**:
- Paste a direct link to the video (YouTube unlisted, Loom, or upload in the form)
- In the text field, reference this doc: "See attached video demonstrating compliance with Content Sharing Guidelines sections: creator_info fetch, mandatory metadata, commercial content disclosure labels, privacy restrictions for branded content, publish-button gating, processing notification."
- The video intentionally does not include the OAuth/authentication flow, which falls under the Login Kit audit, not Direct Post API.
- If asked about unaudited-client-restrictions: confirm your test accounts are currently private and posts went to SELF_ONLY during development.
---
# 📋 Form Answers (copy / paste)
## Describe your organization's work as it relates to TikTok
trypost is a social media scheduling platform that helps authentic creators, small businesses, and agencies plan, schedule, and publish original content across multiple social networks from a single workspace. Our integration with TikTok enables users to compose and schedule short-form video content for their own TikTok accounts, select per-post settings (privacy level, interaction permissions, commercial disclosure) in full compliance with TikTok's Content Sharing Guidelines, preview content before publishing, and manage multiple TikTok accounts side by side — each account's creator_info (privacy options, interaction rules, max video duration) is respected independently.
We do not repost content from other platforms, inject promotional watermarks, or automate content without explicit user action. Every post is composed, reviewed, and published only upon the user's explicit confirmation. Our role is purely to give creators a better scheduling workflow for content they already own.
## Explain the goal of your application and how Content Posting API integration can be beneficial
trypost helps creators and agencies publish original content consistently across social networks from one workspace, so they can focus on content instead of logging into each platform daily. The Content Posting API is essential because it lets us publish directly to TikTok at scheduled times, fetch creator_info at post time so each account's privacy options, interaction rules and max video duration are respected, and enforce TikTok's Content Sharing Guidelines in the UI — including the commercial disclosure flow, the "Promotional content" / "Paid partnership" labels, and the Music Usage and Branded Content Policy declarations. This benefits TikTok by ensuring uploads go through official endpoints (PULL_FROM_URL, status polling, token refresh), and commercial content is correctly disclosed before it reaches the platform.
## Explain how you determined the daily usage estimate (less than 100)
trypost launched publicly very recently, so our active user base is still small. Our current sign-up volume and TikTok account connection rate put realistic daily publishing on TikTok in the low double digits at most, with clear headroom before approaching 100. We chose this tier because it reflects actual observed usage, not a projection we cannot yet back with data. When real traction pushes us close to the cap, we will reapply with concrete numbers from our analytics to request a higher tier.
## Please list the API response data fields that your API client will save in its database
From /v2/oauth/token/ and /v2/user/info/ (social_accounts table):
- open_id (stored as platform_user_id)
- display_name
- username
- avatar_url (image copied to our storage)
- access_token (encrypted at rest)
- refresh_token (encrypted at rest)
- expires_in (converted to a timestamp)
- granted scopes
From /v2/post/publish/video/init/, /content/init/ and /status/fetch/ (post_platforms table):
- publish_id
- publicaly_available_post_id
Responses from /v2/post/publish/creator_info/query/ and analytics endpoints are fetched on demand and not persisted.

View file

@ -9,26 +9,82 @@
use App\Models\User;
use App\Models\Workspace;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class CreatePost
{
/**
* Create a Post with optional platform selection.
*
* `platforms[]` enables specific social accounts. Each entry takes
* `social_account_id` and an optional `content_type` (defaults to the
* platform's default). Accounts not listed remain disabled but are still
* created via SyncPostPlatforms so the user can toggle them later in the
* editor.
*
* `label_ids[]` are attached after creation so the same set of UUIDs
* works for REST, MCP, and web callers.
*
* @param array{
* content?: ?string,
* media?: array<int, mixed>,
* date?: ?string,
* scheduled_at?: ?string,
* platforms?: array<int, array{social_account_id: string, content_type?: string}>,
* label_ids?: array<int, string>
* } $data
*/
public static function execute(Workspace $workspace, User $user, array $data): Post
{
$scheduledAt = self::resolveScheduledAt($data);
return DB::transaction(function () use ($workspace, $user, $data, $scheduledAt): Post {
$post = $workspace->posts()->create([
'user_id' => $user->id,
'content' => data_get($data, 'content', ''),
'media' => data_get($data, 'media', []),
'status' => PostStatus::Draft,
'scheduled_at' => $scheduledAt,
]);
SyncPostPlatforms::execute($post);
foreach (data_get($data, 'platforms', []) as $platformData) {
$accountId = data_get($platformData, 'social_account_id');
if (! $accountId) {
continue;
}
$updates = ['enabled' => true];
if ($contentType = data_get($platformData, 'content_type')) {
$updates['content_type'] = $contentType;
}
$post->postPlatforms()
->where('social_account_id', $accountId)
->update($updates);
}
if ($labelIds = data_get($data, 'label_ids')) {
$post->labels()->sync($labelIds);
}
return $post;
});
}
/**
* @param array<string, mixed> $data
*/
private static function resolveScheduledAt(array $data): Carbon
{
if ($scheduledAt = data_get($data, 'scheduled_at')) {
return Carbon::parse($scheduledAt)->utc();
}
$date = data_get($data, 'date') ?: Carbon::now('UTC')->format('Y-m-d');
$scheduledAt = Carbon::parse($date, 'UTC')
->setTime(9, 0)
->utc();
$post = $workspace->posts()->create([
'user_id' => $user->id,
'content' => data_get($data, 'content', ''),
'media' => data_get($data, 'media', []),
'status' => PostStatus::Draft,
'scheduled_at' => $scheduledAt,
]);
SyncPostPlatforms::execute($post);
return $post;
return Carbon::parse($date, 'UTC')->setTime(9, 0)->utc();
}
}

View file

@ -42,29 +42,31 @@ public static function execute(Workspace $workspace, Post $post, array $data): a
$post->labels()->sync(data_get($data, 'label_ids', []));
}
DB::transaction(function () use ($post, $data) {
$post->postPlatforms()->update(['enabled' => false]);
if (Arr::has($data, 'platforms')) {
DB::transaction(function () use ($post, $data) {
$post->postPlatforms()->update(['enabled' => false]);
foreach (data_get($data, 'platforms', []) as $platformData) {
$updateData = ['enabled' => true];
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'] = array_merge($postPlatform->meta ?? [], data_get($platformData, 'meta'));
if (data_get($platformData, 'content_type') !== null) {
$updateData['content_type'] = data_get($platformData, 'content_type');
}
}
$post->postPlatforms()
->where('id', data_get($platformData, 'id'))
->update($updateData);
}
});
if (data_get($platformData, 'meta') !== null) {
$postPlatform = $post->postPlatforms()->where('id', data_get($platformData, 'id'))->first();
if ($postPlatform) {
$updateData['meta'] = array_merge($postPlatform->meta ?? [], data_get($platformData, 'meta'));
}
}
$post->postPlatforms()
->where('id', data_get($platformData, 'id'))
->update($updateData);
}
});
}
if ($status === PostStatus::Publishing->value) {
$post->update(['scheduled_at' => now()]);

View file

@ -8,32 +8,80 @@ enum Type: string
{
case Image = 'image';
case Video = 'video';
case Document = 'document';
public function label(): string
{
return match ($this) {
self::Image => 'Imagem',
self::Video => 'Vídeo',
self::Document => 'Documento',
};
}
/**
* Allow-list of MIME types we accept on upload / URL fetch.
*
* Video accepts MP4 plus QuickTime/MOV. Modern .mov files (iPhone
* recordings, screen captures) are ISO BMFF containers — the same
* format MP4 uses — so social platforms decode them like MP4 even
* if PHP reports `video/quicktime`. Accepting MOV avoids forcing
* iPhone users to transcode before uploading.
*
* WebM is rejected: X / IG / TikTok / FB / Pinterest / Bluesky /
* Threads all reject the Matroska + VP8/VP9 stack. Without
* server-side transcoding, accepting WebM would just produce
* platform-specific publish failures down the line.
*
* @return array<int, string>
*/
public function allowedMimeTypes(): array
{
return match ($this) {
self::Image => ['image/jpeg', 'image/png', 'image/gif', 'image/webp'],
self::Video => ['video/mp4', 'video/quicktime', 'video/webm'],
self::Document => ['application/pdf'],
self::Video => ['video/mp4', 'video/quicktime'],
};
}
/**
* Filename extensions that match this type. Mirrors allowedMimeTypes
* for callers that validate by name instead of MIME.
*
* @return array<int, string>
*/
public function extensions(): array
{
return match ($this) {
self::Image => ['jpg', 'jpeg', 'png', 'gif', 'webp'],
self::Video => ['mp4', 'mov'],
};
}
public function maxSizeInMb(): int
{
return match ($this) {
self::Image => 10,
self::Video => 2048,
self::Document => 100,
};
return (int) config("trypost.media.max_size_mb.{$this->value}");
}
public function maxSizeInBytes(): int
{
return $this->maxSizeInMb() * 1024 * 1024;
}
public function maxSizeInKb(): int
{
return $this->maxSizeInMb() * 1024;
}
/**
* Resolve a Type from a MIME string. Returns null when the MIME is
* not in any type's allow-list.
*/
public static function fromMime(string $mime): ?self
{
foreach (self::cases() as $type) {
if (in_array($mime, $type->allowedMimeTypes(), true)) {
return $type;
}
}
return null;
}
}

View file

@ -264,15 +264,39 @@ public static function aiSupported(): array
}
/**
* Get all content types for a specific platform.
* Platforms this content_type can be assigned to. Most content types are
* tied to a single platform; Instagram-family types (feed/carousel/reel/
* story) work for both `Instagram` (Basic Display) and `InstagramFacebook`
* (Business via Facebook Page) accounts.
*
* @return array<SocialPlatform>
*/
public function compatiblePlatforms(): array
{
$primary = $this->platform();
return match ($primary) {
SocialPlatform::Instagram => [SocialPlatform::Instagram, SocialPlatform::InstagramFacebook],
default => [$primary],
};
}
/**
* Get all content types for a specific platform. Treats InstagramFacebook
* as an alias for Instagram so both flavors get the same content types.
*
* @return array<self>
*/
public static function forPlatform(SocialPlatform $platform): array
{
$effective = match ($platform) {
SocialPlatform::InstagramFacebook => SocialPlatform::Instagram,
default => $platform,
};
return array_filter(
self::cases(),
fn (self $type) => $type->platform() === $platform
fn (self $type) => $type->platform() === $effective
);
}

View file

@ -59,7 +59,7 @@ public function color(): string
public function allowedMediaTypes(): array
{
return match ($this) {
self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video, MediaType::Document],
self::LinkedIn, self::LinkedInPage => [MediaType::Image, MediaType::Video],
self::X => [MediaType::Image, MediaType::Video],
self::TikTok => [MediaType::Video],
self::YouTube => [MediaType::Video],

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Enums\SocialAccount\Platform;
use App\Http\Resources\Api\PlatformContentTypesResource;
use Illuminate\Http\JsonResponse;
class PlatformController extends Controller
{
/**
* Index of platforms with their valid content_types and publishing
* constraints — used by clients to build correct `platforms[].content_type`
* payloads for `POST /api/posts` and `PUT /api/posts/{id}`.
*/
public function contentTypes(): JsonResponse
{
return response()->json([
'platforms' => PlatformContentTypesResource::collection(Platform::cases())->resolve(),
]);
}
}

View file

@ -8,10 +8,15 @@
use App\Actions\Post\DeletePost;
use App\Actions\Post\UpdatePost;
use App\Enums\Post\Action as PostAction;
use App\Http\Requests\Api\Post\AttachMediaRequest;
use App\Http\Requests\Api\Post\StorePostRequest;
use App\Http\Requests\Api\Post\UpdatePostRequest;
use App\Http\Resources\Api\PostMediaAttachResource;
use App\Http\Resources\Api\PostMetricsResource;
use App\Http\Resources\Api\PostPreviewResource;
use App\Http\Resources\Api\PostResource;
use App\Models\Post;
use App\Services\Post\MediaAttacher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
@ -31,9 +36,7 @@ public function index(Request $request): AnonymousResourceCollection
public function show(Request $request, Post $post): PostResource
{
if ($post->workspace_id !== $request->user()->currentWorkspace->id) {
abort(Response::HTTP_NOT_FOUND);
}
$this->authorize('view', $post);
$post->load(['postPlatforms.socialAccount', 'user', 'labels']);
@ -57,9 +60,7 @@ public function store(StorePostRequest $request): JsonResponse
public function update(UpdatePostRequest $request, Post $post): PostResource|JsonResponse
{
if ($post->workspace_id !== $request->user()->currentWorkspace->id) {
abort(Response::HTTP_NOT_FOUND);
}
$this->authorize('update', $post);
$result = UpdatePost::execute($request->user()->currentWorkspace, $post, $request->validated());
@ -75,12 +76,39 @@ public function update(UpdatePostRequest $request, Post $post): PostResource|Jso
public function destroy(Request $request, Post $post): JsonResponse
{
if ($post->workspace_id !== $request->user()->currentWorkspace->id) {
abort(Response::HTTP_NOT_FOUND);
}
$this->authorize('delete', $post);
DeletePost::execute($post);
return response()->json(null, Response::HTTP_NO_CONTENT);
}
public function attachMedia(AttachMediaRequest $request, Post $post): PostMediaAttachResource
{
$this->authorize('update', $post);
$result = app(MediaAttacher::class)->attachFromUrls($post, $request->validated('urls'));
$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
return new PostMediaAttachResource($post, $result);
}
public function metrics(Request $request, Post $post): PostMetricsResource
{
$this->authorize('view', $post);
$post->load(['postPlatforms.socialAccount']);
return new PostMetricsResource($post);
}
public function preview(Request $request, Post $post): PostPreviewResource
{
$this->authorize('view', $post);
$post->load(['postPlatforms.socialAccount']);
return new PostPreviewResource($post);
}
}

View file

@ -6,6 +6,7 @@
use App\Http\Requests\App\Asset\StoreAssetFromUrlRequest;
use App\Http\Requests\App\Asset\StoreAssetRequest;
use App\Http\Requests\App\Asset\StoreChunkedAssetRequest;
use App\Http\Resources\App\MediaResource;
use App\Models\Media;
use App\Services\UnsplashService;
@ -66,33 +67,17 @@ public function store(StoreAssetRequest $request): MediaResource
return new MediaResource($media);
}
public function storeChunked(Request $request): JsonResponse
public function storeChunked(StoreChunkedAssetRequest $request): JsonResponse
{
$workspace = $request->user()->currentWorkspace;
$this->authorize('createPost', $workspace);
$contentRange = $request->header('Content-Range');
$rangeStart = (int) $request->validated('range_start');
$rangeEnd = (int) $request->validated('range_end');
$totalSize = (int) $request->validated('total_size');
$fileName = (string) $request->validated('file_name');
preg_match('/bytes (\d+)-(\d+)\/(\d+)/', $contentRange, $matches);
if (empty($matches)) {
abort(SymfonyResponse::HTTP_BAD_REQUEST, 'Invalid Content-Range header');
}
$rangeStart = (int) $matches[1];
$rangeEnd = (int) $matches[2];
$totalSize = (int) $matches[3];
$fileName = $request->header('X-File-Name', 'upload');
if (! preg_match('/\.(jpe?g|png|gif|webp|mp4)$/i', $fileName)) {
abort(SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY, 'File type not supported.');
}
if ($totalSize > 1073741824) { // 1GB
abort(SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY, 'File size exceeds the maximum allowed (1GB).');
}
$identifier = md5($request->user()->id.$fileName.$totalSize);
$tempFile = storage_path("app/private/chunks/{$identifier}");

View file

@ -9,7 +9,6 @@
use App\Enums\PostPlatform\ContentType;
use App\Http\Requests\App\Ai\StartPostCreationRequest;
use App\Jobs\Ai\StreamPostCreation;
use App\Models\Media;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Http\JsonResponse;
@ -198,7 +197,9 @@ private function buildMediaArray(Workspace $workspace, array $state): array
*/
private function createMediaItem(Workspace $workspace, string $path, array $meta = []): array
{
$media = new Media([
// Use the relationship (not `mediable_type = Workspace::class`) so
// the morph map alias `'workspace'` is persisted instead of the FQCN.
$media = $workspace->media()->create([
'collection' => 'ai-generated',
'type' => MediaType::Image,
'path' => $path,
@ -208,10 +209,6 @@ private function createMediaItem(Workspace $workspace, string $path, array $meta
'order' => 0,
]);
$media->mediable_type = Workspace::class;
$media->mediable_id = $workspace->id;
$media->save();
return [
'id' => $media->id,
'path' => $media->path,

View file

@ -18,22 +18,13 @@
use App\Http\Resources\App\SocialAccountResource;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Services\Social\BlueskyAnalytics;
use App\Services\Social\FacebookAnalytics;
use App\Services\Social\InstagramAnalytics;
use App\Services\Social\LinkedInPageAnalytics;
use App\Services\Social\MastodonAnalytics;
use App\Services\Social\PinterestAnalytics;
use App\Services\Post\PostMetricsFetcher;
use App\Services\Social\PinterestPublisher;
use App\Services\Social\ThreadsAnalytics;
use App\Services\Social\TikTokCreatorInfo;
use App\Services\Social\XAnalytics;
use App\Services\Social\YouTubeAnalytics;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;
use Inertia\Response;
@ -174,38 +165,13 @@ public function store(Request $request): RedirectResponse|\Symfony\Component\Htt
public function platformMetrics(Request $request, Post $post, PostPlatform $postPlatform): JsonResponse
{
$workspace = $request->user()->currentWorkspace;
if (! $workspace || $post->workspace_id !== $workspace->id) {
abort(404);
}
$this->authorize('view', $workspace);
$this->authorize('view', $post);
if ($postPlatform->post_id !== $post->id) {
abort(404);
}
if ($postPlatform->status->value !== 'published' || ! $postPlatform->platform_post_id) {
return response()->json(['unsupported' => true, 'reason' => 'not_published']);
}
$cacheKey = "post_metrics:{$postPlatform->id}";
$metrics = Cache::remember($cacheKey, 300, fn () => match ($postPlatform->platform) {
Platform::X => app(XAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Bluesky => app(BlueskyAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Mastodon => app(MastodonAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Instagram, Platform::InstagramFacebook => app(InstagramAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Facebook => app(FacebookAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Threads => app(ThreadsAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::LinkedInPage => app(LinkedInPageAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::YouTube => app(YouTubeAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Pinterest => app(PinterestAnalytics::class)->fetchPostMetrics($postPlatform),
default => ['unsupported' => true, 'reason' => 'platform_not_supported'],
});
return response()->json($metrics);
return response()->json(app(PostMetricsFetcher::class)->forPlatform($postPlatform));
}
public function show(Request $request, Post $post): Response|RedirectResponse
@ -216,11 +182,7 @@ public function show(Request $request, Post $post): Response|RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('view', $workspace);
if ($post->workspace_id !== $workspace->id) {
abort(404);
}
$this->authorize('view', $post);
if (in_array($post->status, [PostStatus::Draft, PostStatus::Scheduled, PostStatus::Failed], true)) {
return redirect()->route('app.posts.edit', $post);
@ -242,11 +204,7 @@ public function edit(Request $request, Post $post): Response|RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('view', $workspace);
if ($post->workspace_id !== $workspace->id) {
abort(404);
}
$this->authorize('update', $post);
if (in_array($post->status, [PostStatus::Publishing, PostStatus::Published, PostStatus::PartiallyPublished], true)) {
return redirect()->route('app.posts.show', $post);
@ -302,11 +260,7 @@ public function update(UpdatePostRequest $request, Post $post): RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('createPost', $workspace);
if ($post->workspace_id !== $workspace->id) {
abort(404);
}
$this->authorize('update', $post);
$result = UpdatePost::execute($workspace, $post, $request->validated());
@ -344,11 +298,7 @@ public function destroy(Request $request, Post $post): RedirectResponse
return redirect()->route('app.workspaces.create');
}
$this->authorize('createPost', $workspace);
if ($post->workspace_id !== $workspace->id) {
abort(404);
}
$this->authorize('delete', $post);
if (in_array($post->status, [PostStatus::Publishing, PostStatus::Published, PostStatus::PartiallyPublished], true)) {
session()->flash('flash.banner', __('posts.flash.cannot_delete_published'));

View file

@ -7,7 +7,6 @@
use App\Actions\Post\CreatePost;
use App\Enums\Media\Type as MediaType;
use App\Http\Resources\App\PostTemplateResource;
use App\Models\Media;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Services\Image\TemplateImageGenerator;
@ -122,7 +121,9 @@ private function interpolate(string $text, Workspace $workspace): string
*/
private function createMediaItem(Workspace $workspace, string $path): array
{
$media = new Media([
// Use the relationship (not `mediable_type = Workspace::class`) so
// the morph map alias `'workspace'` is persisted instead of the FQCN.
$media = $workspace->media()->create([
'collection' => 'ai-generated',
'type' => MediaType::Image,
'path' => $path,
@ -132,10 +133,6 @@ private function createMediaItem(Workspace $workspace, string $path): array
'order' => 0,
]);
$media->mediable_type = Workspace::class;
$media->mediable_id = $workspace->id;
$media->save();
return [
'id' => $media->id,
'path' => $media->path,

View file

@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\Api\Post;
use Illuminate\Foundation\Http\FormRequest;
class AttachMediaRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'urls' => ['required', 'array', 'min:1', 'max:10'],
'urls.*' => ['url:http,https', 'active_url'],
];
}
}

View file

@ -4,8 +4,8 @@
namespace App\Http\Requests\Api\Post;
use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Rules\ContentTypeMatchesPlatform;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@ -18,13 +18,31 @@ public function authorize(): bool
public function rules(): array
{
$workspaceId = $this->user()->currentWorkspace->id;
return [
'content' => ['nullable', 'string', 'max:63206'],
'media' => ['sometimes', 'array'],
'platforms' => ['required', 'array', 'min:1'],
'platforms.*.social_account_id' => ['required', 'uuid', Rule::exists('social_accounts', 'id')->where('workspace_id', $this->user()->currentWorkspace->id)],
'platforms.*.content_type' => ['required', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],
'platforms.*.content' => ['nullable', 'string', 'max:63206'],
'platforms.*.social_account_id' => [
'required',
'uuid',
Rule::exists('social_accounts', 'id')
->where('workspace_id', $workspaceId)
->where('is_active', true),
],
'platforms.*.content_type' => [
'required',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
new ContentTypeMatchesPlatform,
],
'scheduled_at' => ['nullable', 'date', 'after:now'],
'status' => ['nullable', 'string', Rule::in(array_column(Status::cases(), 'value'))],
'label_ids' => ['sometimes', 'array'],
'label_ids.*' => [
'uuid',
Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspaceId),
],
];
}
}

View file

@ -7,6 +7,7 @@
use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Models\Post;
use App\Rules\ContentTypeMatchesPostPlatform;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@ -25,7 +26,12 @@ public function rules(): array
'media' => ['sometimes', 'array'],
'platforms' => ['sometimes', 'array'],
'platforms.*.id' => ['required', 'uuid', Rule::exists('post_platforms', 'id')->where('post_id', $this->route('post') instanceof Post ? $this->route('post')->id : $this->route('post'))],
'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value'))],
'platforms.*.content_type' => [
'sometimes',
'string',
Rule::in(array_column(ContentType::cases(), 'value')),
new ContentTypeMatchesPostPlatform,
],
'platforms.*.meta' => ['nullable', 'array'],
'scheduled_at' => [
'nullable',

View file

@ -4,6 +4,7 @@
namespace App\Http\Requests\App\Asset;
use App\Enums\Media\Type as MediaType;
use Illuminate\Foundation\Http\FormRequest;
class StoreAssetRequest extends FormRequest
@ -15,8 +16,17 @@ public function authorize(): bool
public function rules(): array
{
$allowedMimes = [...MediaType::Image->allowedMimeTypes(), ...MediaType::Video->allowedMimeTypes()];
return [
'media' => ['required', 'file', 'max:1048576', 'mimetypes:image/jpeg,image/png,image/gif,image/webp,video/mp4'],
// Use the largest per-type cap as the upper bound; per-type
// enforcement happens after the upload via the Media model.
'media' => [
'required',
'file',
'max:'.MediaType::Video->maxSizeInKb(),
'mimetypes:'.implode(',', $allowedMimes),
],
'meta' => ['sometimes', 'array'],
'meta.width' => ['sometimes', 'integer', 'min:1'],
'meta.height' => ['sometimes', 'integer', 'min:1'],

View file

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests\App\Asset;
use App\Enums\Media\Type as MediaType;
use Illuminate\Foundation\Http\FormRequest;
/**
* Validates a chunked upload request. The chunk metadata (offset / total
* size / filename) is encoded in the `Content-Range` and `X-File-Name`
* headers, not in the body, so we lift it into the request bag via
* `prepareForValidation` and then run standard rules against it.
*/
class StoreChunkedAssetRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
protected function prepareForValidation(): void
{
$parsed = sscanf((string) $this->header('Content-Range'), 'bytes %d-%d/%d') ?: [];
$this->merge([
'range_start' => $parsed[0] ?? null,
'range_end' => $parsed[1] ?? null,
'total_size' => $parsed[2] ?? null,
// Lowercase the name so `ends_with` validation is effectively
// case-insensitive (IMG_1234.JPG vs img_1234.jpg).
'file_name' => strtolower((string) $this->header('X-File-Name', 'upload')),
]);
}
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
$allowedSuffixes = collect([MediaType::Image, MediaType::Video])
->flatMap(fn (MediaType $type) => $type->extensions())
->map(fn (string $ext) => '.'.$ext)
->all();
return [
'range_start' => ['required', 'integer', 'min:0'],
'range_end' => ['required', 'integer', 'gte:range_start'],
'total_size' => ['required', 'integer', 'min:1', 'max:'.MediaType::Video->maxSizeInBytes()],
'file_name' => ['required', 'string', 'ends_with:'.implode(',', $allowedSuffixes)],
];
}
/**
* @return array<string, string>
*/
public function messages(): array
{
return [
'range_start.required' => 'Invalid Content-Range header',
'range_end.required' => 'Invalid Content-Range header',
'total_size.required' => 'Invalid Content-Range header',
'total_size.max' => 'File size exceeds the maximum allowed ('.MediaType::Video->maxSizeInMb().' MB).',
'file_name.ends_with' => 'File type not supported.',
];
}
}

View file

@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* Describes a single SocialPlatform with its valid content_types and
* publishing constraints (length budgets, allowed media types, etc.).
*
* `JsonResource::collection(Platform::cases())` produces the full index.
*/
class PlatformContentTypesResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
/** @var Platform $platform */
$platform = $this->resource;
return [
'platform' => $platform->value,
'label' => $platform->label(),
'max_content_length' => $platform->maxContentLength(),
'recommended_content_length' => $platform->recommendedAiContentLength(),
'allowed_media_types' => array_map(
fn ($type) => $type->value,
$platform->allowedMediaTypes(),
),
'default_content_type' => ContentType::defaultFor($platform)->value,
'content_types' => array_map(
fn (ContentType $type) => [
'value' => $type->value,
'label' => $type->label(),
'description' => $type->description(),
'max_media_count' => $type->maxMediaCount(),
'requires_media' => $type->requiresMedia(),
],
array_values(ContentType::forPlatform($platform)),
),
];
}
}

View file

@ -0,0 +1,36 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* Wraps a Post with the result of an attach-media operation
* (counts + list of failed URLs).
*/
class PostMediaAttachResource extends JsonResource
{
/**
* @param array{attached: array<int, array<string, mixed>>, failed: array<int, string>} $result
*/
public function __construct(Post $post, private readonly array $result)
{
parent::__construct($post);
}
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'post' => (new PostResource($this->resource))->resolve(),
'attached_count' => count($this->result['attached']),
'failed_urls' => $this->result['failed'],
];
}
}

View file

@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api;
use App\Services\Post\PostMetricsFetcher;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* Wraps a Post with its per-platform engagement metrics. The actual fetching
* (with cache + per-platform dispatch) is delegated to PostMetricsFetcher.
*/
class PostMetricsResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'post_id' => $this->id,
'platforms' => app(PostMetricsFetcher::class)->forPost($this->resource)->all(),
];
}
}

View file

@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Api;
use App\Services\Post\PostPreviewer;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* Wraps a Post with per-platform sanitized previews. Sanitization is
* delegated to PostPreviewer (which calls ContentSanitizer).
*/
class PostPreviewResource extends JsonResource
{
/**
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return app(PostPreviewer::class)->forPost($this->resource);
}
}

View file

@ -11,10 +11,16 @@
use App\Mcp\Tools\Label\DeleteLabelTool;
use App\Mcp\Tools\Label\ListLabelsTool;
use App\Mcp\Tools\Label\UpdateLabelTool;
use App\Mcp\Tools\Platform\ListContentTypesTool;
use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
use App\Mcp\Tools\Post\CreatePostTool;
use App\Mcp\Tools\Post\DeletePostTool;
use App\Mcp\Tools\Post\GetPostMetricsTool;
use App\Mcp\Tools\Post\GetPostTool;
use App\Mcp\Tools\Post\ListPostsTool;
use App\Mcp\Tools\Post\PreviewPostTool;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Mcp\Tools\Signature\CreateSignatureTool;
use App\Mcp\Tools\Signature\DeleteSignatureTool;
use App\Mcp\Tools\Signature\ListSignaturesTool;
@ -39,7 +45,15 @@ class TryPostServer extends Server
ListPostsTool::class,
GetPostTool::class,
CreatePostTool::class,
UpdatePostTool::class,
PublishPostTool::class,
PreviewPostTool::class,
DeletePostTool::class,
AttachMediaFromUrlTool::class,
GetPostMetricsTool::class,
// Platforms (read-only metadata)
ListContentTypesTool::class,
// Signatures
ListSignaturesTool::class,

View file

@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Platform;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
#[Description('List the valid content_types per social platform plus their constraints (max content length, recommended length, max media count, whether media is required, default content_type). Use before create-post-tool / update-post-tool to know which content_type to set.')]
class ListContentTypesTool extends Tool
{
public function handle(Request $request): ResponseFactory
{
$platforms = [];
foreach (Platform::cases() as $platform) {
$contentTypes = array_map(
fn (ContentType $type) => [
'value' => $type->value,
'label' => $type->label(),
'description' => $type->description(),
'max_media_count' => $type->maxMediaCount(),
'requires_media' => $type->requiresMedia(),
],
array_values(ContentType::forPlatform($platform)),
);
$platforms[] = [
'platform' => $platform->value,
'label' => $platform->label(),
'max_content_length' => $platform->maxContentLength(),
'recommended_content_length' => $platform->recommendedAiContentLength(),
'allowed_media_types' => array_map(
fn ($type) => $type->value,
$platform->allowedMediaTypes(),
),
'default_content_type' => ContentType::defaultFor($platform)->value,
'content_types' => $contentTypes,
];
}
return Response::structured(['platforms' => $platforms]);
}
}

View file

@ -0,0 +1,59 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Post;
use App\Http\Resources\Api\PostResource;
use App\Models\Post;
use App\Services\Post\MediaAttacher;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
#[Description('Download images or videos from public URLs and attach them to a post. Each URL is fetched, stored, and registered as a Media record on the workspace. Allowed types are intersected with the platforms enabled on the post (e.g. nothing accepted if no platform supports the media type).')]
class AttachMediaFromUrlTool extends Tool
{
public function handle(Request $request): Response|ResponseFactory
{
$validated = $request->validate([
'post_id' => ['required', 'uuid'],
'urls' => ['required', 'array', 'min:1', 'max:10'],
'urls.*' => ['url:http,https', 'active_url'],
]);
$post = Post::where('workspace_id', $request->user()->current_workspace_id)
->find(data_get($validated, 'post_id'));
if (! $post) {
return Response::error('Post not found.');
}
$result = app(MediaAttacher::class)->attachFromUrls(
$post,
data_get($validated, 'urls', []),
);
$post->refresh()->load(['postPlatforms.socialAccount', 'labels']);
return Response::structured([
'post' => (new PostResource($post))->resolve(),
'attached_count' => count($result['attached']),
'failed_urls' => $result['failed'],
]);
}
public function schema(JsonSchema $schema): array
{
return [
'post_id' => $schema->string()->required()->description('UUID of the post to attach media to.'),
'urls' => $schema->array()
->items($schema->string())
->required()
->description('Public HTTP/HTTPS URLs of images or videos. Max 10 URLs per call, 50MB per file. Allowed types: image/jpeg, image/png, image/gif, image/webp, video/mp4, video/quicktime, video/webm.'),
];
}
}

View file

@ -5,29 +5,41 @@
namespace App\Mcp\Tools\Post;
use App\Actions\Post\CreatePost;
use App\Enums\PostPlatform\ContentType;
use App\Http\Resources\Api\PostResource;
use App\Rules\ContentTypeMatchesPlatform;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Validation\Rule;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
#[Description('Create a new draft post in the current workspace. The post is automatically attached to every active social account in the workspace (one PostPlatform per account).')]
#[Description('Create a draft post in the current workspace. Accepts content, scheduled_at, label_ids, and a list of platforms (social accounts to publish on, with their content_type). Use list-content-types-tool to discover valid content_types per platform.')]
class CreatePostTool extends Tool
{
public function handle(Request $request): ResponseFactory
{
$workspace = $request->user()->currentWorkspace;
$validated = $request->validate([
'content' => ['nullable', 'string'],
'date' => ['nullable', 'date_format:Y-m-d'],
'content' => ['nullable', 'string', 'max:63206'],
'scheduled_at' => ['nullable', 'date', 'after:now'],
'label_ids' => ['sometimes', 'array'],
'label_ids.*' => ['uuid', Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspace->id)],
'platforms' => ['sometimes', 'array'],
'platforms.*.social_account_id' => [
'required',
'uuid',
Rule::exists('social_accounts', 'id')
->where('workspace_id', $workspace->id)
->where('is_active', true),
],
'platforms.*.content_type' => ['required', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPlatform],
]);
$post = CreatePost::execute(
$request->user()->currentWorkspace,
$request->user(),
$validated,
);
$post = CreatePost::execute($workspace, $request->user(), $validated);
$post->load(['postPlatforms.socialAccount', 'labels']);
@ -37,8 +49,17 @@ public function handle(Request $request): ResponseFactory
public function schema(JsonSchema $schema): array
{
return [
'content' => $schema->string()->description('The post caption/text content. Optional — can be edited later.'),
'date' => $schema->string()->description('Scheduled date as Y-m-d (e.g. 2026-05-10). Defaults to today. Time is fixed at 09:00 UTC; edit the post later for a specific time.'),
'content' => $schema->string()->description('The post caption/text body. Optional — can be edited later.'),
'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future (e.g. 2026-05-10T15:30:00Z). Defaults to today at 09:00 UTC.'),
'label_ids' => $schema->array()
->items($schema->string())
->description('Workspace label IDs to attach to the post.'),
'platforms' => $schema->array()
->items($schema->object(fn ($p) => [
'social_account_id' => $p->string()->required()->description('UUID of the connected social account.'),
'content_type' => $p->string()->required()->description('Format for this platform (e.g. linkedin_post, x_post, instagram_feed).'),
]))
->description('Platforms to publish on. Accounts not listed remain available but disabled.'),
];
}
}

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Post;
use App\Models\Post;
use App\Services\Post\PostMetricsFetcher;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
#[Description('Fetch engagement metrics (likes, comments, shares, etc.) for a published post across all platforms it was posted to. Returns "unsupported" entries for platforms that do not expose post-level metrics or for unpublished platforms.')]
class GetPostMetricsTool extends Tool
{
public function handle(Request $request): Response|ResponseFactory
{
$validated = $request->validate([
'post_id' => ['required', 'uuid'],
]);
$post = Post::where('workspace_id', $request->user()->current_workspace_id)
->with(['postPlatforms.socialAccount'])
->find(data_get($validated, 'post_id'));
if (! $post) {
return Response::error('Post not found.');
}
return Response::structured([
'post_id' => $post->id,
'platforms' => app(PostMetricsFetcher::class)->forPost($post)->all(),
]);
}
public function schema(JsonSchema $schema): array
{
return [
'post_id' => $schema->string()->required()->description('UUID of the published post.'),
];
}
}

View file

@ -4,7 +4,10 @@
namespace App\Mcp\Tools\Post;
use App\Enums\Post\Status;
use App\Http\Resources\Api\PostResource;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Validation\Rule;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
@ -13,20 +16,55 @@
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
#[Description('List posts for the current workspace, ordered by scheduled date (newest first).')]
#[Description('List posts for the current workspace, ordered by scheduled date (newest first). Optional filters: status (draft|scheduled|published) and search (matches against post content).')]
class ListPostsTool extends Tool
{
public function handle(Request $request): ResponseFactory
{
$posts = $request->user()->currentWorkspace
$validated = $request->validate([
'status' => ['sometimes', 'string', Rule::in([
Status::Draft->value,
Status::Scheduled->value,
Status::Published->value,
Status::Failed->value,
])],
'search' => ['sometimes', 'string', 'max:255'],
'limit' => ['sometimes', 'integer', 'min:1', 'max:100'],
]);
$query = $request->user()->currentWorkspace
->posts()
->with(['postPlatforms.socialAccount', 'labels'])
->latest('scheduled_at')
->limit(50)
->with(['postPlatforms.socialAccount', 'labels']);
$query = match (data_get($validated, 'status')) {
Status::Draft->value => $query->draft(),
Status::Scheduled->value => $query->scheduled(),
Status::Published->value => $query->published(),
Status::Failed->value => $query->failed(),
default => $query,
};
if ($search = data_get($validated, 'search')) {
$query->where('content', 'ilike', '%'.$search.'%');
}
$posts = $query->latest('scheduled_at')
->limit((int) data_get($validated, 'limit', 50))
->get();
return Response::structured([
'posts' => PostResource::collection($posts)->resolve(),
]);
}
public function schema(JsonSchema $schema): array
{
return [
'status' => $schema->string()
->enum(['draft', 'scheduled', 'published', 'failed'])
->description('Filter by status. "published" includes partially-published posts.'),
'search' => $schema->string()->description('Case-insensitive substring match against the post content.'),
'limit' => $schema->integer()->description('Max results (1-100, default 50).'),
];
}
}

View file

@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Post;
use App\Models\Post;
use App\Services\Post\PostPreviewer;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
#[Description('Preview how a post will render on each enabled platform — applies platform-specific content sanitization (length truncation, forbidden chars, etc.) without publishing. Returns the original content alongside per-platform sanitized versions and length stats.')]
class PreviewPostTool extends Tool
{
public function handle(Request $request): Response|ResponseFactory
{
$validated = $request->validate([
'post_id' => ['required', 'uuid'],
]);
$post = Post::where('workspace_id', $request->user()->current_workspace_id)
->with(['postPlatforms.socialAccount'])
->find(data_get($validated, 'post_id'));
if (! $post) {
return Response::error('Post not found.');
}
return Response::structured(app(PostPreviewer::class)->forPost($post));
}
public function schema(JsonSchema $schema): array
{
return [
'post_id' => $schema->string()->required()->description('UUID of the post to preview.'),
];
}
}

View file

@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Post;
use App\Actions\Post\UpdatePost;
use App\Enums\Post\Action as PostAction;
use App\Enums\Post\Status;
use App\Http\Resources\Api\PostResource;
use App\Models\Post;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
#[IsDestructive]
#[Description('Publish a draft post — either immediately or scheduled for a future time. The post must already have at least one enabled platform. Use update-post-tool first to set content/platforms.')]
class PublishPostTool extends Tool
{
public function handle(Request $request): Response|ResponseFactory
{
$workspace = $request->user()->currentWorkspace;
$validated = $request->validate([
'post_id' => ['required', 'uuid'],
'scheduled_at' => ['nullable', 'date', 'after:now'],
]);
$post = Post::where('workspace_id', $workspace->id)->find(data_get($validated, 'post_id'));
if (! $post) {
return Response::error('Post not found.');
}
if (! $post->postPlatforms()->where('enabled', true)->exists()) {
return Response::error('Post has no enabled platforms. Use update-post-tool to enable at least one platform first.');
}
$scheduledAt = data_get($validated, 'scheduled_at');
$result = UpdatePost::execute($workspace, $post, [
'status' => $scheduledAt ? Status::Scheduled->value : Status::Publishing->value,
'scheduled_at' => $scheduledAt,
]);
if (data_get($result, 'action') === PostAction::AlreadyPublished) {
return Response::error('Post is already published.');
}
/** @var Post $updated */
$updated = data_get($result, 'post');
$updated->load(['postPlatforms.socialAccount', 'labels']);
return Response::structured((new PostResource($updated))->resolve());
}
public function schema(JsonSchema $schema): array
{
return [
'post_id' => $schema->string()->required()->description('UUID of the post to publish.'),
'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future. If provided, the post is queued for that time. If omitted, publishing starts immediately.'),
];
}
}

View file

@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Mcp\Tools\Post;
use App\Actions\Post\UpdatePost;
use App\Enums\Post\Action as PostAction;
use App\Enums\Post\Status;
use App\Enums\PostPlatform\ContentType;
use App\Http\Resources\Api\PostResource;
use App\Models\Post;
use App\Rules\ContentTypeMatchesPostPlatform;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\Validation\Rule;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\ResponseFactory;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
#[Description('Update a draft post — content, media, scheduled_at, labels, and which platforms are enabled. Cannot edit a post that has already been published.')]
class UpdatePostTool extends Tool
{
public function handle(Request $request): Response|ResponseFactory
{
$workspace = $request->user()->currentWorkspace;
$postId = data_get($request->all(), 'post_id');
$post = is_string($postId) ? Post::where('workspace_id', $workspace->id)->find($postId) : null;
if (! $post) {
return Response::error('Post not found.');
}
$validated = $request->validate([
'post_id' => ['required', 'uuid'],
'content' => ['nullable', 'string', 'max:63206'],
'scheduled_at' => ['nullable', 'date', 'after:now'],
'status' => ['sometimes', 'string', Rule::in([Status::Draft->value, Status::Scheduled->value])],
'label_ids' => ['sometimes', 'array'],
'label_ids.*' => ['uuid', Rule::exists('workspace_labels', 'id')->where('workspace_id', $workspace->id)],
'platforms' => ['sometimes', 'array'],
'platforms.*.id' => [
'required',
'uuid',
Rule::exists('post_platforms', 'id')->where('post_id', $post->id),
],
'platforms.*.content_type' => ['sometimes', 'string', Rule::in(array_column(ContentType::cases(), 'value')), new ContentTypeMatchesPostPlatform],
'platforms.*.meta' => ['sometimes', 'array'],
]);
$payload = collect($validated)->except('post_id')->all();
$result = UpdatePost::execute($workspace, $post, $payload);
if (data_get($result, 'action') === PostAction::AlreadyPublished) {
return Response::error('Cannot edit a published post.');
}
/** @var Post $updated */
$updated = data_get($result, 'post');
$updated->load(['postPlatforms.socialAccount', 'labels']);
return Response::structured((new PostResource($updated))->resolve());
}
public function schema(JsonSchema $schema): array
{
return [
'post_id' => $schema->string()->required()->description('UUID of the post to update.'),
'content' => $schema->string()->description('New caption/text body.'),
'scheduled_at' => $schema->string()->description('ISO 8601 datetime in the future. Required if status is "scheduled".'),
'status' => $schema->string()
->enum([Status::Draft->value, Status::Scheduled->value])
->description('Post status. Use "draft" to keep editing, "scheduled" to schedule the post. Use publish-post-tool for immediate publish.'),
'label_ids' => $schema->array()
->items($schema->string())
->description('Workspace label IDs to attach (replaces existing labels).'),
'platforms' => $schema->array()
->items($schema->object(fn ($p) => [
'id' => $p->string()->required()->description('UUID of the post_platform row (from get-post-tool / list-posts-tool).'),
'content_type' => $p->string()->description('New content_type for this platform.'),
'meta' => $p->object()->description('Per-platform metadata override (e.g. aspect_ratio, board_id for Pinterest).'),
]))
->description('Platforms to enable for publishing. Any platform NOT listed will be disabled. Pass an empty array to disable all.'),
];
}
}

View file

@ -5,6 +5,7 @@
namespace App\Models;
use App\DataTransferObjects\MediaItem;
use App\Enums\Media\Type;
use App\Enums\Post\Status as PostStatus;
use Database\Factories\PostFactory;
use Illuminate\Database\Eloquent\Builder;
@ -16,6 +17,7 @@
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class Post extends Model
{
@ -129,4 +131,50 @@ public function markAsFailed(): void
{
$this->update(['status' => PostStatus::Failed]);
}
/**
* MediaTypes accepted by this post — the intersection of what every
* enabled platform allows. With no platform enabled, accept anything.
*
* @return array<Type>
*/
public function allowedMediaTypes(): array
{
$platforms = $this->postPlatforms()
->where('enabled', true)
->with('socialAccount')
->get()
->pluck('socialAccount.platform')
->filter();
if ($platforms->isEmpty()) {
return Type::cases();
}
$sets = $platforms
->map(fn ($platform) => array_map(fn ($type) => $type->value, $platform->allowedMediaTypes()))
->all();
return array_map(
Type::from(...),
array_values(array_intersect(...$sets)),
);
}
/**
* Append items to the JSON `media` column under a row lock so
* concurrent writers don't overwrite each other's appends.
*
* @param array<int, array<string, mixed>> $items
*/
public function appendMedia(array $items): void
{
DB::transaction(function () use ($items): void {
$fresh = static::whereKey($this->id)->lockForUpdate()->first();
$fresh->update([
'media' => collect($fresh->media ?? [])->concat($items)->all(),
]);
$this->setRawAttributes($fresh->getAttributes(), true);
});
}
}

View file

@ -164,7 +164,7 @@ private function getMediaType(string $mimeType): string
return 'video';
}
return 'document';
throw new \InvalidArgumentException("Unsupported media MIME type: {$mimeType}");
}
private function getMediaMeta(UploadedFile $file, string $type): array

View file

@ -6,18 +6,58 @@
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class PostPolicy
{
/**
* Authorize duplicating a post into the user's current workspace as a
* fresh draft. The post must live in the user's current workspace and
* the user must have permission to create posts there.
* Authorize viewing a post. The post must live in the user's current
* workspace; cross-workspace lookups deny as 404 so we don't leak
* existence across tenants.
*/
public function duplicate(User $user, Post $post): bool
public function view(User $user, Post $post): bool|Response
{
if ($post->workspace_id !== $user->current_workspace_id) {
return false;
return Response::denyAsNotFound();
}
return true;
}
/**
* Authorize updating a post. Same workspace-tenancy guard as `view`.
*/
public function update(User $user, Post $post): bool|Response
{
if ($post->workspace_id !== $user->current_workspace_id) {
return Response::denyAsNotFound();
}
return true;
}
/**
* Authorize deleting a post. Same workspace-tenancy guard as `view`.
*/
public function delete(User $user, Post $post): bool|Response
{
if ($post->workspace_id !== $user->current_workspace_id) {
return Response::denyAsNotFound();
}
return true;
}
/**
* Authorize duplicating a post into the user's current workspace as a
* fresh draft. The post must live in the user's current workspace
* (404 otherwise — tenancy guard, see `view()`) AND the user must
* have permission to create posts there (403 otherwise).
*/
public function duplicate(User $user, Post $post): bool|Response
{
if ($post->workspace_id !== $user->current_workspace_id) {
return Response::denyAsNotFound();
}
return $user->can('createPost', $user->currentWorkspace);

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace App\Rules;
use App\Enums\PostPlatform\ContentType;
use App\Models\SocialAccount;
use Closure;
use Illuminate\Contracts\Validation\DataAwareRule;
use Illuminate\Contracts\Validation\ValidationRule;
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.
*/
class ContentTypeMatchesPlatform implements DataAwareRule, ValidationRule
{
/** @var array<string, mixed> */
private array $data = [];
/**
* @param array<string, mixed> $data
*/
public function setData(array $data): static
{
$this->data = $data;
return $this;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// attribute is e.g. "platforms.0.content_type" — 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');
if (! $accountId) {
return;
}
$contentType = ContentType::tryFrom((string) $value);
$account = SocialAccount::find($accountId);
if (! $contentType || ! $account) {
return;
}
if (! in_array($account->platform, $contentType->compatiblePlatforms(), true)) {
$fail(sprintf(
'content_type "%s" is not compatible with the %s account.',
$contentType->value,
$account->platform->label(),
));
}
}
}

View file

@ -0,0 +1,58 @@
<?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) {
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(),
));
}
}
}

View file

@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace App\Services\Post;
use App\Enums\Media\Type as MediaType;
use App\Models\Post;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* Downloads public URLs and attaches them as media to a post — used by
* the MCP `AttachMediaFromUrlTool` and the REST attach-media endpoint.
*
* URL syntax + DNS resolvability are validated at the request layer
* (`url:http,https`, `active_url`). Locking, intersection of accepted
* media types, and the JSON-column merge live on the Post model so this
* class can stay focused on the network → MIME-validate → handoff flow.
*/
class MediaAttacher
{
/**
* @param array<int, string> $urls
* @return array{attached: array<int, array<string, mixed>>, failed: array<int, string>}
*/
public function attachFromUrls(Post $post, array $urls): array
{
$attached = [];
$failed = [];
foreach ($urls as $url) {
($item = $this->attachOne($post, $url)) === null
? $failed[] = $url
: $attached[] = $item;
}
if ($attached !== []) {
$post->appendMedia($attached);
}
return ['attached' => $attached, 'failed' => $failed];
}
/**
* @return array<string, mixed>|null
*/
private function attachOne(Post $post, string $url): ?array
{
$download = $this->download($url);
if ($download === null) {
return null;
}
try {
$type = MediaType::fromMime($download['mime'] ?? '');
if ($type === null || ! in_array($type, $post->allowedMediaTypes(), true)) {
return null;
}
if ($download['bytes'] > $type->maxSizeInBytes()) {
return null;
}
$name = basename(parse_url($url, PHP_URL_PATH) ?? '') ?: 'download.bin';
$media = $post->workspace->addMediaFromPath($download['path'], $name, 'assets');
return [
'id' => $media->id,
'path' => $media->path,
'url' => $media->url,
'type' => $media->type,
'mime_type' => $media->mime_type,
'original_filename' => $media->original_filename,
];
} finally {
@unlink($download['path']);
}
}
/**
* Stream the URL to a temp file, aborting once we exceed the largest
* configured per-type cap (video). MIME is sniffed from the file's
* magic bytes — far more reliable than trusting the upstream
* `Content-Type` header (CDNs misconfigure, attackers spoof).
*
* @return array{path: string, mime: ?string, bytes: int}|null
*/
private function download(string $url): ?array
{
$cap = MediaType::Video->maxSizeInBytes();
$temp = tempnam(sys_get_temp_dir(), 'media_');
try {
$response = Http::timeout(20)
->sink($temp)
->withOptions([
'allow_redirects' => false,
'progress' => static function ($total, $downloaded) use ($cap): void {
if ($downloaded > $cap) {
throw new RuntimeException('exceeded max bytes');
}
},
])
->get($url);
} catch (RuntimeException) {
@unlink($temp);
return null;
}
$bytes = filesize($temp) ?: 0;
if (! $response->successful() || $bytes === 0) {
@unlink($temp);
return null;
}
return [
'path' => $temp,
'mime' => mime_content_type($temp) ?: null,
'bytes' => $bytes,
];
}
}

View file

@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace App\Services\Post;
use App\Enums\SocialAccount\Platform;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Services\Social\BlueskyAnalytics;
use App\Services\Social\FacebookAnalytics;
use App\Services\Social\InstagramAnalytics;
use App\Services\Social\LinkedInPageAnalytics;
use App\Services\Social\MastodonAnalytics;
use App\Services\Social\PinterestAnalytics;
use App\Services\Social\ThreadsAnalytics;
use App\Services\Social\XAnalytics;
use App\Services\Social\YouTubeAnalytics;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
/**
* Fetches per-platform post metrics. Used by the web controller, the REST
* API controller, and the MCP `GetPostMetricsTool` so that the per-platform
* dispatch and 5-minute cache stay in one place.
*/
class PostMetricsFetcher
{
/**
* @return Collection<int, array{
* post_platform_id: string,
* platform: string,
* status: string,
* platform_post_id: ?string,
* platform_url: ?string,
* metrics: array<int, array{label: string, value: int}>|array{unsupported: true, reason: string}
* }>
*/
public function forPost(Post $post): Collection
{
return $post->postPlatforms
->where('enabled', true)
->values()
->map(fn (PostPlatform $pp) => [
'post_platform_id' => $pp->id,
'platform' => $pp->platform->value,
'status' => $pp->status->value,
'platform_post_id' => $pp->platform_post_id,
'platform_url' => $pp->platform_url,
'metrics' => $this->forPlatform($pp),
]);
}
/**
* @return array<int, array{label: string, value: int}>|array{unsupported: true, reason: string}
*/
public function forPlatform(PostPlatform $postPlatform): array
{
if ($postPlatform->status->value !== 'published' || ! $postPlatform->platform_post_id) {
return ['unsupported' => true, 'reason' => 'not_published'];
}
return Cache::remember("post_metrics:{$postPlatform->id}", 300, fn () => match ($postPlatform->platform) {
Platform::X => app(XAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Bluesky => app(BlueskyAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Mastodon => app(MastodonAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Instagram, Platform::InstagramFacebook => app(InstagramAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Facebook => app(FacebookAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Threads => app(ThreadsAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::LinkedInPage => app(LinkedInPageAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::YouTube => app(YouTubeAnalytics::class)->fetchPostMetrics($postPlatform),
Platform::Pinterest => app(PinterestAnalytics::class)->fetchPostMetrics($postPlatform),
default => ['unsupported' => true, 'reason' => 'platform_not_supported'],
});
}
}

View file

@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace App\Services\Post;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Services\Social\ContentSanitizer;
use Illuminate\Support\Collection;
/**
* Renders per-platform previews of a post — applies the platform-specific
* `ContentSanitizer` rules without publishing. Used by the REST API
* preview endpoint and the MCP `PreviewPostTool` so the rendering rules
* stay in one place.
*/
class PostPreviewer
{
public function __construct(private readonly ContentSanitizer $sanitizer) {}
/**
* @return array{
* post_id: string,
* original_content: string,
* original_length: int,
* platforms: array<int, array{
* post_platform_id: string,
* platform: string,
* content_type: ?string,
* sanitized_content: string,
* sanitized_length: int,
* max_content_length: int,
* truncated: bool
* }>
* }
*/
public function forPost(Post $post): array
{
$original = (string) $post->content;
return [
'post_id' => $post->id,
'original_content' => $original,
'original_length' => mb_strlen($original),
'platforms' => $this->platformPreviews($post, $original)->all(),
];
}
/**
* @return Collection<int, array<string, mixed>>
*/
private function platformPreviews(Post $post, string $original): Collection
{
return $post->postPlatforms
->where('enabled', true)
->values()
->map(function (PostPlatform $pp) use ($original) {
$platform = $pp->socialAccount?->platform ?? $pp->platform;
$sanitized = $original === '' ? '' : $this->sanitizer->sanitize($original, $platform);
return [
'post_platform_id' => $pp->id,
'platform' => $platform->value,
'content_type' => $pp->content_type?->value,
'sanitized_content' => $sanitized,
'sanitized_length' => mb_strlen($sanitized),
'max_content_length' => $platform->maxContentLength(),
'truncated' => mb_strlen($sanitized) < mb_strlen($original),
];
});
}
}

View file

@ -2,6 +2,7 @@
"agents": [
"claude_code"
],
"cloud": false,
"guidelines": true,
"mcp": true,
"nightwatch_mcp": true,

View file

@ -15,7 +15,7 @@
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
apiPrefix: '',
apiPrefix: 'api',
commands: __DIR__.'/../routes/console.php',
channels: __DIR__.'/../routes/channels.php',
health: '/up',

View file

@ -20,7 +20,7 @@
"threads",
"pinterest"
],
"license": "MIT",
"license": "AGPL-3.0-only",
"homepage": "https://trypost.it",
"support": {
"issues": "https://github.com/trypost-it/trypost/issues",
@ -41,7 +41,7 @@
"laravel/boost": "^2.0",
"laravel/cashier": "^16.2",
"laravel/framework": "^13.0",
"laravel/horizon": "^5.42",
"laravel/horizon": "^5.45",
"laravel/mcp": "^0.6.4",
"laravel/nightwatch": "^1.22",
"laravel/passport": "^13.7",
@ -74,8 +74,7 @@
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"pestphp/pest": "^4.4",
"pestphp/pest-plugin-laravel": "^4.1",
"spatie/laravel-horizon-watcher": "^1.1"
"pestphp/pest-plugin-laravel": "^4.1"
},
"autoload": {
"files": [

795
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -16,6 +16,24 @@
'self_hosted' => env('SELF_HOSTED', true),
/*
|--------------------------------------------------------------------------
| Media Size Limits
|--------------------------------------------------------------------------
|
| Per-type size caps in megabytes. Single source of truth — direct
| uploads (StoreAssetRequest, AssetController::storeChunked), URL
| fetches (MediaAttacher), and the MediaType enum all read from here.
|
*/
'media' => [
'max_size_mb' => [
'image' => (int) env('MEDIA_IMAGE_MAX_SIZE_MB', 10),
'video' => (int) env('MEDIA_VIDEO_MAX_SIZE_MB', 1024),
],
],
/*
|--------------------------------------------------------------------------
| Google Authentication

File diff suppressed because it is too large Load diff

View file

@ -1,322 +0,0 @@
# Account Billing, Plans & Workspaces
## Overview
Introduce an Account entity as the central billing and organizational unit. Account holds the Stripe subscription, plan, and limits. Workspaces group social accounts within an Account. Users belong to one Account with an account-level role (admin/user) and can be assigned to specific workspaces with workspace-level roles (member/viewer). The Account owner has full access to everything.
## Data Model
```
Account (Billable, plan_id, owner_id)
├── Users (account_id, account_role: admin/user)
└── Workspaces
├── Members (user_id, workspace_role: member/viewer)
├── Invites
└── Social Accounts
```
## Roles
### Account-level
Owner is determined by `accounts.owner_id`. No account-level role column on users. Only the owner can manage billing, create workspaces, and delete the account. The owner has full access to all workspaces automatically.
### Workspace-level roles (`user_workspace.role`)
| Role | Permissions |
|---|---|
| Admin | Everything in the workspace: manage members, connect accounts, settings |
| Member | Create posts, schedule |
| Viewer | View only (future: comments) |
The Account owner has full access to all workspaces without needing a workspace pivot record.
## Plans
| Limit | Starter ($19/$190) | Plus ($29/$290) | Pro ($49/$490) | Max ($99/$990) |
|---|---|---|---|---|
| Social accounts | 5 | 10 | 30 | 100 |
| Members | 1 | 5 | 15 | 20 |
| Workspaces | 1 | 5 | 15 | 50 |
| AI Images/month | 50 | 150 | 500 | 2000 |
| AI Videos/month | 10 | 30 | 100 | 500 |
| Data retention (days) | 30 | 60 | 90 | 730 |
| Monthly price | $19 | $29 | $49 | $99 |
| Yearly price | $190 | $290 | $490 | $990 |
All limits are at the **Account level** (totals across all workspaces).
Starter plan: 1 member (owner only), 1 workspace (default, UI hides workspace management).
Trial period: 8 days (configurable via `CASHIER_TRIAL_DAYS`).
---
## Database Changes
### New table: `accounts`
| Column | Type | Notes |
|---|---|---|
| id | uuid, PK | |
| owner_id | FK -> users, nullable initially | Set after user creation (chicken-egg) |
| plan_id | FK -> plans, nullable | Current plan |
| name | string | Account/company name |
| stripe_id | string, nullable, indexed | Stripe customer ID |
| pm_type | string, nullable | Payment method type |
| pm_last_four | string, nullable | Last 4 digits |
| trial_ends_at | timestamp, nullable | |
| timestamps | | |
Note: `owner_id` is nullable because during signup the user and account are created in the same transaction. Set `owner_id` after user creation.
### New table: `plans` (unchanged from current)
Already implemented. slug, name, stripe price IDs, all limits, sort, is_archived.
### Modify table: `users`
Add columns:
- `account_id` (FK -> accounts, nullable, constrained)
- `account_role` (string, default 'user') — enum: admin, user
Remove columns:
- `stripe_id`, `pm_type`, `pm_last_four`, `trial_ends_at` (already removed)
### Modify table: `workspaces`
Remove columns:
- `plan_id` (moves to Account)
- `stripe_id`, `pm_type`, `pm_last_four`, `trial_ends_at` (moves to Account)
Add columns:
- `account_id` (FK -> accounts, constrained, cascade delete)
Keep: `user_id` (original creator, not necessarily the owner), `name`, `timezone`
### Modify table: `user_workspace`
Change `role` values from `owner/admin/member` to `member/viewer`. Owner is determined by Account, not workspace pivot.
### Modify table: `subscriptions`
Change FK from `workspace_id` to `account_id`.
### Modify table: `invites` (rename from `workspace_invites`)
| Column | Type | Notes |
|---|---|---|
| id | uuid, PK | |
| account_id | FK -> accounts, cascade delete | |
| email | string | Invited email |
| workspaces | json | Array of {workspace_id, role} |
| invited_by | FK -> users, nullable | Who sent the invite |
| accepted_at | timestamp, nullable | |
| timestamps | | |
### Remove table: `brands`
Brands concept is replaced by Workspaces. Remove brands table, remove `brand_id` from social_accounts.
---
## Models
### Account (new)
- UUID primary key
- `Billable` trait from Cashier
- Constant: `SUBSCRIPTION_NAME = 'default'`
- Fillable: name, owner_id, plan_id
- Relationships: `owner()` belongsTo User, `plan()` belongsTo Plan, `users()` hasMany User, `workspaces()` hasMany Workspace, `invites()` hasMany Invite
- Methods: `hasActiveSubscription()`, `isOnTrial()`, `stripeEmail()` (owner email), `stripeName()` (account name)
### User (modified)
- Remove `Billable` trait (already removed)
- Add `account_id` and `account_role` to fillable
- Add cast: `account_role` to `AccountRole` enum
- Add relationship: `account()` belongsTo Account
- Remove: `HasWorkspace` trait methods related to billing
- Keep: `currentWorkspace()`, `switchWorkspace()`, workspace navigation methods
- Add: `isAccountOwner()` — `$this->id === $this->account?->owner_id`
- Add: `isAccountAdmin()` — `$this->account_role === AccountRole::Admin || $this->isAccountOwner()`
### Workspace (modified)
- Remove `Billable` trait
- Remove billing fields from fillable (stripe_id, pm_type, pm_last_four, trial_ends_at, plan_id)
- Add `account_id` to fillable
- Add relationship: `account()` belongsTo Account
- Keep: members(), socialAccounts(), posts(), invites is now on Account
### Invite (modified from WorkspaceInvite)
- Rename model from WorkspaceInvite to Invite
- Add: `account_id`, `workspaces` (json), `invited_by`
- Add cast: `workspaces` to array
- Relationship: `account()` belongsTo Account, `invitedBy()` belongsTo User
---
## Enums
### AccountRole (new)
```php
enum AccountRole: string
{
case Admin = 'admin';
case User = 'user';
}
```
### WorkspaceRole (modify existing)
```php
enum WorkspaceRole: string
{
case Member = 'member';
case Viewer = 'viewer';
}
```
Remove `Owner` and `Admin` cases.
---
## Cashier Configuration
### AppServiceProvider
```php
Cashier::useCustomerModel(Account::class);
```
---
## Middleware: EnsureSubscribed
1. If `config('trypost.self_hosted')` → pass
2. Get `$user->account`
3. If account has active subscription or trial → pass
4. Redirect to `/subscribe`
---
## Pennant Features
Scope changes from Workspace to Account:
```php
Feature::resolveScopeUsing(fn () => auth()->user()?->account);
```
All 6 feature classes receive `Account $scope` instead of `Workspace $scope`:
- `SocialAccountLimit` — `$scope->plan?->social_account_limit ?? 5`
- `MemberLimit` — `$scope->plan?->member_limit ?? 1`
- `WorkspaceLimit` — `$scope->plan?->workspace_limit ?? 1` (replaces BrandLimit)
- `AiImagesLimit` — `$scope->plan?->ai_images_limit ?? 50`
- `AiVideosLimit` — `$scope->plan?->ai_videos_limit ?? 10`
- `DataRetentionDays` — `$scope->plan?->data_retention_days ?? 30`
---
## Limit Enforcement
All limits checked at Account level:
- **Social accounts**: total across all workspaces in the account
- **Members**: unique users in the account (excluding owner) — `$account->users()->where('id', '!=', $account->owner_id)->count()`
- **Workspaces**: `$account->workspaces()->count()`
- **AI images/videos**: monthly usage tracked per account
- **Data retention**: applied per account
---
## Controllers
### BillingController
All operations on `$user->account`:
- `$account->subscribed()`, `$account->subscription()`, `$account->invoices()`
### OnboardingController
Signup flow:
1. Create Account
2. Create User with `account_id` and `account_role = admin` (owner)
3. Set `account.owner_id`
4. Create default Workspace with `account_id`
5. Stripe checkout on Account
### StripeEventListener
Find `Account::where('stripe_id', $stripeCustomerId)` instead of Workspace.
### InviteController (replaces WorkspaceInviteController)
- `store()`: create invite on Account with workspaces + roles array
- On accept: set user's `account_id`, create workspace pivot records
---
## Signup Flow
1. User registers (name, email, password)
2. `CreateUser` action:
- Creates Account (name = user's name)
- Creates User with `account_id`, `account_role = admin`
- Sets `account.owner_id = user.id`
- Creates default Workspace within Account
- Sets `user.current_workspace_id`
3. Onboarding: role → connect accounts → Stripe checkout (on Account)
## Invite Flow
1. Owner/Admin creates invite: email + [{workspace_id, role}]
2. Email sent with invite link
3. Person clicks link:
- If no TryPost account: register with `account_id` pre-set, `account_role = user`
- If has TryPost account with same Account: add workspace assignments
- If has TryPost account with different Account: error — must use different email
4. Workspace pivot records created per the invite's workspaces array
---
## UI Behavior by Plan
### Starter (1 workspace, 1 member)
- Workspace switcher hidden
- "Create workspace" hidden
- Invite members hidden
- Simple single-workspace experience
### Plus and above
- Workspace switcher visible
- Create workspace button visible
- Invite members visible
- Full multi-workspace experience
---
## Plans table: workspace_limit replaces brand_limit
| Column change | Old | New |
|---|---|---|
| brand_limit | 0, 5, 15, 50 | renamed to workspace_limit: 1, 5, 15, 50 |
---
## Self-hosted mode
All limits bypassed. Account still exists but no billing. Unlimited workspaces, members, social accounts.
---
## What does NOT change
- Social account OAuth flows (connect/disconnect)
- Post creation and publishing
- Analytics
- Multi-account social connections (multiple accounts per platform)

View file

@ -1,288 +0,0 @@
# Instagram and Facebook Content Variants in Post Editor
**Date:** 2026-04-23
**Branch:** feature/workspace-billing-plans
## Problem
The post editor has per-platform settings for TikTok (`TikTokSettings.vue`) but no equivalent UI for choosing content variants on Instagram (Feed / Reel / Story) and Facebook (Post / Reel / Story). The backend already supports these variants — `ContentType` enum maps to publisher branches in `InstagramPublisher` and `FacebookPublisher`, `UpdatePost` persists `content_type`, and `UpdatePostRequest` validates it — but `SyncPostPlatforms` always defaults to `InstagramFeed` / `FacebookPost` and the frontend has no way for users to change it.
Users currently can only publish Feed posts on Instagram and standard Posts on Facebook, even when they want Reels or Stories.
## Goals
- Let users choose content variant per connected Instagram and Facebook account on the post edit page.
- Match the visual pattern established by `TikTokSettings.vue` (collapsible card with platform context).
- Support multiple connected accounts of the same platform (each card is independent — user can pick different variants for different accounts in the same post).
- Block submission with a clear warning when the chosen variant is incompatible with the attached media (mirrors existing `tiktokComplianceValid` pattern).
- Centralize media rules in a single source of truth, re-used for validation and for per-card warnings.
## Non-Goals
- Backend changes (publishers already handle all variants).
- Variant support for platforms beyond Instagram and Facebook (LinkedIn, Pinterest, etc. come later).
- Restricting the media upload picker based on variant — the variant-driven accept/max logic stays on the validation side, not on the file input (user can still drop any media; we just warn + block publish).
## Design
### New Files
- `resources/js/components/posts/editor/InstagramSettings.vue` — rendered for `Platform::Instagram` and `Platform::InstagramFacebook` (same variant set).
- `resources/js/components/posts/editor/FacebookSettings.vue` — rendered for `Platform::Facebook`.
- `resources/js/composables/useMediaRules.ts` — restored from `main`, single source of truth for per-`content_type` media constraints.
### Modified Files
- `resources/js/pages/posts/Edit.vue` — add `platformContentTypes` state, compliance computeds, update `getSubmitData()` and autosave watcher, pipe new state into `ScheduleTab` and `PreviewTab`.
- `resources/js/components/posts/editor/ScheduleTab.vue` — accept `platformContentTypes` prop, emit `update:platform-content-type`, render `InstagramSettings` / `FacebookSettings` blocks per selected account.
- `resources/js/components/posts/editor/PreviewTab.vue` — read variant from `platformContentTypes[previewPlatform.id]` so preview updates live when user toggles variants.
- `lang/en/posts.php`, `lang/es/posts.php`, `lang/pt-BR/posts.php` — add translation keys for settings card, variant labels, warnings.
### Component Structure (`InstagramSettings.vue`, `FacebookSettings.vue`)
Mirror `TikTokSettings.vue`'s outer shell:
- Collapsible root card with border.
- Header button: platform icon + `"Instagram settings"` / `"Facebook settings"` + chevron up/down.
- Closed by default; clicking the header toggles `open` ref.
- Body (when open):
- "Posting to" row: `Avatar` component + display name + `@username` of the connected account (critical when the user has multiple accounts of the same platform — makes clear which card configures which account).
- Variant picker: three horizontal pill buttons, one per variant. Active pill gets `bg-primary/10 border-primary`; inactive gets muted styling. Clicking emits `update:content-type` with the new value.
- Warning block (conditionally rendered): when `useMediaRules(contentType)` indicates the current `media` array violates the rules, render an `IconAlertTriangle` + short i18n message explaining the specific violation ("Reel requires a video", "Story accepts only 1 media", etc.).
Props:
```ts
interface Props {
socialAccount: SocialAccount | null;
contentType: string; // e.g. 'instagram_reel'
media: MediaItem[]; // to evaluate compliance warnings
disabled?: boolean;
}
```
Emits:
```ts
'update:content-type': [value: string]
```
### Variant Catalog
| Platform | Variants | Default |
|----------|----------|---------|
| Instagram (standalone + via Facebook) | `instagram_feed`, `instagram_reel`, `instagram_story` | `instagram_feed` |
| Facebook | `facebook_post`, `facebook_reel`, `facebook_story` | `facebook_post` |
Labels and descriptions are already defined in `App\Enums\PostPlatform\ContentType` (`label()` and `description()` methods). Frontend uses i18n keys for display so strings stay in translation files, not in enum PHP strings.
### State Management in `Edit.vue`
Add a `platformContentTypes` ref that mirrors the existing `platformMeta` pattern exactly:
```ts
const platformContentTypes = ref<Record<string, string>>(
Object.fromEntries(
post.value.post_platforms.map((pp) => [pp.id, pp.content_type ?? '']),
),
);
const updatePlatformContentType = (platformId: string, contentType: string) => {
platformContentTypes.value = {
...platformContentTypes.value,
[platformId]: contentType,
};
};
```
This produces a dictionary keyed by `post_platform.id`, so two Instagram accounts get two independent entries.
Update `getSubmitData()` to read `content_type` from state instead of the prop:
```ts
const platforms = post.value.post_platforms
.filter((pp) => selectedPlatformIds.value.includes(pp.id))
.map((pp) => ({
id: pp.id,
content_type: platformContentTypes.value[pp.id] ?? pp.content_type,
meta: platformMeta.value[pp.id] ?? pp.meta ?? {},
}));
```
Add `platformContentTypes` to the autosave `watch`:
```ts
watch(
[content, media, selectedPlatformIds, scheduledDateTime, selectedLabelIds, platformMeta, platformContentTypes],
triggerAutosave,
{ deep: true },
);
```
### Media Rules Composable
Restore `resources/js/composables/useMediaRules.ts` from `main` (the file already covered Instagram, Facebook, and every other platform correctly). The restored file keeps its original `useMediaRules(contentTypeRef)` reactive form (used inside settings components) and adds a small non-reactive helper for use in `Edit.vue`'s validation computeds:
- `useMediaRules(contentTypeRef: Ref<string>)` — reactive, already present on `main`, for use in `<script setup>` of settings components.
- `getMediaRules(contentType: string): MediaRules` — new plain helper that returns the same rules dictionary entry imperatively, so compliance computeds in `Edit.vue` don't need to wrap in refs.
The rules object keys off `content_type` values (e.g. `instagram_reel`) and returns `{ maxFiles, minFiles?, acceptImages, acceptVideos, requiresMedia }`.
### Compliance Validation
Add a single media-vs-rules helper in `Edit.vue`:
```ts
const isMediaValidForContentType = (contentType: string, mediaItems: MediaItem[]): boolean => {
const rules = getMediaRules(contentType);
const videos = mediaItems.filter((m) => m.type === 'video' || m.mime_type?.startsWith('video/'));
const images = mediaItems.filter((m) => m.type === 'image' || m.mime_type?.startsWith('image/'));
const total = mediaItems.length;
if (rules.requiresMedia && total === 0) return false;
if (total > rules.maxFiles) return false;
if (rules.minFiles && total < rules.minFiles) return false;
if (!rules.acceptVideos && videos.length > 0) return false;
if (!rules.acceptImages && images.length > 0) return false;
return true;
};
```
Two new computeds parallel to the existing `tiktokComplianceValid`:
```ts
const instagramComplianceValid = computed(() =>
post.value.post_platforms
.filter((pp) => ['instagram', 'instagram-facebook'].includes(pp.platform)
&& selectedPlatformIds.value.includes(pp.id))
.every((pp) => {
const ct = platformContentTypes.value[pp.id];
return Boolean(ct) && isMediaValidForContentType(ct, media.value);
}),
);
const facebookComplianceValid = computed(() =>
post.value.post_platforms
.filter((pp) => pp.platform === 'facebook'
&& selectedPlatformIds.value.includes(pp.id))
.every((pp) => {
const ct = platformContentTypes.value[pp.id];
return Boolean(ct) && isMediaValidForContentType(ct, media.value);
}),
);
```
Submit buttons (`PickTimePopover` trigger and the primary "Post now" / "Schedule" button) gain these computeds in their `:disabled` expression, and `:title` falls back to the first failing platform's i18n message when compliance is false.
### `ScheduleTab.vue` Integration
Add prop and emit:
```ts
defineProps<{
// ...existing props
platformContentTypes: Record<string, string>;
}>();
defineEmits<{
// ...existing emits
'update:platform-content-type': [platformId: string, contentType: string];
}>();
```
Compute filtered lists (complement to existing `selectedTikTokPlatforms`):
```ts
const selectedInstagramPlatforms = computed(() =>
props.postPlatforms.filter(
(pp) => ['instagram', 'instagram-facebook'].includes(pp.platform)
&& props.selectedPlatformIds.includes(pp.id),
),
);
const selectedFacebookPlatforms = computed(() =>
props.postPlatforms.filter(
(pp) => pp.platform === 'facebook' && props.selectedPlatformIds.includes(pp.id),
),
);
```
Render blocks in the existing "Platform-specific settings" region, after the TikTok block:
```vue
<div v-if="selectedInstagramPlatforms.length > 0" class="space-y-4">
<InstagramSettings
v-for="pp in selectedInstagramPlatforms"
:key="pp.id"
:social-account="pp.social_account"
:content-type="platformContentTypes[pp.id] ?? ''"
:media="media ?? []"
:disabled="isReadOnly"
@update:content-type="emit('update:platform-content-type', pp.id, $event)"
/>
</div>
<div v-if="selectedFacebookPlatforms.length > 0" class="space-y-4">
<FacebookSettings
v-for="pp in selectedFacebookPlatforms"
:key="pp.id"
:social-account="pp.social_account"
:content-type="platformContentTypes[pp.id] ?? ''"
:media="media ?? []"
:disabled="isReadOnly"
@update:content-type="emit('update:platform-content-type', pp.id, $event)"
/>
</div>
```
### Preview Reactivity
`PreviewTab.vue` currently receives `contentType` as a prop read from `previewPlatform.content_type` (i.e., the server-side value from the last save). Update `Edit.vue`'s template to read from local state so the preview updates live:
```vue
<PreviewTab
v-if="previewPlatform"
:platform="previewPlatform.platform"
:content="content"
:media="media"
:social-account="previewPlatform.social_account"
:content-type="platformContentTypes[previewPlatform.id] ?? previewPlatform.content_type"
/>
```
### Translation Keys
Add under `posts.form.instagram.*` and `posts.form.facebook.*` (for all three locales):
- `settings` — "Instagram settings" / "Facebook settings"
- `posting_to` — "Posting to"
- `variant.feed`, `variant.reel`, `variant.story` (IG) — pill labels
- `variant.post`, `variant.reel`, `variant.story` (FB) — pill labels
- `variant.*_description` — sub-text for pills (optional, for a11y title)
- `warning.requires_media`, `warning.max_files_exceeded`, `warning.min_files_required`, `warning.no_video_allowed`, `warning.no_image_allowed` — specific violation messages
- `compliance_incomplete` — button tooltip when submit is blocked
## Data Flow
1. Backend seeds `post_platforms.content_type` with `ContentType::defaultFor($platform)` in `SyncPostPlatforms`.
2. `Edit.vue` reads the incoming `post.post_platforms[].content_type` and initializes `platformContentTypes`.
3. User opens Instagram / Facebook card, picks a variant pill → `InstagramSettings`/`FacebookSettings` emits `update:content-type` → `ScheduleTab` re-emits with `pp.id` → `Edit.vue` updates `platformContentTypes` state.
4. Autosave watcher fires → `getSubmitData()` builds platforms array with updated `content_type` → PUT to `app.posts.update` → `UpdatePost::execute` writes `content_type` on `post_platforms`.
5. Preview, warnings, and submit-button gating all read from the live `platformContentTypes` so changes are immediate.
6. At publish time, `InstagramPublisher::publish()` / `FacebookPublisher::publish()` branch on `content_type` (already implemented) and call the correct Graph API endpoint.
## Error Handling
- All card interactions respect `isReadOnly` (published / partially_published posts), consistent with existing patterns.
- If `platformContentTypes[pp.id]` is somehow empty (e.g. legacy row), the card falls back to the prop value, and the compliance computed returns `false`, blocking submit until the user explicitly picks a variant.
- Invalid `content_type` values sent to the backend are rejected by `UpdatePostRequest`'s `Rule::in(ContentType::cases())` validation.
## Testing
- Update or add a feature test for `PostController::update` that submits a payload with `platforms[].content_type = 'instagram_reel'` and asserts the `post_platform` row is updated.
- Add a unit/feature test that `instagram-facebook` platform rows accept Instagram content types (same set as standalone Instagram).
- (Optional) Pest Browser test: open an edit page with an Instagram account connected, click the card, select "Reel", confirm the preview updates and autosave fires.
## Rollout
Single feature branch, single PR. No migration, no config flags. Backend is already capable — this is purely a frontend/UX enablement. Deploying the change instantly unlocks Reel/Story publishing for all users who have an Instagram or Facebook account connected.

View file

@ -1,258 +0,0 @@
# Media Format Matrix for Social Networks
**Date:** 2026-04-23
**Status:** Draft — needs verification of cells marked `?`
Reference map of accepted media formats per platform/variant. Drives the `MediaConverter` service design.
## Images
| Platform / Variant | JPEG | PNG | WebP | GIF | HEIC | Max size | Max dimensions | Aspect ratio | Notes |
|-------------------|------|-----|------|-----|------|----------|----------------|--------------|-------|
| **Instagram Feed** | ✅ | ❌ | ❌ | ❌ | ❌ | ~8 MB | 1920 × 1080 | 4:5 to 1.91:1 | JPEG **only** per official docs. PNG returns error 2207052/2207005. |
| **Instagram Reel** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | **Reel = video only** (media_type REELS requires video_url) |
| **Instagram Story** | ✅ | ❌ | ❌ | ❌ | ❌ | ~8 MB | 1920 × 1080 | 9:16 preferred | JPEG only. Same rules as Feed for image stories. |
| **Facebook Post** | ✅ | ✅ | ? | ? | ❌ | 4 MB | ? | wide range | Postiz maps error 1366046 for size/format violations |
| **Facebook Reel** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only |
| **Facebook Story** | ✅ | ✅ | ? | ? | ❌ | 4 MB | ? | 9:16 preferred | Same as Post format-wise |
| **LinkedIn Post** | ✅ | ✅ | ? | ❌ | ❌ | 5 MB | 6000 × 6000 | wide range | JPEG/PNG safest |
| **LinkedIn Carousel** | ✅ | ✅ | ? | ❌ | ❌ | 5 MB each | 6000 × 6000 | 1:1 to 1:1.91 | Up to 20 images |
| **TikTok Video** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only via this content_type |
| **TikTok Photo** (`auto_add_music`) | ✅ | ✅ | ? | ❌ | ❌ | ? | ? | ? | Postiz has `convertToJPEG: true` |
| **YouTube Shorts** | ❌ | ❌ | ❌ | ❌ | ❌ | — | — | — | Video only |
| **X Post** | ✅ | ✅ | ✅ | ✅ | ❌ | 5 MB | 8192 × 8192 | ≥ 4:1 to ≥ 1:3 | Up to 4 images or 1 video |
| **Threads Post** | ✅ | ✅ | ✅ | ❌ | ❌ | 8 MB | ? | 10:16.5 max | Same as Instagram stack |
| **Pinterest Pin** | ✅ | ✅ | ? | ❌ | ❌ | 20 MB | ? | 2:3 preferred | |
| **Pinterest Carousel** | ✅ | ✅ | ? | ❌ | ❌ | 20 MB | ? | 2:3 preferred | 2–5 images |
| **Bluesky Post** | ✅ | ✅ | ✅ | ✅ | ❌ | **976 KB** | ? | flexible | Postiz auto-resizes to fit 976 KB |
| **Mastodon Post** | ✅ | ✅ | ✅ | ✅ | ❌ | 10 MB (instance-dep) | ? | flexible | Varies by instance |
## Videos
| Platform / Variant | MP4 | MOV | WebM | Max size | Max duration | Min duration | Aspect ratio | Notes |
|-------------------|-----|-----|------|----------|--------------|--------------|--------------|-------|
| **Instagram Feed (video)** | ✅ | ✅ | ❌ | 100 MB | 60 min | 3s | 4:5 to 1.91:1 | Becomes VIDEO or REELS based on aspect |
| **Instagram Reel** | ✅ | ✅ | ❌ | 1 GB | 15 min | 3s | 9:16 preferred | H.264, AAC audio |
| **Instagram Story** | ✅ | ✅ | ❌ | 100 MB | 60s | 3s | 9:16 | |
| **Facebook Post (video)** | ✅ | ✅ | ? | 10 GB | 240 min | — | flexible | Very permissive |
| **Facebook Reel** | ✅ | ✅ | ? | 1 GB | 90s | 3s | 9:16 | |
| **Facebook Story** | ✅ | ✅ | ? | ? | 60s | — | 9:16 | |
| **LinkedIn Post** | ✅ | ? | ? | 5 GB | 10 min | 3s | flexible | |
| **TikTok Video** | ✅ | ✅ | ✅ | max from `creator_info` | max from `creator_info` | 3s | 9:16 preferred | Duration fetched from API per account |
| **YouTube Shorts** | ✅ | ✅ | ✅ | 256 GB | 60s | — | 9:16 | Shorts detection is automatic on vertical vídeo ≤ 60s |
| **X Post (video)** | ✅ | ✅ | ❌ | 512 MB | 140s (std) / 2h 20m (Premium) | 0.5s | wide range | Postiz caps at 2min |
| **Threads Post (video)** | ✅ | ✅ | ❌ | 1 GB | 5 min | — | flexible | |
| **Pinterest Video Pin** | ✅ | ✅ | ❌ | 2 GB | 15 min | 4s | flexible | |
| **Bluesky Post (video)** | ✅ | ✅ | ❌ | 100 MB | 60s | — | flexible | Upload via dedicated endpoint |
| **Mastodon Post (video)** | ✅ | ? | ✅ | 40 MB (instance-dep) | instance-dep | — | flexible | |
## Per-platform "from-to" image normalization
**Philosophy:** every media item passes through the converter before publishing. No env flag. Converter is a no-op when source already matches the platform's accepted set.
| Platform / Variant | Accepted natively (no-op) | Everything else converts to | Also enforces |
|-------------------|---------------------------|-----------------------------|---------------|
| Instagram Feed / Story | JPEG | **JPEG** (q90) | ≤ 1920×1080, aspect 4:5..1.91:1 |
| Instagram Reel | — (video only) | — | — |
| Facebook Post / Story | JPEG | **JPEG** (q90) | ≤ 4 MB |
| Facebook Reel | — (video only) | — | — |
| TikTok Photo mode | JPEG | **JPEG** (q90) | — |
| LinkedIn Post / Carousel | JPEG, PNG | **JPEG** (q90) from WebP/HEIC/GIF | ≤ 5 MB, ≤ 6000×6000 |
| X Post | JPEG, PNG, WebP, GIF | **JPEG** (q90) from HEIC | ≤ 5 MB |
| Threads Post | JPEG, PNG, WebP | **JPEG** (q90) from HEIC/GIF | ≤ 8 MB |
| Pinterest Pin / Carousel | JPEG, PNG | **JPEG** (q90) from WebP/HEIC/GIF | ≤ 20 MB |
| Bluesky Post | JPEG, PNG, WebP, GIF | **JPEG** from HEIC; **iterative resize** if > 976 KB | ≤ 976 KB |
| Mastodon Post | JPEG, PNG, WebP, GIF | **JPEG** (q90) from HEIC | instance-dep |
**Derived rules:**
- **HEIC → always JPEG** (nenhuma plataforma aceita HEIC)
- **WebP → JPEG** para Meta (IG/FB), TikTok Photo, LinkedIn, Pinterest; nativo em X/Threads/Bluesky/Mastodon
- **PNG → JPEG** para Meta + TikTok Photo; nativo no resto
- **GIF → JPEG** (primeiro frame) para Meta + LinkedIn + Pinterest + Threads; nativo em X/Bluesky/Mastodon
- **Animated GIF / Animated WebP**: perde animação quando convertido (limitação v1, flag futuro)
## Video normalization (v1)
**Fora do escopo do converter.** Vídeos passam direto pelo publisher — plataformas validam server-side e a gente surfa erro pro usuário. Transcoding (FFmpeg, codec fix, re-mux) fica pra v2.
## Converter service design
### Service signature
```php
namespace App\Services\Media;
use App\Enums\PostPlatform\ContentType;
use App\Models\Media;
class MediaConverter
{
/**
* Ensure a media item is compatible with the given content_type.
* Returns a Media (original or a newly-created converted copy).
* Idempotent: if the original already complies, returns it as-is.
* Cached: repeated calls for the same (media, content_type) reuse the previously-converted file.
*/
public function ensureCompatible(Media $media, ContentType $contentType): Media;
}
```
### Rules catalog
A single class centralizes the "from-to" table above:
```php
final class PlatformMediaRules
{
public function __construct(
public readonly array $acceptedImageMimes, // ['image/jpeg']
public readonly string $targetImageMime, // 'image/jpeg'
public readonly int $targetJpegQuality, // 90
public readonly ?int $maxImageWidth, // 1920
public readonly ?int $maxImageHeight, // 1080
public readonly ?int $maxImageBytes, // 4_000_000
) {}
public static function for(ContentType $ct): self { /* match per variant */ }
}
```
### When it's called
Each publisher invokes once, at the top of `publish()`:
```php
public function publish(PostPlatform $pp): array
{
$media = $pp->post->mediaItems->map(
fn ($m) => $this->converter->ensureCompatible($m, $pp->content_type),
);
// continue with normalized $media
}
```
Same pattern in every publisher: Instagram, Facebook, TikTok, LinkedIn, X, Threads, Pinterest, Bluesky, Mastodon, YouTube.
### Pipeline (image)
```
1. Fetch original file from storage
2. Detect real MIME via finfo (not trusting extension)
3. If MIME ∈ acceptedImageMimes AND bytes ≤ maxImageBytes AND dims ≤ max → return original Media (no-op)
4. Else:
a. Load into Intervention\Image
b. Resize if > maxImageWidth/Height (keep aspect)
c. For Bluesky: loop shrinking 10% until bytes ≤ 976 KB (Postiz precedent)
d. Encode to targetImageMime at targetJpegQuality
e. Upload to storage: `converted/{media_id}/{file_hash}/{content_type_value}.jpg`
f. Create Media row pointing at converted file (or return cached row if exists)
g. Return the new Media
```
### Caching / idempotency
Path strategy: `converted/{original_media_id}/{original_file_sha256_prefix}/{content_type_value}.{ext}`
- If original file changes → sha256 differs → new path → fresh conversion
- If same original + same target → path exists → reuse
- DB table `media_conversions` (migration) tracks `(source_media_id, content_type, derived_media_id)` for fast lookup without listing storage
### Failure handling
- Conversion happens inside the publish job (already async/queued).
- On failure, publisher catches and marks `post_platform.status = failed` with a clear error ("Could not convert image for Instagram: PNG to JPEG conversion failed"). Same path as any other publish failure.
- Original media is never mutated or deleted. Converted derivatives are never mutated either.
## Dependencies
- **`intervention/image` v3.x** (composer install)
- PHP GD or Imagick extension (already required by Laravel's `Illuminate/Http/UploadedFile` image validation — safe assumption)
- No new queue, no config changes
- **New migration:** `media_conversions` table
## Decisions (confirmed with user)
1. **Bluesky iterative resize:** replicate Postiz — shrink 10% per iteration until ≤ 976 KB. Done **in memory at publish time**, not stored on CDN (Bluesky API accepts bytes directly).
2. **Converted file storage:** **replace the original in place** at upload time. No parallel `converted/` directory, no `media_conversions` table, no cleanup job. One file per Media, always JPEG.
3. **GIF policy:** accepted only on X, Bluesky, Mastodon. Frontend validation blocks submit when GIF is attached and a GIF-incompatible platform is selected. No silent first-frame conversion.
## Revised pipeline
**Principle:** upload-time touches **only the format** (pixel-perfect). Dimensions and bytes are preserved for maximum platform flexibility (9:16 Reel, 4:5 carousel, etc.). Per-platform size/dimension constraints are handled at publish time in memory, without mutating the CDN original.
### At upload time (asset controller)
```
1. Receive upload
2. Detect real MIME via finfo
3. If MIME is an image AND format ≠ JPEG AND format ≠ GIF:
a. Load into Intervention\Image (keeps original dimensions + aspect)
b. Encode as JPEG q100 (no quality loss — format conversion only) with SAME dimensions
c. Overwrite the original file at `medias/{uuid}.jpg`
d. Save Media row with mime_type='image/jpeg'
4. GIFs: keep as GIF (for X/Bluesky/Mastodon only). Frontend blocks incompatible platforms.
5. JPEG already: no-op, store as-is.
6. Videos: unchanged v1 (passthrough).
```
### At publish time (minimal — no resize except Bluesky)
All publishers pass the **single CDN URL** stored on the Media row. No temporary variants, no resize-for-Graph-API dance, no cleanup jobs.
| Platform | Handling at publish |
|----------|---------------------|
| Instagram, Facebook, LinkedIn, X, Threads, Pinterest, TikTok Photo, YouTube thumb, Mastodon | Pass `media.url` as-is to the platform API. If the platform rejects for dimensions/size, the error surfaces to the user via `post_platform.error_message`. |
| **Bluesky (only exception)** | Bluesky's API accepts raw bytes (not URL). Before upload, check byte size: if > 976 KB, do Postiz-style iterative 10 %-shrink loop **in memory** — shrinks only dimensions (not quality — keeps q100). Loops until ≤ 976 KB. Then upload bytes. No CDN round-trip, no temp files. |
### Filename preservation
- UUID stays the same (`abc-123...`)
- Only the extension changes when the real format changes (`.png` → `.jpg`, `.webp` → `.jpg`)
- The DB `media.path` updates (`medias/abc-123.png` → `medias/abc-123.jpg`)
- Old file is deleted from CDN after the new one is written
- Frontend's `Media` object is returned with the updated URL so the editor displays the right image
Why the extension must change: some platform APIs check extension in addition to Content-Type. Keeping `.png` on a file with JPEG bytes risks inconsistent behavior.
### Frontend validation additions
Update `useMediaRules.ts` to track per-`content_type` GIF acceptance:
| Content type | Accepts GIF? |
|--------------|--------------|
| `x_post` | ✅ |
| `bluesky_post` | ✅ |
| `mastodon_post` | ✅ |
| everything else | ❌ |
Extend `isMediaValidForContentType()` in `Edit.vue` (and per-platform compliance computeds) to reject when media contains a GIF and the current `content_type` doesn't accept it.
## Updated dependencies
- **`intervention/image` v3.x** (composer install)
- No new migrations
- No new tables
- No cleanup job
## Cells still needing verification (`?` in tables)
- Facebook Post/Story image max dimensions + WebP support
- LinkedIn Post/Carousel WebP support
- TikTok Photo mode max size/dimensions
- Pinterest WebP support + max dimensions
- Threads image max dimensions
- Mastodon instance-dependent limits
These gaps don't block — normalizing to JPEG q90 ≤ 1920×1080 ≤ ~4 MB covers all of them comfortably.
## Cells still needing verification (`?` in tables)
- Facebook Post/Story image max dimensions + WebP support
- LinkedIn Post/Carousel WebP support
- TikTok Photo mode max size/dimensions
- Pinterest WebP support + max dimensions
- Threads image max dimensions
- Mastodon instance-dependent limits
These gaps don't block the design — falling back to "convert to JPEG" covers all of them safely.

View file

@ -1,96 +0,0 @@
# Manual verification checklist — media pipeline
After code changes to upload conversion + publish flow, run these checks in the running app.
## Prerequisites
- `npm run dev` running
- User logged into trypost with:
- At least one Instagram account connected (any flow: standalone or via Facebook)
- At least one Facebook Page connected
- At least one Bluesky account (optional, for the resize test)
## Check 1 — PNG upload converts to JPEG at CDN
1. Create a new post (or open an existing draft) at `/posts/*/edit`
2. Upload a **PNG** file (e.g., screenshot, logo with transparency)
3. Open browser devtools → Network tab → find the POST to `assets/store`
4. In the response, verify:
- `mime_type` = `image/jpeg`
- `path` ends with `.jpg`
- `url` ends with `.jpg`
5. Open the `url` in a new tab — confirms the file is served as JPEG
## Check 2 — Metadata propagates
1. Upload an image → response `meta` object has `width` and `height` (> 0)
2. Upload a video → response `meta` has `width`, `height`, `duration` (> 0)
3. If duration is missing for videos, check devtools console for errors during `readFileMetadata`
## Check 3 — Instagram publishing (the original bug)
1. With the JPEG from Check 1, select Instagram (standalone or via Facebook) as target
2. Pick "Feed Post" variant
3. Click **Post now**
4. Wait ~10–30 seconds for the async job
5. Open the Instagram account in a browser/app — the post should appear
6. Back in trypost, `post_platform.status` should be `published` (not `failed`)
## Check 4 — GIF validation (frontend)
1. Upload a `.gif` file
2. Select **Instagram** or **Facebook** — the card should show a red warning: *"This platform does not accept GIF..."*
3. Try clicking "Post now" → button is **disabled**
4. Deselect Instagram/Facebook, select **X** only → warning disappears, button enabled
5. Click "Post now" → GIF publishes to X (animated)
## Check 5 — Video duration validation
1. Upload a video > 60 seconds (e.g., 2min MP4)
2. Select Instagram → pick **Reel** variant
3. Warning shows: *"Video is 2min long, but this post type allows up to 15min"* (Reel is 15min) — no warning expected here
4. Select **Story** instead → warning: *"Video is 2min long, but this post type allows up to 60s"*
5. Submit button disabled
## Check 6 — File size validation
1. Upload a large image (> 4MB JPEG — use a high-res photo)
2. Select **Facebook Post**
3. Warning appears: *"Image exceeds the 4.0 MB limit (yours is X.X MB)"*
4. Submit disabled
## Check 7 — Aspect ratio validation
1. Upload a **square (1:1) image**
2. Select **Instagram Reel**
3. Warning appears: *"Aspect ratio 1.00 is too wide (max 0.60)"* (Reel requires ~9:16)
4. Submit disabled
## Check 8 — Bluesky iterative resize
1. Upload an image > 976 KB that's ALSO a JPEG (not to trigger PNG conversion)
2. Select Bluesky only
3. Click "Post now"
4. Check `storage/logs/laravel.log` for MediaOptimizer entries — should NOT see quality reduction warnings (only dimension reduction if the limit is still exceeded)
5. Post appears on Bluesky with acceptable quality
## Check 9 — Non-normalized video passthrough
1. Upload a `.mp4` file
2. `media.path` in DB/response still has `.mp4` extension (no conversion attempted)
3. Publish to any platform that accepts video — works via existing flow
## Troubleshooting
- If Check 1 fails (still PNG in CDN):
- Check `vendor/bin/composer require intervention/image` is installed
- Check `storage/logs/laravel.log` for `HasMedia: image normalization failed`
- GD or Imagick extension must be loaded in PHP
- If Check 3 still fails on Instagram:
- Verify the stored image IS JPEG: `curl -I <url>` should return `Content-Type: image/jpeg`
- Check Instagram error code in `post_platform.error_message`; 2207009 = aspect ratio, 2207004 = too large
- If videos don't validate in frontend (no warnings):
- Browser must be able to read video metadata (codec-dependent)
- Check devtools console for `readFileMetadata` resolving empty `{}`

View file

@ -7,7 +7,19 @@ export default defineConfigWithVueTs(
vue.configs['flat/essential'],
vueTsConfigs.recommended,
{
ignores: ['vendor', 'node_modules', 'public', 'bootstrap/ssr', 'tailwind.config.js', 'resources/js/components/ui/*'],
ignores: [
'vendor',
'node_modules',
'public',
'bootstrap/ssr',
'tailwind.config.js',
'resources/js/components/ui/*',
// Wayfinder regenerates these on every build with import order
// matching PHP file scan, not alphabetical. Excluding them avoids
// a perpetual fight between the generator and import/order.
'resources/js/actions/**',
'resources/js/routes/**',
],
},
{
plugins: {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -19,8 +19,6 @@ import { trans } from 'laravel-vue-i18n';
import { computed } from 'vue';
import { create as createPost, index as postsIndex } from '@/actions/App/Http/Controllers/App/PostController';
import { useFeatureAccess } from '@/composables/useFeatureAccess';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import NavMain from '@/components/NavMain.vue';
import NavUser from '@/components/NavUser.vue';
import { Avatar } from '@/components/ui/avatar';
@ -43,6 +41,8 @@ import {
SidebarMenuItem,
useSidebar,
} from '@/components/ui/sidebar';
import { useFeatureAccess } from '@/composables/useFeatureAccess';
import { useUpgradeDialog } from '@/composables/useUpgradeDialog';
import { accounts, analytics, calendar, settings as settingsHub } from '@/routes/app';
import { index as assets } from '@/routes/app/assets';
import { index as labels } from '@/routes/app/labels';

View file

@ -5,7 +5,7 @@ import { computed } from 'vue';
import { Button } from '@/components/ui/button';
import { redirect as googleRedirect } from '@/routes/auth/google';
const props = defineProps<{
defineProps<{
label: string;
}>();

View file

@ -3,7 +3,6 @@ import { Form } from '@inertiajs/vue3';
import { trans } from 'laravel-vue-i18n';
import { ref } from 'vue';
import { WorkspaceRole } from '@/enums/workspace-role';
import InputError from '@/components/InputError.vue';
import { Button } from '@/components/ui/button';
import {
@ -23,6 +22,7 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { WorkspaceRole } from '@/enums/workspace-role';
import { store as storeInvite } from '@/routes/app/invites';
const open = defineModel<boolean>('open', { default: false });

View file

@ -375,10 +375,6 @@ const showEmojiPicker = (commentId: string) => {
emojiPickerCommentId.value = commentId;
};
const hideEmojiPicker = () => {
emojiPickerCommentId.value = null;
};
const handleKeydown = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key === 'Enter') {
event.preventDefault();

View file

@ -17,8 +17,8 @@ import { computed, nextTick, ref } from 'vue';
import ImagePreviewDialog from '@/components/ImagePreviewDialog.vue';
import EmojiPicker from '@/components/posts/EmojiPicker.vue';
import SignaturesModal from '@/components/posts/SignaturesModal.vue';
import MediaPickerDialog from '@/components/posts/MediaPickerDialog.vue';
import SignaturesModal from '@/components/posts/SignaturesModal.vue';
import { Button } from '@/components/ui/button';
import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';

View file

@ -21,12 +21,6 @@ interface SocialAccount {
avatar_url: string | null;
}
interface PublishConfig {
privacyLevelOptions: string[];
musicUsageConfirmationUrl: string;
brandedContentPolicyUrl: string;
}
interface CreatorInfo {
creator_nickname: string | null;
creator_username: string | null;

View file

@ -1,7 +1,7 @@
import { ref, type Ref } from 'vue';
import { store as storeAsset, storeChunked as storeAssetChunked } from '@/routes/app/assets';
import { getMediaRulesForContentType } from '@/composables/useMediaRules';
import { store as storeAsset, storeChunked as storeAssetChunked } from '@/routes/app/assets';
import { uploadChunked, shouldUseChunkedUpload } from '@/utils/chunkedUpload';
export interface MediaItem {

View file

@ -3,10 +3,10 @@ import { useHttp, usePage } from '@inertiajs/vue3';
import { onBeforeUnmount, onMounted } from 'vue';
import AppHeader from '@/components/AppHeader.vue';
import UpgradeDialog from '@/components/UpgradeDialog.vue';
import AppSidebar from '@/components/AppSidebar.vue';
import Toast from '@/components/Toast.vue';
import { SidebarInset, SidebarProvider } from '@/components/ui/sidebar';
import UpgradeDialog from '@/components/UpgradeDialog.vue';
import { heartbeat as heartbeatRoute } from '@/routes/app/presence';
import type { BreadcrumbItem } from '@/types';

View file

@ -20,7 +20,6 @@ import PageHeader from '@/components/PageHeader.vue';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import {
DropdownMenu,
DropdownMenuContent,
@ -28,6 +27,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import {
Table,

View file

@ -21,7 +21,7 @@ interface Plan {
monthly_credits_limit: number;
}
const props = defineProps<{
defineProps<{
plans: Plan[];
trialDays: number;
}>();

View file

@ -10,9 +10,9 @@ import {
import { trans } from 'laravel-vue-i18n';
import { computed, onUnmounted, ref, watch } from 'vue';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
import AiGenerateDialog from '@/components/posts/ai/AiGenerateDialog.vue';
import AiReviewDialog from '@/components/posts/ai/AiReviewDialog.vue';
import ConfirmDeleteModal from '@/components/ConfirmDeleteModal.vue';
import PostEditorComposer from '@/components/posts/editor/PostEditorComposer.vue';
import PostEditorSidebar from '@/components/posts/editor/PostEditorSidebar.vue';
import PickTimePopover from '@/components/posts/PickTimePopover.vue';

View file

@ -3,9 +3,9 @@ import { Form, Head } from '@inertiajs/vue3';
import { trans } from 'laravel-vue-i18n';
import { computed } from 'vue';
import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';
import HeadingSmall from '@/components/HeadingSmall.vue';
import InputError from '@/components/InputError.vue';
import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

View file

@ -10,9 +10,9 @@ import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import AppLayout from '@/layouts/AppLayout.vue';
import { settings as settingsHub } from '@/routes/app';
import { edit as editAuthentication } from '@/routes/app/authentication';
import { preferences as preferencesRoute } from '@/routes/app/notifications';
import { edit as editProfile } from '@/routes/app/profile';
import { edit as editAuthentication } from '@/routes/app/authentication';
import type { BreadcrumbItem } from '@/types';
interface Preferences {

View file

@ -6,8 +6,8 @@ import { computed } from 'vue';
import BrandTab from '@/components/settings/BrandTab.vue';
import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { index as apiKeysRoute } from '@/routes/app/api-keys';
import { members as membersRoute, settings as settingsHub } from '@/routes/app';
import { index as apiKeysRoute } from '@/routes/app/api-keys';
import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';
import type { BreadcrumbItem } from '@/types';

View file

@ -6,8 +6,8 @@ import { computed } from 'vue';
import SettingsTabsNav from '@/components/settings/SettingsTabsNav.vue';
import WorkspaceTab from '@/components/settings/WorkspaceTab.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import { index as apiKeysRoute } from '@/routes/app/api-keys';
import { members as membersRoute, settings as settingsHub } from '@/routes/app';
import { index as apiKeysRoute } from '@/routes/app/api-keys';
import { brand as brandRoute, settings as workspaceSettings } from '@/routes/app/workspace';
import type { BreadcrumbItem } from '@/types';

View file

@ -4,19 +4,26 @@
use App\Http\Controllers\Api\ApiKeyController;
use App\Http\Controllers\Api\LabelController;
use App\Http\Controllers\Api\PlatformController;
use App\Http\Controllers\Api\PostController;
use App\Http\Controllers\Api\SignatureController;
use App\Http\Controllers\Api\SocialAccountController;
use App\Http\Controllers\Api\WorkspaceController;
use Illuminate\Support\Facades\Route;
Route::prefix('api')->middleware(['auth:api', 'workspace.token', 'throttle:api'])->group(function () {
Route::middleware(['auth:api', 'workspace.token', 'throttle:api'])->group(function () {
// Posts
Route::get('/posts', [PostController::class, 'index'])->name('api.posts.index');
Route::post('/posts', [PostController::class, 'store'])->name('api.posts.store');
Route::get('/posts/{post}', [PostController::class, 'show'])->name('api.posts.show');
Route::put('/posts/{post}', [PostController::class, 'update'])->name('api.posts.update');
Route::delete('/posts/{post}', [PostController::class, 'destroy'])->name('api.posts.destroy');
Route::post('/posts/{post}/media', [PostController::class, 'attachMedia'])->name('api.posts.attach-media');
Route::get('/posts/{post}/metrics', [PostController::class, 'metrics'])->name('api.posts.metrics');
Route::get('/posts/{post}/preview', [PostController::class, 'preview'])->name('api.posts.preview');
// Platforms (read-only metadata)
Route::get('/content-types', [PlatformController::class, 'contentTypes'])->name('api.content-types');
// Workspace
Route::get('/workspace', [WorkspaceController::class, 'show'])->name('api.workspace.show');

View file

@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
beforeEach(function () {
$result = createApiTestToken();
$this->user = $result['user'];
$this->workspace = $result['workspace'];
$this->plainToken = $result['plain_token'];
});
it('lists content types per platform', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.content-types'))
->assertOk()
->assertJsonStructure([
'platforms' => [
'*' => [
'platform',
'label',
'max_content_length',
'recommended_content_length',
'allowed_media_types',
'default_content_type',
'content_types' => [
'*' => ['value', 'label', 'description', 'max_media_count', 'requires_media'],
],
],
],
]);
});
it('rejects content-types without auth', function () {
$this->getJson(route('api.content-types'))->assertUnauthorized();
});

View file

@ -9,6 +9,7 @@
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
beforeEach(function () {
$result = createApiTestToken();
@ -74,6 +75,47 @@
expect(Post::where('workspace_id', $this->workspace->id)->count())->toBe(1);
});
it('creates a post with content, media, and labels', function () {
$label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$payload = [
'content' => 'Hello from the API',
'media' => [['id' => 'media-1', 'path' => 'media/foo.jpg', 'url' => 'https://example.com/foo.jpg', 'type' => 'image']],
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
'label_ids' => [$label->id],
];
$response = $this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), $payload)
->assertCreated();
$post = Post::where('workspace_id', $this->workspace->id)->first();
expect($post->content)->toBe('Hello from the API');
expect($post->media)->toHaveCount(1);
expect($post->labels()->pluck('workspace_labels.id')->all())->toContain($label->id);
$response->assertJsonPath('content', 'Hello from the API');
});
it('rejects creating a post with an inactive social account', function () {
$inactive = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
'is_active' => false,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'platforms' => [
['social_account_id' => $inactive->id, 'content_type' => 'linkedin_post'],
],
])
->assertJsonValidationErrors(['platforms.0.social_account_id']);
});
it('deletes a post', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
@ -255,6 +297,131 @@
->assertJsonValidationErrors(['label_ids.0']);
});
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'],
],
])
->assertJsonValidationErrors(['platforms.0.content_type']);
});
it('rejects creating a post when content_type does not match the social account platform', function () {
// 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'],
],
])
->assertJsonValidationErrors(['platforms.0.content_type']);
});
it('rejects creating a post with a label from another workspace', function () {
$otherWorkspace = Workspace::factory()->create();
$foreignLabel = WorkspaceLabel::factory()->create(['workspace_id' => $otherWorkspace->id]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.store'), [
'platforms' => [
['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,
'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'],
],
])
->assertJsonValidationErrors(['platforms.0.content_type']);
});
it('rejects scheduled status without a future scheduled_at', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
'scheduled_at' => now()->subDay(),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'scheduled',
'scheduled_at' => now()->subHour()->toIso8601String(),
])
->assertJsonValidationErrors(['scheduled_at']);
});
it('accepts draft status with no scheduled_at', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->putJson(route('api.posts.update', $post), [
'status' => 'draft',
])
->assertOk();
});
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'],
],
'scheduled_at' => now()->subDay()->toIso8601String(),
])
->assertJsonValidationErrors(['scheduled_at']);
});
it('list posts returns correct structure', function () {
Post::factory()->create([
'workspace_id' => $this->workspace->id,

View file

@ -0,0 +1,149 @@
<?php
declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Models\Media;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
$result = createApiTestToken();
$this->user = $result['user'];
$this->workspace = $result['workspace'];
$this->plainToken = $result['plain_token'];
$this->socialAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
]);
$this->post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
PostPlatform::factory()->linkedin()->create([
'post_id' => $this->post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => true,
]);
Storage::fake();
});
it('attaches media from url', function () {
Http::fake([
'example.com/photo.png' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media', $this->post), [
'urls' => ['https://example.com/photo.png'],
])
->assertOk()
->assertJsonPath('attached_count', 1)
->assertJsonPath('failed_urls', []);
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
expect($this->post->fresh()->media)->toHaveCount(1);
});
it('reports failures for unreachable urls', function () {
Http::fake([
'example.com/missing.png' => Http::response(null, 404),
]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media', $this->post), [
'urls' => ['https://example.com/missing.png'],
])
->assertOk()
->assertJsonPath('attached_count', 0)
->assertJsonPath('failed_urls.0', 'https://example.com/missing.png');
});
it('cannot attach media to a post from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media', $post), [
'urls' => ['https://example.com/photo.png'],
])
->assertNotFound();
});
it('previews per platform with sanitized content and length', function () {
$this->post->update(['content' => str_repeat('a', 500)]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.preview', $this->post))
->assertOk()
->assertJsonStructure([
'post_id',
'original_content',
'original_length',
'platforms' => [
'*' => [
'post_platform_id',
'platform',
'content_type',
'sanitized_content',
'sanitized_length',
'max_content_length',
'truncated',
],
],
])
->assertJsonPath('original_length', 500);
});
it('returns metrics shape including unsupported reason for unpublished platforms', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $this->post))
->assertOk()
->assertJsonStructure([
'post_id',
'platforms' => [
'*' => [
'post_platform_id',
'platform',
'status',
'platform_post_id',
'platform_url',
'metrics',
],
],
])
->assertJsonPath('platforms.0.metrics.unsupported', true)
->assertJsonPath('platforms.0.metrics.reason', 'not_published');
});
it('cannot get metrics from another workspace post', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.metrics', $post))
->assertNotFound();
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->getJson(route('api.posts.preview', $post))
->assertNotFound();
});
it('rejects attach media payload without urls', function () {
$this->withHeaders(['Authorization' => 'Bearer '.$this->plainToken])
->postJson(route('api.posts.attach-media', $this->post), [])
->assertUnprocessable()
->assertJsonValidationErrors(['urls']);
});

View file

@ -165,15 +165,18 @@
});
test('chunked upload completes with single chunk', function () {
$content = str_repeat('x', 1000);
// Use real PNG bytes so mime_content_type detects image/png. The MIME
// is sniffed from content magic bytes, not the X-File-Name header.
$content = file_get_contents(__DIR__.'/../fixtures/1x1.png');
$size = strlen($content);
$response = $this->actingAs($this->user)->call(
'POST',
route('app.assets.store-chunked'),
[], [], [],
[
'HTTP_CONTENT_RANGE' => 'bytes 0-999/1000',
'HTTP_X_FILE_NAME' => 'test-video.mp4',
'HTTP_CONTENT_RANGE' => 'bytes 0-'.($size - 1).'/'.$size,
'HTTP_X_FILE_NAME' => 'test.png',
'HTTP_ACCEPT' => 'application/json',
'CONTENT_TYPE' => 'application/octet-stream',
],
@ -236,7 +239,9 @@
'data',
);
$response->assertStatus(400);
// FormRequest validation surfaces parse failures as 422
// (range_start / range_end / total_size all required).
$response->assertUnprocessable();
});
test('chunked upload rejects unauthenticated', function () {

View file

@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
use App\Enums\UserWorkspace\Role;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\AttachMediaFromUrlTool;
use App\Models\Media;
use App\Models\Post;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
Storage::fake();
});
test('attaches an image from url and creates a media row', function () {
Http::fake([
'example.com/photo.jpg' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
]);
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => ['https://example.com/photo.jpg'],
]);
$response->assertOk();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
expect($this->post->fresh()->media)->toHaveCount(1);
});
test('rejects url that returns non-image content type', function () {
Http::fake([
'example.org/payload' => Http::response('not an image', 200, ['Content-Type' => 'text/html']),
]);
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => ['https://example.org/payload'],
]);
$response->assertOk();
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(0);
expect($this->post->fresh()->media)->toHaveCount(0);
});
test('reports failures and successes separately', function () {
Http::fake([
'example.com/ok.png' => Http::response(
file_get_contents(__DIR__.'/../../fixtures/1x1.png'),
200,
['Content-Type' => 'image/png'],
),
'example.com/missing.png' => Http::response(null, 404),
]);
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => [
'https://example.com/ok.png',
'https://example.com/missing.png',
],
]);
$response->assertOk()
->assertSee(['example.com/missing.png']);
expect(Media::where('mediable_id', $this->workspace->id)->count())->toBe(1);
expect($this->post->fresh()->media)->toHaveCount(1);
});
test('post 404 from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $post->id,
'urls' => ['https://example.com/photo.jpg'],
]);
$response->assertHasErrors(['Post not found.']);
});
test('rejects urls with non-http(s) schemes', function () {
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => ['ftp://example.com/photo.jpg'],
]);
$response->assertHasErrors();
expect($this->post->fresh()->media)->toBeEmpty();
});
test('rejects malformed url strings', function () {
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => ['not-a-url-at-all'],
]);
$response->assertHasErrors();
});
test('rejects more than 10 urls per call', function () {
$urls = collect(range(1, 11))->map(fn ($i) => "https://example.com/photo-{$i}.jpg")->all();
$response = TryPostServer::actingAs($this->user)
->tool(AttachMediaFromUrlTool::class, [
'post_id' => $this->post->id,
'urls' => $urls,
]);
$response->assertHasErrors();
});

View file

@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
use App\Enums\UserWorkspace\Role;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Platform\ListContentTypesTool;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Testing\Fluent\AssertableJson;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
});
test('list content types returns all platforms with constraints', function () {
$response = TryPostServer::actingAs($this->user)
->tool(ListContentTypesTool::class, []);
$response->assertOk()
->assertStructuredContent(function (AssertableJson $json) {
$json->has('platforms', fn (AssertableJson $platforms) => $platforms
->each(fn (AssertableJson $p) => $p
->hasAll([
'platform',
'label',
'max_content_length',
'recommended_content_length',
'allowed_media_types',
'default_content_type',
'content_types',
])
)
);
});
});
test('list content types includes content types per platform', function () {
$response = TryPostServer::actingAs($this->user)
->tool(ListContentTypesTool::class, []);
$response->assertOk()
->assertSee(['linkedin', 'linkedin_post', 'x_post', 'instagram_feed', 'mastodon_post']);
});

View file

@ -0,0 +1,258 @@
<?php
declare(strict_types=1);
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Enums\UserWorkspace\Role;
use App\Jobs\PublishPost;
use App\Mcp\Servers\TryPostServer;
use App\Mcp\Tools\Post\PublishPostTool;
use App\Mcp\Tools\Post\UpdatePostTool;
use App\Models\Post;
use App\Models\PostPlatform;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use Illuminate\Support\Facades\Queue;
use Illuminate\Testing\Fluent\AssertableJson;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->socialAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
]);
});
// UpdatePostTool
test('update post can change content', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'content' => 'old',
]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $post->id,
'content' => 'new content',
]);
$response->assertOk()
->assertStructuredContent(function (AssertableJson $json) {
$json->where('content', 'new content')->etc();
});
expect($post->fresh()->content)->toBe('new content');
});
test('update post enables platforms', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
$platform = PostPlatform::factory()->linkedin()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => false,
]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $post->id,
'platforms' => [
['id' => $platform->id, 'content_type' => ContentType::LinkedInPost->value],
],
]);
$response->assertOk();
expect($platform->fresh()->enabled)->toBeTrue();
});
test('update post can attach labels', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]);
$label = WorkspaceLabel::factory()->create(['workspace_id' => $this->workspace->id]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $post->id,
'label_ids' => [$label->id],
]);
$response->assertOk();
expect($post->fresh()->labels()->pluck('id')->all())->toBe([$label->id]);
});
test('update post 404 from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, ['post_id' => $post->id, 'content' => 'x']);
$response->assertHasErrors(['Post not found.']);
});
test('update post rejects already-published post', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Published,
]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, ['post_id' => $post->id, 'content' => 'x']);
$response->assertHasErrors(['Cannot edit a published post.']);
});
test('update post rejects 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,
]);
$response = TryPostServer::actingAs($this->user)
->tool(UpdatePostTool::class, [
'post_id' => $myPost->id,
'platforms' => [
['id' => $foreignPlatform->id, 'content_type' => ContentType::LinkedInPost->value],
],
]);
$response->assertHasErrors();
});
test('update post rejects a content_type that does not match the post_platform', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'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'],
],
]);
$response->assertHasErrors();
});
// PublishPostTool
test('publish post immediate dispatches PublishPost job', function () {
Queue::fake();
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
PostPlatform::factory()->linkedin()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => true,
]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
$response->assertOk();
Queue::assertPushed(PublishPost::class);
expect($post->fresh()->status)->toBe(PostStatus::Publishing);
// 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);
});
test('publish post scheduled does not dispatch immediately', function () {
Queue::fake();
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
PostPlatform::factory()->linkedin()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => true,
]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, [
'post_id' => $post->id,
'scheduled_at' => '2099-12-31T15:30:00Z',
]);
$response->assertOk();
Queue::assertNotPushed(PublishPost::class);
expect($post->fresh()->status)->toBe(PostStatus::Scheduled);
});
test('publish post fails when no platforms enabled', function () {
$post = Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
'status' => PostStatus::Draft,
]);
PostPlatform::factory()->linkedin()->create([
'post_id' => $post->id,
'social_account_id' => $this->socialAccount->id,
'enabled' => false,
]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
$response->assertHasErrors(['Post has no enabled platforms. Use update-post-tool to enable at least one platform first.']);
});
test('publish post 404 from another workspace', function () {
$other = Workspace::factory()->create();
$post = Post::factory()->create(['workspace_id' => $other->id, 'user_id' => $this->user->id]);
$response = TryPostServer::actingAs($this->user)
->tool(PublishPostTool::class, ['post_id' => $post->id]);
$response->assertHasErrors(['Post not found.']);
});

View file

@ -13,6 +13,7 @@
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use Illuminate\Testing\Fluent\AssertableJson;
beforeEach(function () {
@ -95,20 +96,38 @@
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'My new post',
'date' => '2026-04-15',
'scheduled_at' => '2099-12-31T15:30:00Z',
]);
$response->assertOk()
->assertStructuredContent(function (AssertableJson $json) {
$json->where('content', 'My new post')
->where('status', 'draft')
->where('scheduled_at', '2026-04-15 09:00:00')
->where('scheduled_at', '2099-12-31 15:30:00')
->etc();
});
expect(Post::where('workspace_id', $this->workspace->id)->count())->toBe(1);
});
test('create post with platforms enables only those', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'content' => 'with platforms',
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
]);
$response->assertOk();
$post = Post::where('workspace_id', $this->workspace->id)->first();
$enabled = $post->postPlatforms()->where('enabled', true)->get();
expect($enabled)->toHaveCount(1);
expect($enabled->first()->social_account_id)->toBe($this->socialAccount->id);
expect($enabled->first()->content_type->value)->toBe('linkedin_post');
});
test('create post without args creates empty draft for today', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, []);
@ -123,9 +142,64 @@
expect(Post::where('workspace_id', $this->workspace->id)->count())->toBe(1);
});
test('create post rejects invalid date format', function () {
test('create post rejects scheduled_at in the past', function () {
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, ['date' => 'not-a-date']);
->tool(CreatePostTool::class, ['scheduled_at' => '2020-01-01T00:00:00Z']);
$response->assertHasErrors();
});
test('create post rejects an inactive social account', function () {
$inactive = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
'platform' => Platform::LinkedIn,
'is_active' => false,
]);
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'platforms' => [
['social_account_id' => $inactive->id, 'content_type' => 'linkedin_post'],
],
]);
$response->assertHasErrors();
});
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'],
],
]);
$response->assertHasErrors();
});
test('create post rejects a content_type that does not match the social account platform', function () {
// 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'],
],
]);
$response->assertHasErrors();
});
test('create post rejects a label_id from another workspace', function () {
$otherWorkspace = Workspace::factory()->create();
$foreignLabel = WorkspaceLabel::factory()->create(['workspace_id' => $otherWorkspace->id]);
$response = TryPostServer::actingAs($this->user)
->tool(CreatePostTool::class, [
'platforms' => [
['social_account_id' => $this->socialAccount->id, 'content_type' => 'linkedin_post'],
],
'label_ids' => [$foreignLabel->id],
]);
$response->assertHasErrors();
});

View file

@ -7,23 +7,36 @@
test('media type has correct values', function () {
expect(Type::Image->value)->toBe('image');
expect(Type::Video->value)->toBe('video');
expect(Type::Document->value)->toBe('document');
});
test('media type has labels', function () {
expect(Type::Image->label())->toBe('Imagem');
expect(Type::Video->label())->toBe('Vídeo');
expect(Type::Document->label())->toBe('Documento');
});
test('media type has allowed mime types', function () {
expect(Type::Image->allowedMimeTypes())->toContain('image/jpeg', 'image/png');
expect(Type::Video->allowedMimeTypes())->toContain('video/mp4', 'video/quicktime');
expect(Type::Document->allowedMimeTypes())->toContain('application/pdf');
});
test('media type has max size in mb', function () {
test('media type max size in mb is read from config', function () {
config(['trypost.media.max_size_mb.image' => 10]);
config(['trypost.media.max_size_mb.video' => 1024]);
expect(Type::Image->maxSizeInMb())->toBe(10);
expect(Type::Video->maxSizeInMb())->toBe(2048);
expect(Type::Document->maxSizeInMb())->toBe(100);
expect(Type::Video->maxSizeInMb())->toBe(1024);
});
test('media type exposes derived size units', function () {
config(['trypost.media.max_size_mb.video' => 1024]);
expect(Type::Video->maxSizeInKb())->toBe(1024 * 1024);
expect(Type::Video->maxSizeInBytes())->toBe(1024 * 1024 * 1024);
});
test('media type resolves from mime', function () {
expect(Type::fromMime('image/jpeg'))->toBe(Type::Image);
expect(Type::fromMime('video/mp4'))->toBe(Type::Video);
expect(Type::fromMime('application/pdf'))->toBeNull();
expect(Type::fromMime('not-a-mime'))->toBeNull();
});

View file

@ -35,7 +35,7 @@
});
test('platform has correct allowed media types', function () {
expect(Platform::LinkedIn->allowedMediaTypes())->toContain(MediaType::Image, MediaType::Video, MediaType::Document);
expect(Platform::LinkedIn->allowedMediaTypes())->toContain(MediaType::Image, MediaType::Video);
expect(Platform::X->allowedMediaTypes())->toContain(MediaType::Image, MediaType::Video);
expect(Platform::TikTok->allowedMediaTypes())->toBe([MediaType::Video]);
expect(Platform::YouTube->allowedMediaTypes())->toBe([MediaType::Video]);

View file

@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
use App\Models\Workspace;
/**
* Regression test for a bug where Media rows ended up with
* `mediable_type = "App\Models\Workspace"` (FQCN) instead of the
* morphMap alias `"workspace"`. The bug source was code that did
* `$media->mediable_type = Workspace::class;`
* which bypasses the morph map. Using the relationship
* (`$workspace->media()->create([...])` or
* `$media->mediable()->associate($workspace)`) is the correct path.
*/
test('Workspace::media()->create persists the morphMap alias, not the FQCN', function () {
$workspace = Workspace::factory()->create();
$media = $workspace->media()->create([
'collection' => 'ai-generated',
'type' => 'image',
'path' => 'test/dummy.webp',
'original_filename' => 'dummy.webp',
'mime_type' => 'image/webp',
'size' => 100,
'order' => 0,
]);
expect($media->mediable_type)->toBe('workspace');
expect($media->mediable_type)->not->toBe(Workspace::class);
expect($media->mediable->is($workspace))->toBeTrue();
});

View file

@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
use App\Enums\PostPlatform\ContentType;
use App\Enums\SocialAccount\Platform;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Rules\ContentTypeMatchesPlatform;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
function runMatchesPlatformRule(string $contentType, ?string $accountId, array $extraData = []): array
{
$errors = [];
$rule = (new ContentTypeMatchesPlatform)->setData(array_merge([
'platforms' => [
['social_account_id' => $accountId, 'content_type' => $contentType],
],
], $extraData));
$rule->validate('platforms.0.content_type', $contentType, function (string $message) use (&$errors): void {
$errors[] = $message;
});
return $errors;
}
test('passes when content_type matches the social account platform', function () {
$workspace = Workspace::factory()->create();
$linkedin = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::LinkedIn,
]);
expect(runMatchesPlatformRule(ContentType::LinkedInPost->value, $linkedin->id))->toBe([]);
expect(runMatchesPlatformRule(ContentType::LinkedInCarousel->value, $linkedin->id))->toBe([]);
});
test('fails when content_type belongs to a different platform', function () {
$workspace = Workspace::factory()->create();
$linkedin = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::LinkedIn,
]);
$errors = runMatchesPlatformRule(ContentType::XPost->value, $linkedin->id);
expect($errors)->toHaveCount(1);
expect($errors[0])->toContain('not compatible');
});
test('passes when an instagram content_type is paired with an instagram-facebook account', function () {
$workspace = Workspace::factory()->create();
$igFacebook = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::InstagramFacebook,
]);
// instagram_feed lists Instagram as its primary platform but is also
// compatible with InstagramFacebook accounts via compatiblePlatforms().
expect(runMatchesPlatformRule(ContentType::InstagramFeed->value, $igFacebook->id))->toBe([]);
expect(runMatchesPlatformRule(ContentType::InstagramReel->value, $igFacebook->id))->toBe([]);
});
test('skips validation when social_account_id is missing', function () {
expect(runMatchesPlatformRule(ContentType::XPost->value, null))->toBe([]);
});
test('skips validation when content_type is not a known enum value', function () {
$workspace = Workspace::factory()->create();
$linkedin = SocialAccount::factory()->create([
'workspace_id' => $workspace->id,
'platform' => Platform::LinkedIn,
]);
// Unknown content_types are caught by Rule::in elsewhere; this rule
// intentionally no-ops so it doesn't double-report.
expect(runMatchesPlatformRule('completely_made_up', $linkedin->id))->toBe([]);
});

View file

@ -0,0 +1,75 @@
<?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([]);
expect(runMatchesPostPlatformRule(ContentType::LinkedInCarousel->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([]);
});

View file

@ -107,12 +107,12 @@
$workspace = Workspace::factory()->create();
$tempFile = tempnam(sys_get_temp_dir(), 'test');
file_put_contents($tempFile, 'fake image content');
file_put_contents($tempFile, file_get_contents(__DIR__.'/../../fixtures/1x1.png'));
$media = $workspace->addMediaFromPath($tempFile, 'uploaded.jpg', 'logo');
$media = $workspace->addMediaFromPath($tempFile, 'uploaded.png', 'logo');
expect($media)->toBeInstanceOf(Media::class);
expect($media->original_filename)->toBe('uploaded.jpg');
expect($media->original_filename)->toBe('uploaded.png');
Storage::assertExists($media->path);
unlink($tempFile);
@ -166,13 +166,12 @@
expect($media->type->value)->toBe('video');
});
test('add media detects document type', function () {
test('add media throws on unsupported MIME type', function () {
$workspace = Workspace::factory()->create();
$file = UploadedFile::fake()->create('document.pdf', 1000, 'application/pdf');
$media = $workspace->addMedia($file, 'logo');
expect($media->type->value)->toBe('document');
expect(fn () => $workspace->addMedia($file, 'logo'))
->toThrow(InvalidArgumentException::class);
});
test('add media includes custom meta', function () {