trypost/app/Http/Controllers/App/WorkspaceController.php

249 lines
7.6 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace App\Http\Controllers\App;
use App\Actions\Ai\AutofillBrand;
use App\Actions\Workspace\CreateWorkspace;
use App\Actions\Workspace\DeleteWorkspace;
use App\Enums\Workspace\BrandFont;
use App\Http\Requests\App\Workspace\StoreWorkspaceRequest;
use App\Http\Requests\App\Workspace\UpdateWorkspaceRequest;
feat: @mentions in comments, AI Action layer + MCP tools, settings tabs Mentions in post comments - @mention autocomplete (workspace members, current user excluded) with marker syntax @[uuid] persisted, display names rendered via CommentBody chips; live edit replaces markers with names and converts back on save. - NotifyMentions action with workspace-scoped membership check, dedupes same user, only newly-added mentions on update. - Email + in-app via SendNotification job, respecting per-user notification_preferences.mentioned_in_comment. - Heartbeat-based presence (Cache, 60s TTL, 30s ping) so online recipients get only the in-app notification — no email noise. - Real-time bell on workspace.{id}.user.{id} private channel (NotificationCreated event), scoped channel name avoids client-side filtering and lays out a convention for future workspace channels. - Mailable localized via lang/{en,es,pt-BR}/mail.php; Maizzle source template for the email is committed and built into resources/views/mail. AI generation refactor (Action layer + MCP) - Extracted Actions/Ai/Generate{Image,Video} with QuotaExhaustedException so agent tools and MCP tools share a single domain entry point. - Mcp/Tools/Ai/Generate{Image,Video}Tool registered in TryPostServer; both return MediaResource payloads. - Orientation::imageApiSize maps non-OpenAI ratios to 1:1/2:3/3:2. - config/ai.php is now the single source of truth driven by env, removing the trypost.ai shim. Default text/image providers flipped to OpenAI. Settings/UX - /settings/workspace split into shadcn Tabs (Workspace / Brand / Users) with three components. - /assets and the in-editor MediaPicker open the ImagePreviewDialog lightbox on image click while preserving action button behaviour. - Comments tab landed via ?tab=comments&comment=<id> from notification click (scroll-to + temporary highlight). - Mention autocomplete popover flips above when near the viewport bottom. - Real social platform PNGs replace Tabler brand glyphs in schedule pills and post list, with hover tooltip carrying display_name + handle. Bug fixes - AcceptInvite: controller now passes workspace + role payload that the Vue page expects; login/register CTAs preselect the invite email. - WorkspaceInvite mailable: stopped referencing nonexistent $invite->workspace and $invite->role; column added to the migration, Invite model casts role to WorkspaceRole, CreateInvite persists it. - PostCommentCreated: added broadcastAs so .PostCommentCreated actually matches the Echo listener; payload now includes mentioned_users so receivers render the chip correctly without a refetch. - Preview components for X/Pinterest/Threads/Bluesky/LinkedIn/Mastodon/ TikTok/YouTube switched from item.type === 'image' to !isVideoMedia(item) so media without a persisted type still renders. - UpdatePostRequest now accepts media.*.{type,mime_type,size,...} so the posts.media JSON keeps the metadata that the previews need. - Removed throttle:6,1 from social connect routes (was 429ing legitimate OAuth retries). - Used MediaType enum cases instead of literal 'image'/'video' strings when creating media rows. Tests - MentionParser unit tests, NotifyMentions feature tests including online/offline channel selection and preference gating, MCP AI tool happy paths, MentionedInComment mailable rendering, AcceptInvite + search-members + index mentioned_users path. 1229 passing.
2026-05-01 23:59:03 +00:00
use App\Http\Resources\App\WorkspaceMemberResource;
use App\Models\Account;
use App\Models\Workspace;
use App\Services\Brand\LogoAttacher;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
feat: @mentions in comments, AI Action layer + MCP tools, settings tabs Mentions in post comments - @mention autocomplete (workspace members, current user excluded) with marker syntax @[uuid] persisted, display names rendered via CommentBody chips; live edit replaces markers with names and converts back on save. - NotifyMentions action with workspace-scoped membership check, dedupes same user, only newly-added mentions on update. - Email + in-app via SendNotification job, respecting per-user notification_preferences.mentioned_in_comment. - Heartbeat-based presence (Cache, 60s TTL, 30s ping) so online recipients get only the in-app notification — no email noise. - Real-time bell on workspace.{id}.user.{id} private channel (NotificationCreated event), scoped channel name avoids client-side filtering and lays out a convention for future workspace channels. - Mailable localized via lang/{en,es,pt-BR}/mail.php; Maizzle source template for the email is committed and built into resources/views/mail. AI generation refactor (Action layer + MCP) - Extracted Actions/Ai/Generate{Image,Video} with QuotaExhaustedException so agent tools and MCP tools share a single domain entry point. - Mcp/Tools/Ai/Generate{Image,Video}Tool registered in TryPostServer; both return MediaResource payloads. - Orientation::imageApiSize maps non-OpenAI ratios to 1:1/2:3/3:2. - config/ai.php is now the single source of truth driven by env, removing the trypost.ai shim. Default text/image providers flipped to OpenAI. Settings/UX - /settings/workspace split into shadcn Tabs (Workspace / Brand / Users) with three components. - /assets and the in-editor MediaPicker open the ImagePreviewDialog lightbox on image click while preserving action button behaviour. - Comments tab landed via ?tab=comments&comment=<id> from notification click (scroll-to + temporary highlight). - Mention autocomplete popover flips above when near the viewport bottom. - Real social platform PNGs replace Tabler brand glyphs in schedule pills and post list, with hover tooltip carrying display_name + handle. Bug fixes - AcceptInvite: controller now passes workspace + role payload that the Vue page expects; login/register CTAs preselect the invite email. - WorkspaceInvite mailable: stopped referencing nonexistent $invite->workspace and $invite->role; column added to the migration, Invite model casts role to WorkspaceRole, CreateInvite persists it. - PostCommentCreated: added broadcastAs so .PostCommentCreated actually matches the Echo listener; payload now includes mentioned_users so receivers render the chip correctly without a refetch. - Preview components for X/Pinterest/Threads/Bluesky/LinkedIn/Mastodon/ TikTok/YouTube switched from item.type === 'image' to !isVideoMedia(item) so media without a persisted type still renders. - UpdatePostRequest now accepts media.*.{type,mime_type,size,...} so the posts.media JSON keeps the metadata that the previews need. - Removed throttle:6,1 from social connect routes (was 429ing legitimate OAuth retries). - Used MediaType enum cases instead of literal 'image'/'video' strings when creating media rows. Tests - MentionParser unit tests, NotifyMentions feature tests including online/offline channel selection and preference gating, MCP AI tool happy paths, MentionedInComment mailable rendering, AcceptInvite + search-members + index mentioned_users path. 1229 passing.
2026-05-01 23:59:03 +00:00
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Log;
use Inertia\Inertia;
use Inertia\Response;
use RuntimeException;
use Symfony\Component\HttpFoundation\Response as SymfonyResponse;
use Throwable;
class WorkspaceController extends Controller
{
feat: @mentions in comments, AI Action layer + MCP tools, settings tabs Mentions in post comments - @mention autocomplete (workspace members, current user excluded) with marker syntax @[uuid] persisted, display names rendered via CommentBody chips; live edit replaces markers with names and converts back on save. - NotifyMentions action with workspace-scoped membership check, dedupes same user, only newly-added mentions on update. - Email + in-app via SendNotification job, respecting per-user notification_preferences.mentioned_in_comment. - Heartbeat-based presence (Cache, 60s TTL, 30s ping) so online recipients get only the in-app notification — no email noise. - Real-time bell on workspace.{id}.user.{id} private channel (NotificationCreated event), scoped channel name avoids client-side filtering and lays out a convention for future workspace channels. - Mailable localized via lang/{en,es,pt-BR}/mail.php; Maizzle source template for the email is committed and built into resources/views/mail. AI generation refactor (Action layer + MCP) - Extracted Actions/Ai/Generate{Image,Video} with QuotaExhaustedException so agent tools and MCP tools share a single domain entry point. - Mcp/Tools/Ai/Generate{Image,Video}Tool registered in TryPostServer; both return MediaResource payloads. - Orientation::imageApiSize maps non-OpenAI ratios to 1:1/2:3/3:2. - config/ai.php is now the single source of truth driven by env, removing the trypost.ai shim. Default text/image providers flipped to OpenAI. Settings/UX - /settings/workspace split into shadcn Tabs (Workspace / Brand / Users) with three components. - /assets and the in-editor MediaPicker open the ImagePreviewDialog lightbox on image click while preserving action button behaviour. - Comments tab landed via ?tab=comments&comment=<id> from notification click (scroll-to + temporary highlight). - Mention autocomplete popover flips above when near the viewport bottom. - Real social platform PNGs replace Tabler brand glyphs in schedule pills and post list, with hover tooltip carrying display_name + handle. Bug fixes - AcceptInvite: controller now passes workspace + role payload that the Vue page expects; login/register CTAs preselect the invite email. - WorkspaceInvite mailable: stopped referencing nonexistent $invite->workspace and $invite->role; column added to the migration, Invite model casts role to WorkspaceRole, CreateInvite persists it. - PostCommentCreated: added broadcastAs so .PostCommentCreated actually matches the Echo listener; payload now includes mentioned_users so receivers render the chip correctly without a refetch. - Preview components for X/Pinterest/Threads/Bluesky/LinkedIn/Mastodon/ TikTok/YouTube switched from item.type === 'image' to !isVideoMedia(item) so media without a persisted type still renders. - UpdatePostRequest now accepts media.*.{type,mime_type,size,...} so the posts.media JSON keeps the metadata that the previews need. - Removed throttle:6,1 from social connect routes (was 429ing legitimate OAuth retries). - Used MediaType enum cases instead of literal 'image'/'video' strings when creating media rows. Tests - MentionParser unit tests, NotifyMentions feature tests including online/offline channel selection and preference gating, MCP AI tool happy paths, MentionedInComment mailable rendering, AcceptInvite + search-members + index mentioned_users path. 1229 passing.
2026-05-01 23:59:03 +00:00
public function searchMembers(Request $request): AnonymousResourceCollection
{
$workspace = $request->user()->currentWorkspace;
abort_if(! $workspace, SymfonyResponse::HTTP_FORBIDDEN);
$this->authorize('view', $workspace);
$term = trim((string) $request->input('q', ''));
$members = $workspace->members()
->where('users.id', '!=', $request->user()->id)
->when($term !== '', fn ($query) => $query->where('users.name', 'ilike', '%'.$term.'%'))
->orderBy('users.name')
->limit(50)
->get(['users.id', 'users.name', 'users.email']);
return WorkspaceMemberResource::collection($members);
}
public function index(Request $request): Response
{
$user = $request->user();
$workspaces = $user->workspaces()
refactor: auth split layout, subscribe redesign, onboarding, i18n, cookie locale Auth pages: - Create AuthSplitLayout with animated feature slides (6 slides, 3 languages) - All auth pages use split layout (form left, visual right) - Add show/hide password toggle with tooltip on Register - Legal footer only shown on Register via showLegal prop Subscribe page: - Redesign to match auth card pattern (centered, clean) - Platform icons, feature checklist, dynamic trial days (trialDays - 1) - Add "Switch workspace" link - Full i18n (en, es, pt-BR) Onboarding: - Rename URLs: step1 -> role, step2 -> connect - Add enforceStep() to prevent skipping/going back steps - Redirect /onboarding to /onboarding/role - Redesign Step2 with AuthSplitLayout and compact platform list - 21 tests covering all step enforcement scenarios Workspaces page: - Redesign with AuthSplitLayout (list with avatars, current badge) Language system: - Move locale from DB to cookie (forever, unencrypted, session.domain) - Create SetLocale middleware (sets cookie if missing, validates against config) - Rename lang/pt-br to lang/pt-BR - Add dayjs es locale Other: - Copy utils.ts from sendkit (formatNumber, formatMoney, copyToClipboard) - ConfirmDeleteModal with text confirmation (sendkit pattern) - i18n for ConfirmDeleteModal internal strings (common.php) - EmptyState component for posts index - Exact match for "All" posts in sidebar - Posts breadcrumbs show current status filter - DialogFooter buttons aligned left - API Keys page redesign with Table, DropdownMenu, EmptyState - Extract CreateApiKeyDialog and InviteMemberDialog to components - Remove API Keys from sidebar - DropdownMenuItem destructive variant for Remove action
2026-03-30 14:53:42 +00:00
->with('media')
->withCount(['socialAccounts', 'posts'])
->latest()
->get();
return Inertia::render('workspaces/Index', [
'workspaces' => $workspaces,
'currentWorkspaceId' => $user->current_workspace_id,
]);
}
public function create(Request $request): Response|RedirectResponse
{
$user = $request->user();
if ($user->ownedWorkspacesCount() > 0 && ! $user->account?->hasActiveSubscription()) {
return redirect()->route('app.billing.index')
->with('message', 'Subscribe to create more workspaces.');
}
if ($this->hasReachedWorkspaceLimit($user->account)) {
return back()->with('flash.error', __('workspaces.limit_reached'));
}
return Inertia::render('workspaces/Create');
}
public function autofillBrand(Request $request, AutofillBrand $autofill): JsonResponse
{
$validated = $request->validate([
'url' => ['required', 'string', 'max:255'],
]);
try {
$metadata = $autofill(data_get($validated, 'url'));
} catch (RuntimeException $e) {
return response()->json(['message' => $e->getMessage()], SymfonyResponse::HTTP_UNPROCESSABLE_ENTITY);
}
return response()->json($metadata->toArray());
}
public function store(StoreWorkspaceRequest $request, LogoAttacher $logoAttacher): RedirectResponse
{
$user = $request->user();
if ($this->hasReachedWorkspaceLimit($user->account)) {
abort(SymfonyResponse::HTTP_FORBIDDEN, __('workspaces.limit_reached'));
}
$validated = $request->validated();
$isFirstWorkspace = ! $user->workspaces()->exists();
$workspace = CreateWorkspace::execute($user, $validated);
if ($logoUrl = data_get($validated, 'logo_url')) {
try {
$logoAttacher->attach($workspace, $logoUrl);
} catch (Throwable $e) {
Log::warning('Logo attach failed during workspace creation', [
'workspace_id' => $workspace->id,
'logo_url' => $logoUrl,
'error' => $e->getMessage(),
]);
}
}
return $isFirstWorkspace
? redirect()->route('app.accounts')->with('success', __('workspaces.create.first_workspace_success'))
: redirect()->route('app.calendar')->with('success', __('workspaces.create.success'));
}
public function switch(Request $request, Workspace $workspace): RedirectResponse
{
$user = $request->user();
if (! $user->belongsToWorkspace($workspace)) {
abort(403);
}
$user->switchWorkspace($workspace);
return redirect()->route('app.calendar');
}
public function settings(Request $request): Response|RedirectResponse
{
$user = $request->user();
$workspace = $user->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
$this->authorize('update', $workspace);
return Inertia::render('settings/workspace/Workspace', [
'workspace' => $workspace,
]);
}
public function brandSettings(Request $request): Response|RedirectResponse
{
$user = $request->user();
$workspace = $user->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
$this->authorize('update', $workspace);
return Inertia::render('settings/workspace/Brand', [
'workspace' => $workspace,
'availableFonts' => BrandFont::values(),
]);
}
public function uploadLogo(Request $request): RedirectResponse
{
$workspace = $request->user()->currentWorkspace;
$this->authorize('update', $workspace);
$request->validate([
'photo' => ['required', 'image', 'max:2048'],
]);
$workspace->clearMediaCollection('logo');
$workspace->addMedia($request->file('photo'), 'logo');
$workspace->unsetRelation('media');
return back()->with('flash.success', __('settings.flash.logo_updated'));
}
public function deleteLogo(Request $request): RedirectResponse
{
$workspace = $request->user()->currentWorkspace;
$this->authorize('update', $workspace);
$workspace->clearMediaCollection('logo');
$workspace->unsetRelation('media');
return back()->with('flash.success', __('settings.flash.logo_deleted'));
}
public function updateSettings(UpdateWorkspaceRequest $request): RedirectResponse
{
$user = $request->user();
$workspace = $user->currentWorkspace;
if (! $workspace) {
return redirect()->route('app.workspaces.create');
}
$this->authorize('update', $workspace);
$workspace->update($request->validated());
return back()->with('flash.success', __('settings.flash.workspace_updated'));
}
public function destroy(Request $request, Workspace $workspace): RedirectResponse
{
$this->authorize('delete', $workspace);
$user = $request->user();
DeleteWorkspace::execute($user, $workspace);
return redirect()->route('app.workspaces.index')
->with('flash.success', __('workspaces.flash.deleted'));
}
/**
* Check whether the account has hit its plan's workspace limit.
* Returns false in self-hosted mode (no plan limits apply).
*/
private function hasReachedWorkspaceLimit(?Account $account): bool
{
if (config('trypost.self_hosted')) {
return false;
}
if (! $account) {
return false;
}
$limit = (int) ($account->plan?->workspace_limit ?? 1);
return $account->workspaces()->count() >= $limit;
}
}