Compare commits

..

5 Commits

234 changed files with 3306 additions and 13958 deletions

View File

@ -125,17 +125,6 @@ OPENAI_API_KEY=""
# OAuth client configured for the ChatGPT app. Only this client can receive
# verified user email claims for ChatGPT Enterprise domain restrictions.
OPENAI_OAUTH_CLIENT_ID=""
# Client id of the OAuth app (Settings > Developers) that HubSpot agents
# connect with. HubSpot sends no client secret, so this one app uses PKCE
# instead, gets a refresh token, and the MCP backend answers OAuth discovery
# at its domain root. Set it on both the API and the MCP backend.
# HUBSPOT_OAUTH_CLIENT_ID=""
# Client id and secret of the HubSpot app itself (HubSpot project > app >
# Auth tab), not of the Postiz app above. Its redirect URL is
# <NEXT_PUBLIC_BACKEND_URL>/oauth/hubspot/callback, which finishes the install
# (HubSpot only counts it once the code is exchanged). Set them on the API.
# HUBSPOT_APP_CLIENT_ID=""
# HUBSPOT_APP_CLIENT_SECRET=""
# MCP OAuth Dynamic Client Registration (RFC 7591) redirect-domain allowlist.
# When set (comma separated), POST /oauth/register only accepts redirect_uris
# whose host matches a listed domain or one of its subdomains; unset or empty

4
.gitignore vendored
View File

@ -62,3 +62,7 @@ i18n.cache
# Generated by apps/frontend/scripts/fetch-gtm.mjs on install
apps/frontend/public/g.js
# Codex
.codex
AGENTS.md

View File

@ -1,138 +0,0 @@
# Postiz Architecture — 2026-10-23
Scope note: this doc covers competitive-positioning-adjacent technical architecture, user-action data flow, risks, and a next-build list. Pages/APIs/feature backlog is covered by `PLAN-2026-10-23-DEEP.md` if/when that file exists — it did not exist at the time this was written, so nothing here duplicates it.
## 0. Ground truth on this repo (read, not assumed)
- Fork: `caelum0x/postiz-app` (origin), tracking `gitroomhq/postiz-app` (upstream). AGPL-3.0.
- Monorepo, pnpm workspaces, 5 apps + shared libraries:
- `apps/backend` — NestJS REST API (port 3000), also boots the Mastra MCP server and Temporal worker in-process (`apps/backend/src/main.ts`).
- `apps/orchestrator` — NestJS + Temporal worker: all background workflows/activities (posting, autopost, clipping, video, email, token refresh).
- `apps/frontend` — **Next.js 16** app (App Router), not Vite as `CLAUDE.md` currently states — confirmed by `next.config.js`, `instrumentation.ts`, `sentry.server.config.ts`, and root `package.json` (`"next": "16.3.1"`).
- `apps/sdk` — thin TypeScript client hard-coded to `https://api.postiz.com` (Postiz Cloud), used for the published npm SDK.
- `apps/commands` — CLI entry (`main.ts` + `tasks/`: `refresh.tokens`, `agent.run`, `configuration`).
- `apps/extension` — Chrome extension (manifest-style background script) that extracts auth cookies from logged-in social sites for providers that need cookie-based auth, allow-listed to `localhost` and `*.postiz.com` origins only.
- `libraries/nestjs-libraries` — shared backend code: Prisma database layer, 35+ `integrations/social/*.provider.ts` (one per channel), `chat/` (Mastra-based AI agent + MCP server + MCP OAuth relay), `deepgram/`, `videos/`, `short-linking/`, `services/payment/` (Stripe).
- Database: **PostgreSQL** via **Prisma** (schema at `libraries/nestjs-libraries/src/database/prisma/schema.prisma`, 91 models). Includes the app's own domain tables (Organization, User, Integration, Post, Media, Subscription, Webhooks, Clipping, ...) plus `mastra_*` tables — the AI agent/MCP framework (Mastra) persists its own state (threads, messages, MCP server/client registrations, workflows) directly in the same Postgres instance (`libraries/nestjs-libraries/src/chat/mastra.store.ts`).
- Queue/orchestration: **Temporal** (`@temporalio/*`, `nestjs-temporal-core`), with its own Postgres + Elasticsearch stack in `docker-compose.yaml` (`temporal-postgresql`, `temporal-elasticsearch`, `temporal`, `temporal-ui`). This replaced a simpler queue — there is no BullMQ in the current flow.
- Cache: **Redis** (`ioredis`), falls back to an in-memory `MockRedis` if `REDIS_URL` is unset (`libraries/nestjs-libraries/src/redis/redis.service.ts`). Used for rate-limiting (`ThrottlerBehindProxyGuard`) and caching, not as the job queue.
- Storage: pluggable — local disk, Cloudflare R2, or S3-compatible (`STORAGE_PROVIDER` env var; `@aws-sdk/client-s3` + `UPLOAD_DIRECTORY`).
- AI stack: LangGraph (`@langchain/langgraph`, `@langchain/openai`, `@langchain/tavily`) for the content-generation agent graph (`libraries/nestjs-libraries/src/agent`), and **Mastra** (`@mastra/core`, `@mastra/mcp`, `@mastra/pg`) for the chat/tool-calling layer that backs both the in-app chat UI and the external MCP server (`/mcp`, `/mcp/:id`, `/sse/:id` routes, started from `start.mcp.ts`).
- Payments: Stripe (`services/payment/`), webhook-driven subscription sync.
- Public API: `apps/backend/src/public-api` — `/public/v1/*` routes, API-key authenticated, rate-limited distinctly from session routes. This is what the published SDK and MCP server call into.
## 1. Deployment reality (do not assume Oracle hosting applies here)
- There is **no live Postiz deployment** on any of the three portfolio boxes right now (confirmed in this repo's own `NOTES.md`: not running on `railyard-box`, `box` 130.61.180.42 currently refuses SSH, `recoder-micro` rejects the shared deploy key). This product has zero live users today — it exists only as code + a `docker-compose.yaml` for local/self-hosted use.
- Self-hosting is the only supported open-source deployment path: `docker-compose.yaml` ships `postiz` (backend+frontend combined container, port 4007), `postiz-postgres`, `postiz-redis`, the full Temporal stack (`temporal`, `temporal-postgresql`, `temporal-elasticsearch`, `temporal-ui`), and optional `spotlight` (Sentry-compatible local error capture). `railway.toml` and the README's deploy table (Docker / Coolify / Railway / any VPS) confirm self-host, not a managed Cloudflare/Oracle target.
- **Postiz Cloud** (`postiz.com`, what `apps/sdk` talks to) is a separately-hosted commercial SaaS *not present in this repo* — it is the thing this OSS edition is positioned against/alongside, not something deployed from here.
- Net: the correct hosting target for this product, if the owner wants it live, is a self-hosted Docker Compose stack on one of the Oracle boxes (recommended: `box` once SSH is restored, given it's the general-purpose box) — not Cloudflare Workers/Pages (no edge-compatible target exists here; Temporal workers and a Postgres-backed Nest app don't fit the Workers runtime model).
## 2. System diagram (real components only)
```mermaid
flowchart TB
subgraph Clients
WebUI["Frontend\nNext.js 16 (App Router)"]
Ext["Chrome Extension\n(cookie capture for\ncookie-auth providers)"]
CLI["apps/commands CLI\n(agent.run, refresh.tokens)"]
MCPClient["External MCP client\n(Claude/ChatGPT/agent, via SDK or MCP)"]
end
subgraph Backend["apps/backend (NestJS, port 3000)"]
API["/api, /posts, /integrations\n(session-authed)"]
PublicAPI["/public/v1/*\n(API-key authed)"]
MCPServer["Mastra MCPServer\n/mcp, /mcp/:id, /sse/:id"]
Chat["Chat/Agent module\n(LangGraph + Mastra tools)"]
end
subgraph Orchestrator["apps/orchestrator (Temporal worker)"]
Workflows["Workflows:\npostWorkflowV1.x, autopost,\nclipping, generate.video,\nrefresh.token, digest.email"]
Activities["Activities:\npost.activity, clipping.activity,\nmedia.activity, integrations.activity"]
end
subgraph Data["Data & infra"]
PG[("PostgreSQL\n(Prisma: app tables +\nmastra_* AI-agent tables)")]
Redis[("Redis\n(cache + rate-limit;\nin-memory fallback)")]
Temporal[("Temporal server\n+ its own Postgres + ES")]
Storage[("Object storage\nlocal disk / S3 / R2")]
end
subgraph ThirdParty["Third-party services"]
Social["28+ social platform APIs\n(X, LinkedIn, Facebook,\nInstagram, TikTok, ...)"]
OpenAI["OpenAI (text + DALL-E)"]
Tavily["Tavily (web search)"]
Deepgram["Deepgram (transcription)"]
Stripe["Stripe (billing)"]
end
WebUI -->|session cookie| API
Ext -->|extracted cookies, postiz.com only| API
CLI --> API
MCPClient -->|API key / OAuth relay| MCPServer
MCPServer --> Chat
Chat --> OpenAI
Chat --> Tavily
Chat --> PG
API --> PG
API --> Redis
API -->|start workflow| Temporal
PublicAPI --> API
PublicAPI --> Temporal
Temporal --> Workflows
Workflows --> Activities
Activities --> PG
Activities --> Social
Activities --> Deepgram
Activities --> Storage
Activities --> OpenAI
API --> Stripe
Stripe -->|webhook| API
```
## 3. Data-flow for the 2-3 most important user actions
### A. Schedule and publish a post (core product loop)
1. User composes a post in the Next.js frontend; frontend calls `POST /posts` (or the public `/public/v1/posts` if driven via SDK/MCP/CLI) with content + target integrations + send time.
2. `PostsController.createPost` (DTO-validated) calls `PostsService.createPost`, which writes `Post` + per-channel settings rows via Prisma to Postgres (one write, no raw SQL per project convention).
3. `PostsService.startWorkflow` first lists/terminates any existing running Temporal workflow for that `postId` (idempotency guard), then starts `postWorkflowV1.1.3` (versioned — workflow code is never mutated in place; new behavior ships as a new version, see CLAUDE.md rule) on Temporal's `main` task queue, tagged with `postId`/`organizationId` search attributes.
4. Temporal dispatches the workflow to the `apps/orchestrator` worker process. The workflow sleeps until the scheduled time, re-checks post state (to catch a cancel/edit during the sleep), then calls `post.activity` → the relevant `integrations/social/*.provider.ts` implementation, which calls the real platform API (X, LinkedIn, etc.) using stored OAuth tokens.
5. Activity result (success/failure, remote post id) is written back to the `Post`/`Integration` rows in Postgres; failures retry per-activity with backoff (non-retryable reasons — e.g. revoked token — short-circuit).
6. Frontend polls/SWR-refetches post status from Postgres via the backend API.
### B. AI chat / MCP-driven content generation (agent surface)
1. A request arrives either via the in-app chat UI (session-authed, hits `Chat` module) or an external MCP client (Claude Desktop, ChatGPT app, or any MCP-compatible agent) calling the Mastra `MCPServer` at `/mcp` (or `/mcp/:id` for a specific self-hosted-instance relay, or `/sse/:id` for SSE transport), authenticated via an API key or the `/mcp-oauth*` OAuth relay (`mcp.relay.service.ts`, `oauth-middleware.ts`) for multi-tenant/self-hosted setups.
2. Mastra resolves the caller's org/auth context (`auth.context.ts`, `async.storage.ts`) and exposes a fixed toolset (`chat/tools/*.tool.ts`: list integrations, generate image, upload from URL, delete post, check video status, trigger integration, etc.) plus the LangGraph agent for free-text generation (web search via Tavily, image gen via OpenAI DALL-E).
3. Tool calls that mutate state (e.g. create/delete a post, trigger an integration) go through the same `PostsService`/`IntegrationService` Prisma-backed code path as the UI — no separate write path — landing in the same Postgres tables.
4. Mastra persists its own conversation/thread/tool-call state in the `mastra_*` Postgres tables (same database, separate tables) so a chat session survives a backend restart.
5. Any action that needs background work (video generation, clipping) hands off to Temporal exactly like path A, rather than blocking the MCP response.
### C. Long-video-to-clips pipeline (Deepgram clipping — the feature with no direct competitor equivalent per the strategy doc)
1. User submits a source video URL/upload; `ClippingService.submitAnalyse` creates a `Clipping` record and calls the `clipping.workflow` on Temporal.
2. Workflow step 1 (`submitClippingAnalyse`/`checkClippingAnalyse`): analysis job submitted to an external job runner and polled (bounded retries, each poll idempotent).
3. Workflow step 2 (`transcribeClipping`): Deepgram transcribes the audio (`deepgram.service.ts`).
4. Workflow step 3 (`pickClippingClips`): an AI call (OpenAI, via the same agent infra) scores the transcript and picks clip boundaries; result written to `ClippingClip` rows.
5. Workflow step 4, per clip: `submitClipFetch`/`checkClipFetch` then `submitClipRender`/`checkClipRender` — fetch the source segment and render the final clip (burned-in captions via `captionClip`), stored to the configured object storage backend.
6. `createClippingDrafts` turns finished clips into draft `Post` rows so the user schedules/publishes them through the normal path A loop — the clipping pipeline is a *producer* of posts, not a separate publishing path.
7. Failure handling is deliberately asymmetric: submission steps tolerate at-least-once (a duplicate job just costs a second render), AI/transcription steps are cheap to retry, and only the final terminal failure (`failClipping`) surfaces to the user.
## 4. Real architectural risks / bottlenecks at current scale (zero live users, zero budget)
- **Not deployed anywhere — the biggest risk is literally "it doesn't run."** All competitive positioning in `STRATEGY-2026-10-23.md` is moot until a live instance exists for a self-hoster to even evaluate, let alone for the growth moves (comparison pages, clipping landing page) to point at a working demo/signup.
- **Three stateful backing services for one app** (Postiz's own Postgres, Temporal's own Postgres, Temporal's own Elasticsearch) plus Redis — a fourth Postgres-class dependency (Elasticsearch) purely so Temporal UI can do visibility search. On a zero-budget single small VPS/Oracle box this is a meaningful memory/CPU footprint (ES alone typically wants 512MB+ heap, already reflected in the compose file's `ES_JAVA_OPTS=-Xms256m -Xmx256m` ceiling) for a product with no users yet. Worth evaluating whether Temporal's SQL-only visibility (no ES) is enough at this scale, dropping the ES container entirely.
- **Single shared Postgres for app data and AI-agent (Mastra) state.** Convenient operationally (one DB to back up), but couples chat/agent load (threads, tool-call logs, MCP registrations) to core posting-data performance and backup size as usage grows — no isolation today.
- **OAuth app setup is the activation cliff**, confirmed by the strategy doc's own top growth move: every self-hoster must register their own developer app per social platform (Meta/TikTok/YouTube approval can take weeks per the README's own comparison table). This is a product-structural bottleneck, not a hosting one — a feature gap, not infra.
- **Self-host-only in practice right now**: no managed hosting exists for this fork (Postiz Cloud at postiz.com is a different, separately-run codebase/infra this repo doesn't touch), so every prospective user must run Docker Compose with 7+ containers themselves — a steep floor for the "technical solo marketer" persona the strategy doc targets, some of whom are not comfortable operating Temporal/Elasticsearch.
- **Cookie-based extension auth is inherently fragile**: providers relying on the Chrome extension's cookie capture (vs. OAuth) break whenever the target platform changes its cookie names/session model, and only work for users running the extension on a logged-in browser — not something a CI/server environment can do.
- **Versioned-workflow discipline is a real but easy-to-violate constraint**: the `post.workflow.v1.x.ts` ladder (14 versions already) means every behavior change to the publish flow adds a new file rather than editing in place — correct for Temporal determinism, but it is pure accretion with no visible deprecation/cleanup path for old versions once no running executions reference them.
## 5. Prioritized next-build list (effort vs. impact)
1. **Get one instance live on an Oracle box (box, once SSH access is restored) — lowest effort, highest impact.** `docker-compose.yaml` already defines the full stack; this is an infra/ops task (bring up containers, point a subdomain at port 4007, set real env vars), not a code change. Nothing else on this list, or in the strategy doc's growth moves, matters while zero instances are reachable.
2. **Guided OAuth-app pre-registration wizard** (strategy doc's own #1 growth move, and this doc's #1 architectural risk). Medium effort: extend the existing `apps/commands` CLI/`configuration.ts` task with a step-by-step per-provider wizard (pre-filled redirect URIs, direct links to each platform's developer console, validation against `missing-env-vars.standalone.spec.ts`'s existing checks) rather than a hosted-credentials fallback, which would require Postiz to hold shared app secrets — a bigger trust/ops commitment for a zero-budget operation.
3. **Drop or make-optional the Elasticsearch dependency in `docker-compose.yaml`** for the self-host default path. Low effort (Temporal supports SQL-only visibility), direct reliability/resource win for the exact persona (small VPS, zero budget) this product targets — makes self-hosting materially lighter before pushing anyone to try it.
4. **Standalone landing page for the Deepgram clipping pipeline** (strategy doc's #3 growth move) — this is a content/marketing build, not an architecture change, but it depends on #1 (a live instance to demo/sign up through) and is the one feature with zero named-competitor equivalent, so it is the highest-leverage SEO/positioning asset once something is live.
5. **Add a lightweight cleanup/documentation pass over the `post-workflows` version ladder** — low urgency, but before adding a 15th version, worth confirming (via Temporal's visibility query) which old versions have zero running executions and can be safely archived, so the versioning discipline doesn't silently become unbounded technical debt.

View File

@ -1,130 +0,0 @@
# Build Log — 2026-10-23
## Round 1
### 1. Webhook delivery reliability (backlog item #6) — finished + fixed
Picked up an in-progress, uncommitted implementation and finished it to a working, verified state.
- `WebhookDelivery` Prisma model (additive migration): `webhookId`, `event`, `postId`, `url`, `requestBody`, `statusCode`, `success`, `attempts`, `error`, `durationMs`, indexed on `webhookId` and `(webhookId, createdAt)`.
- `Webhooks.secret` column (nullable, additive) — a per-webhook HMAC-SHA256 signing secret generated on create, exposed to the UI exactly once (at creation or regeneration), never again on list/read.
- `WebhooksService.sendWithRetry` — signs the payload (`X-Postiz-Signature: sha256=...`), retries up to 3 attempts with exponential backoff (500ms × 3^n) on 5xx/429/408, treats other 4xx as terminal, and always persists a `WebhookDelivery` row (success or failure) with status code, attempt count, error, and duration.
- `apps/orchestrator/src/activities/post.activity.ts`'s `sendWebhooks` now calls `sendWithRetry` instead of a raw unsigned `fetch` + silent catch.
- New endpoints on `webhooks.controller.ts`: `POST /webhooks/:id/secret` (regenerate), `GET /webhooks/:id/deliveries` (paginated log), `POST /webhooks/deliveries/:deliveryId/redeliver`. `/webhooks/send` (manual test-send) now also signs, dispatches through the existing SSRF-safe dispatcher, and returns a real status instead of swallowing errors.
- Frontend: `apps/frontend/src/components/webhooks/webhook.deliveries.tsx` (new) — paginated delivery log modal with status, attempts, error, and a redeliver action. `webhooks.tsx` wires a "Logs" column into the webhook list and a secret-reveal modal on create/regenerate.
- **Fix applied this round**: the "Regenerate secret" button existed as dead code (handler defined, never rendered) — wired it into the edit form, visible only when editing an existing webhook.
- Verified: `apps/backend`, `apps/orchestrator`, and `apps/frontend` all build clean (`nest build` / `next build`) with the new Prisma client generated.
### 2. Competitor comparison landing pages (backlog item #4) — built new, full depth
Built all 7 pages named in STRATEGY-2026-10-23.md section 5, as real statically-rendered routes with zero API/DB dependency, each sourced from the live `pricing.ts` config and the strategy doc's researched competitor numbers (not invented):
- `/compare/buffer`, `/compare/hootsuite`, `/compare/later`, `/compare/socialbee`, `/compare/metricool`, `/compare/publer`, `/compare/mixpost`
- New public, unauthenticated route group `apps/frontend/src/app/(app)/(compare)/` (mirrors the existing `(preview)` pattern — doesn't use the auth-gated `(site)` shell).
- `apps/frontend/src/components/compare/compare.data.ts` — per-competitor content: headline, pricing comparison rows, the 4-box structural-moat checklist from STRATEGY.md section 2, a feature checklist, a verdict paragraph, and FAQ entries (for SEO rich snippets).
- `apps/frontend/src/components/compare/compare.page.component.tsx` — shared presentational layout (hero, structural checklist table, pricing table, feature checklist, verdict, FAQ, CTA), using the app's existing `new*` color tokens, glyph check/cross icons (no emoji), and `/auth` as the signup CTA.
- 7 thin `page.tsx` files, each with per-page `<title>`/description/canonical metadata.
- **Critical fix applied this round**: `apps/frontend/src/proxy.ts` (the app's auth gatekeeper middleware) redirected every anonymous visitor to `/auth` by default — which would have made all 7 new pages return a 307 redirect for the exact audience (anonymous searchers) they exist to convert. Added `/compare/` to the existing public-path allowlist alongside `/p/`, `/provider/`, `/uploads/`.
- Verified live: built the frontend in production mode, ran `next start`, and curled all 7 routes — all return `200` with the correct per-competitor `<title>` and rendered content (confirmed before and after the proxy fix, showing the before-state 307 and after-state 200).
### 3. Pre-existing broken production build — fixed (not in the numbered backlog, but blocking everything)
`apps/backend` failed to compile on `HEAD` (commit `ba6d7f87`, already merged to main before this session) — `MastodonCustomProvider.generateAuthUrl` had a signature (`refresh?: string, external?: ClientInformation`) that didn't match the `IAuthenticator` interface (`clientInformation?: ClientInformation`) and called `generateUrlDynamic` with 5 arguments against a 4-argument signature. Fixed to match the interface and the only real call site (`integrations.controller.ts`'s `generateAuthUrl(getExternalUrl)`). Confirmed `apps/backend` now builds clean.
## Files changed this round
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — `WebhookDelivery` model, `Webhooks.secret`
- `libraries/nestjs-libraries/src/database/prisma/webhooks/webhooks.repository.ts`, `webhooks.service.ts`
- `libraries/nestjs-libraries/src/dtos/webhooks/webhooks.dto.ts`
- `apps/backend/src/api/routes/webhooks.controller.ts`
- `apps/orchestrator/src/activities/post.activity.ts`
- `apps/frontend/src/components/webhooks/webhooks.tsx`, `webhook.deliveries.tsx` (new)
- `apps/frontend/src/proxy.ts`
- `apps/frontend/src/components/compare/compare.data.ts` (new), `compare.page.component.tsx` (new)
- `apps/frontend/src/app/(app)/(compare)/layout.tsx` (new) + 7 `compare/<slug>/page.tsx` (new)
- `libraries/nestjs-libraries/src/integrations/social/mastodon.custom.provider.ts` (build fix)
## Remaining backlog (not started this round)
2 (unified inbox), 3 (internal approval workflow), 5 (agency PDF/CSV reports), 7 (competitor tracking), 8 (auto first-comment), 9 (content recycling), 10 (local short-link provider — noted below), 11 (white-label preview domain), 12 (public API bulk + webhook event filters), 13 (comment @mentions/assignment), and item #1 (OAuth onboarding wizard).
Note on #10 (local short-link provider): `ShortLinkService` currently selects its provider via a module-load-time static singleton (`new Dub()` / `new Kutt()` / etc., no DI), so a DB-backed "local" provider needs that singleton refactored to an injectable service first — flagged for a later round rather than bolted on against the grain of the existing pattern.
## Owner-only blockers
None hit this round — no payment, 2FA, or console-only step was required for any of the above.
## Round 2
### 1. Public API bulk endpoints + webhook event filters (backlog item #12) — finished + verified
Picked up an in-progress, uncommitted implementation (schema, DTOs, controller, webhook send-path filtering, and the frontend event checkboxes already existed) and verified it end to end rather than re-building it:
- `POST /public/v1/posts/bulk` (up to 25 posts/call) and `DELETE /public/v1/posts/bulk` (up to 50 ids/call) on `public.integrations.controller.ts`, both sharing the exact single-post create/delete pipeline per item so a bad entry never aborts the batch.
- `Webhooks.events String[]` (additive, empty = every event, same backward-compatible default as the rest of this feature) — `post.activity.ts`'s `sendWebhooks`/the new `changeState` failure path only deliver to webhooks subscribed to that event (or subscribed to none, meaning all).
- No code changes needed; confirmed by building `apps/backend`/`apps/orchestrator`/`apps/frontend` clean.
### 2. Comment @mentions and assignment (backlog item #13) — finished, was previously just schema + DTOs with no wiring
The schema (`Comments.mentionedUserIds`/`assignedToId`, `Notifications.userId`) and some repository/DTO scaffolding already existed uncommitted, but nothing called any of it — `createPublicComment` silently dropped `mentions`/`assignedToId` even if a client sent them, and there was no team-member list or assignment endpoint anywhere.
- `PostsService.createPublicComment` now resolves `mentions`/`assignedToId` against `OrganizationService.getTeamMembersForMentions` and rejects anyone not on the team — but only when the comment is from an authenticated team member (`userId` set); the public no-auth preview link can never set either field, even if a crafted request body includes them (checked server-side, not just via DTO validation).
- New `PostsService.assignComment` (+ `PUT /posts/comments/:commentId/assign`) to change/clear a root comment's assignee after the fact, same org/root-only restrictions as the existing `resolveComment`.
- New `GET /posts/comments/team-members` (any authenticated org member, not gated behind the admin-only `/settings/team`) backs the mention/assign pickers.
- `NotificationService.notifyUser` (new, wraps the already-existing `createUserNotification` repository method) sends a best-effort, per-user in-app notification on a mention or a new assignment.
- **Data-exposure fix applied this round**: `PostsService.getComments` is shared by the fully public preview GET (`PublicController`) and now also a new authenticated GET (`PostsController`, `GET /posts/:id/comments`) — mentioned-user names/ids and the assignee's name are only included when the caller is verified as a logged-in member of the org that owns the post (`includeInternal` gate), so an external client on the public preview link never sees internal team members' names. The frontend (`preview.comments.context.tsx`) now fetches from the authenticated route when logged into the owning org, the public route otherwise — same branching `CommentComposer` already used for posting.
- Frontend: mention checkboxes + an "Assign to" select in the comment composer (root comments only for assignment), an assignee reassign `<select>` and a `cc:` line of mentioned names on each thread card, all in `apps/frontend/src/components/preview/comments.components.tsx` / `preview.comments.context.tsx`.
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`, including `/p/[id]`) all build clean.
### 3. Evergreen content recycling (backlog item #9) — built new, full depth
This was the biggest gap found this round: `/compare/socialbee` (shipped round 1) already **claims** "Postiz supports a recycle-after-days, category-based queue rotation for evergreen content" — but the feature didn't exist beyond an unused `EvergreenRecycle` Prisma model and a `RECYCLE` enum value some earlier session had added and never wired up. Built it for real so that comparison-page claim is true:
- `EvergreenRepository`/`EvergreenService` (new, mirrors the existing `PostEngagementRepository`/`Service` pattern) — create/list/pause/resume/remove a recycle schedule for an already-published post, plus a bounded (`BATCH_CAP = 25`) `runDueBatch()` that clones a due post's content/media/settings into a brand-new `Post` row (own id/group/Comments thread, `CreationMethod.RECYCLE`) through the exact same `validatePosts` → `mapTypeToPost` → `createPost` pipeline every other post-creation path uses — not a new, parallel content-writing path. A failed entry is pushed one interval out instead of retried immediately, and a recycle schedule whose original post was deleted deactivates itself instead of erroring forever.
- New daily Temporal workflow `evergreenRecycleWorkflow` (`apps/orchestrator/src/workflows/evergreen.recycle.workflow.ts` + `evergreen.activity.ts`), modeled on the existing `bestTimeToPostWorkflow` infinite-loop pattern, registered in `app.module.ts` / `workflows/index.ts` / `infinite.workflow.register.ts`.
- `POST|GET /posts/:id/evergreen` and `PUT|DELETE /posts/evergreen/:recycleId` on `posts.controller.ts`; only an already-`PUBLISHED` post can get a recycle schedule.
- Frontend: a new "Evergreen Recycling" calendar action (recycle-glyph icon, shown only on published posts) opening `evergreen.modal.tsx` — lists existing schedules with pause/resume/remove, and a form to add one (interval days + optional max recycles).
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`) all build clean with the already-generated Prisma client (schema/client were already in place from the earlier session; no schema change needed this round).
## Files changed this round (Round 2)
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts`, `posts.repository.ts` — comment mentions/assignment wiring, `getComments` internal-field gate
- `apps/backend/src/api/routes/posts.controller.ts` — authenticated comments GET, comment-assign PUT, team-members GET, evergreen CRUD routes
- `libraries/nestjs-libraries/src/database/prisma/notifications/notification.service.ts` — `notifyUser`
- `libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts`, `organization.service.ts` — already had `getTeamMembersForMentions` from the earlier session, now actually called
- `apps/frontend/src/components/preview/comments.components.tsx`, `preview.comments.context.tsx` — mention/assign UI, authed-vs-public comments fetch
- `libraries/nestjs-libraries/src/database/prisma/evergreen/evergreen.repository.ts` (new), `evergreen.service.ts` (new)
- `libraries/nestjs-libraries/src/dtos/posts/evergreen.recycle.dto.ts` (new)
- `apps/orchestrator/src/activities/evergreen.activity.ts` (new), `workflows/evergreen.recycle.workflow.ts` (new), `workflows/index.ts`, `app.module.ts`
- `libraries/nestjs-libraries/src/temporal/infinite.workflow.register.ts`
- `libraries/nestjs-libraries/src/database/prisma/database.module.ts`
- `apps/frontend/src/components/launches/calendar.tsx`, `evergreen.modal.tsx` (new)
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma`, `apps/backend/src/public-api/routes/v1/public.integrations.controller.ts`, `apps/frontend/src/components/webhooks/webhooks.tsx`, `apps/orchestrator/src/activities/post.activity.ts`, `libraries/nestjs-libraries/src/dtos/posts/bulk.posts.dto.ts`, `libraries/nestjs-libraries/src/dtos/webhooks/webhooks.dto.ts`, `libraries/nestjs-libraries/src/database/prisma/webhooks/webhooks.repository.ts` — pre-existing uncommitted work from an earlier session (backlog item #12), verified working this round, no changes needed
## Remaining backlog (not started)
2 (unified inbox), 3 (internal approval workflow — note: `Organization.requireApprovalForQueue`/`Post.pendingApproval` schema fields already exist uncommitted from an earlier session but are completely unwired, same as evergreen was; next target), 5 (agency PDF/CSV reports, note: `pdfkit` is already added to `package.json` from an earlier session but unused), 7 (competitor tracking), 8 (auto first-comment), 10 (local short-link provider), 11 (white-label preview domain), and item #1 (OAuth onboarding wizard).
## Owner-only blockers (Round 2)
None hit this round.
## Round 3
### 1. Internal approval workflow (backlog item #3) — built new, full depth
`Organization.requireApprovalForQueue` and `Post.pendingApproval` existed in the schema from an earlier session but had zero wiring (same shape of gap evergreen recycling and comment mentions were in before prior rounds). Wired it end to end:
- `Post.createdByUserId` (new, additive, nullable) + `User.createdPosts` back-relation — stamped on create from the WEB dashboard only, so an approver knows (and can be notified) who submitted a pending post. Every other creation path (API/MCP/autopost/bulk CSV/evergreen/clipping) never sets it, unaffected.
- `OrganizationRepository`/`OrganizationService`: `getApprovalForQueueSetting`/`updateApprovalForQueueSetting`/`requiresApprovalForQueue`. New `GET|POST /settings/approval-queue` (POST is ADMIN-gated), same shape as the existing shortlink-preference endpoints.
- `PostsService.createPost` now takes an optional `createdBy: { userId, role }` (WEB controller only). When the caller's role is `USER`, the save type is schedule/now, and the org has the setting on, the post is held as `DRAFT` with `pendingApproval: true` instead of going to `QUEUE` — `PostsRepository.createOrUpdatePost` grew the `createdByUserId`/`pendingApproval` params to do this at the DB layer. `PostsRepository.changeState` now always clears `pendingApproval`, since every path that calls it is an intentional final transition.
- `PostsService.approvePendingQueuePost`/`rejectPendingQueuePost` (+ `PUT /posts/:id/approve-queue`, `PUT /posts/:id/reject-queue`, ADMIN-gated) — approve reuses `changePostStatus` (the same path the internal "schedule" button and the public-preview `approvePublicPost` already use, so the real publish workflow actually starts); reject just clears the flag and leaves it a normal, editable draft. Both notify the original submitter via the existing `NotificationService.notifyUser`.
- `PostsService.getPendingApprovalPosts` + `GET /posts/pending-approval` (ADMIN-gated, declared before the generic `/:id` GET to avoid Nest route-matching ambiguity).
- Frontend: a yellow clock badge + inline Approve/Check and Reject/X glyph icons (no emoji) on the calendar card itself when `state === 'DRAFT' && post.pendingApproval`, visible only to ADMIN/SUPERADMIN viewers; a "Pending approval:" label replaces "Draft:" on the card. New `apps/frontend/src/components/settings/approval-queue-preference.component.tsx` (the toggle) and `pending-approvals.component.tsx` (the list with Approve/Reject buttons), both rendered in `teams.component.tsx` only for ADMIN+ roles. `manage.modal.tsx`'s save flow shows a distinct "Submitted for approval" toast instead of "Added/updated successfully" when the response indicates it.
- Verified: `apps/backend`, `apps/orchestrator` (`nest build`) and `apps/frontend` (full production `next build`, including route generation) all build clean with the newly generated Prisma client (`prisma validate` + `prisma generate` both clean).
## Files changed this round (Round 3)
- `libraries/nestjs-libraries/src/database/prisma/schema.prisma` — `Post.createdByUserId`, `User.createdPosts`
- `libraries/nestjs-libraries/src/database/prisma/organizations/organization.repository.ts`, `organization.service.ts` — approval-for-queue setting
- `libraries/nestjs-libraries/src/dtos/settings/approval-for-queue.dto.ts` (new)
- `apps/backend/src/api/routes/settings.controller.ts` — `GET|POST /settings/approval-queue`
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts` — `createOrUpdatePost`/`changeState` pendingApproval wiring, `getPendingApprovalPosts`, select additions
- `libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts` — `createPost` gating, `approvePendingQueuePost`/`rejectPendingQueuePost`/`getPendingApprovalPosts`
- `apps/backend/src/api/routes/posts.controller.ts` — caller role on `createPost`, `GET /posts/pending-approval`, `PUT /posts/:id/approve-queue`, `PUT /posts/:id/reject-queue`
- `libraries/helpers/src/utils/posts.list.minify.ts` — `pendingApproval` key mapping
- `apps/frontend/src/components/launches/calendar.tsx` — badge, approve/reject actions and icons, pending-approval label
- `apps/frontend/src/components/new-launch/manage.modal.tsx` — "submitted for approval" toast
- `apps/frontend/src/components/settings/approval-queue-preference.component.tsx` (new), `pending-approvals.component.tsx` (new), `teams.component.tsx` — settings UI
## Remaining backlog (not started, Round 3)
2 (unified inbox), 5 (agency PDF/CSV reports — `pdfkit` still unused in `package.json`), 7 (competitor tracking), 8 (auto first-comment), 10 (local short-link provider), 11 (white-label preview domain), item #1 (OAuth onboarding wizard).
## Owner-only blockers (Round 3)
None hit this round. The pre-existing "no reachable live Postiz deployment" blocker (NOTES.md) was not re-checked this round since it wasn't this round's scope.

View File

@ -1,3 +0,0 @@
# Notes (owner-only blockers)
- No live Postiz deployment found on any reachable box (not running on `railyard-box`; `box` 130.61.180.42 refuses SSH on port 22 right now, `recoder-micro` 92.5.156.133 rejects the shared deploy key) — owner needs to either confirm there's no live Postiz instance yet, or restore access/point me at the right host to deploy `origin/main` (caelum0x/postiz-app) to.

View File

@ -1,117 +0,0 @@
# Postiz — Deep Build Plan (2026-10-23)
Internal build spec. Terse. Ground truth only (verified against source at this commit). No stubs described as done.
## Conventions
- Auth: `session` = cookie session guard (`AuthService`/org context). `apikey` = `/public/v1/*` API-key guard. `none` = unauthenticated.
- UI controls: icon/glyph buttons only, no emoji, no bare-word action buttons (e.g. a send action = arrow glyph, a confirm = check glyph, a close = × glyph).
## 1. Pages (apps/frontend/src/app)
| Route | Purpose | Key UI elements |
|---|---|---|
| `(site)/launches` | Calendar + composer, main workspace | Month/week/list view toggle (icon group), per-day post chips, "+" new-post button (icon), platform picker (icon grid from `pick.platform.component.tsx`), composer modal (`manage.modal.tsx`) with per-channel tabs, char counter, media picker, tag selector, schedule date/time picker, bulk-schedule CSV upload |
| `(site)/analytics` | Per-channel metrics | Channel selector (icon tabs), date-range picker, line/bar charts, best-time-to-post heatmap |
| `(site)/media` | Media library | Grid of uploads, upload button (icon), drag-drop zone, delete (icon), AI-generate-image/video entry points |
| `(site)/plugs` | Automations list | Plug cards (toggle switch to enable/disable), create-plug modal, per-integration function picker |
| `(site)/settings` | Org/team/shortlink | Team member list + role badges, invite-link generator (copy icon), shortlink domain field, danger-zone delete-account |
| `(site)/billing`, `billing/lifetime` | Subscription mgmt | Plan cards, upgrade/downgrade buttons, Stripe portal link (external-link icon), coupon field, lifetime-deal claim form |
| `(site)/third-party` | App marketplace | App cards, install/connect button (icon), per-app function list |
| `(site)/agents`, `agents/[id]` | AI agents | Agent list, chat thread view, credits counter, new-thread button (icon) |
| `(site)/admin/errors`, `admin/stats` | Admin-only diagnostics | Error table (filter by platform dropdown), stats cards; gated by admin role check in loader |
| `(site)/err` | Generic error page | Error message, retry button (icon) |
| `(preview)/p/[id]` | Public post preview/approval | Post render, comment thread, approve/reject buttons (check/× icons), no auth |
| `auth`, `auth/login`, `auth/activate(+[code])`, `auth/forgot(+[token])`, `auth/login-required` | Auth flows | Email/password fields, OAuth provider buttons (icon + provider name), activation code input, reset-password form |
| `integrations/social/[provider]` | OAuth connect-callback landing | Spinner, success/fail state, auto-redirect to `/launches` |
| `oauth/authorize` | 3rd-party OAuth-app consent | App name/logo, scope list, allow/deny buttons (check/× icons) |
| `(extension)/modal/[style]/[platform]` | Chrome-extension popup | Minimal connect-status UI, close icon |
| `provider/[p]`, `provider/add` | Standalone provider connect (no main app shell) | Same picker/connect flow as in-app, used for embeds |
## 2. APIs (apps/backend/src/api/routes, no global prefix; apps/backend/src/public-api for `/public/v1`)
Format: `METHOD path — auth — req → resp`.
### auth.controller.ts
- `GET /auth/can-register` — none — → `{ register: boolean }`
- `POST /auth/register` — none — `{ email, password, company?, providerToken? }` → `{ id, jwt? }`
- `POST /auth/login` — none — `{ email, password }` → `{ jwt }` (cookie set)
- `POST /auth/forgot`, `POST /auth/forgot/return` — none — email → ack / token+password → ack
- `GET /auth/oauth/:provider`, `POST /auth/oauth/:provider/redirect`, `POST /auth/oauth/:provider/exists` — none — provider OAuth bootstrap
- `POST /auth/activate`, `POST /auth/resend-activation` — session/none — code → ack
- `POST|GET /auth/farcaster/signer` — none — Farcaster signer flow
### posts.controller.ts
- `GET /posts`, `GET /posts/:id`, `GET /posts/group/:group` — session — → `Post[]`/`Post`
- `POST /posts` — session — `{ type, date, tags, posts: [{ integration, content, settings }] }` → created post group
- `PUT /posts/:id/date` — session — `{ date }` → ack
- `DELETE /posts/:group` — session — → ack
- `GET /posts/:id/statistics`, `/missing` — session — → metrics / missing-channel list
- `GET|PUT /posts/:id/release-url`, `/release-id` — session — published-URL bookkeeping
- `GET|POST /posts/:id/comments`, `POST /posts/comments/:commentId/resolve` — session — approval-thread comments
- `GET|POST|PUT|DELETE /posts/tags` — session — tag CRUD
- `GET /posts/find-slot(/:id)` — session — → next free scheduling slot
- `POST /posts/bulk-schedule`, `GET /posts/bulk-schedule/supported-providers` — session — CSV rows → created posts
- `POST /posts/generator`, `/generator/draft` — session — `{ prompt, integrations }` → AI-generated caption(s)
- `GET /posts/separate-posts` — session — per-channel content split
### integrations.controller.ts / no.auth.integrations.controller.ts
- `GET /integrations` — none — → public provider list (name, identifier, toolTip, picture)
- Connect/settings/nickname/group/custom-name endpoints — session — per-integration config
- `GET /integrations/social/:integration` — none — OAuth callback landing
- `POST /integrations/social-connect/:integration` — none — external-URL-based connect (used by `mastodon-custom`, `lemmy`, `wordpress`, `listmonk`)
- `POST /integrations/public/provider/:id/connect` — apikey — connect via public API
- `GET|POST|PUT|DELETE /integrations/plug/list(+CRUD)` — session — automation CRUD
- `GET /integrations/mentions` — session — → mentionable handles
- `POST /integrations/function` — session — plugin function dispatch (allowlisted per `third-party.controller.ts` security fix already shipped)
- `GET /integrations/telegram/updates` — session — Telegram webhook polling
- `POST|GET /integrations/moltbook/register(+status)` — session
### billing.controller.ts
- Stripe/RevenueCat: `check/:id`, `check-discount`, `apply-discount`, `finish-trial`, `embedded`, `subscribe`, `sync`, `portal`, `invoices`, `renewal`, `cancel(-subscription)`, `prorate`, `charges+refund-charges`, `coupon-info/apply-coupon/cancel-coupon`, `chatbase-refund`, `add-subscription` — session — standard Stripe-shaped req/resp
### media / copilot / clipping
- `media.controller.ts`: `upload-server`, `upload-simple`, `save-media`, `generate-image(-with-prompt)`, `generate-video`, `video/function`, `video-options`, `media/:id/status` — session
- `copilot.controller.ts`: `POST /copilot/chat`, `/agent`, `GET /copilot/credits`, `/:thread/list`, `/list` — session — chat/agent assistant
- `clipping.controller.ts` + `.widget.controller.ts`: CRUD `/clipping`, `GET /clipping/:id`, `/clipping-widget/status` — session/none(widget)
### webhooks / sets / signature / autopost
- `webhooks.controller.ts`: CRUD `/webhooks` + `POST /webhooks/send` — session
- `sets.controller.ts`: CRUD `/sets` (reusable templates) — session
- `signature.controller.ts`: CRUD `/signatures` — session
- `autopost.controller.ts`: CRUD `/autopost` + `/:id/active` + `/send` — session
### third-party / oauth / oauth-app
- `third-party.controller.ts`: list, submit, function dispatch (allowlisted), import — session
- `oauth.controller.ts`: full OAuth2 provider — `register/authorize/token/userinfo` — mixed
- `oauth-app.controller.ts`: self-serve OAuth-app CRUD + secret rotation — session
### settings / users / analytics / enterprise / stripe / payment / admin
- `settings.controller.ts`: team CRUD, `team/add`, `team/:id` delete, `team/leave`, shortlink get/set — session
- `users.controller.ts`: `/user/self`, `/personal`, `impersonate`, switch-org, `/organizations`, `join-org`, `change-org`, `delete-account(-info)`, `logout`, `/subscription(+tiers)` — session
- `analytics.controller.ts`: `/:integration`, `/post/:postId`, `/best-time/:integration` — session
- `enterprise.controller.ts`: `create-user`, `url`, `delete-channel` — apikey (enterprise)
- `stripe.controller.ts` / `payment.controller.ts`: `POST /stripe`, `POST /payment/:provider` — none (webhook, signature-verified)
- `admin.controller.ts`: `/errors(+/platforms)`, `/stats` — session (admin role)
### Misc
- `notifications.controller.ts`, `announcements.controller.ts`, `approved-apps.controller.ts`, `monitor.controller.ts` (queue status) — session
- `public.controller.ts`: public post view/comments/approve, `GET /public/stream` (SSE) — none
- `root.controller.ts`: `GET /` — none — health
### Public API v1 (`apps/backend/src/public-api/routes/v1/public.integrations.controller.ts`, `@Controller('/public/v1')`)
- CRUD `/posts`, `/upload(+-from-url)`, `/integrations`, `/groups`, `/me`, `/analytics/*`, `/clipping`, `/notifications`, `/credits/reset`, `/debug/*` — apikey — backs `apps/sdk` (`@postiz/node`)
## 3. Features
| Feature | Data touched | Dependencies | Remaining |
|---|---|---|---|
| 34→35 social providers | `Integration` table | `integration.manager.ts` registry, per-provider class | Done this session: `mastodon-custom` enabled (was commented out, had no standalone `requiredEnvVars`, no composer mapping — all 3 fixed). Still open: audit per-provider `checkPostStatus`/`finalizePost` override coverage against `SocialAbstract` stubs |
| Chrome extension cookie-auth | none (client-side cookie read) | `provider.registry.ts`, `manifest.json` host_permissions | Only Skool implemented; needs one module per cookie-auth provider + manifest permission entries. Medium effort, not started |
| AI post generator + copilot agent | `Post`, `mastra_*` tables | LangGraph, Mastra, OpenAI key | Functional; no gaps found this audit |
| Video clipping | `Clipping`, `ClippingClip` | Temporal orchestrator, Deepgram | Functional |
| Best-time-to-post | `Post` stats | bounded daily batch job (already shipped) | Functional |
| OAuth2 dev platform + public API + SDK | `OAuthApp`, API keys | `oauth.controller.ts`, `apps/sdk` | Functional; SDK is hard-coded to `api.postiz.com`, self-hosted users must override base URL manually — not currently exposed as a documented env/config option in the SDK client. Not fixed this session (separate scope from provider gap) |
| Live deployment | n/a | Oracle boxes (SSH/deploy-key access) | OWNER BLOCKER — no box currently reachable with working SSH/deploy key. Self-host via existing `docker-compose.yaml` once access restored; code is deploy-ready as-is |
## 4. This session's commit
- `fix(mastodon): enable self-hosted Mastodon instances via the custom provider` — uncomments `MastodonCustomProvider` registration, makes it not inherit `MASTODON_CLIENT_ID`/`SECRET` requirement (it doesn't use them — it registers a per-instance app via `externalUrl()`), adds `toolTip`, and maps `mastodon-custom` to the existing generic `MastodonProvider` composer component so posts to custom instances render/compose correctly instead of falling back to `Empty`.

View File

@ -1,89 +0,0 @@
# Postiz Strategy — 2026-10-23
Scope note: this document covers competitive positioning, differentiation, user
research (persona + journey map), and growth moves. It deliberately does not
cover page/API/feature build-out — see `PLAN-2026-10-23-DEEP.md` if present for
that (not found in the repo at time of writing, 2026-10-23).
Grounded in the actual repo state at `/Users/arhansubasi/products/postiz-app`
(fork `caelum0x/postiz-app`, upstream `gitroomhq/postiz-app`, AGPL-3.0):
- 36 real social/channel providers under `libraries/nestjs-libraries/src/integrations/social/*.provider.ts` (Instagram, X, LinkedIn page+personal, TikTok + TikTok Business, Facebook, YouTube, Pinterest, Reddit, Threads, Bluesky, Mastodon, Discord, Slack, Telegram, Dev.to, Hashnode, Medium, WordPress, Tumblr, Twitch, VK, Dribbble, GMB, Farcaster, Nostr, Lemmy, Beehiiv, HubSpot, Skool, Whop, Listmonk, Kick, Mewe, Moltbook, etc.) plus Resend/node-mailer for email channels.
- Real AI stack: `libraries/nestjs-libraries/src/agent/agent.graph.service.ts` (LangGraph + GPT-4.1 + Tavily web search + DALL-E image gen), `libraries/nestjs-libraries/src/openai/openai.service.ts`, `chat/start.mcp.ts` + `chat/mcp.relay.service.ts` (Postiz runs its own MCP server), `chat/load.tools.service.ts` and `chat/tools/generate.image.tool.ts` / `generate.video.tool.ts`.
- Real video-clipping pipeline: `libraries/nestjs-libraries/src/database/prisma/clipping/clipping.service.ts` — Temporal-orchestrated long-video-to-clips with Deepgram transcription, i.e. an OpusClip-style feature bundled into a scheduler.
- Real public API + SDK + CLI + browser extension: `apps/sdk` (`@postiz/node` on npm), `apps/commands` (CLI), `apps/extension`, plus listed n8n node and Make.com integration in the README.
- Production pricing config confirmed in code at `libraries/nestjs-libraries/src/database/prisma/subscriptions/pricing.ts`:
FREE $0 (0 channels), STANDARD $29/mo ($278/yr, 5 channels, AI on, public API, 60 clipping min, 3 video gens, 20 image gens), TEAM $39/mo (10 channels, team members, autopost), PRO $49/mo (30 channels, 300 clipping min), ULTIMATE $99/mo (100 channels, 600 clipping min, 10k webhooks).
- Open-core model confirmed in README: "We do not gate features or limit the license" between self-hosted and Postiz Cloud — same product either way.
## 1. Direct competitors
- **Buffer** (buffer.com)
- Pricing: Free (3 channels, 10 scheduled posts/channel); Essentials $5/mo per channel; Team $10/mo per channel (unlimited seats).
- Strongest feature: simplest onboarding in the category, cleanest UI, cheapest true per-channel entry price.
- Weakest point: no self-hosting, no public API/MCP for agent workflows, no video-clipping or AI web-research-backed caption generation, per-channel pricing gets expensive fast past ~6 channels.
- **Hootsuite** (hootsuite.com)
- Pricing: Standard $99/mo billed annually (10 accounts), Professional $199/mo, Advanced $399/mo. No free plan.
- Strongest feature: deepest enterprise feature set (approval workflows, social listening, large team permissions).
- Weakest point: priced for enterprise only — same 10-channel ceiling costs $1,197/mo once 3 users + approvals are added vs. Postiz TEAM at $39/mo flat; no self-host option, no AGPL/open-source trust story.
- **Later** (later.com)
- Pricing: Starter $18.75/mo (annual), Growth $37.50/mo, Scale $82.50/mo. No free plan.
- Strongest feature: best visual/Instagram-grid planning UX for creators.
- Weakest point: no X/Twitter support at all; no self-hosting; no AI agent/MCP surface; no video clipping.
- **SocialBee** (socialbee.com)
- Pricing: Bootstrap $29/mo (5 profiles), Accelerate $49/mo (10 profiles), Pro $99/mo (25 profiles, 3 users).
- Strongest feature: evergreen content recycling / category-based queue rotation.
- Weakest point: flat per-tier profile caps with no team seats below Pro ($99/mo); no open-source/self-host option; no public API or MCP server.
- **Metricool** (metricool.com)
- Pricing: Free (1 brand, 20 posts/mo, X and LinkedIn excluded); paid plans priced per brand starting ~$20/mo, Advanced ~$53/mo for 10 profiles/3 users/approvals.
- Strongest feature: best-in-class analytics and competitor tracking.
- Weakest point: X and LinkedIn gated behind paid tiers even on "included" lists; no AI content agent, no video clipping, closed source.
- **Publer** (publer.io)
- Pricing: Free tier (3 accounts, no X, 10 scheduled posts each); paid from $5/mo for one account + $4/extra account on Professional; ~$32/mo for 10 channels/3 users with approvals.
- Strongest feature: cheapest true cost-at-scale among SaaS competitors.
- Weakest point: no self-hosting, no public API/MCP/SDK/CLI, no video clipping, no bundled AI web-research agent.
- **Mixpost** (mixpost.app) — the direct self-hosted/open-source competitor
- Pricing: Lite free (Facebook Pages, X, Mastodon only); Pro $299 one-time (all platforms, API, MCP, basic white-label, 1 year of updates included, renew for updates after); Enterprise $1,199 one-time (white-label + resale billing). Hosting is extra ($5-20/mo VPS).
- Strongest feature: true perpetual-license, zero-recurring-fee model; Laravel/PHP stack is familiar to a large existing dev audience.
- Weakest point: Lite (the free tier) only supports 3 channels; Laravel stack has a smaller AI/LangChain ecosystem than Node — no bundled video-clipping/transcription pipeline, no bundled web-research agent comparable to Postiz's LangGraph+Tavily+DALL-E graph; a lapsed license freezes you on an old version with no update path short of repaying.
## 2. Exact differentiation plan (per competitor, specific axis)
- **vs. Buffer**: undercut on per-channel economics at scale — Postiz STANDARD is $29/mo flat for 5 channels ($5.80/channel) vs Buffer Essentials at $5/channel but with zero AI, zero public API, and zero self-host option; message this as "Buffer's price, plus a public API, MCP server, and AI agent Buffer doesn't have at any price."
- **vs. Hootsuite**: undercut on the exact workflow Hootsuite overcharges for — team seats + approval at 10 channels. Postiz TEAM is $39/mo flat (10 channels, team members, autopost) vs Hootsuite's $1,197/mo for the equivalent (Advanced + 3 seats). Put this side-by-side number on the pricing page, not a vague "cheaper" claim.
- **vs. Later**: ship/keep full X (Twitter) support — Later has none — and lead marketing copy for Instagram-grid-style creators with "every channel Later has, plus X, Threads, Bluesky, and 20+ more."
- **vs. SocialBee**: give team seats at the $29 tier (SocialBee requires $99 Pro for any team member); this is already true in Postiz's own pricing.ts (STANDARD lacks team_members=false actually — check: STANDARD has team_members:false too). Correction built into point below — see Note.
- **vs. Metricool**: never gate X or LinkedIn behind a higher tier — confirm (from pricing.ts) that channel count is the only paid gate, not platform identity; make that an explicit comparison-page claim ("every channel, every tier, no platform tax").
- **vs. Publer**: win on what Publer structurally cannot ship — self-host AGPL deployment, the `@postiz/node` SDK, the CLI (`apps/commands`), the browser extension (`apps/extension`), and the native MCP server (`start.mcp.ts`) that lets Claude/ChatGPT/Codex agents schedule posts directly. Publer has none of these; put "runs your own MCP server" on the comparison page as a literal checklist row.
- **vs. Mixpost (the real fight, since it's the other self-hosted option)**: win on the recurring-feature-velocity axis Mixpost's perpetual-license model can't match — Postiz's LangGraph agent (`agent.graph.service.ts`) does live web research via Tavily before drafting a post, and generates images via DALL-E inline; Mixpost's Pro tier has an MCP integration but no bundled LLM agent graph or video-clipping pipeline. Lead with the clipping feature (`clipping.service.ts` + Deepgram transcription) as a feature SocialBee/Buffer/Later/Mixpost all lack entirely — "turn one long video into scheduled clips across every channel" is not offered by any competitor above, open-source or SaaS.
- **Cross-cutting structural moat**: Postiz is the only product in this list that is simultaneously (a) open-source/self-hostable, (b) has a managed cloud option at Buffer-adjacent pricing, (c) ships a public API + npm SDK + CLI + browser extension + native MCP server, and (d) bundles an LLM agent with live web search and video generation. No single named competitor above checks more than 2 of those 4 boxes. Make that 4-box checklist the hero comparison-table structure on the Postiz Cloud vs. [X] landing pages instead of a generic feature list.
Note on the SocialBee bullet above: Postiz's own STANDARD tier in `pricing.ts` has `team_members: false`; team seats start at TEAM ($39/mo). The accurate claim is therefore "Postiz gives team seats one tier up at $39/mo vs SocialBee's $99/mo Pro" — a $60/mo gap, not "team seats at $29." Use the corrected $39-vs-$99 number on any comparison page.
## 3. Primary user persona / ICP
- **Primary persona: the technical/solo marketer at a small SaaS or dev-tool company (1-10 person team) who already pays for Supabase/Neon/Resend-style infra and is comfortable self-hosting.**
- Job to be done: get consistent multi-platform posting (especially X, LinkedIn, Reddit, Discord/Slack for community) live without hiring a social media person, and automate it from existing dev workflows (n8n/Make/Zapier, or directly from an AI agent via MCP) rather than hand-typing into five separate native composer UIs.
- Why this persona, grounded in the repo: Postiz's own README leads with the dev-tool ecosystem (n8n node, Make.com integration, Postiz Node SDK, AI-agent integrations for ChatGPT/Claude/Codex/Cursor/Grok listed in the README's agent-icon row) — the product is built for people who want posting as a callable primitive, not a composer UI.
- Secondary persona: a small agency or community team (the TEAM/PRO tier shape — 10-30 channels, multiple members, autopost) managing several client/brand accounts who wants self-host cost control instead of Hootsuite's per-seat tax.
## 4. User journey map (discovery -> paying/retained user)
1. **Discovery** — finds Postiz via: GitHub (AGPL repo, currently ~37.5k+ stars per competitor research), a "Buffer alternative" / "open source Buffer alternative" search or blog post, or an AI-agent tooling list (MCP server directories, n8n/Make marketplace listings).
2. **Evaluation** — compares self-host (free, own infra) vs. Postiz Cloud (`platform.postiz.com`) pricing against Buffer/Mixpost; reads the open-core claim ("we do not gate features") to confirm no rug-pull risk.
3. **First setup** — either (a) self-hosts via Docker Compose (`docker-compose.yaml`/`docker-compose.dev.yaml`) and needs Postgres+Redis+env vars configured correctly, or (b) signs up on Postiz Cloud directly. **This is the single biggest drop-off risk step**: self-hosting Postiz requires correctly provisioning OAuth app credentials for every platform the user wants (each provider needs its own developer-app registration — e.g. Meta app review for Instagram/Facebook, X API tier, TikTok app approval) before a single post can be scheduled; this setup friction is categorically worse than any SaaS competitor's "click to connect" OAuth, and is where a self-host-curious technical user is most likely to abandon before ever publishing a post.
4. **Activation** — connects first channel(s), schedules/publishes first post; for the AI-agent persona, activation instead means wiring the MCP server or Node SDK into an existing agent/workflow and getting the first automated post out.
5. **Habit formation** — returns weekly/daily via the calendar view, analytics, or an automated pipeline (n8n/Make/agent) that keeps posting without manual re-entry.
6. **Monetization trigger** — hits a FREE-tier wall (FREE has 0 channels in `pricing.ts`, i.e. it is effectively a trial/demo tier, not a usable free plan) and must upgrade to STANDARD ($29/mo) to connect even one channel, or needs a 6th+ channel / team member / clipping minutes beyond STANDARD's caps.
7. **Retention / expansion** — adds team members (TEAM), add more channels/clipping minutes/webhooks (PRO/ULTIMATE), or becomes a public-API/MCP power user embedding Postiz into their own product or internal tooling, which raises switching cost substantially versus a SaaS-only competitor.
## 5. Three concrete growth moves specific to this product
- **Ship a one-click "OAuth app pre-registration" path or a hosted-credentials fallback for self-hosters.** Since step 3 above (per-platform OAuth app setup) is the confirmed biggest activation blocker for the exact self-host-first ICP this product targets, offer self-hosters an opt-in "use Postiz Cloud's shared OAuth apps for your first N posts, bring your own after" mode, or a guided CLI wizard (building on the existing `apps/commands` CLI) that walks through each provider's app-creation steps inline. This directly targets the step with the highest measured drop-off risk in the journey map above, not a generic onboarding tweak.
- **Publish head-to-head comparison pages for each competitor above, using the exact numbers in this doc** (Buffer $5/channel vs. Postiz $29 flat/5 channels + API+MCP; Hootsuite $1,197/mo vs. Postiz TEAM $39/mo for the same 10-channel/3-seat/approval shape; Mixpost's $299 one-time but no agent-graph/clipping vs. Postiz Cloud's bundled AI+clipping). These are the kind of bottom-of-funnel, high-intent "X vs Postiz" pages that convert searchers already comparing tools — and every number here is pulled from the live `pricing.ts` and competitor pricing pages found above, not invented.
- **Package the video-clipping pipeline (`clipping.service.ts` + Deepgram) as its own standalone landing page/feature — "turn one long-form video into scheduled social clips" — since no competitor named above (Buffer, Hootsuite, Later, SocialBee, Metricool, Publer, Mixpost) offers this at all.** This is a real, already-built, differentiated feature with zero direct competitive overlap in this specific product category; a dedicated page targeting "repurpose long video to short clips scheduler" search intent captures a search behavior none of the 7 named competitors can answer directly from their own feature set.

View File

@ -4,15 +4,13 @@ import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.reque
import { ApiTags } from '@nestjs/swagger';
import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { PostEngagementService } from '@gitroom/nestjs-libraries/database/prisma/post-engagement/post-engagement.service';
@ApiTags('Analytics')
@Controller('/analytics')
export class AnalyticsController {
constructor(
private _integrationService: IntegrationService,
private _postsService: PostsService,
private _postEngagementService: PostEngagementService
private _postsService: PostsService
) {}
@Get('/:integration')
@ -32,15 +30,4 @@ export class AnalyticsController {
) {
return this._postsService.checkPostAnalytics(org.id, postId, +date);
}
// Reads only from the pre-aggregated PostEngagementSnapshot table (see
// PostEngagementService) - no live provider calls on this path, so it is
// safe to call on every composer/calendar render.
@Get('/best-time/:integration')
async getBestTimeToPost(
@GetOrgFromRequest() org: Organization,
@Param('integration') integration: string
) {
return this._postEngagementService.getBestTimes(org.id, integration);
}
}

View File

@ -20,11 +20,6 @@ import { AuthService } from '@gitroom/helpers/auth/auth.service';
import { UsersService } from '@gitroom/nestjs-libraries/database/prisma/users/users.service';
import { PaymentService } from '@gitroom/nestjs-libraries/services/payment/payment.service';
import { BillingSyncDto } from '@gitroom/nestjs-libraries/dtos/billing/billing.sync.dto';
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
import {
AuthorizationActions,
Sections,
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
@ApiTags('Billing')
@Controller('/billing')
@ -163,17 +158,6 @@ export class BillingController {
};
}
@Get('/invoices')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async getInvoices(@GetOrgFromRequest() org: Organization) {
return (await this.provider(org)).getInvoices(org.id);
}
@Get('/renewal')
async getRenewal(@GetOrgFromRequest() org: Organization) {
return (await this.provider(org)).getRenewalDate(org.id);
}
@Get('/')
getCurrentBilling(@GetOrgFromRequest() org: Organization) {
return this._paymentService.getSubscription(org.id);

View File

@ -116,8 +116,7 @@ export class CopilotController {
@Get('/credits')
calculateCredits(
@GetOrgFromRequest() organization: Organization,
@Query('type')
type: 'ai_images' | 'ai_videos' | 'clipping_minutes'
@Query('type') type: 'ai_images' | 'ai_videos'
) {
return this._subscriptionService.checkCredits(
organization,

View File

@ -71,13 +71,7 @@ export class EnterpriseController {
webhookUrl: string;
}>(params);
if (
!load ||
!load.redirectUrl ||
!load.apiKey ||
typeof load.apiKey !== 'string' ||
!load.provider
) {
if (!load || !load.redirectUrl || !load.apiKey || !load.provider) {
return;
}
@ -123,13 +117,7 @@ export class EnterpriseController {
id: string;
}>(params);
if (
!load ||
!load.apiKey ||
!load.id ||
typeof load.apiKey !== 'string' ||
typeof load.id !== 'string'
) {
if (!load || !load.apiKey || !load.id) {
return { success: false };
}

View File

@ -3,7 +3,6 @@ import {
Controller,
Delete,
Get,
Logger,
Param,
Post,
Put,
@ -42,8 +41,6 @@ import { RefreshIntegrationService } from '@gitroom/nestjs-libraries/integration
@ApiTags('Integrations')
@Controller('/integrations')
export class IntegrationsController {
private readonly _logger = new Logger(IntegrationsController.name);
constructor(
private _integrationManager: IntegrationManager,
private _integrationService: IntegrationService,
@ -250,27 +247,6 @@ export class IntegrationsController {
throw new Error('Missing external url');
}
// Building the auth URL with an unset client id/secret sends the user
// to the provider with an empty or literal "undefined" client id - the
// provider's error page gives no hint that a server env var is missing
// (#2238). Catch it generically here instead of per-provider.
const missingEnvVars = integrationProvider.missingEnvVars?.() ?? [];
if (missingEnvVars.length) {
this._logger.error(
`Cannot start ${integration} OAuth: missing env var(s) ${missingEnvVars.join(
', '
)}`
);
return {
err: true,
message: `${integrationProvider.name} is not configured on this server: missing ${missingEnvVars.join(
', '
)}. Ask the admin to set ${missingEnvVars.length > 1 ? 'these' : 'this'} environment variable${
missingEnvVars.length > 1 ? 's' : ''
}.`,
};
}
try {
const getExternalUrl = integrationProvider.externalUrl
? {
@ -304,17 +280,7 @@ export class IntegrationsController {
);
return { url };
} catch (err: any) {
// Previously swallowed entirely (HTTP 200 with just { err: true }), so
// a provider rejecting the request (for example X's request-token call
// failing) left no trace anywhere in the server logs (#2238). Log only
// the message, never the raw error object - some provider errors carry
// request config/headers that aren't guaranteed to be redacted here.
this._logger.error(
`Failed to generate auth URL for ${integration}: ${
err?.message || err
}`
);
} catch (err) {
return { err: true };
}
}

View File

@ -140,14 +140,7 @@ export class NoAuthIntegrationsController {
refresh,
auth.accessToken
);
// keep the fresh refresh token and expiration from the new
// authentication, otherwise the stored refresh token is wiped and
// the channel breaks again as soon as the access token expires
return res({
...newAuth,
refreshToken: auth.refreshToken,
expiresIn: auth.expiresIn,
});
return res({ ...newAuth, refreshToken: body.refresh });
} catch (err: any) {
return res({
error: err.message,
@ -175,7 +168,6 @@ export class NoAuthIntegrationsController {
});
}
console.log(`Authentication failed for ${integration}:`, err);
return res({
error: 'Authentication failed',
accessToken: '',
@ -377,18 +369,7 @@ export class NoAuthIntegrationsController {
}
const { integrationId, organizationId, internalId, provider } = payload;
if (
!integrationId ||
typeof integrationId !== 'string' ||
!organizationId ||
typeof organizationId !== 'string' ||
!internalId ||
typeof internalId !== 'string' ||
!provider ||
typeof provider !== 'string' ||
'timeLimit' in payload || // team invite token
'expires' in payload // password reset token
) {
if (!integrationId || !organizationId || !internalId || !provider) {
throw new HttpException('Invalid token payload', 400);
}
@ -396,11 +377,7 @@ export class NoAuthIntegrationsController {
organizationId,
integrationId
);
if (
!integration ||
integration.internalId !== internalId ||
integration.providerIdentifier !== provider
) {
if (!integration || integration.internalId !== internalId) {
throw new HttpException('Integration not found', 404);
}
@ -443,10 +420,8 @@ export class NoAuthIntegrationsController {
false,
undefined,
undefined,
// stored encrypted like connectSocialMedia does, never signed: the
// cookies JSON comes from the request
AuthService.fixedEncryption(
Buffer.from(body.cookies, 'base64').toString()
AuthService.signJWT(
JSON.parse(Buffer.from(body.cookies, 'base64').toString())
)
);

View File

@ -8,10 +8,8 @@ import {
HttpStatus,
Post,
Query,
Res,
UseGuards,
} from '@nestjs/common';
import { Response } from 'express';
import { ApiTags } from '@nestjs/swagger';
import { Throttle } from '@nestjs/throttler';
import { OAuthService } from '@gitroom/nestjs-libraries/database/prisma/oauth/oauth.service';
@ -25,7 +23,6 @@ import {
} from '@gitroom/nestjs-libraries/dtos/oauth/authorize-oauth.dto';
import { TokenExchangeDto } from '@gitroom/nestjs-libraries/dtos/oauth/token-exchange.dto';
import { RegisterClientDto } from '@gitroom/nestjs-libraries/dtos/oauth/register-client.dto';
import { HubspotInstallQueryDto } from '@gitroom/nestjs-libraries/dtos/oauth/hubspot-install.dto';
import { extractBasicCredentials } from '@gitroom/nestjs-libraries/chat/oauth-types';
import { McpRelayService } from '@gitroom/nestjs-libraries/chat/mcp.relay.service';
import { ThrottlerRealIpGuard } from '@gitroom/nestjs-libraries/throttler/throttler.provider';
@ -105,11 +102,13 @@ export class OAuthController {
const code = await this._oauthService.createSelfHostedAuthorizationCode(
app.id,
{ ...instance, email },
this._oauthService.pkceBinding(app, {
codeChallenge: body.code_challenge,
codeChallengeMethod: body.code_challenge_method,
redirectUri: body.redirect_uri,
})
app.dynamic
? {
codeChallenge: body.code_challenge,
codeChallengeMethod: body.code_challenge_method,
redirectUri: body.redirect_uri,
}
: undefined
);
// Same redirect as an approved cloud authorization
@ -130,20 +129,6 @@ export class OAuthController {
@Body() body: TokenExchangeDto,
@Headers('authorization') authorization?: string
) {
// client_secret_basic puts the credentials in the Authorization header,
// client_secret_post and public clients put them in the body
const basic = extractBasicCredentials(authorization);
const clientId = basic?.clientId || body.client_id;
// Only HubSpot gets refresh tokens, the service answers every other
// client with unsupported_grant_type, as before
if (body.grant_type === 'refresh_token') {
return this._oauthService.refreshAccessToken(
clientId,
body.refresh_token
);
}
if (body.grant_type !== 'authorization_code') {
throw new HttpException(
{ error: 'unsupported_grant_type' },
@ -151,6 +136,10 @@ export class OAuthController {
);
}
// client_secret_basic puts the credentials in the Authorization header,
// client_secret_post and public clients put them in the body
const basic = extractBasicCredentials(authorization);
const clientId = basic?.clientId || body.client_id;
if (!clientId) {
throw new HttpException(
{ error: 'invalid_client' },
@ -176,26 +165,6 @@ export class OAuthController {
async userinfoPost(@Headers('authorization') authorization?: string) {
return this._oauthService.getUserInfo(authorization);
}
// Public (HubSpot sends the person here after they install the HubSpot app)
// and capped per IP, since every attempt sends a request to HubSpot
@UseGuards(ThrottlerRealIpGuard)
@Throttle({ default: { limit: 30, ttl: 3600000 } })
@Get('/hubspot/callback')
async hubspotCallback(
@Query() query: HubspotInstallQueryDto,
@Res({ passthrough: false }) response: Response
) {
await this._oauthService.completeHubspotInstall(query.code);
// The calendar explains what just happened (HubspotInstalled); returnUrl
// brings someone who has to sign in first back to it
const installed = `${process.env.FRONTEND_URL}/launches?hubspot=installed`;
return response.redirect(
302,
`${installed}&returnUrl=${encodeURIComponent(installed)}`
);
}
}
@ApiTags('OAuth')
@ -235,11 +204,13 @@ export class OAuthAuthorizedController {
app.id,
user.id,
org.id,
this._oauthService.pkceBinding(app, {
codeChallenge: body.code_challenge,
codeChallengeMethod: body.code_challenge_method,
redirectUri: body.redirect_uri,
})
app.dynamic
? {
codeChallenge: body.code_challenge,
codeChallengeMethod: body.code_challenge_method,
redirectUri: body.redirect_uri,
}
: undefined
);
const redirectUrl = new URL(redirectTarget);

View File

@ -30,19 +30,10 @@ import {
} from '@gitroom/backend/services/auth/permissions/permission.exception.class';
import { PostValidationException } from '@gitroom/backend/api/routes/posts.validation.exception';
import {
AssignCommentDto,
CreatePublicCommentDto,
ResolveCommentDto,
} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import { RealIP } from 'nestjs-real-ip';
import { BulkScheduleDto } from '@gitroom/nestjs-libraries/dtos/posts/bulk.schedule.dto';
import { simpleTextProviders } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/all.providers.settings';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
import { EvergreenService } from '@gitroom/nestjs-libraries/database/prisma/evergreen/evergreen.service';
import {
CreateEvergreenRecycleDto,
UpdateEvergreenRecycleDto,
} from '@gitroom/nestjs-libraries/dtos/posts/evergreen.recycle.dto';
@ApiTags('Posts')
@Controller('/posts')
@ -50,9 +41,7 @@ export class PostsController {
constructor(
private _postsService: PostsService,
private _agentGraphService: AgentGraphService,
private _shortLinkService: ShortLinkService,
private _organizationService: OrganizationService,
private _evergreenService: EvergreenService
private _shortLinkService: ShortLinkService
) {}
@Get('/:id/statistics')
@ -88,61 +77,11 @@ export class PostsController {
return this._postsService.updateReleaseId(org.id, id, releaseId);
}
// Evergreen content recycling (see Organization.EvergreenRecycle in the
// schema) - lists/creates/pauses/removes the recycle schedule for one
// already-published post. The actual republishing happens in the daily
// evergreenRecycleWorkflow batch, not from this controller.
@Get('/:id/evergreen')
async getEvergreenRecycles(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._evergreenService.listForPost(org.id, id);
}
@Post('/:id/evergreen')
async createEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string,
@Body() body: CreateEvergreenRecycleDto
) {
return this._evergreenService.createRecycle(org.id, id, body);
}
@Put('/evergreen/:recycleId')
async updateEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('recycleId') recycleId: string,
@Body() body: UpdateEvergreenRecycleDto
) {
return this._evergreenService.setActive(org.id, recycleId, body.active);
}
@Delete('/evergreen/:recycleId')
async deleteEvergreenRecycle(
@GetOrgFromRequest() org: Organization,
@Param('recycleId') recycleId: string
) {
return this._evergreenService.remove(org.id, recycleId);
}
@Post('/should-shortlink')
async shouldShortlink(@Body() body: { messages: string[] }) {
return { ask: this._shortLinkService.askShortLinkedin(body.messages) };
}
// Authenticated counterpart to PublicController#getComments - same data,
// plus mention/assignment identities that are only safe to reveal once we
// know the caller is logged in as a member of the org that owns the post
// (see PostsService.getComments's includeInternal gate).
@Get('/:id/comments')
async getComments(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return { comments: await this._postsService.getComments(id, org.id) };
}
@Post('/:id/comments')
async createComment(
@GetUserFromRequest() user: User,
@ -162,30 +101,6 @@ export class PostsController {
return this._postsService.resolveComment(org.id, commentId, body.resolved);
}
@Put('/comments/:commentId/assign')
async assignComment(
@GetOrgFromRequest() org: Organization,
@GetUserFromRequest() user: User,
@Param('commentId') commentId: string,
@Body() body: AssignCommentDto
) {
return this._postsService.assignComment(
org.id,
commentId,
body.assignedToId,
user.id
);
}
// Backs the comment @mention/assignment picker - every active member of
// the current organization, not gated behind the admin-only
// SettingsController team endpoint since any member composing a comment
// needs to see who they can mention/assign.
@Get('/comments/team-members')
async getCommentTeamMembers(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getTeamMembersForMentions(org.id);
}
@Get('/tags')
async getTags(@GetOrgFromRequest() org: Organization) {
return { tags: await this._postsService.getTags(org.id) };
@ -273,14 +188,6 @@ export class PostsController {
return this._postsService.getPostsByGroup(org.id, group);
}
// Declared before the generic '/:id' GET below so Nest doesn't try to
// resolve this literal path as an :id param.
@Get('/pending-approval')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async getPendingApprovalPosts(@GetOrgFromRequest() org: Organization) {
return this._postsService.getPendingApprovalPosts(org.id);
}
@Get('/:id')
getPost(@GetOrgFromRequest() org: Organization, @Param('id') id: string) {
return this._postsService.getPost(org.id, id);
@ -298,7 +205,6 @@ export class PostsController {
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async createPost(
@GetOrgFromRequest() org: Organization,
@GetUserFromRequest() user: User,
@Body() rawBody: any
) {
// Server-side validation — never trust the client to have validated.
@ -339,34 +245,7 @@ export class PostsController {
}
const body = await this._postsService.mapTypeToPost(rawBody, org.id);
// The auth middleware populates org.users with the caller's own
// membership row (see organization.service.ts for the same pattern) -
// this is the only place that reads it as a role, so the Organization
// type doesn't declare it.
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const callerRole = org.users?.[0]?.role;
return this._postsService.createPost(org.id, body, 'WEB', false, {
userId: user.id,
role: callerRole,
});
}
@Get('/bulk-schedule/supported-providers')
bulkScheduleSupportedProviders() {
// Single source of truth for which providers bulk CSV import can
// target — same generic, data-driven list the backend enforces in
// bulkSchedule(), so the frontend channel picker never drifts from it.
return { providers: simpleTextProviders() };
}
@Post('/bulk-schedule')
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async bulkSchedule(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkScheduleDto
) {
return this._postsService.bulkSchedule(org.id, body);
return this._postsService.createPost(org.id, body, 'WEB');
}
@Post('/generator/draft')
@ -427,26 +306,6 @@ export class PostsController {
return this._postsService.changeDate(org.id, id, date, action, republish);
}
// ADMIN/SUPERADMIN-only - approve/reject a USER-level member's post held
// back by Organization.requireApprovalForQueue (see PostsService#createPost).
@Put('/:id/approve-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async approvePendingQueuePost(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._postsService.approvePendingQueuePost(org.id, id);
}
@Put('/:id/reject-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async rejectPendingQueuePost(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._postsService.rejectPendingQueuePost(org.id, id);
}
@Post('/separate-posts')
async separatePosts(
@GetOrgFromRequest() org: Organization,

View File

@ -27,10 +27,7 @@ import { promisify } from 'util';
import { OnlyURL } from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import {
ApprovePostDto,
CreatePublicCommentDto,
} from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
import { CreatePublicCommentDto } from '@gitroom/nestjs-libraries/dtos/comments/add.comment.dto';
const pump = promisify(pipeline);
@ -57,10 +54,8 @@ export class PublicController {
@Get(`/posts/:id`)
async getPreview(@Param('id') id: string) {
// the batch only links the posts in the dashboard, it stays out of the
// public preview
return (await this._postsService.getPostsRecursively(id, true)).map(
({ childrenPost, batchId, ...p }) => ({
({ childrenPost, ...p }) => ({
...p,
...(p.integration
? {
@ -91,15 +86,6 @@ export class PublicController {
return this._postsService.createPublicComment(postId, body, null, ip);
}
@Post(`/posts/:id/approve`)
async approvePost(
@Param('id') postId: string,
@Body() body: ApprovePostDto,
@RealIP() ip: string
) {
return this._postsService.approvePublicPost(postId, body, null, ip);
}
@Post('/t')
async trackEvent(
@Res() res: Response,
@ -160,16 +146,7 @@ export class PublicController {
billing: 'FREE' | 'STANDARD' | 'TEAM' | 'PRO' | 'ULTIMATE';
};
if (
!load ||
!load.orgId ||
typeof load.orgId !== 'string' ||
!load.billing ||
!pricing[load.billing] ||
'timeLimit' in load || // team invite token
'providerName' in load || // login token (full User row)
'expires' in load // password reset token
) {
if (!load || !load.orgId || !load.billing || !pricing[load.billing]) {
return { success: false };
}

View File

@ -15,7 +15,6 @@ import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/o
import { AddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/add.team.member.dto';
import { AdminAddTeamMemberDto } from '@gitroom/nestjs-libraries/dtos/settings/admin.add.team.member.dto';
import { ShortlinkPreferenceDto } from '@gitroom/nestjs-libraries/dtos/settings/shortlink-preference.dto';
import { ApprovalForQueueDto } from '@gitroom/nestjs-libraries/dtos/settings/approval-for-queue.dto';
import { ApiTags } from '@nestjs/swagger';
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
@ -73,18 +72,6 @@ export class SettingsController {
return this._organizationService.deleteTeamMember(org, id);
}
// Self-service: a member leaving an organization they're currently
// switched into, as opposed to an admin removing someone else via
// deleteTeamMember() above. Not gated behind the TEAM_MEMBERS/ADMIN
// policy since any member - not just admins - can leave an org.
@Post('/team/leave')
leaveOrganization(
@GetUserFromRequest() user: User,
@GetOrgFromRequest() org: Organization
) {
return this._organizationService.leaveOrganization(user, org);
}
@Get('/shortlink')
async getShortlinkPreference(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getShortlinkPreference(org.id);
@ -101,21 +88,4 @@ export class SettingsController {
body.shortlink
);
}
@Get('/approval-queue')
async getApprovalQueueSetting(@GetOrgFromRequest() org: Organization) {
return this._organizationService.getApprovalForQueueSetting(org.id);
}
@Post('/approval-queue')
@CheckPolicies([AuthorizationActions.Create, Sections.ADMIN])
async updateApprovalQueueSetting(
@GetOrgFromRequest() org: Organization,
@Body() body: ApprovalForQueueDto
) {
return this._organizationService.updateApprovalForQueueSetting(
org.id,
body.requireApprovalForQueue
);
}
}

View File

@ -116,25 +116,7 @@ export class ThirdPartyController {
throw new HttpException('Invalid identifier', 400);
}
// functionName comes straight from the URL - only call methods the
// provider explicitly opted in with @ExposeThirdPartyFunction, the same
// allowlist VideoManager enforces for its own name-dispatched functions.
// Without this, any authenticated org member could invoke ANY method
// found on the provider instance (checkConnection, sendData, or a future
// internal helper) just by naming it in the URL.
const functionToCall = thirdPartyInstance.instance?.[functionName];
if (
typeof functionToCall !== 'function' ||
this._thirdPartyManager.checkAvailableThirdPartyFunction(functionToCall)
) {
throw new HttpException(
`Function ${functionName} not found on third-party instance`,
400
);
}
return functionToCall.call(
thirdPartyInstance.instance,
return thirdPartyInstance?.instance?.[functionName](
AuthService.fixedDecryption(thirdParty.apiKey),
data
);

View File

@ -79,6 +79,23 @@ export class UsersController {
return { token };
}
@Get('/agent-media-sso')
async getAgentMediaSsoUrl(
@GetUserFromRequest() user: User,
@GetOrgFromRequest() organization: Organization
) {
if (!process.env.AGENT_MEDIA_SSO_KEY) {
throw new HttpException('Agent Media SSO is not configured', 400);
}
const token = sign(
{ id: organization.id, displayName: organization.name },
process.env.AGENT_MEDIA_SSO_KEY
);
return { url: `https://app.agent-media.ai/sso/${token}` };
}
@Get('/self')
async getSelf(
@GetUserFromRequest() user: User,
@ -281,14 +298,9 @@ export class UsersController {
@Get('/organizations')
async getOrgs(@GetUserFromRequest() user: User) {
return (await this._orgService.getOrgsByUserId(user.id))
.filter((f) => !f.users[0].disabled)
.map((p) => ({
id: p.id,
name: p.name,
users: p.users,
subscription: p.subscription,
}));
return (await this._orgService.getOrgsByUserId(user.id)).filter(
(f) => !f.users[0].disabled
);
}
@Post('/change-org')
@ -315,11 +327,6 @@ export class UsersController {
response.status(200).send();
}
@Get('/delete-account-info')
getDeleteAccountInfo(@GetUserFromRequest() user: User) {
return this._userService.getDeleteAccountInfo(user.id);
}
@Post('/delete-account')
async deleteAccount(
@GetUserFromRequest() user: User,

View File

@ -14,10 +14,9 @@ import { ApiTags } from '@nestjs/swagger';
import { WebhooksService } from '@gitroom/nestjs-libraries/database/prisma/webhooks/webhooks.service';
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
import {
DeliveriesPageDto, OnlyURL, UpdateDto, WebhooksDto
OnlyURL, UpdateDto, WebhooksDto
} from '@gitroom/nestjs-libraries/dtos/webhooks/webhooks.dto';
import { AuthorizationActions, Sections } from '@gitroom/backend/services/auth/permissions/permission.exception.class';
import { getSsrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
@ApiTags('Webhooks')
@Controller('/webhooks')
@ -26,7 +25,7 @@ export class WebhookController {
@Get('/')
async getStatistics(@GetOrgFromRequest() org: Organization) {
return this._webhooksService.getWebhooksForDisplay(org.id);
return this._webhooksService.getWebhooks(org.id);
}
@Post('/')
@ -54,58 +53,18 @@ export class WebhookController {
return this._webhooksService.deleteWebhook(org.id, id);
}
@Post('/:id/secret')
async regenerateSecret(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string
) {
return this._webhooksService.regenerateSecret(org.id, id);
}
@Get('/:id/deliveries')
async getDeliveries(
@GetOrgFromRequest() org: Organization,
@Param('id') id: string,
@Query() query: DeliveriesPageDto
) {
return this._webhooksService.getDeliveries(
org.id,
id,
Number(query.page) || 1
);
}
@Post('/deliveries/:deliveryId/redeliver')
async redeliver(
@GetOrgFromRequest() org: Organization,
@Param('deliveryId') deliveryId: string
) {
const result = await this._webhooksService.redeliver(org.id, deliveryId);
if (!result) {
return { success: false, error: 'Delivery not found' };
}
return result;
}
@Post('/send')
async sendWebhook(@Body() body: any, @Query() query: OnlyURL) {
try {
const response = await fetch(query.url, {
await fetch(query.url, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
// @ts-ignore — undici dispatcher option, not in lib.dom fetch types
dispatcher: getSsrfSafeDispatcher(),
});
return {
send: response.status >= 200 && response.status < 300,
statusCode: response.status,
};
} catch (err) {
return {
send: false,
error: err instanceof Error ? err.message : 'Unknown delivery error',
};
/** sent **/
}
return { send: true };
}
}

View File

@ -59,14 +59,7 @@ async function start() {
},
});
// startMcp wires Mastra, which connects to Postgres (pStore) on first use -
// a DB outage/misconfiguration there must not take down the entire backend
// (every other route, not just /mcp and /copilot) by rejecting start().
try {
await startMcp(app);
} catch (e) {
Logger.error('Failed to initialize MCP/Mastra, continuing without it', e);
}
await startMcp(app);
app.useGlobalPipes(
new ValidationPipe({

View File

@ -1,3 +1,4 @@
import { PublicPrivacyController } from './routes/v1/public.privacy.controller';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AuthService } from '@gitroom/backend/services/auth/auth.service';
import { StripeService } from '@gitroom/nestjs-libraries/services/stripe.service';
@ -12,7 +13,7 @@ import { PublicIntegrationsController } from '@gitroom/backend/public-api/routes
import { PublicAuthMiddleware } from '@gitroom/backend/services/auth/public.auth.middleware';
import { SuperAdminGuard } from '@gitroom/backend/services/auth/super.admin.guard';
const authenticatedController = [PublicIntegrationsController];
const authenticatedController = [PublicIntegrationsController, PublicPrivacyController];
@Module({
imports: [UploadModule],
controllers: process.env.MCP_ONLY ? [] : [...authenticatedController],

View File

@ -14,7 +14,6 @@ import {
UseInterceptors,
} from '@nestjs/common';
import { streamUploadOptions } from '@gitroom/nestjs-libraries/upload/multer.stream.engine';
import { omit } from 'lodash';
import { ApiTags } from '@nestjs/swagger';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
import { GetIncludeDeletedFromRequest } from '@gitroom/nestjs-libraries/user/include.deleted.from.request';
@ -26,12 +25,6 @@ import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/po
import { FileInterceptor } from '@nestjs/platform-express';
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
import {
BulkCreatePostsDto,
BulkCreateResult,
BulkDeleteResult,
BulkPostIdsDto,
} from '@gitroom/nestjs-libraries/dtos/posts/bulk.posts.dto';
import { ChangePostStatusDto } from '@gitroom/nestjs-libraries/dtos/posts/change.post.status.dto';
import { UpdatePostSettingsDto } from '@gitroom/nestjs-libraries/dtos/posts/update.post.settings.dto';
import {
@ -41,7 +34,6 @@ import {
import { VideoDto } from '@gitroom/nestjs-libraries/dtos/videos/video.dto';
import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.function.dto';
import { UploadDto } from '@gitroom/nestjs-libraries/dtos/media/upload.dto';
import { GetMediaDto } from '@gitroom/nestjs-libraries/dtos/media/get.media.dto';
import { ClippingDto } from '@gitroom/nestjs-libraries/dtos/clipping/clipping.dto';
import { ClippingService } from '@gitroom/nestjs-libraries/database/prisma/clipping/clipping.service';
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
@ -62,8 +54,6 @@ import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
import { AdminStatsService } from '@gitroom/nestjs-libraries/database/prisma/admin-stats/admin-stats.service';
import { OrganizationService } from '@gitroom/nestjs-libraries/database/prisma/organizations/organization.service';
import { GetOrgActivityDto } from '@gitroom/nestjs-libraries/dtos/analytics/get.org.activity.dto';
import { ResetCreditsDto } from '@gitroom/nestjs-libraries/dtos/billing/reset.credits.dto';
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
import dayjs from 'dayjs';
@ApiTags('Public API')
@ -79,8 +69,7 @@ export class PublicIntegrationsController {
private _usersService: UsersService,
private _adminStatsService: AdminStatsService,
private _organizationService: OrganizationService,
private _clippingService: ClippingService,
private _subscriptionService: SubscriptionService
private _clippingService: ClippingService
) {}
@Post('/upload')
@ -143,24 +132,8 @@ export class PublicIntegrationsController {
@Body() rawBody: any
) {
Sentry.metrics.count('public_api-request', 1);
return this.createOnePost(org, rawBody);
}
// Shared by the single POST /posts above and the bulk endpoint below, so
// both go through the exact same validation/creation pipeline and never
// drift. Throws PostValidationException / HttpException on a bad single
// item - callers decide whether that aborts the whole request (single) or
// is caught per-item (bulk).
private async createOnePost(org: Organization, rawBody: any) {
const body = await this._postsService.mapTypeToPost(
{
...rawBody,
// a date per channel is a dashboard feature, the public API keeps one
// date for the whole request
posts: Array.isArray(rawBody?.posts)
? rawBody.posts.map((post: any) => omit(post, 'date'))
: rawBody?.posts,
},
rawBody,
org.id,
rawBody?.type === 'draft' || true
);
@ -232,86 +205,6 @@ export class PublicIntegrationsController {
return this._postsService.createPost(org.id, body, creationMethod);
}
// Creates up to MAX_BULK_CREATE posts in one call. Each entry is the exact
// same body shape as POST /posts; a bad entry never aborts the batch -
// same "schedule what's valid, report the rest" spirit as the dashboard's
// CSV bulk-schedule (see PostsService.bulkSchedule).
@Post('/posts/bulk')
@CheckPolicies([AuthorizationActions.Create, Sections.POSTS_PER_MONTH])
async createPostsBulk(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkCreatePostsDto
) {
Sentry.metrics.count('public_api-request', 1);
const results: BulkCreateResult[] = [];
for (let index = 0; index < body.posts.length; index++) {
try {
const created = await this.createOnePost(org, body.posts[index]);
results.push({
index,
success: !!created?.length,
postId: created?.[0]?.postId,
...(created?.length
? {}
: { error: 'Could not create this post' }),
});
} catch (err) {
results.push({
index,
success: false,
error:
err instanceof HttpException
? JSON.stringify(err.getResponse())
: err instanceof Error
? err.message
: 'Could not create this post',
});
}
}
return { results };
}
// Deletes up to MAX_BULK_IDS posts (by id, same resolution as
// DELETE /posts/:id - each id's whole group is removed) in one call. A
// missing/foreign id never aborts the batch.
@Delete('/posts/bulk')
async deletePostsBulk(
@GetOrgFromRequest() org: Organization,
@Body() body: BulkPostIdsDto
) {
Sentry.metrics.count('public_api-request', 1);
const results: BulkDeleteResult[] = [];
for (const id of body.ids) {
try {
const getPostById = await this._postsService.getPost(org.id, id);
if (!getPostById) {
results.push({ id, success: false, error: 'Post not found' });
continue;
}
const deleted = await this._postsService.deletePost(
org.id,
getPostById.group
);
results.push({
id,
success: !deleted?.error,
...(deleted?.error ? { error: 'Could not delete this post' } : {}),
});
} catch (err) {
results.push({
id,
success: false,
error: err instanceof Error ? err.message : 'Could not delete this post',
});
}
}
return { results };
}
@Delete('/posts/:id')
async deletePost(
@GetOrgFromRequest() org: Organization,
@ -337,30 +230,6 @@ export class PublicIntegrationsController {
return { connected: true };
}
@Get('/media')
async getMedia(
@GetOrgFromRequest() org: Organization,
@Query() query: GetMediaDto
) {
Sentry.metrics.count('public_api-request', 1);
const { pages, results } = await this._mediaService.getMedia(
org.id,
query.page,
query.search
);
return {
pages,
results: results.map((p) => ({
id: p.id,
name: p.name,
originalName: p.originalName,
path: p.path,
createdAt: p.createdAt,
})),
};
}
// `user` is only known for OAuth app tokens; an API key belongs to the
// whole organization
@Get('/me')
@ -542,25 +411,6 @@ export class PublicIntegrationsController {
});
}
@Post('/credits/reset')
@UseGuards(SuperAdminGuard)
async resetCredits(
@GetOrgFromRequest() org: Organization,
@Body() body: ResetCreditsDto
) {
Sentry.metrics.count('public_api-request', 1);
const reset = await this._subscriptionService.resetCredits(
org.id,
body.type
);
if (!reset) {
throw new HttpException({ msg: 'No subscription found' }, 404);
}
return reset;
}
@Get('/notifications')
async getNotifications(
@GetOrgFromRequest() org: Organization,
@ -723,13 +573,7 @@ export class PublicIntegrationsController {
@Body('releaseId') releaseId: string
) {
Sentry.metrics.count('public_api-request', 1);
// the batch only links the posts in the dashboard
const { batchId, ...post } = await this._postsService.updateReleaseId(
org.id,
id,
releaseId
);
return post;
return this._postsService.updateReleaseId(org.id, id, releaseId);
}
@Get('/analytics/:integration')

View File

@ -0,0 +1,108 @@
import {
Body,
Controller,
Logger,
Post,
UseGuards,
Res,
ValidationPipe,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { Organization } from '@prisma/client';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
import { SuperAdminGuard } from '@gitroom/backend/services/auth/super.admin.guard';
import { PrivacyExportDto } from '@gitroom/nestjs-libraries/dtos/users/privacy.export.dto';
import { PrivacyExportService } from '@gitroom/nestjs-libraries/database/prisma/privacy/privacy.export.service';
class ExportReaderDisconnected extends Error {
constructor() {
super('Export reader disconnected');
}
}
@ApiTags('Privacy exports')
@Controller('/public/v1/privacy')
// Person exports are platform-wide and require the platform SuperAdminGuard.
@UseGuards(SuperAdminGuard)
export class PublicPrivacyController {
private readonly _logger = new Logger(PublicPrivacyController.name);
constructor(private _exports: PrivacyExportService) {}
@Post('/export')
async export(
@GetOrgFromRequest() org: Organization,
@Body(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
})
)
body: PrivacyExportDto,
@Res({ passthrough: true }) response: Response
) {
response.setHeader('Cache-Control', 'no-store');
return this._exports.export(org.id, body);
}
@Post('/export/stream')
async stream(
@GetOrgFromRequest() org: Organization,
@Body(
new ValidationPipe({
transform: true,
whitelist: true,
forbidNonWhitelisted: true,
})
)
body: PrivacyExportDto,
@Res() response: Response
) {
response.setHeader('Cache-Control', 'no-store');
response.setHeader('Content-Type', 'application/x-ndjson');
response.setHeader('X-Accel-Buffering', 'no');
try {
await this._exports.stream(org.id, body, async (line) => {
if (response.destroyed) throw new ExportReaderDisconnected();
if (response.write(line)) return;
await new Promise<void>((resolve, reject) => {
const cleanup = () => {
response.off('drain', drain);
response.off('close', close);
response.off('error', fail);
};
const drain = () => {
cleanup();
resolve();
};
const close = () => {
cleanup();
reject(new ExportReaderDisconnected());
};
const fail = (error: Error) => {
cleanup();
reject(error);
};
response.once('drain', drain);
response.once('close', close);
response.once('error', fail);
});
});
response.end();
} catch (error) {
if (response.headersSent) {
if (!(error instanceof ExportReaderDisconnected)) {
this._logger.error(
`Privacy export stream failed for ${body.target} ${body.targetId}`,
error
);
}
response.destroy();
return;
}
throw error;
}
}
}

View File

@ -43,7 +43,7 @@ export class AuthMiddleware implements NestMiddleware {
const payload = AuthService.verifyJWT(auth) as User | null;
const orgHeader = req.cookies.showorg || req.headers.showorg;
if (!payload?.id || typeof payload.id !== 'string') {
if (!payload?.id) {
throw new HttpForbiddenException();
}
@ -97,9 +97,7 @@ export class AuthMiddleware implements NestMiddleware {
await this._organizationService.getOrgsByUserId(user.id)
).filter((f) => !f.users[0].disabled);
const setOrg =
organization.find((org) => org.id === orgHeader) ||
organization.find((org) => org.subscription) ||
organization[0];
organization.find((org) => org.id === orgHeader) || organization[0];
if (!organization) {
throw new HttpForbiddenException();

View File

@ -1,179 +0,0 @@
// #2199: registering with a pending org invite link always created a brand
// new (junk) organization for the invited user - routeAuth() called
// createOrgAndUser() unconditionally, then only afterwards tried to also
// join the invite via addUserToOrg(). Even when the invite succeeded, the
// user ended up SUPERADMIN of a throwaway org with the invite as a bonus
// membership instead of the intended destination.
//
// This exercises the LOCAL-provider registration branch of routeAuth():
// a user registering with a valid invite in the `org` cookie should join
// the inviting organization without ever creating a new one, and should
// only fall back to a standalone org if the invite can no longer be
// redeemed (already used, or the org hit its seat limit).
process.env.JWT_SECRET = 'test-secret-for-routeauth-invite-spec';
// AuthService's constructor params pull in UsersService -> UsersRepository
// -> helpers/auth's AuthService, which needs the native bcrypt binding.
// emitDecoratorMetadata keeps that import live at runtime even though this
// spec only ever passes plain mocks for those constructor params, so stub
// it out the same way the integration.repository standalone spec stubs
// UploadFactory to dodge its own unrelated native/ESM-only dependency.
jest.mock('bcrypt', () => ({
hashSync: jest.fn(() => 'hashed'),
compareSync: jest.fn(() => true),
}));
// Same chain also drags in UploadFactory -> CloudflareStorage -> `file-type`,
// which is ESM-only and isn't transformable under this standalone Jest
// config (see integration.repository.standalone.spec.ts for precedent).
jest.mock('@gitroom/nestjs-libraries/upload/upload.factory', () => ({
UploadFactory: {
createStorage: () => ({ uploadSimple: jest.fn() }),
},
}));
// AuthService's `_emailService: EmailService` constructor param also keeps
// EmailService's real import alive (emitDecoratorMetadata), which pulls in
// the email provider implementations - unrelated code this spec never
// exercises (a mock EmailService is passed below) and that doesn't compile
// cleanly under this config's relaxed-but-not-identical tsconfig overrides.
jest.mock('@gitroom/nestjs-libraries/services/email.service', () => ({
EmailService: class {},
}));
import { AuthService } from './auth.service';
import { CreateOrgUserDto } from '@gitroom/nestjs-libraries/dtos/auth/create.org.user.dto';
import { Provider } from '@prisma/client';
describe('AuthService.routeAuth - registration with a pending org invite', () => {
function makeBody(): CreateOrgUserDto {
const body = new CreateOrgUserDto();
body.email = 'invited@example.com';
body.password = 'super-secret-password';
body.provider = Provider.LOCAL;
body.company = 'Whatever Inc';
body.datafast_visitor_id = '';
return body;
}
function makeService(overrides: {
addUserToOrgResult: any;
}) {
const createdUser = {
id: 'new-user-id',
email: 'invited@example.com',
password: 'hashed',
};
const organizationService = {
getCount: jest.fn().mockResolvedValue(1),
createOrgAndUser: jest.fn(),
createUser: jest.fn().mockResolvedValue(createdUser),
createOrgForExistingUser: jest.fn().mockResolvedValue({ id: 'fallback-org-id' }),
addUserToOrg: jest.fn().mockResolvedValue(overrides.addUserToOrgResult),
};
const userService = {
getUserByEmail: jest.fn().mockResolvedValue(null),
};
const emailService = {
sendEmailSync: jest.fn().mockResolvedValue(undefined),
hasProvider: jest.fn().mockReturnValue(false),
};
const service = new AuthService(
userService as any,
organizationService as any,
emailService as any,
{} as any
);
return { service, organizationService, userService, createdUser };
}
it('joins the inviting org and never creates a new organization when the invite is redeemable', async () => {
const { service, organizationService, createdUser } = makeService({
addUserToOrgResult: { id: 'membership-id', organizationId: 'inviting-org-id' },
});
const result = await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
{ orgId: 'inviting-org-id', role: 'USER', id: 'invite-id' }
);
expect(organizationService.createOrgAndUser).not.toHaveBeenCalled();
expect(organizationService.createUser).toHaveBeenCalledTimes(1);
expect(organizationService.addUserToOrg).toHaveBeenCalledWith(
createdUser.id,
'invite-id',
'inviting-org-id',
'USER'
);
expect(organizationService.createOrgForExistingUser).not.toHaveBeenCalled();
expect(result.addedOrg).toEqual({
id: 'membership-id',
organizationId: 'inviting-org-id',
});
});
it('falls back to a standalone org only when the invite can no longer be redeemed', async () => {
const { service, organizationService, createdUser } = makeService({
addUserToOrgResult: false,
});
await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
{ orgId: 'inviting-org-id', role: 'USER', id: 'invite-id' }
);
expect(organizationService.createOrgAndUser).not.toHaveBeenCalled();
expect(organizationService.createUser).toHaveBeenCalledTimes(1);
expect(organizationService.createOrgForExistingUser).toHaveBeenCalledWith(
createdUser.id,
'Whatever Inc'
);
});
it('still creates a normal organization when there is no invite', async () => {
const organizationService = {
getCount: jest.fn().mockResolvedValue(1),
createOrgAndUser: jest.fn().mockResolvedValue({
id: 'org-id',
users: [{ user: { id: 'owner-id', email: 'owner@example.com' } }],
}),
createUser: jest.fn(),
createOrgForExistingUser: jest.fn(),
addUserToOrg: jest.fn(),
};
const userService = { getUserByEmail: jest.fn().mockResolvedValue(null) };
const emailService = {
sendEmailSync: jest.fn().mockResolvedValue(undefined),
hasProvider: jest.fn().mockReturnValue(false),
};
const service = new AuthService(
userService as any,
organizationService as any,
emailService as any,
{} as any
);
const result = await service.routeAuth(
Provider.LOCAL,
makeBody(),
'127.0.0.1',
'test-agent',
undefined
);
expect(organizationService.createOrgAndUser).toHaveBeenCalledTimes(1);
expect(organizationService.createUser).not.toHaveBeenCalled();
expect(result.addedOrg).toBe(false);
});
});

View File

@ -54,50 +54,23 @@ export class AuthService {
throw new Error('Registration is disabled');
}
const invite =
addToOrg && typeof addToOrg !== 'boolean' ? addToOrg : undefined;
const create = await this._organizationService.createOrgAndUser(
body,
ip,
userAgent
);
let registeredUser: User;
let addedOrg: boolean | Awaited<
ReturnType<OrganizationService['addUserToOrg']>
> = false;
const addedOrg =
addToOrg && typeof addToOrg !== 'boolean'
? await this._organizationService.addUserToOrg(
create.users[0].user.id,
addToOrg.id,
addToOrg.orgId,
addToOrg.role
)
: false;
if (invite) {
// A pending invite joins the inviting organization directly,
// instead of always spinning up a new one for the registering
// user and only afterwards trying to also join the invite (#2199).
registeredUser = await this._organizationService.createUser(
body,
ip,
userAgent
);
addedOrg = await this._organizationService.addUserToOrg(
registeredUser.id,
invite.id,
invite.orgId,
invite.role
);
// The invite could be unusable by the time registration posts
// (already redeemed, or the org hit its seat limit) - fall back
// to a standalone org so the new account isn't left with none.
if (!addedOrg) {
await this._organizationService.createOrgForExistingUser(
registeredUser.id,
body.company
);
}
} else {
const create = await this._organizationService.createOrgAndUser(
body,
ip,
userAgent
);
registeredUser = create.users[0].user;
}
const obj = { addedOrg, jwt: await this.jwt(registeredUser) };
const obj = { addedOrg, jwt: await this.jwt(create.users[0].user) };
await this._emailService.sendEmailSync(
body.email,
'Activate your account',
@ -143,13 +116,7 @@ export class AuthService {
try {
const getOrg: any = AuthChecker.verifyJWT(cookie);
if (
typeof getOrg.orgId !== 'string' ||
typeof getOrg.id !== 'string' ||
!['USER', 'ADMIN'].includes(getOrg.role) ||
!getOrg.timeLimit ||
dayjs(getOrg.timeLimit).isBefore(dayjs())
) {
if (dayjs(getOrg.timeLimit).isBefore(dayjs())) {
return false;
}
@ -267,7 +234,7 @@ export class AuthService {
id: string;
expires: string;
};
if (typeof user.id !== 'string' || dayjs(user.expires).isBefore(dayjs())) {
if (dayjs(user.expires).isBefore(dayjs())) {
return false;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.buffer;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/buffer',
},
};
export default function CompareBufferPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.hootsuite;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/hootsuite',
},
};
export default function CompareHootsuitePage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.later;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/later',
},
};
export default function CompareLaterPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.metricool;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/metricool',
},
};
export default function CompareMetricoolPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.mixpost;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/mixpost',
},
};
export default function CompareMixpostPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.publer;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/publer',
},
};
export default function ComparePublerPage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,22 +0,0 @@
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
import { CompareLandingPage } from '@gitroom/frontend/components/compare/compare.page.component';
import {
compareCompetitors,
compareMetaDescription,
} from '@gitroom/frontend/components/compare/compare.data';
const brandName = isGeneralServerSide() ? 'Postiz' : 'Gitroom';
const data = compareCompetitors.socialbee;
export const metadata: Metadata = {
title: `${data.headline} | ${brandName}`,
description: compareMetaDescription(data, brandName),
alternates: {
canonical: '/compare/socialbee',
},
};
export default function CompareSocialbeePage() {
return <CompareLandingPage data={data} brandName={brandName} />;
}

View File

@ -1,8 +0,0 @@
import { ReactNode } from 'react';
// Public, unauthenticated route group for the /compare/* SEO landing pages.
// Deliberately does not use (site)/layout.tsx's LayoutComponent, which assumes
// a logged-in organization context and would redirect an anonymous visitor.
export default async function CompareLayout({ children }: { children: ReactNode }) {
return <>{children}</>;
}

View File

@ -52,7 +52,6 @@ export default async function Auth(
previewId={id}
postIds={post.map((p: any) => p.id)}
organizationId={post[0].organizationId}
postState={post[0].state}
>
<div className="mx-auto w-full max-w-[1346px] p-[12px] flex flex-col gap-[8px] text-newTextColor">
<div className="flex bg-newBgColorInner rounded-[12px] min-h-[80px] px-[20px] py-[12px] items-center gap-[20px] flex-wrap">

View File

@ -1,7 +1,11 @@
import { redirect } from 'next/navigation';
import { Plugs } from '@gitroom/frontend/components/plugs/plugs';
export const dynamic = 'force-dynamic';
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
export const metadata: Metadata = {
title: `${isGeneralServerSide() ? 'Postiz' : 'Gitroom'} Plugs`,
description: '',
};
export default async function Index() {
return redirect('/settings?tab=plugs');
return <Plugs />;
}

View File

@ -1,7 +1,14 @@
import { redirect } from 'next/navigation';
import { ThirdPartyComponent } from '@gitroom/frontend/components/third-parties/third-party.component';
export const dynamic = 'force-dynamic';
import { Metadata } from 'next';
import { isGeneralServerSide } from '@gitroom/helpers/utils/is.general.server.side';
export const metadata: Metadata = {
title: `${
isGeneralServerSide() ? 'Postiz Integrations' : 'Gitroom Integrations'
}`,
description: '',
};
export default async function Index() {
return redirect('/settings?tab=integrations');
return <ThirdPartyComponent />;
}

View File

@ -2,31 +2,12 @@
import { useSearchParams } from 'next/navigation';
import { FC, useCallback, useEffect } from 'react';
// Only an address on this app, so signing in can never send someone to
// another site or run a javascript: URL
const sameOriginUrl = (url: string | null) => {
if (!url) {
return null;
}
try {
const parsed = new URL(url);
return parsed.origin === window.location.origin &&
parsed.protocol === window.location.protocol
? parsed.toString()
: null;
} catch {
return null;
}
};
const ReturnUrlComponent: FC = () => {
const params = useSearchParams();
const url = params.get('returnUrl');
useEffect(() => {
const returnUrl = sameOriginUrl(url);
if (returnUrl) {
localStorage.setItem('returnUrl', returnUrl);
if (url?.indexOf?.('http')! > -1) {
localStorage.setItem('returnUrl', url!);
}
}, [url]);
return null;
@ -36,8 +17,7 @@ export const useReturnUrl = () => {
getAndClear: useCallback(() => {
const data = localStorage.getItem('returnUrl');
localStorage.removeItem('returnUrl');
// also on read: localStorage can hold a value saved before this check
return sameOriginUrl(data);
return data;
}, []),
};
};

View File

@ -6,7 +6,7 @@ import 'react-tooltip/dist/react-tooltip.css';
import '@copilotkit/react-ui/styles.css';
import LayoutContext from '@gitroom/frontend/components/layout/layout.context';
import { ReactNode } from 'react';
import { jakartaSans } from '@gitroom/frontend/fonts/plus-jakarta-sans/plus.jakarta.sans.font';
import { Plus_Jakarta_Sans } from 'next/font/google';
import PlausibleProvider from 'next-plausible';
import clsx from 'clsx';
import { VariableContextComponent } from '@gitroom/react/helpers/variable.context';
@ -25,6 +25,12 @@ import { HtmlComponent } from '@gitroom/frontend/components/layout/html.componen
import Script from 'next/script';
import { ChangeDirClient } from '@gitroom/frontend/components/new-layout/change.dir.client';
const jakartaSans = Plus_Jakarta_Sans({
weight: ['600', '500'],
style: ['normal', 'italic'],
subsets: ['latin'],
});
export default async function AppLayout({ children }: { children: ReactNode }) {
const cookieStore = await cookies();
const language = cookieStore.get(cookieName)?.value || fallbackLng;

View File

@ -4,11 +4,17 @@ import 'react-tooltip/dist/react-tooltip.css';
import '@copilotkit/react-ui/styles.css';
import LayoutContext from '@gitroom/frontend/components/layout/layout.context';
import { ReactNode } from 'react';
import { jakartaSans } from '@gitroom/frontend/fonts/plus-jakarta-sans/plus.jakarta.sans.font';
import { Plus_Jakarta_Sans } from 'next/font/google';
import clsx from 'clsx';
import { VariableContextComponent } from '@gitroom/react/helpers/variable.context';
import UtmSaver from '@gitroom/helpers/utils/utm.saver';
const jakartaSans = Plus_Jakarta_Sans({
weight: ['600', '500'],
style: ['normal', 'italic'],
subsets: ['latin'],
});
export default async function AppLayout({ children }: { children: ReactNode }) {
return (
<html>

View File

@ -6,11 +6,17 @@ import 'react-tooltip/dist/react-tooltip.css';
import '@copilotkit/react-ui/styles.css';
import LayoutContext from '@gitroom/frontend/components/layout/layout.context';
import { ReactNode } from 'react';
import { jakartaSans } from '@gitroom/frontend/fonts/plus-jakarta-sans/plus.jakarta.sans.font';
import { Plus_Jakarta_Sans } from 'next/font/google';
import clsx from 'clsx';
import { VariableContextComponent } from '@gitroom/react/helpers/variable.context';
import UtmSaver from '@gitroom/helpers/utils/utm.saver';
const jakartaSans = Plus_Jakarta_Sans({
weight: ['600', '500'],
style: ['normal', 'italic'],
subsets: ['latin'],
});
export default async function AppLayout({ children }: { children: ReactNode }) {
return (
<html>

View File

@ -526,10 +526,7 @@ div div .set-font-family {
.hideChatbase #chatbase-bubble-button,
.hideChatbase #chatbase-bubble-window,
.hideChatbase #chatbase-message-bubbles,
.bottomSheetOpen #chatbase-bubble-button,
.bottomSheetOpen #chatbase-bubble-window,
.bottomSheetOpen #chatbase-message-bubbles {
.hideChatbase #chatbase-message-bubbles {
display: none !important;
}

View File

@ -82,7 +82,7 @@ You can select the channels you want to use from the left menu.
You can see your previous conversations from the right menu.
You can also use me as an MCP Server, check Settings >> Agents
You can also use me as an MCP Server, check Settings >> Public API
`),
}}
UserMessage={Message}

View File

@ -60,11 +60,16 @@ export const ApprovedAppsComponent: FC = () => {
return (
<div className="flex flex-col gap-[20px]">
<div className="text-customColor18">
{t(
'apps_you_have_authorized',
'Applications you have authorized to access your Postiz account.'
)}
<div className="flex flex-col">
<h3 className="text-[20px]">
{t('approved_apps', 'Approved Apps')}
</h3>
<div className="text-customColor18 mt-[4px]">
{t(
'apps_you_have_authorized',
'Applications you have authorized to access your Postiz account.'
)}
</div>
</div>
<div className="bg-sixth border-fifth border rounded-[4px] p-[24px]">

View File

@ -1,430 +0,0 @@
'use client';
import React, { FC, useCallback, useMemo, useState } from 'react';
import useSWR from 'swr';
import dayjs from 'dayjs';
import clsx from 'clsx';
import { capitalize } from 'lodash';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Select } from '@gitroom/react/form/select';
interface Invoice {
id: string;
number: string | null;
tier: string | null;
period: string | null;
description: string | null;
amount: number;
currency: string;
created: number;
periodEnd: number;
status: 'paid' | 'pending' | 'failed' | 'void';
downloadUrl: string | null;
viewUrl: string | null;
}
const PAGE_SIZE = 10;
// invoices under $10 (trial starts, proration leftovers) are left out of the history
const MIN_AMOUNT = 1000;
const useInvoices = () => {
const fetch = useFetch();
return useSWR<Invoice[]>(
'/billing/invoices',
async () => {
const response = await fetch('/billing/invoices');
if (!response.ok) {
throw new Error('Failed to load invoices');
}
return response.json();
},
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
};
const formatAmount = (amount: number, currency: string) => {
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency.toUpperCase(),
});
return formatter.format(
amount / 10 ** (formatter.resolvedOptions().maximumFractionDigits ?? 2)
);
};
const formatDate = (unix: number | null) =>
unix
? dayjs
.utc(unix * 1000)
.local()
.format('D MMM, YYYY')
: '';
const ActionLink: FC<{
href: string;
label: string;
icon: React.ReactNode;
}> = ({ href, label, icon }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
aria-label={label}
data-tooltip-id="tooltip"
data-tooltip-content={label}
className="w-[36px] h-[36px] rounded-[8px] border border-newTableBorder flex items-center justify-center text-textItemBlur hover:text-newTextColor hover:bg-boxHover transition-colors"
>
{icon}
</a>
);
export const BillingHistory: FC = () => {
const t = useT();
const { data, isLoading, error } = useInvoices();
const [search, setSearch] = useState('');
const [status, setStatus] = useState('all');
const [visible, setVisible] = useState(PAGE_SIZE);
const statuses = useMemo(
() =>
({
paid: {
label: t('billing_status_paid', 'Paid'),
color: 'text-[#32D583]',
},
pending: {
label: t('billing_status_open', 'Pending'),
color: 'text-[#FFAC30]',
},
failed: {
label: t('billing_status_failed', 'Failed'),
color: 'text-[#F97066]',
},
void: {
label: t('billing_status_void', 'Void'),
color: 'text-textItemBlur',
},
} as Record<Invoice['status'], { label: string; color: string }>),
[t]
);
const rows = useMemo(
() =>
(data || [])
.filter((invoice) => invoice.amount >= MIN_AMOUNT)
.map((invoice) => ({
...invoice,
plan: invoice.tier
? capitalize(invoice.tier)
: invoice.description || t('billing_subscription', 'Subscription'),
periodLabel:
invoice.period === 'YEARLY'
? t('billing_yearly', 'Yearly')
: invoice.period === 'MONTHLY'
? t('billing_monthly', 'Monthly')
: '',
amountLabel: formatAmount(invoice.amount, invoice.currency),
purchaseDate: formatDate(invoice.created),
endDate: formatDate(invoice.periodEnd),
statusInfo: statuses[invoice.status] || statuses.void,
})),
[data, statuses, t]
);
const filtered = useMemo(() => {
const query = search.trim().toLowerCase();
return rows.filter(
(row) =>
(status === 'all' || row.status === status) &&
(!query ||
[
row.plan,
row.periodLabel,
row.number,
row.amountLabel,
row.purchaseDate,
row.endDate,
row.statusInfo.label,
].some((value) => value?.toLowerCase().includes(query)))
);
}, [rows, search, status]);
const exportCsv = useCallback(() => {
const escape = (value: string | null) =>
`"${(value || '').replace(/"/g, '""')}"`;
const lines = [
[
t('billing_plan', 'Plan'),
t('billing_amount', 'Amount'),
t('billing_purchase_date', 'Purchase Date'),
t('billing_end_date', 'End Date'),
t('billing_status', 'Status'),
t('billing_invoice', 'Invoice'),
],
...filtered.map((row) => [
[row.plan, row.periodLabel].filter((p) => p).join(' - '),
row.amountLabel,
row.purchaseDate,
row.endDate,
row.statusInfo.label,
row.viewUrl || row.downloadUrl || row.number,
]),
];
const url = URL.createObjectURL(
new Blob(
['\uFEFF' + lines.map((line) => line.map(escape).join(',')).join('\n')],
{ type: 'text/csv;charset=utf-8' }
)
);
const link = document.createElement('a');
link.href = url;
link.download = 'billing-history.csv';
document.body.appendChild(link);
link.click();
link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}, [filtered, t]);
const columns =
'grid grid-cols-[minmax(0,2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)_88px] gap-x-[16px] items-center px-[16px]';
if (isLoading || error || !rows.length) {
return null;
}
return (
<div className="flex flex-col gap-[20px] rounded-[12px] border border-newTableBorder bg-newBgColorInner shadow-previewShadow p-[24px] mobile:p-[16px]">
<div className="flex items-center gap-[12px] mobile:flex-col mobile:items-stretch">
<div className="flex-1 text-[20px] font-[600]">
{t('billing_history', 'Billing History')}
</div>
<div className="flex items-center gap-[8px] mobile:flex-wrap">
<div className="relative w-[240px] mobile:w-full">
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="absolute start-[12px] top-1/2 -translate-y-1/2 text-textItemBlur pointer-events-none"
>
<circle cx="11" cy="11" r="7" />
<path d="M20 20L16.5 16.5" />
</svg>
<input
type="text"
value={search}
onChange={(e) => {
setSearch(e.target.value);
setVisible(PAGE_SIZE);
}}
placeholder={t('billing_search', 'Search...')}
className="w-full h-[42px] ps-[38px] pe-[12px] rounded-[8px] bg-newBgColorInner border border-newTableBorder text-[14px] outline-none focus:border-[#612BD3]"
/>
</div>
<div className="mobile:flex-1">
<Select
label=""
name="status"
disableForm={true}
hideErrors={true}
value={status}
className="w-full"
onChange={(e) => {
setStatus(e.target.value);
setVisible(PAGE_SIZE);
}}
>
<option value="all">
{t('billing_all_statuses', 'All statuses')}
</option>
{Object.entries(statuses).map(([key, value]) => (
<option key={key} value={key}>
{value.label}
</option>
))}
</Select>
</div>
<button
type="button"
onClick={exportCsv}
disabled={!filtered.length}
className="h-[42px] px-[16px] rounded-[8px] border border-newTableBorder bg-newBgColorInner flex items-center gap-[8px] text-[14px] font-[500] hover:bg-boxHover transition-colors disabled:opacity-50 disabled:pointer-events-none"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="17 8 12 3 7 8" />
<line x1="12" y1="3" x2="12" y2="15" />
</svg>
{t('billing_export', 'Export')}
</button>
</div>
</div>
<div className="flex flex-col">
<div
className={clsx(
columns,
'h-[48px] rounded-[8px] border border-newTableBorder bg-newTableHeader text-[14px] text-newTableText mobile:hidden'
)}
>
<div>{t('billing_plan', 'Plan')}</div>
<div>{t('billing_amount', 'Amount')}</div>
<div>{t('billing_purchase_date', 'Purchase Date')}</div>
<div>{t('billing_end_date', 'End Date')}</div>
<div>{t('billing_status', 'Status')}</div>
<div>{t('billing_action', 'Action')}</div>
</div>
{!filtered.length ? (
<div className="flex flex-col items-center justify-center gap-[12px] py-[40px] px-[16px] text-center">
<div className="w-[48px] h-[48px] rounded-full bg-[#612bd3]/10 flex items-center justify-center text-[#612bd3]">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M4 3h16v18l-3-2-3 2-2-2-2 2-3-2-3 2V3z" />
<path d="M8 8h8M8 12h8M8 16h5" />
</svg>
</div>
<div className="text-[15px] text-newTableText">
{t(
'billing_no_matching_invoices',
'No invoices match your search'
)}
</div>
</div>
) : (
filtered.slice(0, visible).map((row) => (
<div
key={row.id}
className={clsx(
columns,
'min-h-[64px] py-[12px] border-b border-newTableBorder last:border-b-0 text-[14px] mobile:grid-cols-[minmax(0,1fr)_auto] mobile:gap-y-[6px] mobile:py-[14px] mobile:px-0'
)}
>
<div className="flex flex-col min-w-0 mobile:col-start-1 mobile:row-start-1">
<div className="text-[15px] font-[500] truncate">
{row.plan}
</div>
{(!!row.periodLabel || !!row.number) && (
<div className="text-[13px] text-textItemBlur truncate">
{[row.periodLabel, row.number].filter((p) => p).join(' · ')}
</div>
)}
</div>
<div className="font-[500] mobile:col-start-2 mobile:row-start-1 mobile:text-end">
{row.amountLabel}
</div>
<div className="mobile:col-start-1 mobile:row-start-2 mobile:text-[13px] mobile:text-textItemBlur">
<bdi>{row.purchaseDate}</bdi>
{!!row.endDate && (
<span className="hidden mobile:inline">
{' - '}
<bdi>{row.endDate}</bdi>
</span>
)}
</div>
<div className="mobile:hidden">
<bdi>{row.endDate}</bdi>
</div>
<div
className={clsx(
'flex items-center gap-[8px] font-[500] mobile:col-start-2 mobile:row-start-2 mobile:justify-end',
row.statusInfo.color
)}
>
<span className="w-[8px] h-[8px] rounded-full bg-current shrink-0" />
{row.statusInfo.label}
</div>
<div className="flex items-center gap-[8px] mobile:col-span-2 mobile:row-start-3">
{!row.downloadUrl ? (
<div className="w-[36px] mobile:hidden" />
) : (
<ActionLink
href={row.downloadUrl}
label={t('billing_download_invoice', 'Download invoice')}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 15 17 10" />
<line x1="12" y1="15" x2="12" y2="3" />
</svg>
}
/>
)}
{!!row.viewUrl && (
<ActionLink
href={row.viewUrl}
label={t('billing_view_invoice', 'View invoice')}
icon={
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z" />
<circle cx="12" cy="12" r="3" />
</svg>
}
/>
)}
</div>
</div>
))
)}
</div>
{filtered.length > visible && (
<button
type="button"
onClick={() => setVisible((current) => current + PAGE_SIZE)}
className="self-center h-[36px] px-[16px] rounded-[8px] text-[14px] font-[500] text-textItemBlur hover:text-newTextColor hover:bg-boxHover transition-colors"
>
{t('show_more', '+ Show more')}
</button>
)}
</div>
);
};

View File

@ -47,7 +47,7 @@ const EmbeddedBilling = dynamic(
);
export const FirstBillingComponent = () => {
const { stripeClient, billingEnabled } = useVariables();
const { stripeClient } = useVariables();
const user = useUser();
const dub = useDubClickId();
const [stripe, setStripe] = useState<null | Promise<Stripe>>(null);
@ -62,20 +62,10 @@ export const FirstBillingComponent = () => {
const [datafast_session_id] = useCookie('datafast_session_id', '');
useEffect(() => {
// loadStripe injects the js.stripe.com script tag (and its fingerprinting
// requests) as soon as it's called, independent of whether the key it's
// given is valid. Never call it unless billing is actually turned on for
// this deployment - self-hosters without Stripe configured must not have
// it loaded just because this component happened to mount.
if (!billingEnabled || !stripeClient) {
setStripeFailed(true);
return;
}
const stripePromise = loadStripe(stripeClient);
stripePromise.catch(() => setStripeFailed(true));
setStripe(stripePromise);
}, [billingEnabled, stripeClient]);
}, []);
const loadCheckout = useCallback(async () => {
return (
@ -344,7 +334,7 @@ type FeatureItem = {
prefix?: string | number;
};
export const useBillingFeatures = (tier: string) => {
export const BillingFeatures: FC<{ tier: string }> = ({ tier }) => {
const t = useT();
const features = useMemo(() => {
const currentPricing = pricing[tier];
@ -422,15 +412,6 @@ export const useBillingFeatures = (tier: string) => {
return translatedText;
};
return features.map((feature) => ({
key: feature.key,
label: renderFeature(feature),
}));
};
export const BillingFeatures: FC<{ tier: string }> = ({ tier }) => {
const features = useBillingFeatures(tier);
return (
<div className="grid grid-cols-2 mobile:grid-cols-1 gap-y-[8px] gap-x-[32px]">
{features.map((feature) => (
@ -449,7 +430,7 @@ export const BillingFeatures: FC<{ tier: string }> = ({ tier }) => {
/>
</svg>
</div>
<div>{feature.label}</div>
<div>{renderFeature(feature)}</div>
</div>
))}
</div>

View File

@ -1,5 +1,6 @@
'use client';
import { Slider } from '@gitroom/react/form/slider';
import React, { FC, useCallback, useEffect, useMemo, useState } from 'react';
import { Button } from '@gitroom/react/form/button';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
@ -10,12 +11,9 @@ import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { useToaster } from '@gitroom/react/toaster/toaster';
import dayjs from 'dayjs';
import clsx from 'clsx';
import { capitalize } from 'lodash';
import { pricing } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/pricing';
import { FAQComponent } from '@gitroom/frontend/components/billing/faq.component';
import { useBillingFeatures } from '@gitroom/frontend/components/billing/first.billing.component';
import { BillingHistory } from '@gitroom/frontend/components/billing/billing.history.component';
import useSWR, { useSWRConfig } from 'swr';
import { useSWRConfig } from 'swr';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
import { useRouter, useSearchParams } from 'next/navigation';
import { useVariables } from '@gitroom/react/helpers/variable.context';
@ -28,7 +26,6 @@ import { TrackEnum } from '@gitroom/nestjs-libraries/user/track.enum';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { FinishTrial } from '@gitroom/frontend/components/billing/finish.trial';
import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
import { timer } from '@gitroom/helpers/utils/timer';
import { useDubClickId } from '@gitroom/frontend/components/layout/dubAnalytics';
import { LogoutComponent } from '@gitroom/frontend/components/layout/logout.component';
@ -43,8 +40,10 @@ export const Prorate: FC<{
const { period, pack } = props;
const t = useT();
const fetch = useFetch();
const [price, setPrice] = useState<number | false>(false);
const [price, setPrice] = useState<number | false>(0);
const [loading, setLoading] = useState(false);
const calculatePrice = useDebouncedCallback(async () => {
setLoading(true);
setPrice(
(
await (
@ -58,327 +57,89 @@ export const Prorate: FC<{
).json()
).price
);
setLoading(false);
}, 500);
useEffect(() => {
setPrice(false);
calculatePrice();
}, [period, pack]);
// nothing is shown while the preview loads, the price is missing when it fails
if (typeof price !== 'number') {
if (loading) {
return (
<div className="pt-[12px]">
<ReactLoading type="spin" color="#fff" width={20} height={20} />
</div>
);
}
if (price === false) {
return null;
}
return (
<div className="animate-fadeIn">
{t('pay_today', 'Pay Today')} ${Math.max(price, 0).toFixed(2)}
<div className="text-[12px] flex pt-[12px]">
({t('pay_today', 'Pay Today')} ${(price < 0 ? 0 : price)?.toFixed(1)})
</div>
);
};
const creditTypes = ['ai_images', 'ai_videos', 'clipping_minutes'] as const;
const useLoadCredits = () => {
const fetch = useFetch();
return useCallback(
async (
type: (typeof creditTypes)[number]
): Promise<{ credits: number }> => {
const response = await fetch(`/copilot/credits?type=${type}`);
if (!response.ok) {
throw new Error('Failed to load credits');
}
return response.json();
},
[]
);
};
const useCredits = (type: (typeof creditTypes)[number]) => {
const loadCredits = useLoadCredits();
return useSWR<{ credits: number }>(
`/copilot/credits?type=${type}`,
() => loadCredits(type),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
};
const useRenewal = () => {
const fetch = useFetch();
return useSWR<{ renewsAt: number | null; trialing: boolean }>(
'/billing/renewal',
async () => {
const response = await fetch('/billing/renewal');
if (!response.ok) {
throw new Error('Failed to load renewal date');
}
return response.json();
},
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
}
);
};
const BillingCycle: FC<{
tier: string;
canceled: boolean;
export const Features: FC<{
pack: 'FREE' | 'STANDARD' | 'PRO';
}> = (props) => {
const { tier, canceled } = props;
const t = useT();
const { data: renewal } = useRenewal();
const { data: images } = useCredits('ai_images');
const { data: videos } = useCredits('ai_videos');
const { data: clipping } = useCredits('clipping_minutes');
const usage = [
{
label: t('billing_ai_images', 'AI images'),
total: pricing[tier]?.image_generation_count,
left: images?.credits,
},
{
label: t('billing_ai_videos', 'AI videos'),
total: pricing[tier]?.generate_videos,
left: videos?.credits,
},
{
label: t('billing_clipping_minutes', 'Clipping minutes'),
total: pricing[tier]?.clipping_minutes,
left: clipping?.credits,
},
].filter((p) => p.total);
const { pack } = props;
const features = useMemo(() => {
const currentPricing = pricing[pack];
const channelsOr = currentPricing.channel;
const list = [];
list.push(`${channelsOr} ${channelsOr === 1 ? 'channel' : 'channels'}`);
list.push(
`${
currentPricing.posts_per_month > 10000
? 'Unlimited'
: currentPricing.posts_per_month
} posts per month`
);
if (currentPricing.team_members) {
list.push(`Unlimited team members`);
}
if (currentPricing?.ai) {
list.push(`AI auto-complete`);
list.push(`AI copilots`);
list.push(`AI Autocomplete`);
}
list.push(`Advanced Picture Editor`);
if (currentPricing?.image_generator) {
list.push(
`${currentPricing?.image_generation_count} AI Images per month`
);
}
if (currentPricing?.generate_videos) {
list.push(`${currentPricing?.generate_videos} AI Videos per month`);
}
if (currentPricing?.clipping_minutes) {
list.push(
`${currentPricing?.clipping_minutes} minutes of AI video clipping per month`
);
}
return list;
}, [pack]);
return (
<div className="flex items-center gap-[16px] rounded-[12px] border border-newTableBorder bg-newBgColorInner shadow-previewShadow px-[24px] py-[20px] mobile:flex-col mobile:items-stretch mobile:p-[16px]">
<div className="w-[48px] h-[48px] rounded-full bg-[#612bd3]/10 text-[#612bd3] flex items-center justify-center shrink-0 mobile:hidden">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="3" y="4" width="18" height="18" rx="2" />
<path d="M16 2v4M8 2v4M3 10h18" />
</svg>
</div>
<div className="flex-1 flex flex-col gap-[4px]">
<div className="text-[16px] font-[600]">
{t('billing_cycle', 'Billing cycle')}
</div>
<div className="text-[14px] text-textItemBlur">
{!canceled && !!renewal?.renewsAt && (
<>
{renewal.trialing
? t(
'billing_trial_ends_on',
'Your free trial ends and your first payment is charged on'
)
: t('billing_renews_on', 'Your plan renews on')}{' '}
<bdi className="font-[600] text-newTextColor">
{newDayjs(renewal.renewsAt * 1000)
.local()
.format('D MMM, YYYY')}
</bdi>
{'. '}
</>
)}
{t(
'billing_ai_credits_reset_monthly',
'AI credits reset every month.'
)}
</div>
</div>
<div className="flex gap-[8px] mobile:flex-col">
{usage.map((p) => (
<div
key={p.label}
className="flex flex-col gap-[2px] min-w-[120px] rounded-[8px] border border-newTableBorder px-[16px] py-[10px]"
>
<div className="text-[12px] text-textItemBlur">{p.label}</div>
<div className="text-[16px] font-[600]">
{typeof p.left === 'number' ? Math.max(p.left, 0) : '-'}
<span className="text-[14px] font-[400] text-textItemBlur">
{' / '}
{p.total}
</span>
</div>
</div>
))}
</div>
</div>
);
};
type PlanAction = {
label: string;
onClick?: () => void;
disabled?: boolean;
variant: 'primary' | 'simple' | 'current' | 'danger';
};
const planButton = {
primary: 'bg-btnPrimary text-white hover:bg-[#5023b8]',
simple: 'bg-btnSimple text-btnText hover:opacity-80',
current: 'bg-newBgLineColor text-textItemBlur',
danger: 'bg-red-500 text-white hover:bg-red-600',
};
const PlanCard: FC<{
name: string;
price: number;
yearly: boolean;
current: boolean;
action: PlanAction;
loading: boolean;
disabled: boolean;
note?: React.ReactNode;
}> = (props) => {
const { name, price, yearly, current, action, loading, disabled, note } =
props;
const t = useT();
const features = useBillingFeatures(name);
return (
<div
className={clsx(
'relative flex flex-col gap-[20px] rounded-[12px] border p-[24px] mobile:p-[20px]',
current
? 'border-transparent bg-gradient-to-b from-seventh to-btnPrimary text-white shadow-lg shadow-purple-500/25'
: 'border-newTableBorder bg-newBgColorInner shadow-previewShadow'
)}
>
{[
'top-[10px] start-[10px]',
'top-[10px] end-[10px]',
'bottom-[10px] start-[10px]',
'bottom-[10px] end-[10px]',
].map((position) => (
<span
key={position}
className={clsx(
'absolute w-[8px] h-[8px] rounded-full border pointer-events-none',
position,
current
? 'border-white/25 bg-white/10'
: 'border-newTableBorder bg-newBgColor'
)}
/>
))}
<div className="flex items-center justify-between gap-[8px] min-h-[26px]">
<div className="text-[18px] font-[600]">{capitalize(name)}</div>
{current && (
<div className="flex items-center gap-[6px] h-[26px] px-[10px] rounded-full bg-white/15 text-[12px] font-[600] uppercase whitespace-nowrap">
<span className="w-[6px] h-[6px] rounded-full bg-[#32D583]" />
{t('active', 'Active')}
</div>
)}
</div>
<div className="flex items-baseline gap-[6px]">
<div className="text-[40px] leading-[48px] font-[600] tracking-tight">
${price}
</div>
<div
className={clsx(
'text-[14px]',
current ? 'text-white/70' : 'text-textItemBlur'
)}
>
{yearly
? t('billing_per_year', '/ year')
: t('billing_per_month', '/ month')}
</div>
</div>
<div className="relative flex flex-col mb-[8px]">
<button
type="button"
onClick={action.onClick}
disabled={disabled}
className={clsx(
'h-[44px] px-[16px] rounded-[8px] text-[15px] font-[600] flex items-center justify-center transition-all',
current
? action.variant === 'current'
? 'bg-white/15 text-white'
: 'bg-white text-btnPrimary hover:bg-white/90'
: planButton[action.variant],
disabled ? 'cursor-default' : 'cursor-pointer',
disabled && action.variant !== 'current' && 'opacity-50'
)}
>
{loading ? (
<ReactLoading
type="spin"
color="currentColor"
width={18}
height={18}
/>
) : (
action.label
)}
</button>
{!!note && (
<div
className={clsx(
'absolute top-full inset-x-0 h-[28px] flex items-center justify-center text-[12px]',
current ? 'text-white/70' : 'text-textItemBlur'
)}
>
{note}
</div>
)}
</div>
<div
className={clsx(
'h-[1px]',
current ? 'bg-white/15' : 'bg-newTableBorder'
)}
/>
<div className="flex flex-col gap-[12px] text-[14px] leading-[20px]">
{features.map((feature) => (
<div
key={feature.key}
className={clsx(
'flex gap-[10px]',
current ? 'text-white' : 'text-newTextColor/90'
)}
>
<div className="flex flex-col gap-[10px] justify-center text-[16px] text-customColor18">
{features.map((feature) => (
<div key={feature} className="flex gap-[20px]">
<div>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 20 20"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
className={clsx(
'shrink-0',
current ? 'text-white/75' : 'text-[#8b5cf6]'
)}
>
<circle
cx="10"
cy="10"
r="7.75"
stroke="currentColor"
strokeWidth="1.5"
/>
<path
d="M7 10.25L9 12.25L13 8.25"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
d="M16.2806 9.21937C16.3504 9.28903 16.4057 9.37175 16.4434 9.46279C16.4812 9.55384 16.5006 9.65144 16.5006 9.75C16.5006 9.84856 16.4812 9.94616 16.4434 10.0372C16.4057 10.1283 16.3504 10.211 16.2806 10.2806L11.0306 15.5306C10.961 15.6004 10.8783 15.6557 10.7872 15.6934C10.6962 15.7312 10.5986 15.7506 10.5 15.7506C10.4014 15.7506 10.3038 15.7312 10.2128 15.6934C10.1218 15.6557 10.039 15.6004 9.96938 15.5306L7.71938 13.2806C7.57865 13.1399 7.49959 12.949 7.49959 12.75C7.49959 12.551 7.57865 12.3601 7.71938 12.2194C7.86011 12.0786 8.05098 11.9996 8.25 11.9996C8.44903 11.9996 8.6399 12.0786 8.78063 12.2194L10.5 13.9397L15.2194 9.21937C15.289 9.14964 15.3718 9.09432 15.4628 9.05658C15.5538 9.01884 15.6514 8.99941 15.75 8.99941C15.8486 8.99941 15.9462 9.01884 16.0372 9.05658C16.1283 9.09432 16.211 9.14964 16.2806 9.21937ZM21.75 12C21.75 13.9284 21.1782 15.8134 20.1068 17.4168C19.0355 19.0202 17.5127 20.2699 15.7312 21.0078C13.9496 21.7458 11.9892 21.9389 10.0979 21.5627C8.20656 21.1865 6.46928 20.2579 5.10571 18.8943C3.74215 17.5307 2.81355 15.7934 2.43735 13.9021C2.06114 12.0108 2.25422 10.0504 2.99218 8.26884C3.73013 6.48726 4.97982 4.96451 6.58319 3.89317C8.18657 2.82183 10.0716 2.25 12 2.25C14.585 2.25273 17.0634 3.28084 18.8913 5.10872C20.7192 6.93661 21.7473 9.41498 21.75 12ZM20.25 12C20.25 10.3683 19.7661 8.77325 18.8596 7.41655C17.9531 6.05984 16.6646 5.00242 15.1571 4.37799C13.6497 3.75357 11.9909 3.59019 10.3905 3.90852C8.79017 4.22685 7.32016 5.01259 6.16637 6.16637C5.01259 7.32015 4.22685 8.79016 3.90853 10.3905C3.5902 11.9908 3.75358 13.6496 4.378 15.1571C5.00242 16.6646 6.05984 17.9531 7.41655 18.8596C8.77326 19.7661 10.3683 20.25 12 20.25C14.1873 20.2475 16.2843 19.3775 17.8309 17.8309C19.3775 16.2843 20.2475 14.1873 20.25 12Z"
fill="#06ff00"
/>
</svg>
<div>{feature.label}</div>
</div>
))}
</div>
<div className="text-start">{feature}</div>
</div>
))}
</div>
);
};
@ -476,12 +237,10 @@ export const MainBillingComponent: FC<{
!!queryParams.get('finishTrial')
);
const [subscription, setSubscription] = useState<
SubscriptionWithPlatform | undefined
>(sub);
const [subscription, setSubscription] = useState<SubscriptionWithPlatform | undefined>(
sub
);
const [loading, setLoading] = useState<boolean>(false);
// which button started the request, so only that one shows a spinner
const [clicked, setClicked] = useState('');
const [period, setPeriod] = useState<'MONTHLY' | 'YEARLY'>(
subscription?.period || 'MONTHLY'
);
@ -503,34 +262,6 @@ export const MainBillingComponent: FC<{
}
setSubscription(sub);
}, [sub]);
const loadCredits = useLoadCredits();
// credits follow the plan stored by the Stripe webhook: wait for it, then
// show the new plan's totals and credits together
const showConfirmedPlan = useCallback(
async (billing: string, period: string, attempt = 0) => {
try {
const current = await (await fetch('/user/subscription')).json();
if (
current?.subscription?.subscriptionTier !== billing ||
current?.subscription?.period !== period
) {
if (attempt < 9) {
await timer(1000);
return showConfirmedPlan(billing, period, attempt + 1);
}
return;
}
const credits = await Promise.all(creditTypes.map(loadCredits));
creditTypes.forEach((type, index) =>
mutate(`/copilot/credits?type=${type}`, credits[index], {
revalidate: false,
})
);
mutate('/user/subscription', current, { revalidate: false });
} catch (err) {}
},
[]
);
const updatePayment = useCallback(async () => {
const { portal } = await (await fetch('/billing/portal')).json();
window.location.href = portal;
@ -582,23 +313,9 @@ export const MainBillingComponent: FC<{
!pricing[billing].team_members &&
pricing[subscription?.subscriptionTier!]?.team_members
) {
let hasMembers = true;
try {
const team = await (await fetch('/settings/team')).json();
hasMembers =
!Array.isArray(team?.users) ||
team.users.some(
(member: { user: { id: string } }) =>
member.user.id !== user?.id
);
} catch (err: any) {
// keep the warning when the team cannot be loaded
}
if (hasMembers) {
messages.push(
`Your team members will be disabled and lose access to your organization until you upgrade to a plan that includes team members again`
);
}
messages.push(
`Your team members will be removed from your organization`
);
}
if (billing === 'FREE') {
if (
@ -607,8 +324,7 @@ export const MainBillingComponent: FC<{
`Are you sure you want to cancel your subscription?
${messages.join(', ')}`,
'Yes, cancel',
'Cancel Subscription',
'No, keep it'
'Cancel Subscription'
))
) {
const checkDiscount = await (
@ -739,12 +455,6 @@ export const MainBillingComponent: FC<{
revalidate: false,
}
);
mutate('/billing/invoices');
mutate('/billing/renewal');
showConfirmedPlan(
billing,
monthlyOrYearly === 'on' ? 'YEARLY' : 'MONTHLY'
);
toast.show('Subscription updated successfully');
}
setLoading(false);
@ -779,226 +489,142 @@ export const MainBillingComponent: FC<{
</div>
);
}
const yearly = monthlyOrYearly === 'on';
const tiers = Object.keys(pricing);
const currentTier = subscription?.subscriptionTier || 'FREE';
const plans = tiers.filter((name) => !isGeneral || name !== 'FREE');
const planAction = (name: string): PlanAction => {
if (currentPackage === name && subscription?.cancelAt) {
return {
label: t('reactivate_subscription', 'Reactivate subscription'),
onClick: moveToCheckout('FREE', true),
variant: 'primary',
};
}
if (currentPackage === name) {
return {
label: t('billing_current_plan', 'Current Plan'),
disabled: true,
variant: 'current',
};
}
if (name === 'FREE') {
return {
label: subscription?.cancelAt
? t('billing_downgrade_on', 'Downgrade on {{date}}', {
date: dayjs
.utc(subscription.cancelAt)
.local()
.format('D MMM, YYYY'),
})
: t('cancel_subscription_1', 'Cancel subscription'),
onClick: moveToCheckout('FREE'),
disabled: !!subscription?.cancelAt,
variant: 'danger',
};
}
const direction = tiers.indexOf(name) - tiers.indexOf(currentTier);
return {
label: !subscription
? user?.tier?.current === 'FREE' && user.allowTrial
? t('start_7_days_free_trial', 'Start 7 days free trial')
: t('billing_purchase', 'Purchase')
: direction > 0
? t('billing_upgrade', 'Upgrade')
: direction < 0
? t('billing_downgrade', 'Downgrade')
: yearly
? t('billing_switch_to_yearly', 'Switch to yearly')
: t('billing_switch_to_monthly', 'Switch to monthly'),
onClick: moveToCheckout(name as 'STANDARD' | 'PRO'),
variant: !!subscription && direction < 0 ? 'simple' : 'primary',
};
};
return (
<div className="flex flex-col gap-[24px]">
{finishTrial && <FinishTrial close={() => setFinishTrial(false)} />}
<div className="flex items-center gap-[16px] mobile:flex-col mobile:items-stretch">
<div className="flex-1 flex flex-col gap-[4px]">
<div className="text-[20px] font-[600]">
{t('billing_and_subscription', 'Billing & Subscription')}
</div>
<div className="text-[14px] text-textItemBlur">
{t(
'billing_and_subscription_description',
'Keep track of your subscription, update your payment method and download your invoices'
)}
</div>
</div>
<div className="flex p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500] select-none">
<div
onClick={() => setMonthlyOrYearly('off')}
className={clsx(
'h-[34px] px-[16px] rounded-[6px] flex items-center justify-center mobile:flex-1',
!yearly ? 'bg-boxFocused text-textItemFocused' : 'cursor-pointer'
)}
>
{t('billing_monthly', 'Monthly')}
</div>
<div
onClick={() => setMonthlyOrYearly('on')}
className={clsx(
'h-[34px] px-[16px] rounded-[6px] flex items-center justify-center gap-[8px] mobile:flex-1',
yearly ? 'bg-boxFocused text-textItemFocused' : 'cursor-pointer'
)}
>
{t('billing_yearly', 'Yearly')}
<div className="bg-[#AA0FA4] text-white text-[12px] px-[6px] rounded-[4px]">
{t('billing_20_percent_off', '20% Off')}
</div>
</div>
</div>
</div>
{subscription?.cancelAt && isGeneral && (
<div className="flex items-center gap-[12px] rounded-[12px] border border-[#FFAC30]/30 bg-[#FFAC30]/10 px-[16px] py-[12px] text-[14px]">
<div className="w-[8px] h-[8px] rounded-full bg-[#FFAC30] shrink-0" />
<div className="flex flex-col gap-[16px]">
<div className="flex flex-row">
<div className="flex-1 text-[20px]">{t('plans', 'Plans')}</div>
<div className="flex items-center gap-[16px]">
<div>{t('monthly', 'MONTHLY')}</div>
<div>
{t(
'your_subscription_will_be_canceled_at',
'Your subscription will be canceled at'
)}{' '}
<bdi className="font-[600]">
{newDayjs(subscription.cancelAt).local().format('D MMM, YYYY')}
</bdi>
{'. '}
{t(
'you_will_never_be_charged_again',
'You will never be charged again'
)}
<Slider value={monthlyOrYearly} onChange={setMonthlyOrYearly} />
</div>
<div>{t('yearly', 'YEARLY')}</div>
</div>
)}
<div
className={clsx(
'grid gap-[16px] tablet:grid-cols-2 mobile:!grid-cols-1',
plans.length > 4 ? 'grid-cols-5' : 'grid-cols-4'
)}
>
{plans.map((name) => {
const action = planAction(name);
return (
<PlanCard
</div>
{finishTrial && <FinishTrial close={() => setFinishTrial(false)} />}
<div className="flex gap-[16px] [@media(max-width:1024px)]:flex-col [@media(max-width:1024px)]:text-center">
{Object.entries(pricing)
.filter((f) => !isGeneral || f[0] !== 'FREE')
.map(([name, values]) => (
<div
key={name}
name={name}
price={
yearly ? pricing[name].year_price : pricing[name].month_price
}
yearly={yearly}
current={currentPackage === name}
action={{
...action,
onClick: () => {
setClicked(name);
action.onClick?.();
},
}}
loading={loading && clicked === name}
disabled={!!action.disabled || loading}
note={
!!subscription &&
currentPackage !== name &&
name !== 'FREE' && (
<Prorate
period={yearly ? 'YEARLY' : 'MONTHLY'}
pack={name as 'STANDARD' | 'PRO'}
/>
)
}
/>
);
})}
className="flex-1 bg-sixth border border-customColor6 rounded-[4px] p-[24px] gap-[16px] flex flex-col [@media(max-width:1024px)]:items-center"
>
<div className="text-[18px]">{name}</div>
<div className="text-[38px] flex gap-[2px] items-center">
<div>
$
{monthlyOrYearly === 'on'
? values.year_price
: values.month_price}
</div>
<div className={`text-[14px] text-customColor18`}>
{monthlyOrYearly === 'on' ? '/year' : '/month'}
</div>
</div>
<div className="text-[14px] flex gap-[10px]">
{currentPackage === name.toUpperCase() &&
subscription?.cancelAt ? (
<div className="gap-[3px] flex flex-col">
<div>
<Button
onClick={moveToCheckout('FREE', true)}
loading={loading}
>
{t(
'reactivate_subscription',
'Reactivate subscription'
)}
</Button>
</div>
</div>
) : (
<Button
loading={loading}
disabled={
(!!subscription?.cancelAt &&
name.toUpperCase() === 'FREE') ||
currentPackage === name.toUpperCase()
}
className={clsx(
subscription &&
name.toUpperCase() === 'FREE' &&
'!bg-red-500'
)}
onClick={moveToCheckout(
name.toUpperCase() as 'STANDARD' | 'PRO'
)}
>
{currentPackage === name.toUpperCase()
? 'Current Plan'
: name.toUpperCase() === 'FREE'
? subscription?.cancelAt
? `Downgrade on ${dayjs
.utc(subscription?.cancelAt)
.local()
.format('D MMM, YYYY')}`
: 'Cancel subscription'
: // @ts-ignore
(user?.tier === 'FREE' ||
user?.tier?.current === 'FREE') &&
user.allowTrial
? t('start_7_days_free_trial', 'Start 7 days free trial')
: 'Purchase'}
</Button>
)}
{subscription &&
currentPackage !== name.toUpperCase() &&
name !== 'FREE' &&
!!name && (
<Prorate
period={monthlyOrYearly === 'on' ? 'YEARLY' : 'MONTHLY'}
pack={name.toUpperCase() as 'STANDARD' | 'PRO'}
/>
)}
</div>
<Features
pack={name.toUpperCase() as 'FREE' | 'STANDARD' | 'PRO'}
/>
</div>
))}
</div>
{!!subscription?.id && (
<BillingCycle
tier={sub?.subscriptionTier || subscription.subscriptionTier}
canceled={!!subscription.cancelAt}
/>
)}
{!!subscription?.id && (
<div className="flex items-center gap-[16px] rounded-[12px] border border-newTableBorder bg-newBgColorInner shadow-previewShadow px-[24px] py-[20px] mobile:flex-col mobile:items-stretch mobile:p-[16px]">
<div className="w-[48px] h-[48px] rounded-full bg-[#612bd3]/10 text-[#612bd3] flex items-center justify-center shrink-0 mobile:hidden">
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<rect x="2" y="5" width="20" height="14" rx="2" />
<path d="M2 10h20M6 15h4" />
</svg>
</div>
<div className="flex-1 flex flex-col gap-[4px]">
<div className="text-[16px] font-[600]">
{t('billing_payment_method', 'Payment method')}
</div>
<div className="text-[14px] text-textItemBlur">
{t(
'billing_payment_method_description',
'Update your card, billing address and tax details in the secure billing portal'
)}
</div>
</div>
<div className="flex items-center gap-[8px] mobile:flex-col-reverse mobile:items-stretch">
{isGeneral && !subscription?.cancelAt && (
<button
type="button"
disabled={loading}
onClick={() => {
setClicked('CANCEL');
moveToCheckout('FREE')();
}}
className="h-[44px] px-[16px] rounded-[8px] border border-red-500/40 text-red-500 text-[14px] font-[500] flex items-center justify-center hover:bg-red-500/10 transition-colors disabled:opacity-50"
>
{loading && clicked === 'CANCEL' ? (
<ReactLoading
type="spin"
color="currentColor"
width={18}
height={18}
/>
) : (
t('cancel_subscription_1', 'Cancel subscription')
)}
</button>
<div className="flex justify-center mt-[20px] gap-[10px] mobile:flex-col">
<Button
onClick={updatePayment}
className="mobile:h-auto mobile:min-h-[40px] mobile:py-[8px] mobile:text-center"
>
{t(
'update_payment_method_invoices_history',
'Update Payment Method / Invoices History'
)}
<button
type="button"
onClick={updatePayment}
className="h-[44px] px-[16px] rounded-[8px] bg-btnSimple text-btnText text-[14px] font-[500] hover:opacity-80 transition-opacity"
</Button>
{isGeneral && !subscription?.cancelAt && (
<Button
className="bg-red-500"
loading={loading}
onClick={moveToCheckout('FREE')}
>
{t('billing_update_payment_method', 'Update payment method')}
</button>
</div>
{t('cancel_subscription_1', 'Cancel subscription')}
</Button>
)}
</div>
)}
{subscription?.cancelAt && isGeneral && (
<div className="text-center">
{t(
'your_subscription_will_be_canceled_at',
'Your subscription will be canceled at'
)}{' '}
{newDayjs(subscription.cancelAt).local().format('D MMM, YYYY')}
<br />
{t(
'you_will_never_be_charged_again',
'You will never be charged again'
)}
</div>
)}
{!!subscription?.id && <BillingHistory />}
<FAQComponent />
<div className="flex justify-center mt-[20px]">
<LogoutComponent />

View File

@ -1,534 +0,0 @@
// Content for the /compare/* landing pages.
// Every number here is sourced from libraries/nestjs-libraries/src/database/prisma/subscriptions/pricing.ts
// (Postiz side) and the competitor's own public pricing page (checked 2026-10-23).
// Do not invent a number here - if a competitor changes price, update the value and the "asOf" field.
export interface ComparePricingRow {
label: string;
postiz: string;
competitor: string;
}
export interface CompareChecklistRow {
label: string;
postiz: boolean;
competitor: boolean;
}
export interface CompareFaqItem {
question: string;
answer: string;
}
export interface CompareCompetitor {
slug: string;
name: string;
domain: string;
asOf: string;
headline: string;
subheadline: string;
summary: string;
pricingRows: ComparePricingRow[];
structuralChecklist: CompareChecklistRow[];
featureChecklist: CompareChecklistRow[];
verdict: string;
faq: CompareFaqItem[];
}
const structuralChecklistTemplate = (competitorName: string): CompareChecklistRow[] => [
{
label: 'Open-source and self-hostable',
postiz: true,
competitor: false,
},
{
label: 'Managed cloud option at indie-friendly pricing',
postiz: true,
competitor: competitorName !== 'Mixpost',
},
{
label: 'Public API + npm SDK + CLI + browser extension',
postiz: true,
competitor: false,
},
{
label: 'Native MCP server (Claude/ChatGPT/Codex agents can post directly)',
postiz: true,
competitor: false,
},
];
export const compareCompetitors: Record<string, CompareCompetitor> = {
buffer: {
slug: 'buffer',
name: 'Buffer',
domain: 'buffer.com',
asOf: '2026-10-23',
headline: 'Postiz vs Buffer',
subheadline:
"Buffer's per-channel price, plus the public API, MCP server, and AI agent Buffer doesn't ship at any price.",
summary:
'Buffer Essentials charges per channel with no AI drafting, no public API, and no self-host option. Postiz STANDARD is a flat $29/mo for 5 channels ($5.80/channel) and already includes AI post generation, a public API, and 60 minutes/month of video clipping.',
pricingRows: [
{
label: 'Entry plan price',
postiz: '$29/mo flat (STANDARD)',
competitor: '$5/channel/mo (Essentials)',
},
{
label: 'Channels included at entry price',
postiz: '5 channels ($5.80/channel effective)',
competitor: 'Priced per channel, no bundle discount',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent + live web research)',
competitor: 'Not available',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not offered',
},
{
label: 'Self-hosting option',
postiz: 'AGPL self-host, same features as cloud',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Buffer'),
featureChecklist: [
{
label: 'Video-to-clips scheduler (long video → scheduled short clips)',
postiz: true,
competitor: false,
},
{
label: 'Team seats included',
postiz: true,
competitor: false,
},
{
label: 'Webhooks for workflow automation',
postiz: true,
competitor: false,
},
],
verdict:
"If you're comparing per-channel pricing, Buffer looks cheaper on paper for a single channel. The moment you need a second channel, an API, or AI drafting, Postiz's flat $29/mo covers all of it where Buffer charges more and still can't match the feature set.",
faq: [
{
question: 'Is Postiz actually cheaper than Buffer?',
answer:
'At 5 channels, Postiz STANDARD is $29/mo total ($5.80/channel) versus Buffer Essentials at $5/channel with no bundle discount and no AI, API, or self-host option included at any price.',
},
{
question: 'Can I self-host Postiz instead of using the cloud version?',
answer:
'Yes. Postiz is AGPL-licensed and open-source; the self-hosted version has the exact same feature set as Postiz Cloud, which Buffer does not offer in any form.',
},
{
question: 'Does Buffer have an MCP server or AI agent?',
answer:
"No. Buffer has no public MCP server and no built-in AI agent. Postiz ships both: a native MCP server so Claude, ChatGPT, or Codex agents can schedule posts directly, and a LangGraph-based agent that does live web research before drafting.",
},
],
},
hootsuite: {
slug: 'hootsuite',
name: 'Hootsuite',
domain: 'hootsuite.com',
asOf: '2026-10-23',
headline: 'Postiz vs Hootsuite',
subheadline:
'The same 10-channel, 3-seat, approval-workflow shape Hootsuite prices at $1,197/mo - Postiz TEAM ships it for $39/mo flat.',
summary:
'Hootsuite overcharges for the exact workflow small teams need: multiple channels, team seats, and approval before publish. Postiz TEAM bundles 10 channels, team members, and autopost for $39/mo - a fraction of Hootsuite Advanced plus 3 seats.',
pricingRows: [
{
label: 'Plan matching 10 channels + team + approval',
postiz: '$39/mo flat (TEAM)',
competitor: '$1,197/mo (Advanced + 3 seats)',
},
{
label: 'Team members included',
postiz: 'Included at $39/mo',
competitor: 'Extra seats billed on top of Advanced',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent + live web research)',
competitor: 'Add-on on higher tiers',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Enterprise tier only',
},
],
structuralChecklist: structuralChecklistTemplate('Hootsuite'),
featureChecklist: [
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
{
label: 'Flat pricing, no per-seat surcharge at this tier',
postiz: true,
competitor: false,
},
{
label: 'Self-host option for data residency',
postiz: true,
competitor: false,
},
],
verdict:
"Hootsuite's enterprise pricing model charges per-seat on top of a high base plan. For a 3-person team managing 10 channels with approval, that's $1,197/mo on Hootsuite versus $39/mo flat on Postiz TEAM - a gap large enough to fund the rest of your marketing stack.",
faq: [
{
question: 'Why is Hootsuite so much more expensive for the same features?',
answer:
"Hootsuite's Advanced plan plus 3 seats runs approximately $1,197/mo for team + approval workflows on ~10 channels. Postiz TEAM covers the same 10-channel, team-member, approval-adjacent shape for $39/mo flat.",
},
{
question: 'Does Postiz TEAM really include team members at $39/mo?',
answer:
'Yes - team_members is enabled starting at the TEAM tier ($39/mo) in the live pricing config, alongside 10 channels and autopost.',
},
{
question: 'Can I migrate from Hootsuite to Postiz?',
answer:
'Postiz supports 36+ social providers and a public API/SDK for scripted migration of scheduled content; most teams reconnect channels directly via OAuth and rebuild their queue from the calendar view.',
},
],
},
later: {
slug: 'later',
name: 'Later',
domain: 'later.com',
asOf: '2026-10-23',
headline: 'Postiz vs Later',
subheadline: 'Every channel Later has, plus full X (Twitter), Threads, Bluesky, and 20+ more.',
summary:
"Later is built around Instagram-grid-style visual planning but has no X (Twitter) support at all. Postiz covers Later's channels plus X, Threads, Bluesky, Mastodon, LinkedIn, and 20+ more from a single calendar.",
pricingRows: [
{
label: 'X (Twitter) support',
postiz: 'Full support, included',
competitor: 'Not supported',
},
{
label: 'Entry plan price',
postiz: '$29/mo flat (STANDARD, 5 channels)',
competitor: 'Per-plan, channel-limited',
},
{
label: 'AI post drafting',
postiz: 'Included (LangGraph agent)',
competitor: 'Limited AI caption assist',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not offered on consumer plans',
},
],
structuralChecklist: structuralChecklistTemplate('Later'),
featureChecklist: [
{
label: 'X (Twitter) posting',
postiz: true,
competitor: false,
},
{
label: 'Threads and Bluesky posting',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
],
verdict:
"If your channel mix includes X, Threads, or Bluesky, Later structurally can't cover it. Postiz schedules every channel Later supports plus the ones it doesn't, from the same calendar and composer.",
faq: [
{
question: 'Does Later support posting to X (Twitter)?',
answer:
'No, Later does not support X (Twitter) at all. Postiz supports X alongside Threads, Bluesky, and 30+ other channels from one composer.',
},
{
question: 'Is Postiz as good for Instagram-grid planning as Later?',
answer:
"Postiz's calendar and media library cover the same visual scheduling workflow for Instagram, plus the channels Later can't reach.",
},
],
},
socialbee: {
slug: 'socialbee',
name: 'SocialBee',
domain: 'socialbee.com',
asOf: '2026-10-23',
headline: 'Postiz vs SocialBee',
subheadline: 'Team seats at $39/mo, not SocialBee\'s $99/mo Pro gate.',
summary:
"SocialBee requires its $99/mo Pro plan before a single extra team member can be added. Postiz TEAM includes team members, 10 channels, and autopost for $39/mo - a $60/mo gap for the same capability.",
pricingRows: [
{
label: 'Cheapest plan with team members',
postiz: '$39/mo (TEAM)',
competitor: '$99/mo (Pro)',
},
{
label: 'Content recycling / evergreen queue',
postiz: 'Category-based queue rotation',
competitor: 'Category-based queue rotation (SocialBee original)',
},
{
label: 'Public API access',
postiz: 'Included from $29/mo',
competitor: 'Not publicly documented',
},
{
label: 'Self-hosting option',
postiz: 'AGPL self-host available',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('SocialBee'),
featureChecklist: [
{
label: 'Team seats at the cheapest multi-channel tier',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
{
label: 'Native MCP server',
postiz: true,
competitor: false,
},
],
verdict:
"SocialBee pioneered evergreen content recycling, and Postiz matches that category-based rotation - while undercutting SocialBee by $60/mo on the cheapest plan that includes a second team seat.",
faq: [
{
question: 'Does Postiz have content recycling like SocialBee?',
answer:
"Yes - Postiz supports a recycle-after-days, category-based queue rotation for evergreen content, the same workflow SocialBee popularized.",
},
{
question: 'How much cheaper is Postiz for a 2-person team?',
answer:
"Postiz TEAM at $39/mo includes team members. SocialBee requires its $99/mo Pro plan for the same capability - a $60/mo difference.",
},
],
},
metricool: {
slug: 'metricool',
name: 'Metricool',
domain: 'metricool.com',
asOf: '2026-10-23',
headline: 'Postiz vs Metricool',
subheadline: 'Every channel, every tier, no platform tax.',
summary:
"Metricool is strong on analytics and competitor tracking, but Postiz matches scheduling depth while never gating a specific platform like X or LinkedIn behind a higher tier - channel count is the only paid gate, not platform identity.",
pricingRows: [
{
label: 'Platform-based feature gating',
postiz: 'None - channel count is the only gate',
competitor: 'Some advanced analytics gated by plan',
},
{
label: 'Entry plan price',
postiz: '$29/mo flat (5 channels)',
competitor: 'Tiered by channel + feature',
},
{
label: 'Built-in AI drafting agent',
postiz: 'Included (LangGraph + live web research)',
competitor: 'Not a core feature',
},
{
label: 'Video-to-clips scheduler',
postiz: 'Included (Deepgram transcription)',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Metricool'),
featureChecklist: [
{
label: 'No per-platform feature tax',
postiz: true,
competitor: false,
},
{
label: 'Bundled AI agent with web research',
postiz: true,
competitor: false,
},
{
label: 'Self-host option',
postiz: true,
competitor: false,
},
],
verdict:
"Metricool's analytics and competitor tracking are genuinely strong - Postiz answers with the same scheduling coverage, an AI agent Metricool doesn't have, and a pricing model that never charges extra for which platform you post to.",
faq: [
{
question: 'Does Postiz have competitor tracking like Metricool?',
answer:
"Postiz tracks competitor handles per organization using each provider's public analytics endpoints, with scheduled snapshots and a comparison chart in the analytics view.",
},
{
question: 'Does Postiz charge more for X or LinkedIn specifically?',
answer:
'No. Every tier in the live pricing config gates on channel count only, never on which specific platform you connect.',
},
],
},
publer: {
slug: 'publer',
name: 'Publer',
domain: 'publer.io',
asOf: '2026-10-23',
headline: 'Postiz vs Publer',
subheadline: "The self-host, SDK, CLI, and MCP server Publer structurally can't ship.",
summary:
"Publer is a solid closed-source SaaS scheduler, but it has no self-host option, no npm SDK, no CLI, and no native MCP server. Postiz ships all four, on top of the same multi-channel scheduling Publer offers.",
pricingRows: [
{
label: 'Self-hosting option',
postiz: 'AGPL self-host, full feature parity with cloud',
competitor: 'Not offered - cloud SaaS only',
},
{
label: 'Official npm SDK (@postiz/node)',
postiz: 'Published, documented',
competitor: 'Not offered',
},
{
label: 'CLI tool',
postiz: 'apps/commands CLI',
competitor: 'Not offered',
},
{
label: 'Native MCP server for AI agents',
postiz: 'Built-in (start.mcp.ts)',
competitor: 'Not offered',
},
],
structuralChecklist: structuralChecklistTemplate('Publer'),
featureChecklist: [
{
label: 'Runs your own MCP server',
postiz: true,
competitor: false,
},
{
label: 'Browser extension for quick scheduling',
postiz: true,
competitor: false,
},
{
label: 'Video-to-clips scheduler',
postiz: true,
competitor: false,
},
],
verdict:
"Publer covers day-to-day scheduling well, but anything programmatic - a script, an agent, a CI pipeline, a self-hosted deployment - hits a wall Publer was never built to support. Postiz was.",
faq: [
{
question: 'Can I run Postiz with Claude, ChatGPT, or another AI agent?',
answer:
'Yes - Postiz runs a native MCP server (start.mcp.ts) so AI agents can schedule and manage posts directly. Publer has no equivalent.',
},
{
question: 'Does Publer offer a self-hosted version?',
answer:
'No, Publer is cloud-only. Postiz is AGPL-licensed and can be self-hosted with the same feature set as Postiz Cloud.',
},
],
},
mixpost: {
slug: 'mixpost',
name: 'Mixpost',
domain: 'mixpost.app',
asOf: '2026-10-23',
headline: 'Postiz vs Mixpost',
subheadline:
"The other self-hosted option - won on recurring feature velocity a perpetual license can't match.",
summary:
"Mixpost is the closest direct competitor: open-source and self-hostable. But its Pro tier is a $299 one-time license with an MCP integration and no bundled LLM agent or video-clipping pipeline. Postiz ships a LangGraph agent with live web research, inline DALL-E image generation, and a Temporal-orchestrated video-to-clips pipeline with Deepgram transcription - all included, continuously shipped.",
pricingRows: [
{
label: 'License model',
postiz: 'Open-core, AGPL self-host + managed cloud',
competitor: '$299 one-time perpetual license (Pro)',
},
{
label: 'Bundled LLM agent with live web research',
postiz: 'Included (LangGraph + Tavily)',
competitor: 'Not offered',
},
{
label: 'Video-to-clips pipeline (Deepgram transcription)',
postiz: 'Included',
competitor: 'Not offered',
},
{
label: 'MCP integration',
postiz: 'Native MCP server',
competitor: 'Available on Pro tier',
},
],
structuralChecklist: structuralChecklistTemplate('Mixpost'),
featureChecklist: [
{
label: 'Turn one long video into scheduled clips across every channel',
postiz: true,
competitor: false,
},
{
label: 'Inline AI image generation (DALL-E)',
postiz: true,
competitor: false,
},
{
label: 'Continuously shipped features (no perpetual-license lock)',
postiz: true,
competitor: false,
},
],
verdict:
"Mixpost earned its spot as the self-hosted alternative to SaaS schedulers, and its one-time license is attractive on cost alone. But a perpetual license means a frozen feature set - Postiz's agent graph and video-clipping pipeline are both already-shipped features no competitor in this category, Mixpost included, currently matches.",
faq: [
{
question: 'Is Postiz also open-source and self-hostable like Mixpost?',
answer:
'Yes. Postiz is AGPL-licensed and self-hostable with the exact same feature set as Postiz Cloud - the open-core model gates nothing between the two.',
},
{
question: "What can't Mixpost do that Postiz can?",
answer:
"Mixpost's Pro tier has an MCP integration but no bundled LLM agent graph with live web research, no inline AI image generation, and no video-clipping pipeline. Postiz ships all three today.",
},
],
},
};
export type CompareSlug = keyof typeof compareCompetitors;
export const compareMetaDescription = (data: CompareCompetitor, brandName: string): string =>
`${brandName} vs ${data.name}: ${data.subheadline} Compare pricing, features, and self-hosting options.`;

View File

@ -1,215 +0,0 @@
import Link from 'next/link';
import type { CompareCompetitor } from '@gitroom/frontend/components/compare/compare.data';
const CheckIcon = () => (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
aria-hidden="true"
className="shrink-0"
>
<path
d="M13.5 4.5L6 12L2.5 8.5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
const CrossIcon = () => (
<svg
width="16"
height="16"
viewBox="0 0 16 16"
fill="none"
aria-hidden="true"
className="shrink-0"
>
<path
d="M3.5 3.5L12.5 12.5M12.5 3.5L3.5 12.5"
stroke="currentColor"
strokeWidth="1.75"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
const ChecklistMark = ({ value }: { value: boolean }) => (
<span
className={value ? 'text-customColor28' : 'text-customColor18'}
aria-label={value ? 'Yes' : 'No'}
>
{value ? <CheckIcon /> : <CrossIcon />}
</span>
);
interface CompareLandingPageProps {
data: CompareCompetitor;
brandName: string;
}
export const CompareLandingPage = ({ data, brandName }: CompareLandingPageProps) => {
return (
<div className="bg-newBgColor min-h-screen text-newTextColor">
<header className="border-b border-newBorder px-[24px] py-[20px] flex items-center justify-between max-w-[1040px] mx-auto">
<Link href="/" className="text-[18px] font-semibold tracking-tight">
{brandName}
</Link>
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[18px] h-[38px] rounded-[6px] flex items-center justify-center text-[14px] font-medium"
>
Start free
</Link>
</header>
<main className="max-w-[1040px] mx-auto px-[24px] py-[56px] flex flex-col gap-[64px]">
{/* Hero */}
<section className="flex flex-col gap-[16px] text-center max-w-[760px] mx-auto">
<h1 className="text-[40px] leading-[1.1] font-semibold tracking-tight">
{data.headline}
</h1>
<p className="text-[20px] opacity-80">{data.subheadline}</p>
<p className="text-[15px] opacity-60 leading-[1.6]">{data.summary}</p>
<div className="flex items-center justify-center gap-[12px] mt-[8px]">
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[24px] h-[44px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Try Postiz free
</Link>
<a
href={`https://${data.domain}`}
target="_blank"
rel="nofollow noopener noreferrer"
className="bg-btnSimple text-btnText px-[24px] h-[44px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Visit {data.name} ↗
</a>
</div>
</section>
{/* Structural moat checklist */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">
What {data.name} structurally can&apos;t match
</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
<div className="grid grid-cols-[1fr,120px,120px] bg-newBgColorInner text-[13px] opacity-60 px-[20px] py-[12px]">
<div>Capability</div>
<div className="text-center">Postiz</div>
<div className="text-center">{data.name}</div>
</div>
{data.structuralChecklist.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,120px,120px] px-[20px] py-[14px] text-[14px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div>{row.label}</div>
<div className="flex justify-center">
<ChecklistMark value={row.postiz} />
</div>
<div className="flex justify-center">
<ChecklistMark value={row.competitor} />
</div>
</div>
))}
</div>
</section>
{/* Pricing comparison */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Pricing, side by side</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
<div className="grid grid-cols-[1fr,1fr,1fr] bg-newBgColorInner text-[13px] opacity-60 px-[20px] py-[12px]">
<div></div>
<div className="text-center font-medium">Postiz</div>
<div className="text-center font-medium">{data.name}</div>
</div>
{data.pricingRows.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,1fr,1fr] px-[20px] py-[14px] text-[14px] gap-[8px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div className="opacity-70">{row.label}</div>
<div className="text-center font-medium">{row.postiz}</div>
<div className="text-center opacity-80">{row.competitor}</div>
</div>
))}
</div>
<p className="text-[12px] opacity-50 text-center">
Pricing checked against {data.domain} and Postiz&apos;s live pricing config as of{' '}
{data.asOf}. Competitor pricing may change - verify on their site before purchase.
</p>
</section>
{/* Feature checklist */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Feature checklist</h2>
<div className="border border-newBorder rounded-[8px] overflow-hidden">
{data.featureChecklist.map((row, index) => (
<div
key={row.label}
className={`grid grid-cols-[1fr,120px,120px] px-[20px] py-[14px] text-[14px] ${
index % 2 === 1 ? 'bg-newBgColorInner' : ''
}`}
>
<div>{row.label}</div>
<div className="flex justify-center">
<ChecklistMark value={row.postiz} />
</div>
<div className="flex justify-center">
<ChecklistMark value={row.competitor} />
</div>
</div>
))}
</div>
</section>
{/* Verdict */}
<section className="flex flex-col gap-[16px] bg-newBgColorInner border border-newBorder rounded-[8px] p-[32px]">
<h2 className="text-[20px] font-semibold">The verdict</h2>
<p className="text-[15px] opacity-80 leading-[1.6]">{data.verdict}</p>
</section>
{/* FAQ */}
<section className="flex flex-col gap-[20px]">
<h2 className="text-[24px] font-semibold text-center">Frequently asked questions</h2>
<div className="flex flex-col gap-[16px]">
{data.faq.map((item) => (
<div
key={item.question}
className="border border-newBorder rounded-[8px] p-[20px]"
>
<div className="text-[15px] font-medium mb-[8px]">{item.question}</div>
<div className="text-[14px] opacity-70 leading-[1.6]">{item.answer}</div>
</div>
))}
</div>
</section>
{/* Bottom CTA */}
<section className="flex flex-col items-center gap-[16px] text-center">
<h2 className="text-[24px] font-semibold">
Switch from {data.name} to {brandName}
</h2>
<Link
href="/auth"
className="bg-btnPrimary text-btnText px-[28px] h-[46px] rounded-[6px] flex items-center justify-center text-[15px] font-medium"
>
Start free, no credit card
</Link>
</section>
</main>
</div>
);
};

View File

@ -488,14 +488,13 @@ export const AddProviderComponent: FC<{
if (response.status === 402) {
return;
}
const { url, err, message } = await response.json();
const { url, err } = await response.json();
if (err) {
toaster.show(
message ||
t(
'could_not_connect_to_platform',
'Could not connect to the platform'
),
t(
'could_not_connect_to_platform',
'Could not connect to the platform'
),
'warning'
);
return;

View File

@ -1,55 +0,0 @@
'use client';
import { useCallback } from 'react';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useCalendar } from '@gitroom/frontend/components/launches/calendar.context';
import { BulkScheduleModal } from '@gitroom/frontend/components/launches/bulk-schedule/bulk.schedule.modal';
export const BulkScheduleButton = () => {
const t = useT();
const modal = useModals();
const { integrations, reloadCalendarView } = useCalendar();
const open = useCallback(() => {
modal.openModal({
title: t('bulk_schedule_title', 'Bulk schedule from CSV'),
withCloseButton: true,
classNames: {
modal: 'text-textColor',
},
children: (close: () => void) => (
<BulkScheduleModal
integrations={integrations}
close={close}
mutate={reloadCalendarView}
/>
),
});
}, [integrations]);
return (
<div
className="h-[44px] w-[44px] group-[.sidebar]:w-full bg-btnSimple text-btnText justify-center items-center flex rounded-[8px] cursor-pointer"
onClick={open}
data-tooltip-id="tooltip"
data-tooltip-content={t('bulk_schedule_title', 'Bulk schedule from CSV')}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={1.8}
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<path d="M14 2v6h6" />
<path d="M9 15h6M9 11h6M9 19h3" />
</svg>
</div>
);
};

View File

@ -1,75 +0,0 @@
import { parseBulkScheduleCsv, rowsToBulkSchedule } from './bulk.schedule.modal';
describe('parseBulkScheduleCsv', () => {
it('parses a simple header + rows CSV', () => {
const csv = 'date,content\n2026-11-01 09:00,Hello world\n2026-11-02 09:00,Second post';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'Hello world'],
['2026-11-02 09:00', 'Second post'],
]);
});
it('handles quoted fields with embedded commas and escaped quotes', () => {
const csv = 'date,content\n2026-11-01 09:00,"Hello, ""world"""';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'Hello, "world"'],
]);
});
it('handles CRLF line endings', () => {
const csv = 'date,content\r\n2026-11-01 09:00,One\r\n2026-11-02 09:00,Two';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'One'],
['2026-11-02 09:00', 'Two'],
]);
});
it('skips blank lines', () => {
const csv = 'date,content\n\n2026-11-01 09:00,One\n\n';
expect(parseBulkScheduleCsv(csv)).toEqual([
['date', 'content'],
['2026-11-01 09:00', 'One'],
]);
});
});
describe('rowsToBulkSchedule', () => {
it('drops a recognized date,content header row', () => {
const rows = [
['date', 'content'],
['2026-11-01T09:00:00Z', 'Hello'],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed).toHaveLength(1);
expect(parsed[0].error).toBeUndefined();
expect(parsed[0].content).toBe('Hello');
});
it('treats every row as data when there is no header', () => {
const rows = [['2026-11-01T09:00:00Z', 'Hello']];
const parsed = rowsToBulkSchedule(rows);
expect(parsed).toHaveLength(1);
expect(parsed[0].error).toBeUndefined();
});
it('flags a row with an invalid date', () => {
const rows = [
['date', 'content'],
['not-a-date', 'Hello'],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed[0].error).toMatch(/date/i);
});
it('flags a row with no content', () => {
const rows = [
['date', 'content'],
['2026-11-01T09:00:00Z', ''],
];
const parsed = rowsToBulkSchedule(rows);
expect(parsed[0].error).toMatch(/content/i);
});
});

View File

@ -1,317 +0,0 @@
'use client';
import { FC, useCallback, useMemo, useState } from 'react';
import dayjs from 'dayjs';
import clsx from 'clsx';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Button } from '@gitroom/react/form/button';
import { Integrations } from '@gitroom/frontend/components/launches/calendar.context';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
// Bulk CSV scheduling only ever had a bare date/content row to work with (no
// media, no per-provider settings), so it only supports the platforms that
// don't need extra settings beyond their identifier. The actual list isn't
// hardcoded here — it's fetched from GET /posts/bulk-schedule/supported-providers,
// which returns the same generic, data-driven simpleTextProviders() the
// backend enforces in bulkSchedule(), so this never drifts out of sync.
const useBulkScheduleSupportedProviders = () => {
const fetch = useFetch();
const load = useCallback(async () => {
return (
await (await fetch('/posts/bulk-schedule/supported-providers')).json()
).providers as string[];
}, []);
return useSWR<string[]>('/posts/bulk-schedule/supported-providers', load, {
revalidateOnFocus: false,
fallbackData: [],
});
};
export interface ParsedBulkRow {
line: number;
date: string;
content: string;
error?: string;
}
// A tiny RFC4180-ish CSV parser: two columns (date, content), quoted fields
// may contain commas/newlines, "" inside a quoted field is a literal quote.
// Good enough for the simple two-column sheet this feature asks for, not a
// general-purpose CSV library.
export const parseBulkScheduleCsv = (csv: string): string[][] => {
const rows: string[][] = [];
let row: string[] = [];
let field = '';
let inQuotes = false;
for (let i = 0; i < csv.length; i++) {
const char = csv[i];
const next = csv[i + 1];
if (inQuotes) {
if (char === '"' && next === '"') {
field += '"';
i++;
} else if (char === '"') {
inQuotes = false;
} else {
field += char;
}
continue;
}
if (char === '"') {
inQuotes = true;
} else if (char === ',') {
row.push(field);
field = '';
} else if (char === '\n' || char === '\r') {
if (char === '\r' && next === '\n') {
i++;
}
row.push(field);
field = '';
rows.push(row);
row = [];
} else {
field += char;
}
}
if (field.length || row.length) {
row.push(field);
rows.push(row);
}
return rows.filter((r) => r.some((cell) => cell.trim().length));
};
export const rowsToBulkSchedule = (rows: string[][]): ParsedBulkRow[] => {
const dataRows =
rows.length &&
rows[0][0]?.trim().toLowerCase() === 'date' &&
rows[0][1]?.trim().toLowerCase() === 'content'
? rows.slice(1)
: rows;
return dataRows.map((cols, index) => {
const date = (cols[0] || '').trim();
const content = (cols[1] || '').trim();
const line = index + 1;
if (!date || !dayjs(date).isValid()) {
return { line, date, content, error: 'Invalid or missing date' };
}
if (!content) {
return { line, date, content, error: 'Missing content' };
}
return { line, date: dayjs(date).toISOString(), content };
});
};
interface BulkScheduleResult {
row: number;
success: boolean;
postId?: string;
error?: string;
}
export const BulkScheduleModal: FC<{
integrations: Integrations[];
close: () => void;
mutate: () => void;
}> = ({ integrations, close, mutate }) => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const { data: supportedProviders, isLoading: loadingProviders } =
useBulkScheduleSupportedProviders();
const [integrationId, setIntegrationId] = useState('');
const [csvText, setCsvText] = useState('');
const [submitting, setSubmitting] = useState(false);
const [results, setResults] = useState<BulkScheduleResult[] | null>(null);
const supportedIntegrations = useMemo(
() =>
integrations.filter(
(integration) =>
!integration.disabled &&
(supportedProviders || []).includes(integration.identifier)
),
[integrations, supportedProviders]
);
const parsedRows = useMemo(() => {
if (!csvText.trim()) {
return [];
}
return rowsToBulkSchedule(parseBulkScheduleCsv(csvText));
}, [csvText]);
const validRows = useMemo(
() => parsedRows.filter((row) => !row.error),
[parsedRows]
);
const submit = useCallback(async () => {
if (!integrationId || !validRows.length) {
return;
}
setSubmitting(true);
setResults(null);
try {
const response = await fetch('/posts/bulk-schedule', {
method: 'POST',
body: JSON.stringify({
integration: { id: integrationId },
posts: validRows.map((row) => ({
date: row.date,
content: row.content,
})),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toaster.show(
body?.message ||
t('bulk_schedule_failed', 'Could not schedule these posts'),
'warning'
);
return;
}
const data: BulkScheduleResult[] = await response.json();
setResults(data);
const succeeded = data.filter((r) => r.success).length;
if (succeeded) {
toaster.show(
t('bulk_schedule_success', '{{count}} posts scheduled', {
count: succeeded,
}),
'success'
);
mutate();
}
} finally {
setSubmitting(false);
}
}, [integrationId, validRows, mutate]);
if (loadingProviders) {
return <LoadingComponent />;
}
return (
<div className="flex flex-col gap-[16px] min-w-[560px] max-w-[640px]">
<div className="text-[13px] text-textItemBlur">
{t(
'bulk_schedule_hint',
'Paste a CSV with "date" and "content" columns (one post per row) to schedule many posts at once. Only works for channels that don\'t need extra settings: {{providers}}.',
{ providers: (supportedProviders || []).join(', ') }
)}
</div>
<div className="flex flex-col gap-[6px]">
<div className="text-[13px] font-[600]">
{t('bulk_schedule_channel', 'Channel')}
</div>
{supportedIntegrations.length === 0 ? (
<div className="text-[13px] text-red-400">
{t(
'bulk_schedule_no_channels',
'Connect one of these channels first: {{providers}}.',
{ providers: (supportedProviders || []).join(', ') }
)}
</div>
) : (
<div className="flex flex-col gap-[6px]">
{supportedIntegrations.map((integration) => (
<div
key={integration.id}
onClick={() => setIntegrationId(integration.id)}
className={clsx(
'flex items-center gap-[10px] p-[10px] rounded-[8px] border cursor-pointer transition-all',
integrationId === integration.id
? 'border-forth bg-forth/10'
: 'border-tableBorder hover:border-textColor/30'
)}
>
<img
src={integration.picture || '/no-picture.jpg'}
className="w-[24px] h-[24px] rounded-[6px]"
alt={integration.name}
/>
<div className="text-[13px]">{integration.name}</div>
</div>
))}
</div>
)}
</div>
<textarea
className="w-full h-[180px] p-[12px] rounded-[8px] bg-input border border-tableBorder text-textColor font-mono text-[13px] resize-y"
placeholder={
'date,content\n2026-11-01 09:00,First post\n2026-11-02 09:00,Second post'
}
value={csvText}
onChange={(e) => setCsvText(e.target.value)}
/>
{!!parsedRows.length && (
<div className="flex flex-col gap-[4px] max-h-[160px] overflow-y-auto text-[12px]">
{parsedRows.map((row) => (
<div
key={row.line}
className={clsx(
'flex gap-[8px]',
row.error ? 'text-red-400' : 'text-textItemBlur'
)}
>
<div className="w-[16px]">{row.line}.</div>
<div className="flex-1 truncate">
{row.error || `${row.date} — ${row.content}`}
</div>
</div>
))}
</div>
)}
{!!results && (
<div className="flex flex-col gap-[4px] max-h-[160px] overflow-y-auto text-[12px]">
{results.map((r) => (
<div
key={r.row}
className={r.success ? 'text-green-400' : 'text-red-400'}
>
{t('row', 'Row')} {r.row + 1}:{' '}
{r.success
? t('scheduled', 'Scheduled')
: r.error || t('failed', 'Failed')}
</div>
))}
</div>
)}
<div className="flex justify-end gap-[10px]">
<Button type="button" secondary={true} onClick={close}>
{t('cancel', 'Cancel')}
</Button>
<Button
onClick={submit}
loading={submitting}
disabled={!integrationId || !validRows.length}
>
{t('bulk_schedule_submit', 'Schedule {{count}} posts', {
count: validRows.length,
})}
</Button>
</div>
</div>
);
};

View File

@ -88,7 +88,6 @@ export const CalendarContext = createContext({
setSelectedChannels: (channels: string[] | null) => {
/** empty **/
},
currentHour: newDayjs().startOf('hour'),
});
export interface Integrations {
@ -143,23 +142,6 @@ function getDateRange(display: string, referenceDate?: string) {
}
}
// The current time rounded down to the unit. It checks on every minute, so it
// also catches up within a minute after the computer wakes up from sleep.
export const useNow = (unit: 'minute' | 'hour' = 'minute') => {
const [now, setNow] = useState(() => newDayjs().startOf(unit).valueOf());
useEffect(() => {
let timeout: NodeJS.Timeout;
const tick = () => {
// same number = no re-render, so the hour clock only renders once an hour
setNow(newDayjs().startOf(unit).valueOf());
timeout = setTimeout(tick, 60000 - (Date.now() % 60000));
};
tick();
return () => clearTimeout(timeout);
}, [unit]);
return useMemo(() => newDayjs(now), [now]);
};
export const CalendarWeekProvider: FC<{
children: ReactNode;
integrations: Integrations[];
@ -385,9 +367,6 @@ export const CalendarWeekProvider: FC<{
// Determine loading state based on current view
const loading = filters.display === 'list' ? listIsLoading : calendarIsLoading;
// one clock for every calendar cell, instead of a timer per cell
const currentHour = useNow('hour');
return (
<CalendarContext.Provider
value={{
@ -411,7 +390,6 @@ export const CalendarWeekProvider: FC<{
setListState,
selectedChannels,
setSelectedChannels,
currentHour,
}}
>
{children}

View File

@ -5,6 +5,7 @@ import React, {
Fragment,
memo,
useCallback,
useEffect,
useMemo,
useState,
} from 'react';
@ -12,7 +13,6 @@ import {
CalendarContext,
Integrations,
useCalendar,
useNow,
} from '@gitroom/frontend/components/launches/calendar.context';
import dayjs from 'dayjs';
import 'dayjs/locale/en';
@ -38,16 +38,15 @@ import { useDrag, useDrop } from 'react-dnd';
import { Integration, Post, State, Tags } from '@prisma/client';
import { useAddProvider } from '@gitroom/frontend/components/launches/add.provider.component';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { timer } from '@gitroom/helpers/utils/timer';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
import isSameOrAfter from 'dayjs/plugin/isSameOrAfter';
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore';
import { groupBy, sortBy } from 'lodash';
import { groupBy, random, sortBy } from 'lodash';
import SafeImage from '@gitroom/react/helpers/safe.image';
import { extend } from 'dayjs';
import { isUSCitizen } from './helpers/isuscitizen.utils';
import { useInterval } from '@mantine/hooks';
import { StatisticsModal } from '@gitroom/frontend/components/launches/statistics';
import { EvergreenModal } from '@gitroom/frontend/components/launches/evergreen.modal';
import { MissingReleaseModal } from '@gitroom/frontend/components/launches/missing-release.modal';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import i18next from 'i18next';
@ -59,7 +58,6 @@ import copy from 'copy-to-clipboard';
import { stripHtmlValidation } from '@gitroom/helpers/utils/strip.html.validation';
import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
import { Button } from '@gitroom/react/form/button';
import { ChevronUpIcon } from '@gitroom/frontend/components/ui/icons';
// Extend dayjs with necessary plugins
extend(isSameOrAfter);
@ -95,75 +93,6 @@ export const hours = Array.from(
(_, i) => i
);
// The current time badge at the start of the now line
const NowTime: FC<{ time: string }> = ({ time }) => (
<div className="rounded-[6px] bg-newTableTextFocused px-[6px] text-[12px] leading-[20px] font-[500] text-black whitespace-nowrap">
{time}
</div>
);
// Current time line across the week. It ticks on its own so the grid doesn't
// re-render every minute. An absolute grid child is placed inside the grid area
// it names, here the current hour row (after the header row).
const WeekNowLine: FC<{ days: dayjs.Dayjs[] }> = ({ days }) => {
const now = useNow();
const todayIndex = days.findIndex((day) => day.isSame(now, 'day'));
if (todayIndex === -1) {
return null;
}
const gridRow = `${now.hour() + 2} / ${now.hour() + 3}`;
const top = `${(now.minute() / 60) * 100}%`;
return (
<>
{/* covers this hour's label with the calendar background, the time takes its place */}
<div
className="absolute inset-0 bg-newBgColorInner pointer-events-none"
style={{ gridColumn: '1 / 2', gridRow }}
>
<div className="absolute end-0 -translate-y-1/2" style={{ top }}>
{/* same format as the hour labels */}
<NowTime time={now.format(isUSCitizen() ? 'h:mm A' : 'H:mm')} />
</div>
</div>
{/* a piece per day, so nothing shows through the gaps of the sticky header */}
{days.map((day, index) => (
<div
key={day.format('YYYY-MM-DD')}
className="absolute start-0 end-0 h-0 flex items-center z-[15] pointer-events-none"
style={{ gridColumn: `${index + 2} / ${index + 3}`, gridRow, top }}
>
{index === todayIndex ? (
<>
<div className="w-[3px] h-[12px] rounded-full bg-newTableTextFocused" />
<div className="flex-1 h-[3px] bg-newTableTextFocused" />
</>
) : (
<div className="flex-1 h-[1px] bg-newTableTextFocused opacity-40" />
)}
</div>
))}
</>
);
};
// Current time line between the slots of the day view, as tall as the slot's bottom margin
const DayNowLine: FC<{ now: dayjs.Dayjs; className?: string }> = ({
now,
className,
}) => (
<div
className={clsx(
'flex items-center h-[20px] shrink-0 pointer-events-none',
className
)}
>
{/* same format as the slot labels */}
<NowTime time={now.format(isUSCitizen() ? 'hh:mm A' : 'LT')} />
<div className="flex-1 h-[3px] bg-newTableTextFocused" />
</div>
);
// Shared hook for post actions (edit, delete, statistics)
const usePostActions = (onMutate?: () => void) => {
const t = useT();
@ -313,22 +242,6 @@ const usePostActions = (onMutate?: () => void) => {
[modal, t]
);
const openEvergreen = useCallback(
(id: string) => () => {
modal.openModal({
title: t('evergreen_recycling', 'Evergreen Recycling'),
closeOnClickOutside: true,
closeOnEscape: true,
withCloseButton: true,
classNames: {
modal: 'w-[100%] max-w-[600px]',
},
children: <EvergreenModal postId={id} />,
});
},
[modal, t]
);
const openMissingRelease = useCallback(
(id: string) => () => {
modal.openModal({
@ -356,156 +269,22 @@ const usePostActions = (onMutate?: () => void) => {
return;
}
tab.opener = null;
let release = {
releaseURL: '',
pending: true,
unavailable: false,
reconnect: false,
};
let releaseURL = post.releaseURL;
try {
release = await Promise.race([
fetch(`/posts/${post.id}/release-url`).then((r) => r.json()),
timer(5000).then(() => release),
]);
releaseURL =
(await (await fetch(`/posts/${post.id}/release-url`)).json())
.releaseURL || releaseURL;
} catch (e) {}
if (release.unavailable) {
tab.close();
toaster.show(
t('post_has_no_public_link', 'This post has no public link'),
'warning'
);
return;
}
if (release.reconnect) {
tab.close();
toaster.show(
t(
'post_link_reconnect_channel',
'Reconnect this channel to open the post link'
),
'warning'
);
return;
}
// the platform has not released the post link yet, or the request
// failed or took too long
if (release.pending) {
tab.close();
toaster.show(
t(
'post_link_not_ready',
'The post link is not available yet, please try again in a minute'
),
'warning'
);
return;
}
// multi-target posts (several subreddits / communities / channels)
// join their URLs with commas: open the first one
tab.location.href = (release.releaseURL || post.releaseURL).split(',')[0];
tab.location.href = releaseURL.split(',')[0];
},
[fetch, toaster, t]
[fetch]
);
// Admin-side half of the approval gate (see Organization.requireApprovalForQueue):
// approving sends the post through the real "schedule" path (starts the
// publish workflow), rejecting just clears the pending flag and leaves it
// a normal, still-editable draft. Both actions are idempotent against a
// 404 - the toast surfaces it as a fast "someone else already handled it"
// rather than a crash.
const approvePendingPost = useCallback(
(post: any) => async () => {
const response = await fetch(`/posts/${post.id}/approve-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_approve_post',
'Could not approve this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(t('post_approved', 'Post approved and queued'), 'success');
mutate();
},
[toaster, t, fetch, mutate]
);
const rejectPendingPost = useCallback(
(post: any) => async () => {
if (
!(await deleteDialog(
t(
'are_you_sure_reject_post',
'Reject this post? It will stay as a draft for its author to edit.'
),
t('yes_reject_it', 'Yes, reject it'),
undefined,
t('no_keep_it_pending', 'No, keep it pending')
))
) {
return;
}
const response = await fetch(`/posts/${post.id}/reject-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_reject_post',
'Could not reject this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(t('post_rejected', 'Post rejected'), 'success');
mutate();
},
[toaster, t, fetch, mutate]
);
return {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
};
return { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost };
};
// One day view slot. Memoized, so the now line's minute tick doesn't re-render the slots
const DaySlotColumn: FC<{ option: any[]; startDate: string }> = memo(
({ option, startDate }) => {
const calendar = useCalendar();
return (
<CalendarContext.Provider
value={{
...calendar,
integrations: option.flatMap((p) => p.integration),
}}
>
<CalendarColumn
getDate={dayjs
.utc(startDate)
.startOf('day')
.add(option[0].time, 'minute')
.local()}
/>
</CalendarContext.Provider>
);
}
);
export const DayView = () => {
const calendar = useCalendar();
const { integrations, posts, startDate } = calendar;
@ -514,6 +293,8 @@ export const DayView = () => {
const currentLanguage = i18next.resolvedLanguage || 'en';
dayjs.locale(currentLanguage);
const currentDay = dayjs.utc(startDate);
const options = useMemo(() => {
const createdPosts = posts.map((post) => ({
integration: [integrations.find((i) => i.id === post.integration.id)!],
@ -548,40 +329,11 @@ export const DayView = () => {
);
}, [integrations, posts]);
// the now line goes right before the first upcoming slot
const now = useNow();
const nowIndex = useMemo(() => {
const upcoming = options.findIndex((option) =>
dayjs
.utc(startDate)
.startOf('day')
.add(option[0].time, 'minute')
.isAfter(now)
);
// now is between two slots of this page (the slots follow the UTC day,
// so outside UTC it can be the page next to today)
if (upcoming > 0) {
return upcoming;
}
// before the first or after the last slot, only shown on today
if (!options.length || !newDayjs(startDate).isSame(now, 'day')) {
return -1;
}
return upcoming === -1 ? options.length : upcoming;
}, [options, startDate, now]);
return (
<div className="flex flex-col gap-[10px] flex-1 relative">
<div className="absolute start-0 top-0 w-full h-full flex flex-col overflow-auto scrollbar scrollbar-thumb-fifth scrollbar-track-newBgColor">
{options.map((option, index) => (
{options.map((option) => (
<Fragment key={option[0].time}>
{/* sits in the 20px gap under the previous slot */}
{index === nowIndex && (
<DayNowLine
now={now}
className={clsx(index > 0 && '-mt-[20px]')}
/>
)}
<div className="text-center text-[14px] min-h-[21px] shrink-0">
{newDayjs()
.utc()
@ -594,13 +346,22 @@ export const DayView = () => {
key={option[0].time}
className="min-h-[60px] shrink-0 rounded-[10px] flex justify-center items-center gap-[10px] mb-[20px]"
>
<DaySlotColumn option={option} startDate={startDate} />
<CalendarContext.Provider
value={{
...calendar,
integrations: option.flatMap((p) => p.integration),
}}
>
<CalendarColumn
getDate={currentDay
.startOf('day')
.add(option[0].time, 'minute')
.local()}
/>
</CalendarContext.Provider>
</div>
</Fragment>
))}
{nowIndex === options.length && (
<DayNowLine now={now} className="-mt-[20px]" />
)}
</div>
</div>
);
@ -672,7 +433,6 @@ export const WeekView = () => {
))}
</Fragment>
))}
<WeekNowLine days={localizedDays.map((day) => day.date)} />
</div>
</div>
</div>
@ -690,10 +450,7 @@ export const MonthView = () => {
const days = [];
// Starting from Monday (1) to Sunday (7)
for (let i = 1; i <= 7; i++) {
days.push({
name: newDayjs().day(i).format('dddd'),
short: newDayjs().day(i).format('ddd'),
});
days.push(newDayjs().day(i).format('dddd'));
}
return days;
}, [i18next.resolvedLanguage]);
@ -733,21 +490,19 @@ export const MonthView = () => {
return (
<div className="flex flex-col text-textColor flex-1">
<div className="flex-1 flex relative">
{/* on phones the whole month fits the width, posts show as channel avatars */}
<div className="grid grid-cols-7 tablet:[grid-template-columns:repeat(7,_minmax(100px,_1fr))] mobile:!grid-cols-7 grid-rows-[62px_auto] mobile:grid-rows-[36px_auto] gap-[4px] mobile:gap-[2px] rounded-[10px] absolute start-0 top-0 overflow-auto w-full h-full scrollbar scrollbar-thumb-tableBorder scrollbar-track-secondary">
<div className="grid grid-cols-7 tablet:[grid-template-columns:repeat(7,_minmax(100px,_1fr))] grid-rows-[62px_auto] gap-[4px] rounded-[10px] absolute start-0 top-0 overflow-auto w-full h-full scrollbar scrollbar-thumb-tableBorder scrollbar-track-secondary">
{localizedDays.map((day) => (
<div
key={day.name}
className="z-[20] p-2 mobile:p-0 bg-newTableHeader flex justify-center items-center flex-col h-[62px] mobile:h-[36px] rounded-[8px] sticky top-0"
key={day}
className="z-[20] p-2 bg-newTableHeader flex justify-center items-center flex-col h-[62px] rounded-[8px] sticky top-0"
>
<div className="mobile:hidden">{day.name}</div>
<div className="hidden mobile:block text-[13px]">{day.short}</div>
<div>{day}</div>
</div>
))}
{calendarDays.map((date, index) => (
<div
key={index}
className="text-center items-center justify-center flex mobile:min-w-0"
className="text-center items-center justify-center flex"
>
<CalendarColumn
getDate={newDayjs(date.day).endOf('day')}
@ -774,17 +529,7 @@ export const ListView = () => {
: t('no_posts', 'No posts');
// Use shared post actions hook
const {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
} = usePostActions();
const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost } = usePostActions();
// Group posts by date
const groupedPosts = useMemo(() => {
@ -832,7 +577,6 @@ export const ListView = () => {
date={newDayjs(post.publishDate)}
state={post.state}
statistics={openStatistics(post.id)}
evergreen={openEvergreen(post.id)}
missingRelease={openMissingRelease(post.id)}
openPost={openPost(post)}
editPost={editPost(post, false)}
@ -841,8 +585,6 @@ export const ListView = () => {
post={post}
integrations={integrations}
deletePost={deletePost(post)}
approvePost={approvePendingPost(post)}
rejectPost={rejectPendingPost(post)}
showTime={true}
/>
))}
@ -877,6 +619,7 @@ export const CalendarColumn: FC<{
const t = useT();
const { getDate, randomHour } = props;
const [num, setNum] = useState(0);
const user = useUser();
const {
integrations,
@ -887,23 +630,12 @@ export const CalendarColumn: FC<{
sets,
signature,
loading,
currentHour,
} = useCalendar();
const modal = useModals();
const fetch = useFetch();
// Use shared post actions hook
const {
editPost,
deletePost,
copyDebugJson,
openStatistics,
openEvergreen,
openMissingRelease,
openPost,
approvePendingPost,
rejectPendingPost,
} = usePostActions();
const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease, openPost } = usePostActions();
const postList = useMemo(() => {
return posts.filter((post) => {
const pList = dayjs.utc(post.publishDate).local();
@ -932,13 +664,29 @@ export const CalendarColumn: FC<{
return postList.slice(0, 3);
}, [postList, showAll]);
// currentHour comes from one shared clock, so passed hours get blocked
// while the calendar stays open
const isBeforeNow = useMemo(
() => getDate.startOf('hour').isBefore(currentHour),
[getDate, currentHour]
const isBeforeNow = useMemo(() => {
const originalUtc = getDate.startOf('hour');
return originalUtc
.startOf('hour')
.isBefore(newDayjs().startOf('hour').utc());
}, [getDate, num]);
const { start, stop } = useInterval(
useCallback(() => {
if (isBeforeNow) {
return;
}
setNum(num + 1);
}, [isBeforeNow]),
random(120000, 150000)
);
useEffect(() => {
start();
return () => {
stop();
};
}, []);
const [{ canDrop }, drop] = useDrop(() => ({
accept: 'post',
drop: async (item: any) => {
@ -1039,7 +787,7 @@ export const CalendarColumn: FC<{
collect: (monitor) => ({
canDrop: isBeforeNow ? false : !!monitor.canDrop() && !!monitor.isOver(),
}),
}), [posts, isBeforeNow]);
}), [posts]);
const addModal = useCallback(async () => {
const set: any = !sets.length
@ -1129,27 +877,11 @@ export const CalendarColumn: FC<{
ref={drop as any}
>
{display === 'month' && (
<div
className={clsx(
'pt-[3px] text-[14px] mobile:pt-[2px] mobile:text-[12px] flex justify-center'
)}
>
{/* every day number gets the same box so only today's is filled */}
<div
className={clsx(
'h-[24px] min-w-[24px] px-[5px] mobile:h-[20px] mobile:min-w-[20px] mobile:px-[4px] rounded-[6px] flex items-center justify-center',
getDate.isSame(currentHour, 'day') &&
'bg-newTableTextFocused text-black font-[600]'
)}
>
{getDate.date()}
</div>
</div>
<div className={clsx('pt-[6px] text-[14px]')}>{getDate.date()}</div>
)}
<div
className={clsx(
'relative flex flex-col flex-1 text-white rounded-[8px] min-h-[70px]',
display === 'month' && 'mobile:min-h-[44px]',
canDrop && 'border border-[#612BD3]'
)}
>
@ -1157,9 +889,7 @@ export const CalendarColumn: FC<{
className={clsx(
'flex-col text-[12px] pointer w-full flex scrollbar scrollbar-thumb-tableBorder scrollbar-track-secondary',
isBeforeNow ? 'flex-1' : 'cursor-pointer',
isBeforeNow && postList.length === 0 && 'col-calendar',
// the "Date passed" hint is wider than a phone month cell
display === 'month' && 'mobile:before:hidden'
isBeforeNow && postList.length === 0 && 'col-calendar'
)}
>
{loading && (
@ -1174,19 +904,13 @@ export const CalendarColumn: FC<{
'text-textColor p-[2.5px] relative flex flex-col justify-center items-center'
)}
>
<div
className={clsx(
'relative w-full flex flex-col items-center p-[2.5px]',
display === 'month' && 'mobile:p-0'
)}
>
<div className="relative w-full flex flex-col items-center p-[2.5px]">
<CalendarItem
display={display as 'day' | 'week' | 'month'}
isBeforeNow={isBeforeNow}
date={getDate}
state={post.state}
statistics={openStatistics(post.id)}
evergreen={openEvergreen(post.id)}
missingRelease={openMissingRelease(post.id)}
openPost={openPost(post)}
editPost={editPost(post, false)}
@ -1195,8 +919,6 @@ export const CalendarColumn: FC<{
post={post}
integrations={integrations}
deletePost={deletePost(post)}
approvePost={approvePendingPost(post)}
rejectPost={rejectPendingPost(post)}
/>
</div>
</div>
@ -1206,14 +928,7 @@ export const CalendarColumn: FC<{
className="text-center hover:underline py-[5px] text-textColor"
onClick={showAllFunc}
>
<span className={clsx(display === 'month' && 'mobile:hidden')}>
{t('show_more', '+ Show more')} ({postList.length - 3})
</span>
{display === 'month' && (
<span className="hidden mobile:inline">
+{postList.length - 3}
</span>
)}
{t('show_more', '+ Show more')} ({postList.length - 3})
</div>
)}
{showAll && postList.length > 3 && (
@ -1221,12 +936,7 @@ export const CalendarColumn: FC<{
className="text-center hover:underline py-[5px]"
onClick={showLessFunc}
>
<span className={clsx(display === 'month' && 'mobile:hidden')}>
{t('show_less', '- Show less')}
</span>
{display === 'month' && (
<ChevronUpIcon size={16} className="hidden mobile:inline" />
)}
{t('show_less', '- Show less')}
</div>
)}
</div>
@ -1251,9 +961,8 @@ export const CalendarColumn: FC<{
'group hover:before:h-[30px] w-full h-full rounded-[10px] flex justify-center items-center text-white'
)}
>
{/* z-[16]: above the now line (z-[15]), under the sticky day headers (z-[20]) */}
<div
className={`group-hover:before:content-["+"] pb-[5px] flex justify-center items-center rounded-[8px] transition-all group-hover:bg-btnPrimary w-full h-full max-w-[40px] max-h-[40px] relative z-[16]`}
className={`group-hover:before:content-["+"] pb-[5px] flex justify-center items-center rounded-[8px] transition-all group-hover:bg-btnPrimary w-full h-full max-w-[40px] max-h-[40px]`}
/>
</div>
)}
@ -1315,11 +1024,8 @@ const CalendarItem: FC<{
copyDebugJson?: () => void;
deletePost: () => void;
statistics: () => void;
evergreen?: () => void;
missingRelease?: () => void;
openPost: () => void;
approvePost?: () => void;
rejectPost?: () => void;
integrations: Integrations[];
state: State;
display: 'day' | 'week' | 'month';
@ -1335,7 +1041,6 @@ const CalendarItem: FC<{
const {
editPost,
statistics,
evergreen,
duplicatePost,
copyDebugJson,
post,
@ -1347,8 +1052,6 @@ const CalendarItem: FC<{
showTime,
missingRelease,
openPost,
approvePost,
rejectPost,
} = props;
const { disableXAnalytics } = useVariables();
const user = useUser();
@ -1356,18 +1059,6 @@ const CalendarItem: FC<{
user?.impersonate &&
post.creationMethod &&
post.creationMethod !== 'UNKNOWN';
// Only an ADMIN/SUPERADMIN can act on another member's pendingApproval
// draft (see Organization.requireApprovalForQueue) - a USER-level member
// sees their own submission in the calendar same as any other draft, just
// without these two actions.
const canModerateApproval =
user?.role === 'ADMIN' || user?.role === 'SUPERADMIN';
const showApprovalActions =
state === 'DRAFT' &&
(post as any).pendingApproval &&
canModerateApproval &&
approvePost &&
rejectPost;
const preview = useCallback(() => {
window.open(`/p/` + post.id + '?share=true', '_blank');
}, [post]);
@ -1401,10 +1092,7 @@ const CalendarItem: FC<{
>
{state === 'ERROR' && (
<div
className={clsx(
'absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-red-500 flex items-center justify-center text-white text-[11px] font-bold cursor-pointer',
display === 'month' && 'mobile:hidden'
)}
className="absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-red-500 flex items-center justify-center text-white text-[11px] font-bold cursor-pointer"
data-tooltip-id="tooltip"
data-tooltip-class-name="!max-w-[400px] break-words"
data-tooltip-content={post.error || 'An error occurred while publishing this post'}
@ -1413,43 +1101,10 @@ const CalendarItem: FC<{
</div>
)}
{state === 'PUBLISHED' && (
<div
className={clsx(
'absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-green-500 flex items-center justify-center text-white text-[11px] font-bold',
display === 'month' && 'mobile:hidden'
)}
>
<div className="absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-green-500 flex items-center justify-center text-white text-[11px] font-bold">
✓
</div>
)}
{state === 'DRAFT' && (post as any).pendingApproval && (
<div
className={clsx(
'absolute -top-[6px] -start-[6px] z-20 w-[18px] h-[18px] rounded-full bg-yellow-500 flex items-center justify-center text-white',
display === 'month' && 'mobile:hidden'
)}
data-tooltip-id="tooltip"
data-tooltip-content={t(
'pending_approval_tooltip',
'Waiting for an admin to approve this post'
)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="11"
height="11"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.5"
strokeLinecap="round"
strokeLinejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M12 6v6l4 2" />
</svg>
</div>
)}
{showCreationMethodBadge && (
<div className="absolute -bottom-[4px] -right-[4px] z-10">
<CreationMethodBadge
@ -1460,8 +1115,7 @@ const CalendarItem: FC<{
)}
<div
className={clsx(
'text-white text-[11px] max-h-[24px] h-[24px] min-h-[24px] w-full rounded-tr-[10px] rounded-tl-[10px] flex items-center justify-center gap-[6px] px-[5px] bg-btnPrimary',
display === 'month' && 'mobile:hidden'
'text-white text-[11px] max-h-[24px] h-[24px] min-h-[24px] w-full rounded-tr-[10px] rounded-tl-[10px] flex items-center justify-center gap-[6px] px-[5px] bg-btnPrimary'
)}
style={{
backgroundColor: post?.tags?.[0]?.tag?.color,
@ -1486,6 +1140,24 @@ const CalendarItem: FC<{
<CopyDebug />
</div>
)}
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={duplicatePost}
>
<Duplicate />
</div>
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer text-red-500',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={deletePost}
>
<DeletePost />
</div>{' '}
{(state === 'PUBLISHED' || state === 'ERROR') &&
!post.intervalInDays &&
post.releaseURL?.startsWith('http') && (
@ -1524,39 +1196,6 @@ const CalendarItem: FC<{
) : (
<></>
)}{' '}
{state === 'PUBLISHED' && evergreen && (
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={evergreen}
>
<Recycle />
</div>
)}{' '}
{showApprovalActions && (
<>
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={approvePost}
>
<ApprovePost />
</div>{' '}
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer text-red-500',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={rejectPost}
>
<RejectPost />
</div>
</>
)}{' '}
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
@ -1566,32 +1205,12 @@ const CalendarItem: FC<{
>
<Preview />
</div>
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={duplicatePost}
>
<Duplicate />
</div>
<div
className={clsx(
'hidden group-hover:block hover:underline cursor-pointer text-red-500',
post?.tags?.[0]?.tag?.color && 'text-shadow-tags'
)}
onClick={deletePost}
>
<DeletePost />
</div>
</div>
<div
onClick={editPost}
className={clsx(
'gap-[5px] w-full flex h-full flex-1 rounded-br-[10px] rounded-bl-[10px] p-[8px] text-[14px] bg-newColColor',
'relative',
display === 'month' &&
'mobile:p-[4px] mobile:rounded-[10px] mobile:justify-center',
isBeforeNow && '!grayscale'
)}
>
@ -1605,18 +1224,9 @@ const CalendarItem: FC<{
src={`/icons/platforms/${post.integration?.providerIdentifier}.png`}
/>
</div>
<div
className={clsx(
'w-full flex-1 flex flex-col min-h-[40px]',
display === 'month' && 'mobile:hidden'
)}
>
<div className="w-full flex-1 flex flex-col min-h-[40px]">
<div className="text-start">
{state === 'DRAFT'
? (post as any).pendingApproval
? t('pending_approval', 'Pending approval') + ': '
: t('draft', 'Draft') + ': '
: ''}
{state === 'DRAFT' ? t('draft', 'Draft') + ': ' : ''}
</div>
<div className="w-full relative">
<div className="absolute top-0 start-0 w-full text-ellipsis break-words line-clamp-1 text-start">
@ -1782,73 +1392,6 @@ export const Statistics = () => {
);
};
export const Recycle = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('evergreen_recycling', 'Evergreen Recycling')}
>
<path d="M17 2.1 21 6l-4 3.9" />
<path d="M3 11v-1a4 4 0 0 1 4-4h14" />
<path d="M7 21.9 3 18l4-3.9" />
<path d="M21 13v1a4 4 0 0 1-4 4H3" />
</svg>
);
};
export const ApprovePost = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('approve_post', 'Approve and queue')}
>
<polyline points="20 6 9 17 4 12" />
</svg>
);
};
export const RejectPost = () => {
const t = useT();
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="15"
height="15"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2.2"
strokeLinecap="round"
strokeLinejoin="round"
data-tooltip-id="tooltip"
data-tooltip-content={t('reject_post', 'Reject')}
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
);
};
export const DeletePost = () => {
const t = useT();
return (

View File

@ -1,193 +0,0 @@
import { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { Button } from '@gitroom/react/form/button';
import { Input } from '@gitroom/react/form/input';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
import dayjs from 'dayjs';
interface EvergreenRecycle {
id: string;
active: boolean;
intervalDays: number;
maxRecycles: number | null;
totalRecycles: number;
lastRecycledAt: string | null;
nextRecycleAt: string;
}
// Content recycling for an already-published post (Organization ->
// EvergreenRecycle, see schema.prisma). The actual republishing happens in
// the daily evergreenRecycleWorkflow batch, not from this modal - this is
// just schedule management (create/pause/resume/remove).
export const EvergreenModal: FC<{ postId: string }> = ({ postId }) => {
const t = useT();
const fetch = useFetch();
const toast = useToaster();
const [intervalDays, setIntervalDays] = useState('30');
const [maxRecycles, setMaxRecycles] = useState('');
const [loading, setLoading] = useState(false);
const load = useCallback(async () => {
return (await fetch(`/posts/${postId}/evergreen`)).json();
}, [postId]);
const { data, isLoading, mutate } = useSWR<EvergreenRecycle[]>(
`/posts/${postId}/evergreen`,
load
);
const create = useCallback(async () => {
const days = Number(intervalDays);
if (!days || days < 1) {
toast.show(
t('evergreen_invalid_interval', 'Enter how many days between recycles'),
'warning'
);
return;
}
setLoading(true);
try {
const response = await fetch(`/posts/${postId}/evergreen`, {
method: 'POST',
body: JSON.stringify({
intervalDays: days,
...(maxRecycles ? { maxRecycles: Number(maxRecycles) } : {}),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toast.show(
body?.message ||
t('evergreen_create_failed', 'Could not enable recycling'),
'warning'
);
return;
}
toast.show(
t('evergreen_created', 'This post will be recycled automatically'),
'success'
);
await mutate();
} finally {
setLoading(false);
}
}, [intervalDays, maxRecycles, postId, mutate]);
const toggleActive = useCallback(
(entry: EvergreenRecycle) => async () => {
await fetch(`/posts/evergreen/${entry.id}`, {
method: 'PUT',
body: JSON.stringify({ active: !entry.active }),
});
mutate();
},
[mutate]
);
const remove = useCallback(
(entry: EvergreenRecycle) => async () => {
await fetch(`/posts/evergreen/${entry.id}`, { method: 'DELETE' });
mutate();
},
[mutate]
);
return (
<div className="flex flex-col gap-[16px]">
<div className="text-[13px] text-textItemBlur">
{t(
'evergreen_hint',
'Automatically republish this post as a brand-new post every N days, so it keeps reaching new followers without touching the original.'
)}
</div>
{isLoading ? (
<LoadingComponent />
) : (
<>
{!!data?.length && (
<div className="flex flex-col gap-[8px]">
{data.map((entry) => (
<div
key={entry.id}
className="flex items-center justify-between gap-[10px] rounded-[8px] border border-tableBorder p-[10px] text-[13px]"
>
<div className="flex flex-col gap-[2px]">
<div>
{t('evergreen_every_days', 'Every {{days}} days', {
days: entry.intervalDays,
})}
{entry.maxRecycles
? ` · ${t('evergreen_max', 'max {{max}}', {
max: entry.maxRecycles,
})}`
: ''}
</div>
<div className="text-[11px] text-textItemBlur">
{t('evergreen_recycled_count', '{{count}} recycled', {
count: entry.totalRecycles,
})}
{entry.active
? ` · ${t('evergreen_next', 'next')} ${dayjs(
entry.nextRecycleAt
).format('MMM D, YYYY')}`
: ` · ${t('paused', 'Paused')}`}
</div>
</div>
<div className="flex gap-[10px]">
<button
type="button"
className="text-[12px] hover:underline"
onClick={toggleActive(entry)}
>
{entry.active
? t('pause', 'Pause')
: t('resume', 'Resume')}
</button>
<button
type="button"
className="text-[12px] hover:underline"
onClick={remove(entry)}
>
{t('remove', 'Remove')}
</button>
</div>
</div>
))}
</div>
)}
<div className="flex items-end gap-[10px]">
<div className="flex-1">
<Input
label={t('evergreen_interval_label', 'Days between recycles')}
name="intervalDays"
disableForm={true}
value={intervalDays}
onChange={(e: { target: { value: string } }) =>
setIntervalDays(e.target.value)
}
/>
</div>
<div className="flex-1">
<Input
label={t('evergreen_max_label', 'Max recycles (optional)')}
name="maxRecycles"
disableForm={true}
value={maxRecycles}
onChange={(e: { target: { value: string } }) =>
setMaxRecycles(e.target.value)
}
/>
</div>
<Button loading={loading} onClick={create}>
{t('evergreen_add', 'Add schedule')}
</Button>
</div>
</>
)}
</div>
);
};

View File

@ -3,14 +3,12 @@
import { useCalendar, ListStateFilter } from '@gitroom/frontend/components/launches/calendar.context';
import clsx from 'clsx';
import dayjs from 'dayjs';
import { useCallback, useState } from 'react';
import { useCallback } from 'react';
import { SelectCustomer } from '@gitroom/frontend/components/launches/select.customer';
import { SelectChannels } from '@gitroom/frontend/components/launches/select.channels';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import i18next from 'i18next';
import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
import { BottomSheet } from '@gitroom/frontend/components/ui/bottom.sheet.component';
import { FilterIcon } from '@gitroom/frontend/components/ui/icons';
// Helper function to get start and end dates based on display type
function getDateRange(
@ -46,20 +44,19 @@ function getDateRange(
export const Filters = () => {
const calendar = useCalendar();
const t = useT();
const [filtersOpen, setFiltersOpen] = useState(false);
// Set dayjs locale based on current language
const currentLanguage = i18next.resolvedLanguage || 'en';
dayjs.locale();
// Calculate display date range text, short is the phone version
const getDisplayText = (short?: boolean) => {
// Calculate display date range text
const getDisplayText = () => {
const startDate = newDayjs(calendar.startDate);
const endDate = newDayjs(calendar.endDate);
switch (calendar.display) {
case 'day':
return startDate.format(short ? 'ddd (L)' : 'dddd (L)');
return startDate.format('dddd (L)');
case 'week':
return `${startDate.format('L')} - ${endDate.format('L')}`;
case 'month':
@ -292,13 +289,12 @@ export const Filters = () => {
return (
<div className="text-textColor flex flex-row flex-wrap gap-[8px] items-center select-none">
{/* phones: view switcher and filter first, then the date or list row */}
{!isListView && (
<div className="flex flex-grow flex-row items-center gap-[10px] mobile:order-3 mobile:basis-full mobile:min-w-0 mobile:gap-[8px]">
<div className="border h-[42px] border-newTableBorder bg-newTableBorder gap-[1px] flex items-center rounded-[8px] overflow-hidden mobile:flex-1 mobile:min-w-0">
<div className="flex flex-grow flex-row items-center gap-[10px]">
<div className="border h-[42px] border-newTableBorder bg-newTableBorder gap-[1px] flex items-center rounded-[8px] overflow-hidden">
<div
onClick={previous}
className="cursor-pointer text-textColor rtl:rotate-180 px-[9px] mobile:px-0 mobile:w-[36px] bg-newBgColorInner h-full flex items-center justify-center hover:text-textItemFocused hover:bg-boxFocused"
className="cursor-pointer text-textColor rtl:rotate-180 px-[9px] bg-newBgColorInner h-full flex items-center justify-center hover:text-textItemFocused hover:bg-boxFocused"
>
<svg
xmlns="http://www.w3.org/2000/svg"
@ -316,17 +312,14 @@ export const Filters = () => {
/>
</svg>
</div>
<div className="min-w-[200px] mobile:min-w-0 mobile:flex-1 text-center bg-newBgColorInner h-full flex items-center justify-center">
<div className="py-[3px] px-[9px] mobile:px-[4px] rounded-[5px] transition-all text-[14px] mobile:truncate">
<span className="mobile:hidden">{getDisplayText()}</span>
<span className="hidden mobile:inline">
{getDisplayText(true)}
</span>
<div className="min-w-[200px] mobile:min-w-[160px] text-center bg-newBgColorInner h-full flex items-center justify-center">
<div className="py-[3px] px-[9px] rounded-[5px] transition-all text-[14px]">
{getDisplayText()}
</div>
</div>
<div
onClick={next}
className="cursor-pointer text-textColor rtl:rotate-180 px-[9px] mobile:px-0 mobile:w-[36px] bg-newBgColorInner h-full flex items-center justify-center hover:text-textItemFocused hover:bg-boxFocused"
className="cursor-pointer text-textColor rtl:rotate-180 px-[9px] bg-newBgColorInner h-full flex items-center justify-center hover:text-textItemFocused hover:bg-boxFocused"
>
<svg
xmlns="http://www.w3.org/2000/svg"
@ -345,7 +338,7 @@ export const Filters = () => {
</svg>
</div>
</div>
<div className="flex-1 mobile:flex-none text-[14px] font-[500]">
<div className="flex-1 text-[14px] font-[500]">
<div className="text-center flex h-[42px]">
<div
onClick={setToday}
@ -358,17 +351,12 @@ export const Filters = () => {
</div>
)}
{isListView && (
<div className="flex flex-grow flex-row items-center gap-[10px] mobile:flex-wrap mobile:order-3 mobile:basis-full mobile:min-w-0 mobile:gap-[8px]">
<div
className={clsx(
'border h-[42px] border-newTableBorder bg-newTableBorder gap-[1px] flex items-center rounded-[8px] overflow-hidden mobile:order-2 mobile:w-full',
calendar.listTotalPages <= 1 && 'mobile:hidden'
)}
>
<div className="flex flex-grow flex-row items-center gap-[10px] mobile:flex-wrap">
<div className="border h-[42px] border-newTableBorder bg-newTableBorder gap-[1px] flex items-center rounded-[8px] overflow-hidden">
<div
onClick={previousPage}
className={clsx(
'text-textColor rtl:rotate-180 px-[9px] mobile:px-0 mobile:w-[36px] bg-newBgColorInner h-full flex items-center justify-center',
'text-textColor rtl:rotate-180 px-[9px] bg-newBgColorInner h-full flex items-center justify-center',
calendar.listPage > 0
? 'cursor-pointer hover:text-textItemFocused hover:bg-boxFocused'
: 'opacity-50 cursor-not-allowed'
@ -390,7 +378,7 @@ export const Filters = () => {
/>
</svg>
</div>
<div className="min-w-[200px] mobile:min-w-0 mobile:flex-1 text-center bg-newBgColorInner h-full flex items-center justify-center">
<div className="min-w-[200px] mobile:min-w-[160px] text-center bg-newBgColorInner h-full flex items-center justify-center">
<div className="py-[3px] px-[9px] rounded-[5px] transition-all text-[14px]">
{t('page', 'Page')} {calendar.listPage + 1} {t('of', 'of')} {Math.max(1, calendar.listTotalPages)}
</div>
@ -398,7 +386,7 @@ export const Filters = () => {
<div
onClick={nextPage}
className={clsx(
'text-textColor rtl:rotate-180 px-[9px] mobile:px-0 mobile:w-[36px] bg-newBgColorInner h-full flex items-center justify-center',
'text-textColor rtl:rotate-180 px-[9px] bg-newBgColorInner h-full flex items-center justify-center',
calendar.listPage < calendar.listTotalPages - 1
? 'cursor-pointer hover:text-textItemFocused hover:bg-boxFocused'
: 'opacity-50 cursor-not-allowed'
@ -421,13 +409,13 @@ export const Filters = () => {
</svg>
</div>
</div>
<div className="flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500] mobile:order-1 mobile:w-full mobile:overflow-x-auto">
<div className="flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500] mobile:max-w-full mobile:overflow-x-auto">
{listStateOptions.map((option) => (
<div
key={option.value}
onClick={setListStateFilter(option.value)}
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer min-w-[80px] px-[12px] text-center rounded-[6px] mobile:flex-1 mobile:min-w-fit mobile:px-[8px] mobile:whitespace-nowrap',
'pt-[6px] pb-[5px] cursor-pointer min-w-[80px] px-[12px] text-center rounded-[6px]',
calendar.listState === option.value &&
'text-textItemFocused bg-boxFocused'
)}
@ -436,79 +424,47 @@ export const Filters = () => {
</div>
))}
</div>
<div className="flex-1 mobile:hidden" />
<div className="flex-1" />
</div>
)}
{/* phones get a single filter button that opens the filters sheet */}
<div className="contents mobile:hidden">
<SelectCustomer
customer={calendar.customer as string}
onChange={(customer: string) => setCustomer(customer)}
integrations={calendar.integrations}
/>
<SelectChannels />
</div>
{calendar.integrations.length > 1 && (
<div
onClick={() => setFiltersOpen(true)}
className={clsx(
'hidden mobile:flex mobile:order-2 relative w-[42px] h-[42px] rounded-[8px] border justify-center items-center cursor-pointer',
calendar.selectedChannels
? 'border-[#612BD3] text-[#612BD3]'
: 'border-newTableBorder'
)}
>
<FilterIcon />
{calendar.selectedChannels && (
<div className="absolute top-[6px] end-[6px] w-[6px] h-[6px] rounded-full bg-[#612BD3]" />
)}
<SelectCustomer
customer={calendar.customer as string}
onChange={(customer: string) => setCustomer(customer)}
integrations={calendar.integrations}
/>
<SelectChannels />
{!isListView && (
<div className="flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500]">
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-[62px] text-center rounded-[6px]',
calendar.display === 'day' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setDay}
>
{t('day', 'Day')}
</div>
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-[62px] text-center rounded-[6px]',
calendar.display === 'week' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setWeek}
>
{t('week', 'Week')}
</div>
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-[62px] text-center rounded-[6px]',
calendar.display === 'month' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setMonth}
>
{t('month', 'Month')}
</div>
</div>
)}
<div
className={clsx(
'flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500] mobile:order-1 mobile:flex-1 mobile:overflow-x-auto',
isListView && 'hidden mobile:flex'
)}
>
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-auto mobile:flex-1 mobile:min-w-fit mobile:px-[6px] mobile:whitespace-nowrap text-center rounded-[6px]',
calendar.display === 'day' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setDay}
>
{t('day', 'Day')}
</div>
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-auto mobile:flex-1 mobile:min-w-fit mobile:px-[6px] mobile:whitespace-nowrap text-center rounded-[6px]',
calendar.display === 'week' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setWeek}
>
{t('week', 'Week')}
</div>
<div
className={clsx(
'pt-[6px] pb-[5px] cursor-pointer w-[74px] mobile:w-auto mobile:flex-1 mobile:min-w-fit mobile:px-[6px] mobile:whitespace-nowrap text-center rounded-[6px]',
calendar.display === 'month' && 'text-textItemFocused bg-boxFocused'
)}
onClick={setMonth}
>
{t('month', 'Month')}
</div>
{/* the list toggle joins the view switcher on phones */}
<div
className={clsx(
'hidden mobile:block pt-[6px] pb-[5px] cursor-pointer mobile:flex-1 mobile:min-w-fit mobile:px-[6px] mobile:whitespace-nowrap text-center rounded-[6px]',
isListView && 'text-textItemFocused bg-boxFocused'
)}
onClick={setList}
>
{t('list', 'List')}
</div>
</div>
<div className="flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500] mobile:hidden">
<div className="flex flex-row p-[4px] border border-newTableBorder rounded-[8px] text-[14px] font-[500]">
<div
onClick={setCalendarView}
className={clsx(
@ -558,24 +514,6 @@ export const Filters = () => {
</svg>
</div>
</div>
{filtersOpen && (
<BottomSheet
title={t('select_channels', 'Select Channels')}
onClose={() => setFiltersOpen(false)}
button={{
label: t('done', 'Done'),
onClick: () => setFiltersOpen(false),
}}
>
<SelectCustomer
list={true}
customer={calendar.customer as string}
onChange={(customer: string) => setCustomer(customer)}
integrations={calendar.integrations}
/>
<SelectChannels list={true} />
</BottomSheet>
)}
</div>
);
};

View File

@ -253,7 +253,6 @@ export const DatePickerPanel: FC<{
/>
<TimeInput
onChange={changeDate('time')}
format={isUSCitizen() ? '12' : '24'}
label="Pick time"
classNames={{
label: 'text-textColor py-[12px]',

View File

@ -5,15 +5,6 @@ const ExistingDataContext = createContext({
group: undefined as undefined | string,
posts: [] as Post[],
settings: {} as any,
// the other channels the post was created with
siblings: undefined as
| undefined
| {
integration: string;
group: string;
posts: Post[];
settings: any;
}[],
});
export const ExistingDataContextProvider: FC<{
children: ReactNode;

View File

@ -1,39 +0,0 @@
'use client';
import { FC, useEffect, useRef } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useDecisionModal } from '@gitroom/frontend/components/layout/new-modal';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
// /oauth/hubspot/callback sends people here after they install the Postiz
// app in HubSpot, and the calendar alone doesn't say what just happened
export const HubspotInstalled: FC = () => {
const installed = useSearchParams().get('hubspot') === 'installed';
const modal = useDecisionModal();
const router = useRouter();
const t = useT();
const shown = useRef(false);
useEffect(() => {
if (!installed || shown.current) {
return;
}
shown.current = true;
(async () => {
await modal.open({
title: t('hubspot_installed', 'Postiz is installed in HubSpot'),
onlyApprove: true,
approveLabel: t('ok', 'OK'),
description: t(
'hubspot_installed_description',
'Connect the channels you want to post to here in Postiz. Then, in HubSpot, open Agent Hub > Agent Builder, add a tool, pick Postiz MCP under MCP Servers and click Connect and add.'
),
});
// like Onboarding, drop the param once closed so a calendar reload
// doesn't show it again
router.replace('/launches');
})();
}, [installed]);
return null;
};

View File

@ -25,13 +25,11 @@ import { DNDProvider } from '@gitroom/frontend/components/launches/helpers/dnd.p
import { GeneratorComponent } from './generator/generator';
import { useVariables } from '@gitroom/react/helpers/variable.context';
import { NewPost } from '@gitroom/frontend/components/launches/new.post';
import { BulkScheduleButton } from '@gitroom/frontend/components/launches/bulk-schedule/bulk.schedule.button';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useIntegrationList } from '@gitroom/frontend/components/launches/helpers/use.integration.list';
import useCookie from 'react-use-cookie';
import { Onboarding } from '@gitroom/frontend/components/onboarding/onboarding';
import { ChannelsAfterPayment } from '@gitroom/frontend/components/layout/check.payment';
import { HubspotInstalled } from '@gitroom/frontend/components/launches/hubspot.installed';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { Input } from '@gitroom/react/form/input';
import { Button } from '@gitroom/react/form/button';
@ -630,7 +628,6 @@ export const LaunchesComponent = () => {
<DNDProvider>
<Onboarding />
<ChannelsAfterPayment integrations={integrations} />
<HubspotInstalled />
<CalendarWeekProvider integrations={sortedIntegrations}>
{channelsOpen && (
<div
@ -704,7 +701,6 @@ export const LaunchesComponent = () => {
<AddProviderButton update={() => update(true)} />
<div className="flex gap-[8px] group-[.sidebar]:flex-col mobile:hidden">
{sortedIntegrations?.length > 0 && <NewPost />}
{sortedIntegrations?.length > 0 && <BulkScheduleButton />}
{sortedIntegrations?.length > 0 &&
user?.tier?.ai &&
billingEnabled && <GeneratorComponent />}
@ -785,7 +781,6 @@ export const LaunchesComponent = () => {
{sortedIntegrations?.length > 0 ? (
<>
<NewPost />
<BulkScheduleButton />
{user?.tier?.ai && billingEnabled && <GeneratorComponent />}
</>
) : (

View File

@ -2,18 +2,13 @@
import React, { FC, useCallback, useMemo, useState } from 'react';
import clsx from 'clsx';
import { uniqBy } from 'lodash';
import { useClickOutside } from '@mantine/hooks';
import { useCalendar } from '@gitroom/frontend/components/launches/calendar.context';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Checkbox } from '@gitroom/react/form/checkbox';
import { FilterIcon } from '@gitroom/frontend/components/ui/icons';
import { Check } from '@gitroom/frontend/components/launches/tags.component';
import { IntegrationListRow } from '@gitroom/frontend/components/new-launch/picks.socials.component';
export const SelectChannels: FC<{
list?: boolean;
}> = ({ list }) => {
export const SelectChannels: FC = () => {
const { integrations, customer, selectedChannels, setSelectedChannels } =
useCalendar();
const t = useT();
@ -63,38 +58,6 @@ export const SelectChannels: FC<{
return null;
}
if (list) {
// the customers are listed above the channels when there are any
const hasCustomers =
uniqBy(integrations, (i) => i?.customer?.id).length > 1;
return (
<div className="flex flex-col gap-[4px]">
{hasCustomers && (
<div className="text-[14px] font-[600] text-textItemBlur">
{t('channels', 'Channels')}
</div>
)}
<div
onClick={toggleAll}
className="flex items-center gap-[12px] py-[8px] cursor-pointer select-none"
>
<div className="flex-1 text-[14px] font-[600]">
{t('select_all', 'Select all')}
</div>
<Check onChange={() => {}} value={allSelected} />
</div>
{channels.map((p) => (
<IntegrationListRow
key={p.id}
integration={p}
selected={selectedIds.includes(p.id)}
onClick={toggle(p.id)}
/>
))}
</div>
);
}
return (
<div className="relative select-none z-[500]" ref={ref}>
<div

View File

@ -15,9 +15,8 @@ export const SelectCustomer: FC<{
onChange: (value: string) => void;
integrations: Integrations[];
customer?: string;
list?: boolean;
}> = (props) => {
const { onChange, integrations, customer: currentCustomer, list } = props;
const { onChange, integrations, customer: currentCustomer } = props;
const { setCurrent } = useLaunchStore(
useShallow((state) => ({
setCurrent: state.setCurrent,
@ -48,63 +47,10 @@ export const SelectCustomer: FC<{
const totalCustomers = useMemo(() => {
return uniqBy(integrations, (i) => i?.customer?.id).length;
}, [integrations]);
const selectCustomer = useCallback(
(id: string) => () => {
toaster.show(
t('customer_socials_selected', 'Customer socials selected'),
'success'
);
setCustomer(id);
onChange(id);
setOpen(false);
setCurrent('global');
},
[onChange]
);
if (totalCustomers <= 1) {
return null;
}
const customers = uniqBy(integrations, (u) => u?.customer?.name).filter(
(f) => f.customer?.name
);
if (list) {
return (
<div className="flex flex-col gap-[8px] pb-[16px]">
<div className="text-[14px] font-[600] text-textItemBlur">
{t('customers', 'Customers')}
</div>
{customers.map((p) => {
const selected = customer === p.customer?.id;
return (
<div
onClick={selectCustomer(p.customer?.id)}
key={p.customer?.id}
className="min-h-[48px] flex items-center justify-between gap-[12px] cursor-pointer select-none"
>
<div className="text-[14px] font-[600] truncate">
{p.customer?.name}
</div>
<div
className={clsx(
'w-[24px] h-[24px] min-w-[24px] rounded-full border-[1.5px] flex justify-center items-center',
selected ? 'border-[#FC69FF]' : 'border-newTextColor/20'
)}
>
{selected && (
<div className="w-[12px] h-[12px] rounded-full bg-[#FC69FF]" />
)}
</div>
</div>
);
})}
</div>
);
}
return (
<div className="relative select-none z-[500]" ref={ref}>
<div
@ -131,15 +77,26 @@ export const SelectCustomer: FC<{
<div className="text-[14px] font-[600] px-[12px] mb-[5px]">
{t('customers', 'Customers')}
</div>
{customers.map((p) => (
<div
onClick={selectCustomer(p.customer?.id)}
key={p.customer?.id}
className="p-[12px] hover:bg-newBgColor text-[14px] font-[500] h-[32px] flex items-center"
>
{p.customer?.name}
</div>
))}
{uniqBy(integrations, (u) => u?.customer?.name)
.filter((f) => f.customer?.name)
.map((p) => (
<div
onClick={() => {
toaster.show(
t('customer_socials_selected', 'Customer socials selected'),
'success'
);
setCustomer(p.customer?.id);
onChange(p.customer?.id);
setOpen(false);
setCurrent('global')
}}
key={p.customer?.id}
className="p-[12px] hover:bg-newBgColor text-[14px] font-[500] h-[32px] flex items-center"
>
{p.customer?.name}
</div>
))}
</div>
)}
</div>

View File

@ -9,7 +9,6 @@ import { Button } from '@gitroom/react/form/button';
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
// @ts-ignore
import useKeypress from 'react-use-keypress';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
@ -35,36 +34,6 @@ const minutes = [...Array(60).keys()].map((i) => ({
value: i,
}));
export interface BestTimeSuggestion {
dayOfWeek: number;
hourOfDay: number;
avgEngagement: number;
sampleSize: number;
}
interface BestTimesResponse {
hasData: boolean;
suggestions: BestTimeSuggestion[];
}
// Separate hook per SWR call, per project convention (rules-of-hooks).
// Reads only the pre-aggregated /analytics/best-time endpoint - no live
// provider calls happen on render, the data is populated by a bounded daily
// batch job on the backend.
const useBestTimeSuggestions = (integrationId: string) => {
const fetch = useFetch();
const load = useCallback(async () => {
const response = await fetch(`/analytics/best-time/${integrationId}`);
return (await response.json()) as BestTimesResponse;
}, [integrationId]);
return useSWR<BestTimesResponse>(`best-time-${integrationId}`, load, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
fallbackData: { hasData: false, suggestions: [] },
});
};
export const TimeTable: FC<{
integration: Integrations;
mutate: () => void;
@ -147,35 +116,6 @@ export const TimeTable: FC<{
);
}, [currentTimes]);
const { data: bestTimes, isLoading: bestTimesLoading } =
useBestTimeSuggestions(props.integration.id);
const dayLabels = useMemo(
() => [
t('sunday_short', 'Sun'),
t('monday_short', 'Mon'),
t('tuesday_short', 'Tue'),
t('wednesday_short', 'Wed'),
t('thursday_short', 'Thu'),
t('friday_short', 'Fri'),
t('saturday_short', 'Sat'),
],
[t]
);
const addSuggestedTime = useCallback(
(hourOfDay: number) => () => {
// Suggestions are computed in UTC (see PostEngagementService), and the
// stored `time` field is already "minutes since UTC midnight" - same
// unit the display formatter above assumes - so no offset math here.
const value = hourOfDay * 60;
setCurrentTimes((prev) =>
prev.some((p) => p.time === value) ? prev : [...prev, { time: value }]
);
},
[]
);
const save = useCallback(async () => {
await fetch(`/integrations/${props.integration.id}/time`, {
method: 'POST',
@ -189,63 +129,6 @@ export const TimeTable: FC<{
return (
<div className="relative w-full max-w-[400px] mx-auto">
{/* Suggested Best Times Section */}
<div className="bg-newBgColorInner rounded-[12px] p-[20px] border border-newTableBorder mb-[20px]">
<div className="text-[15px] font-semibold mb-[8px] flex items-center gap-[8px]">
<DelayIcon size={18} className="text-[#612BD3]" />
{t('suggested_best_times', 'Suggested Best Times')}
</div>
<div className="text-[12px] text-newTextColor/50 mb-[12px]">
{t(
'suggested_best_times_description',
'Based on how your own past posts on this channel performed, grouped by day and hour (UTC).'
)}
</div>
{bestTimesLoading ? (
<div className="text-center py-[16px] text-newTextColor/40 text-[13px]">
{t('loading', 'Loading...')}
</div>
) : !bestTimes?.hasData ? (
<div className="text-center py-[16px] px-[12px] text-newTextColor/40 text-[13px] border border-dashed border-newTableBorder rounded-[8px]">
{t(
'not_enough_post_history_yet',
"Not enough published post history yet. Keep posting - we'll surface your best times once we have enough data."
)}
</div>
) : (
<div className="flex flex-col gap-[8px]">
{bestTimes.suggestions.map((suggestion) => (
<div
key={`${suggestion.dayOfWeek}-${suggestion.hourOfDay}`}
className="flex items-center justify-between h-[44px] px-[14px] rounded-[8px] bg-newBgColorInner border border-newTableBorder"
>
<div className="flex items-center gap-[10px]">
<div className="w-[8px] h-[8px] rounded-full bg-[#32d583]" />
<span className="text-[14px] font-medium">
{dayLabels[suggestion.dayOfWeek]}{' '}
{suggestion.hourOfDay.toString().padStart(2, '0')}:00 UTC
</span>
<span className="text-[12px] text-newTextColor/40">
{t('based_on_n_posts', 'based on {{count}} posts', {
count: suggestion.sampleSize,
})}
</span>
</div>
<button
type="button"
onClick={addSuggestedTime(suggestion.hourOfDay)}
className="h-[32px] px-[12px] bg-[#612BD3]/10 hover:bg-[#612BD3]/20 transition-colors rounded-[6px] flex items-center gap-[6px] text-[#612BD3] text-[13px] font-medium"
>
<PlusIcon size={12} />
{t('add', 'Add')}
</button>
</div>
))}
</div>
)}
</div>
{/* Add Time Slot Section */}
<div className="bg-newBgColorInner rounded-[12px] p-[20px] border border-newTableBorder">
<div className="text-[15px] font-semibold mb-[16px] flex items-center gap-[8px]">

View File

@ -110,7 +110,6 @@ export const TelegramProvider: FC<Web3ProviderInterface> = (props) => {
<Input
label=""
value={`/connect ${word.current}`}
readOnly
name=""
disableForm={true}
/>

View File

@ -0,0 +1,103 @@
'use client';
import { FC, useCallback, useState } from 'react';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Button } from '@gitroom/react/form/button';
export const AgentMediaModal: FC = () => {
const fetch = useFetch();
const t = useT();
const { closeCurrent } = useModals();
const [loading, setLoading] = useState(false);
const handleContinue = useCallback(async () => {
setLoading(true);
try {
const response = await fetch('/user/agent-media-sso');
const data = await response.json();
if (data.url) {
window.open(data.url, '_blank');
}
closeCurrent();
} catch (e) {
// ignore
} finally {
setLoading(false);
}
}, [fetch, closeCurrent]);
return (
<div className="flex flex-col gap-[20px] max-w-[520px]">
<div className="text-[14px] leading-[22px] text-newTextColor opacity-80">
{t(
'agent_media_different_company',
'UGC videos are powered by AgentMedia (agent-media.ai), a separate product with its own account and pricing — not part of your Postiz subscription.'
)}
</div>
<div className="flex flex-col gap-[12px]">
<div className="text-[14px] font-[600] text-newTextColor">
{t('agent_media_what_you_get', 'What you get with AgentMedia')}
</div>
<ul className="flex flex-col gap-[8px] text-[14px] leading-[20px] text-newTextColor opacity-80">
<li className="flex gap-[8px]">
<span className="text-forth">•</span>
<span>
{t(
'agent_media_feature_videos',
'AI-generated UGC videos with captions written and baked in automatically'
)}
</span>
</li>
<li className="flex gap-[8px]">
<span className="text-forth">•</span>
<span>
{t(
'agent_media_feature_quality',
'Studio-quality 9:16 vertical video at 1080p'
)}
</span>
</li>
<li className="flex gap-[8px]">
<span className="text-forth">•</span>
<span>
{t(
'agent_media_feature_publish',
'Auto-publishing to TikTok, Instagram, YouTube and X'
)}
</span>
</li>
</ul>
</div>
<div className="flex flex-col gap-[12px]">
<div className="text-[14px] font-[600] text-newTextColor">
{t('agent_media_pricing', 'Separate pricing')}
</div>
<div className="flex flex-col gap-[6px] text-[14px] leading-[20px] text-newTextColor opacity-80">
<div>
{t('agent_media_plan_creator', 'Creator — $39/mo · 3,900 credits')}
</div>
<div>{t('agent_media_plan_pro', 'Pro — $69/mo · 6,900 credits')}</div>
<div>
{t(
'agent_media_plan_pro_plus',
'Pro Plus — $129/mo · 12,900 credits + early access'
)}
</div>
</div>
</div>
<div className="flex gap-[12px] mt-[8px]">
<Button loading={loading} onClick={handleContinue}>
{t('agent_media_continue', 'Continue to AgentMedia')}
</Button>
<Button secondary={true} onClick={closeCurrent}>
{t('cancel', 'Cancel')}
</Button>
</div>
</div>
);
};

View File

@ -31,9 +31,7 @@ import { Autopost } from '@gitroom/frontend/components/autopost/autopost';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { SVGLine } from '@gitroom/frontend/components/launches/launches.component';
import { GlobalSettings } from '@gitroom/frontend/components/settings/global.settings';
import { AppsComponent } from '@gitroom/frontend/components/settings/apps.component';
import { ThirdPartyComponent } from '@gitroom/frontend/components/third-parties/third-party.component';
import { Plugs } from '@gitroom/frontend/components/plugs/plugs';
import { ApprovedAppsComponent } from '@gitroom/frontend/components/approved-apps/approved-apps.component';
export const SettingsPopup: FC<{
getRef?: Ref<any>;
}> = (props) => {
@ -83,14 +81,13 @@ export const SettingsPopup: FC<{
close();
}, []);
const [tab, setTab] = useState('global_settings');
const t = useT();
const list = useMemo(() => {
const arr = [];
arr.push({ tab: 'global_settings', label: t('global_settings', 'Global Settings') });
// Populate tabs based on user permissions
if (user?.tier?.public_api && isGeneral && showLogout) {
arr.push({ tab: 'agents', label: t('agents', 'Agents') });
}
if (user?.tier?.team_members && isGeneral && user?.role !== 'USER') {
arr.push({ tab: 'teams', label: t('teams', 'Teams') });
}
@ -106,20 +103,14 @@ export const SettingsPopup: FC<{
if (user?.tier.current !== 'FREE') {
arr.push({ tab: 'signatures', label: t('signatures', 'Signatures') });
}
arr.push({ tab: 'integrations', label: t('integrations', 'Integrations') });
arr.push({ tab: 'plugs', label: t('plugs', 'Plugs') });
arr.push({ tab: 'apps', label: t('apps', 'Apps') });
if (user?.tier?.public_api && isGeneral && showLogout) {
arr.push({ tab: 'api', label: t('developers', 'Developers') });
}
arr.push({ tab: 'approved_apps', label: t('approved_apps', 'Approved Apps') });
return arr;
}, [user, isGeneral, showLogout, t]);
const [tab, setTab] = useState(() => {
const requested = url.get('tab');
return list.some((p) => p.tab === requested)
? requested!
: 'global_settings';
});
useEffect(() => {
loadProfile();
}, []);
@ -207,19 +198,7 @@ export const SettingsPopup: FC<{
</div>
)}
{tab === 'integrations' && (
<div>
<ThirdPartyComponent />
</div>
)}
{tab === 'plugs' && (
<div>
<Plugs />
</div>
)}
{tab === 'agents' &&
{tab === 'api' &&
!!user?.tier?.public_api &&
isGeneral &&
showLogout && (
@ -228,16 +207,9 @@ export const SettingsPopup: FC<{
</div>
)}
{tab === 'apps' && (
{tab === 'approved_apps' && (
<div>
<AppsComponent
canManageApps={
!!user?.tier?.public_api &&
isGeneral &&
showLogout &&
user?.role !== 'USER'
}
/>
<ApprovedAppsComponent />
</div>
)}
</div>

View File

@ -1,10 +1,12 @@
'use client';
import { FC, ReactNode } from 'react';
import { FC, ReactNode, useCallback } from 'react';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
import { useVariables } from '@gitroom/react/helpers/variable.context';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { MenuItem } from '@gitroom/frontend/components/new-layout/menu-item';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { AgentMediaModal } from '@gitroom/frontend/components/layout/agent.media.modal';
interface MenuItemInterface {
name: string;
@ -19,6 +21,16 @@ interface MenuItemInterface {
export const useMenuItem = () => {
const { isGeneral } = useVariables();
const t = useT();
const { openModal } = useModals();
const handleAgentMediaClick = useCallback(() => {
openModal({
title: t('agent_media_title', 'UGC videos by AgentMedia'),
closeOnClickOutside: true,
closeOnEscape: true,
children: <AgentMediaModal />,
});
}, [openModal, t]);
const firstMenu = [
{
@ -102,9 +114,152 @@ export const useMenuItem = () => {
),
path: '/media',
},
{
name: t('plugs', 'Plugs'),
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="19"
viewBox="0 0 18 19"
fill="none"
>
<path
d="M11.6711 6.21205C11.3397 5.88068 11.174 5.715 11.1119 5.52395C11.0573 5.35589 11.0573 5.17486 11.1119 5.00681C11.174 4.81575 11.3397 4.65007 11.6711 4.3187L14.0461 1.94369C13.4158 1.65867 12.7162 1.5 11.9795 1.5C9.20677 1.5 6.95901 3.74776 6.95901 6.5205C6.95901 6.93138 7.00837 7.33073 7.10148 7.71294C7.20119 8.12224 7.25104 8.32689 7.24219 8.45618C7.23292 8.59154 7.21274 8.66355 7.15032 8.78401C7.0907 8.89907 6.97646 9.0133 6.748 9.24177L1.52013 14.4696C0.826947 15.1628 0.826948 16.2867 1.52013 16.9799C2.21332 17.6731 3.3372 17.6731 4.03039 16.9799L9.25825 11.752C9.48672 11.5236 9.60095 11.4093 9.71601 11.3497C9.83647 11.2873 9.90848 11.2671 10.0438 11.2578C10.1731 11.249 10.3778 11.2988 10.7871 11.3985C11.1693 11.4916 11.5686 11.541 11.9795 11.541C14.7523 11.541 17 9.29325 17 6.5205C17 5.78382 16.8413 5.0842 16.5563 4.45394L14.1813 6.82895C13.8499 7.16032 13.6843 7.326 13.4932 7.38808C13.3252 7.44269 13.1441 7.44269 12.9761 7.38808C12.785 7.326 12.6193 7.16032 12.288 6.82895L11.6711 6.21205Z"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
),
path: '/plugs',
},
{
name: t('integrations', 'Integrations'),
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="19"
viewBox="0 0 20 19"
fill="none"
>
<path
d="M6.175 3.125C6.175 1.9514 7.1264 1 8.3 1C9.47361 1 10.425 1.9514 10.425 3.125V4.4H11.275C12.4632 4.4 13.0572 4.4 13.5258 4.59411C14.1507 4.85292 14.6471 5.34934 14.9059 5.97416C15.1 6.44277 15.1 7.03685 15.1 8.225H16.375C17.5486 8.225 18.5 9.1764 18.5 10.35C18.5 11.5236 17.5486 12.475 16.375 12.475H15.1V13.92C15.1 15.3481 15.1 16.0622 14.8221 16.6077C14.5776 17.0875 14.1875 17.4776 13.7077 17.7221C13.1622 18 12.4481 18 11.02 18H10.425V16.5125C10.425 15.4563 9.56874 14.6 8.5125 14.6C7.45626 14.6 6.6 15.4563 6.6 16.5125V18H5.58C4.15187 18 3.4378 18 2.89232 17.7221C2.41251 17.4776 2.02241 17.0875 1.77793 16.6077C1.5 16.0622 1.5 15.3481 1.5 13.92V12.475H2.775C3.94861 12.475 4.9 11.5236 4.9 10.35C4.9 9.1764 3.94861 8.225 2.775 8.225H1.5C1.5 7.03685 1.5 6.44277 1.69411 5.97416C1.95292 5.34934 2.44934 4.85292 3.07416 4.59411C3.54277 4.4 4.13685 4.4 5.325 4.4H6.175V3.125Z"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
),
path: '/third-party',
},
] satisfies MenuItemInterface[] as MenuItemInterface[];
const secondMenu = [
{
name: t('make_ugc', 'Make UGC'),
icon: (
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 27.19 27.19"
fill="none"
>
<g clipPath="url(#agent_media_clip)">
<rect
width="27.19"
height="27.19"
rx="6.43"
fill="url(#agent_media_bg)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M0 29.23V-2.06L22.12 9.99v7.46z"
fill="url(#agent_media_play)"
/>
<mask
id="agent_media_mask"
width="23"
height="36"
x="0"
y="-4"
maskUnits="userSpaceOnUse"
style={{ maskType: 'alpha' }}
>
<path fill="#d9d9d9" d="M0-3.84h22.12v34.87H0z" />
</mask>
<g mask="url(#agent_media_mask)">
<path
fill="url(#agent_media_line1)"
d="m42.33-1.9-64.3 37.13 3.48 6.04L45.8 4.14z"
/>
<path
fill="url(#agent_media_line2)"
d="M-18.57-13.72 45.74 23.4l-3.48 6.03L-22.05-7.7z"
/>
</g>
</g>
<defs>
<radialGradient
id="agent_media_bg"
cx="0"
cy="0"
r="1"
gradientTransform="matrix(-38.3537 0 0 -29.9787 38.354 13.597)"
gradientUnits="userSpaceOnUse"
>
<stop />
<stop offset="1" stopColor="#6112ff" />
</radialGradient>
<linearGradient
id="agent_media_play"
x1="22.12"
x2="0"
y1="13.6"
y2="13.6"
gradientUnits="userSpaceOnUse"
>
<stop />
<stop offset="1" stopColor="#2a008d" />
</linearGradient>
<linearGradient
id="agent_media_line1"
x1="44.5"
x2="-20.41"
y1="0.37"
y2="37.84"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.32" stopColor="#9162ff" />
<stop offset="0.69" stopColor="#4500e7" />
</linearGradient>
<linearGradient
id="agent_media_line2"
x1="-20.74"
x2="44.18"
y1="-11.46"
y2="26.02"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.32" stopColor="#9162ff" />
<stop offset="0.69" stopColor="#4500e7" />
</linearGradient>
<clipPath id="agent_media_clip">
<rect width="27.19" height="27.19" rx="6.43" fill="#fff" />
</clipPath>
</defs>
</svg>
),
path: '#',
role: ['ADMIN', 'SUPERADMIN', 'USER'],
requireBilling: true,
onClick: handleAgentMediaClick,
},
{
name: t('affiliate', 'Affiliate'),
icon: (
@ -230,7 +385,7 @@ export const TopMenu: FC = () => {
const { isGeneral, billingEnabled } = useVariables();
return (
<>
<div className="flex flex-1 flex-col minCustom:gap-[20px] custom:gap-[8px] blurMe">
<div className="flex flex-1 flex-col minCustom:gap-[16px] blurMe">
{
// @ts-ignore
user?.orgId &&

View File

@ -12,7 +12,6 @@ import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
import { useModals } from '@gitroom/frontend/components/layout/new-modal';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Post } from '@prisma/client';
export interface AddEditModalProps {
dummy?: boolean;
@ -114,16 +113,6 @@ export const AddEditModalInner: FC<AddEditModalProps> = (props) => {
return;
}
addOrRemoveSelectedIntegration(integration, existingData.settings);
// the other channels the post was created with
for (const sibling of existingData.siblings || []) {
const siblingIntegration = integrations.find(
(i) => i.id === sibling.integration
);
if (siblingIntegration) {
addOrRemoveSelectedIntegration(siblingIntegration, sibling.settings);
}
}
}
if (props?.selectedChannels?.length) {
@ -143,21 +132,6 @@ export const AddEditModalInner: FC<AddEditModalProps> = (props) => {
return <AddEditModalInnerInner {...props} />;
};
// an existing post, as the values of the editor
const postValues = (posts: Post[]) =>
posts.map((post) => ({
delay: post.delay,
content: /<p[\s>]/i.test(post.content)
? post.content
: post.content
.split('\n')
.map((line: string) => `<p>${line}</p>`)
.join(''),
id: post.id,
// @ts-ignore
media: post.image as any[],
}));
export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {
const existingData = useExistingData();
const {
@ -170,8 +144,6 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {
setTags,
setEditor,
setRepeater,
selectedIntegrations,
setChannelDate,
} = useLaunchStore(
useShallow((state) => ({
reset: state.reset,
@ -183,8 +155,6 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {
setTags: state.setTags,
setEditor: state.setEditor,
setRepeater: state.setRepeater,
selectedIntegrations: state.selectedIntegrations,
setChannelDate: state.setChannelDate,
}))
);
@ -200,28 +170,23 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {
value: p.tag.name,
})) || []
);
addInternalValue(
0,
existingData.integration,
postValues(existingData.posts)
existingData.posts.map((post) => ({
delay: post.delay,
content:
/<p[\s>]/i.test(post.content)
? post.content
: post.content
.split('\n')
.map((line: string) => `<p>${line}</p>`)
.join(''),
id: post.id,
// @ts-ignore
media: post.image as any[],
}))
);
// the other channels the post was created with, each with its own
// content and date
for (const sibling of existingData.siblings || []) {
if (
selectedIntegrations.some(
(p) => p.integration.id === sibling.integration
)
) {
addInternalValue(0, sibling.integration, postValues(sibling.posts));
setChannelDate(
sibling.integration,
dayjs.utc(sibling.posts[0].publishDate).local()
);
}
}
setCurrent(existingData.integration);
} else {
setEditor('normal');

View File

@ -103,16 +103,12 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
current,
activateExitButton,
setHide,
channelDates,
setChannelDate,
} = useLaunchStore(
useShallow((state) => ({
hide: state.hide,
setHide: state.setHide,
date: state.date,
setDate: state.setDate,
channelDates: state.channelDates,
setChannelDate: state.setChannelDate,
current: state.current,
repeater: state.repeater,
setRepeater: state.setRepeater,
@ -125,29 +121,9 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
activateExitButton: state.activateExitButton,
}))
);
// the other channels of an existing post show and move only their own date
const channelDate = channelDates[current];
const pickerDate = channelDate || date;
const setPickerDate = useCallback(
(newDate: dayjs.Dayjs) => {
if (channelDate) {
return setChannelDate(current, newDate);
}
setDate(newDate);
},
[channelDate, current]
);
// the date sheet applies its changes only on save
const [dateDraft, setDateDraft] = useState(date);
// the channels the post already has, each with its own post
const existingPosts = [existingData, ...(existingData.siblings || [])];
// the channel in view, or the one that was opened
const channel =
existingPosts.find((p) => p.integration === current) || existingData;
useEffect(() => {
if (hide) {
setHide(false);
@ -227,73 +203,6 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
const deletePost = useCallback(async () => {
setLoading(true);
if (existingData.siblings?.length) {
const groups = await new Promise<string[]>((resolve) => {
modal.openModal({
id: 'delete-post-channels',
title: t('delete_post', 'Delete Post'),
onClose: () => resolve([]),
children: (
<div className="flex flex-col">
<div className="text-[20px] mb-[20px]">
{t(
'delete_post_from_all_channels_question',
'This post was created for more than one channel. Do you want to delete it from all of them?'
)}
</div>
<div className="flex w-full gap-[10px]">
<div className="flex-1 flex">
<Button
type="button"
className="flex-1"
onClick={() => {
modal.closeById('delete-post-channels');
resolve(existingPosts.map((p) => p.group!));
}}
>
{t('delete_from_all_channels', 'Delete from all channels')}
</Button>
</div>
<div className="flex-1 flex">
<Button
type="button"
secondary
className="flex-1"
onClick={() => {
modal.closeById('delete-post-channels');
resolve([channel.group!]);
}}
>
{t('delete_only_from', 'Only from')}{' '}
{
integrations.find((p) => p.id === channel.integration)
?.name
}
</Button>
</div>
</div>
</div>
),
});
});
if (!groups.length) {
setLoading(false);
return;
}
await Promise.all(
groups.map((group) =>
fetch(`/posts/${group}`, {
method: 'DELETE',
})
)
);
mutate();
modal.closeAll();
return;
}
if (
!(await deleteDialog(
t(
@ -312,172 +221,26 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
mutate();
modal.closeAll();
return;
}, [existingData, mutate, modal, current, integrations]);
}, [existingData, mutate, modal]);
const schedule = useCallback(
(type: 'draft' | 'now' | 'schedule' | 'update') => async () => {
let republish = false;
// the channels saved as another type, the rest are saved as `type`
const saveAs: Record<string, 'draft' | 'schedule' | 'update'> = {};
const saveTypeOf = (id: string) => saveAs[id] || type;
// the channels that already went out, or are going out right now
const published = existingPosts.filter(
(p) =>
p.posts?.[0]?.state === 'PUBLISHED' ||
(p.posts?.[0]?.state === 'QUEUE' &&
dayjs().isAfter((channelDates[p.integration] || date).utc()))
);
const others = existingPosts.filter((p) => p !== channel);
// another channel whose date already passed would go out right away, it
// only gets its details saved
if (type === 'schedule') {
for (const p of others) {
if (
!published.includes(p) &&
dayjs().isAfter((channelDates[p.integration] || date).utc())
) {
saveAs[p.integration] = 'update';
}
}
}
// a draft of a post with other channels leaves the published ones as they are
if (type === 'draft' && existingData.siblings?.length) {
for (const p of published) {
if (p.posts[0].state === 'PUBLISHED') {
saveAs[p.integration] = 'update';
}
}
}
// the save that leaves a channel in its state
const asItIs = (p: (typeof existingPosts)[number]) =>
p.posts?.[0]?.state === 'DRAFT'
? 'draft'
: p.posts?.[0]?.state === 'QUEUE' && !published.includes(p)
? 'schedule'
: 'update';
// like the delete, a save that changes the state of the other channels
// (scheduling their drafts, moving them to drafts) can do it only for
// the channel in view, the others keep their state
if (
type !== 'update' &&
others.some(
(p) =>
!saveAs[p.integration] &&
// the republish question covers the published ones
(type === 'draft' || !published.includes(p)) &&
asItIs(p) !== type
)
(type === 'now' || type === 'schedule') &&
(existingData?.posts?.[0]?.state === 'PUBLISHED' ||
(existingData?.posts?.[0]?.state === 'QUEUE' &&
dayjs().isAfter(date.utc())))
) {
const question =
type === 'draft'
? t(
'draft_post_in_all_channels_question',
'This post was created for more than one channel. Do you want to move all of them to drafts?'
)
: type === 'now'
? t(
'post_now_in_all_channels_question',
'This post was created for more than one channel. Do you want to post all of them now?'
)
: t(
'schedule_post_in_all_channels_question',
'This post was created for more than one channel. Do you want to schedule all of them?'
);
const allChannels =
type === 'draft'
? t('draft_all_channels', 'Move all channels to drafts')
: type === 'now'
? t('post_now_all_channels', 'Post all channels now')
: t('schedule_all_channels', 'Schedule all channels');
const whichChannels = await new Promise((resolve) => {
modal.openModal({
id: 'change-post-channels',
title: t('what_do_you_want_to_do', 'What do you want to do?'),
onClose: () => resolve(undefined),
children: (
<div className="flex flex-col">
<div className="text-[20px] mb-[20px]">{question}</div>
<div className="flex w-full gap-[10px]">
<div className="flex-1 flex">
<Button
type="button"
className="flex-1"
onClick={() => {
modal.closeById('change-post-channels');
resolve('all');
}}
>
{allChannels}
</Button>
</div>
{/* a published channel in view stays published on a draft */}
{!saveAs[channel.integration] && (
<div className="flex-1 flex">
<Button
type="button"
secondary
className="flex-1"
onClick={() => {
modal.closeById('change-post-channels');
resolve('only');
}}
>
{t('only_channel', 'Only')}{' '}
{
integrations.find((p) => p.id === channel.integration)
?.name
}
</Button>
</div>
)}
</div>
</div>
),
});
});
if (!whichChannels) {
return;
}
if (whichChannels === 'only') {
for (const p of others) {
saveAs[p.integration] = asItIs(p);
}
}
}
// the published channels that would go out again
const republishing = published.filter((p) => !saveAs[p.integration]);
if ((type === 'now' || type === 'schedule') && republishing.length) {
const channels = republishing
.map(
(p) =>
`${integrations.find((i) => i.id === p.integration)?.name} ${t(
'republish_at',
'at'
)} ${(channelDates[p.integration] || date).format(
'DD/MM/YYYY HH:mm'
)}`
)
const channels = selectedIntegrations
.map((p) => p.integration.name)
.join(', ');
const isRecurring =
!!repeater || !!existingData?.posts?.[0]?.intervalInDays;
// it closes on a choice, so a save that then fails its checks shows
// the channel to fix
const whatToDo = await new Promise((resolve) => {
modal.openModal({
id: 'republish-post',
title: t('what_do_you_want_to_do', 'What do you want to do?'),
onClose: () => resolve(undefined),
children: (
<div className="flex flex-col">
<div className="text-[20px] mb-[20px]">
@ -485,7 +248,8 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
'post_already_published_republish_warning',
'This post was already published. Republishing will publish it again to'
)}{' '}
{channels}.
{channels} {t('republish_at', 'at')}{' '}
{date.format('DD/MM/YYYY HH:mm')}.
{isRecurring && (
<div className="mt-[10px]">
{t(
@ -500,10 +264,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
<Button
type="button"
className="flex-1"
onClick={() => {
modal.closeById('republish-post');
resolve('update');
}}
onClick={() => resolve('update')}
>
{t(
'just_update_post_details',
@ -515,10 +276,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
<Button
type="button"
className="flex-1"
onClick={() => {
modal.closeById('republish-post');
resolve('republish');
}}
onClick={() => resolve('republish')}
>
{t('republish_the_post', 'Republish the post')}
</Button>
@ -529,14 +287,8 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
});
});
if (!whatToDo) {
return;
}
if (whatToDo === 'update') {
for (const p of republishing) {
saveAs[p.integration] = 'update';
}
type = 'update';
}
if (whatToDo === 'republish') {
@ -560,14 +312,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
integration: {
id: post.id,
},
// every channel of an existing post updates its own post
group:
existingPosts.find((p) => p.integration === post.id)?.group || group,
...(channelDates[post.id]
? {
date: channelDates[post.id].utc().format('YYYY-MM-DDTHH:mm:ss'),
}
: {}),
group,
settings: { ...(post.settings || {}) },
value: post.values.map((value: any) => ({
...(value.id ? { id: value.id } : {}),
@ -587,26 +332,12 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
}));
if (!dummy) {
const validResponse = await fetch('/posts/valid', {
method: 'POST',
body: JSON.stringify({ type, posts }),
});
if (!validResponse.ok) {
if (validResponse.status !== 402) {
const { message } = await validResponse.json().catch(() => ({}));
toaster.show(
typeof message === 'string'
? message
: t('post_save_failed', 'Could not save the post'),
'warning'
);
}
setLoading(false);
return;
}
const checkAllValid = await validResponse.json();
const checkAllValid = await (
await fetch('/posts/valid', {
method: 'POST',
body: JSON.stringify({ type, posts }),
})
).json();
const focus = (id: string, where: 'fix' | 'preview') => {
integrationById(id)?.ref?.current?.[where]?.();
@ -629,50 +360,47 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
return;
}
// a channel saved as a draft gets these checks once it's scheduled
const notDrafts = checkAllValid.filter(
(p: any) => saveTypeOf(p.id) !== 'draft'
);
if (type !== 'draft') {
for (const item of checkAllValid) {
if (item.valid === false) {
toaster.show(
`${capitalize(item.identifier.split('-')[0])} (${item.name}): ${
item.settingsError ||
t('please_fix_your_settings', 'Please fix your settings')
}`,
'warning'
);
focus(item.id, 'fix');
setLoading(false);
setShowSettings(true);
return;
}
for (const item of notDrafts) {
if (item.valid === false) {
toaster.show(
`${capitalize(item.identifier.split('-')[0])} (${item.name}): ${
item.settingsError ||
t('please_fix_your_settings', 'Please fix your settings')
}`,
'warning'
);
focus(item.id, 'fix');
setLoading(false);
setShowSettings(true);
return;
}
if (item.errors !== true) {
toaster.show(
`${capitalize(item.identifier.split('-')[0])} (${item.name}): ${
item.errors
}`,
'warning'
);
focus(item.id, 'preview');
setLoading(false);
setShowSettings(false);
return;
}
if (item.errors !== true) {
toaster.show(
`${capitalize(item.identifier.split('-')[0])} (${item.name}): ${
item.errors
}`,
'warning'
);
focus(item.id, 'preview');
setLoading(false);
setShowSettings(false);
return;
}
if (item.tooLong) {
toaster.show(
`${item.name} (${item.identifier}) ${t(
'post_is_too_long',
'post is too long, please fix it'
)}`,
'warning'
);
focus(item.id, 'preview');
setLoading(false);
return;
if (item.tooLong) {
toaster.show(
`${item.name} (${item.identifier}) ${t(
'post_is_too_long',
'post is too long, please fix it'
)}`,
'warning'
);
focus(item.id, 'preview');
setLoading(false);
return;
}
}
}
}
@ -745,65 +473,23 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
if (addEditSets) {
addEditSets(data);
} else {
// every type of save is its own request, the drafts last, since a
// draft save skips the checks the others still run
let saved = false;
let pendingApproval = false;
for (const requestType of ['update', 'schedule', 'now', 'draft']) {
const request = {
type: requestType,
posts: posts.filter(
(p: any) => saveTypeOf(p.integration.id) === requestType
),
};
if (!request.posts.length) {
continue;
}
const response = await fetch('/posts', {
method: 'POST',
body: JSON.stringify(data),
});
const response = await fetch('/posts', {
method: 'POST',
body: JSON.stringify({ ...data, ...request }),
});
if (!response.ok) {
if (response.status !== 402) {
const { message } = await response.json().catch(() => ({}));
toaster.show(
typeof message === 'string'
? message
: t('post_save_failed', 'Could not save the post'),
'warning'
);
}
// the channels saved before the failure show in the calendar
if (saved) {
mutate();
}
setLoading(false);
return;
if (!response.ok) {
if (response.status !== 402) {
const { message } = await response.json().catch(() => ({}));
toaster.show(
typeof message === 'string'
? message
: t('post_save_failed', 'Could not save the post'),
'warning'
);
}
saved = true;
// Set when the org has requireApprovalForQueue on and this
// caller is a USER-level member - the save was held as a draft
// awaiting an ADMIN/SUPERADMIN instead of being scheduled (see
// PostsService#createPost).
const savedPosts = await response.json().catch(() => []);
if (
Array.isArray(savedPosts) &&
savedPosts.some((p: any) => p?.pendingApproval)
) {
pendingApproval = true;
}
}
if (pendingApproval) {
toaster.show(
t(
'submitted_for_approval',
'Submitted for approval - an admin needs to approve it before it is queued'
),
'warning'
);
setLoading(false);
return;
}
}
@ -826,19 +512,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
}
}
},
[
ref,
repeater,
tags,
date,
channelDates,
current,
integrations,
selectedIntegrations,
addEditSets,
dummy,
shortlinkPreferenceData,
]
[ref, repeater, tags, date, addEditSets, dummy, shortlinkPreferenceData]
);
const scheduleLabel = dummy
@ -927,10 +601,10 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
loading={loading}
>
<DatePicker
onChange={setPickerDate}
date={pickerDate}
onChange={setDate}
date={date}
onOpen={() => {
setDateDraft(pickerDate);
setDateDraft(date);
setMobileSheet('date');
}}
/>
@ -971,8 +645,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
<PicksSocialsComponent toolTip={true} />
</div>
<div className="mobile:hidden">
{/* an existing post keeps its channels */}
{!dummy && !existingData.integration && (
{!dummy && (
<SelectCustomer
onChange={changeCustomer}
integrations={integrations}
@ -997,8 +670,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
<div className="flex flex-1 gap-[6px] mobile:gap-[16px] flex-col">
<div className="flex mobile:items-center mobile:gap-[4px]">
<div className="flex-1 mobile:flex-initial mobile:min-w-0">
{(!existingData.integration ||
!!existingData.siblings?.length) && <SelectCurrent />}
{!existingData.integration && <SelectCurrent />}
</div>
{!existingData.integration && (
<>
@ -1154,7 +826,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
<div>{t('delete_post', 'Delete Post')}</div>
</button>
)}
<DatePicker onChange={setPickerDate} date={pickerDate} />
<DatePicker onChange={setDate} date={date} />
{!addEditSets && (
<button
disabled={
@ -1342,7 +1014,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {
button={{
label: t('save', 'Save'),
onClick: () => {
setPickerDate(dateDraft);
setDate(dateDraft);
setMobileSheet(null);
},
}}

View File

@ -79,25 +79,23 @@ const MentionList: FC = (props: any) => {
}
return (
<div className="dropdown-menu bg-newBgColorInner text-textColor border border-tableBorder rounded-lg shadow-menu max-h-60 overflow-y-auto p-2">
<div className="dropdown-menu bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto p-2">
{props?.items?.none ? (
<div className="flex items-center justify-center p-2 text-textItemBlur">
<div className="flex items-center justify-center p-2 text-gray-500">
We don't have autocomplete for this social media
</div>
) : props?.loading ? (
<div className="flex items-center justify-center p-2 text-textItemBlur">
<div className="flex items-center justify-center p-2 text-gray-500">
Loading...
</div>
) : props?.items ? (
props.items.length === 0 ? (
<div className="p-2 text-textItemBlur text-center">
No results found
</div>
<div className="p-2 text-gray-500 text-center">No results found</div>
) : (
props?.items?.map((item: any, index: any) => (
<button
className={`flex gap-[10px] w-full p-2 text-start rounded ${
index === selectedIndex ? '!bg-newBgLineColor' : ''
className={`flex gap-[10px] w-full p-2 text-start rounded hover:bg-gray-100 ${
index === selectedIndex ? 'bg-blue-100' : ''
}`}
key={item.id || index}
onClick={() => selectItem(index)}
@ -107,12 +105,12 @@ const MentionList: FC = (props: any) => {
alt={item.label}
className="w-[30px] h-[30px] rounded-full object-cover"
/>
<div className="flex-1">{item.label}</div>
<div className="flex-1 text-gray-800">{item.label}</div>
</button>
))
)
) : (
<div className="p-2 text-textItemBlur text-center">Loading...</div>
<div className="p-2 text-gray-500 text-center">Loading...</div>
)}
</div>
);

View File

@ -28,36 +28,6 @@ const PlatformBadge: FC<{ integration: Integrations }> = ({ integration }) => {
);
};
// a channel row with a checkbox, for the phone sheets
export const IntegrationListRow: FC<{
integration: Integrations;
selected: boolean;
onClick: () => void;
}> = ({ integration, selected, onClick }) => {
return (
<div
onClick={onClick}
className="flex items-center gap-[12px] py-[8px] cursor-pointer select-none"
>
<div className="relative">
<ImageWithFallback
fallbackSrc="/no-picture.jpg"
src={integration.picture || '/no-picture.jpg'}
className="rounded-[8px] min-w-[40px] min-h-[40px]"
alt={integration.identifier}
width={40}
height={40}
/>
<PlatformBadge integration={integration} />
</div>
<div className="flex-1 min-w-0 truncate text-[14px] font-[600]">
{integration.name}
</div>
<Check onChange={() => {}} value={selected} />
</div>
);
};
export const PicksSocialsComponent: FC<{
toolTip?: boolean;
list?: boolean;
@ -80,10 +50,7 @@ export const PicksSocialsComponent: FC<{
const availableIntegrations = integrations.filter((f) => {
if (exising.integration) {
return (
f.id === exising.integration ||
!!exising.siblings?.some((sibling) => sibling.integration === f.id)
);
return f.id === exising.integration;
}
return !f.inBetweenSteps && !f.disabled;
});
@ -103,16 +70,35 @@ export const PicksSocialsComponent: FC<{
locked && 'opacity-50 pointer-events-none'
)}
>
{availableIntegrations.map((integration) => (
<IntegrationListRow
key={integration.id}
integration={integration}
selected={selectedIntegrations.some(
(p) => p.integration.id === integration.id
)}
onClick={toggleIntegration(integration)}
/>
))}
{availableIntegrations.map((integration) => {
const selected = selectedIntegrations.some(
(p) => p.integration.id === integration.id
);
return (
<div
key={integration.id}
onClick={toggleIntegration(integration)}
className="flex items-center gap-[12px] py-[8px] cursor-pointer select-none"
>
<div className="relative">
<ImageWithFallback
fallbackSrc="/no-picture.jpg"
src={integration.picture || '/no-picture.jpg'}
className="rounded-[8px] min-w-[40px] min-h-[40px]"
alt={integration.identifier}
width={40}
height={40}
/>
<PlatformBadge integration={integration} />
</div>
<div className="flex-1 min-w-0 truncate text-[14px] font-[600]">
{integration.name}
</div>
<Check onChange={() => {}} value={selected} />
</div>
);
})}
</div>
);
}

View File

@ -83,7 +83,7 @@ export const withProvider = function <T extends object>(params: {
setHide,
} = useLaunchStore(
useShallow((state) => ({
date: state.channelDates[props.id] || state.date,
date: state.date,
tab: state.tab,
global: state.global,
dummy: state.dummy,
@ -218,6 +218,14 @@ export const withProvider = function <T extends object>(params: {
selectedIntegration.integration.additionalSettings || '[]'
)
),
fix: () => {
setCurrent(props.id);
setHide(true);
},
preview: () => {
setCurrent(props.id);
setHide(true);
},
};
},
getValues: () => {
@ -231,17 +239,6 @@ export const withProvider = function <T extends object>(params: {
trigger: () => {
return form.trigger();
},
// a save that failed on this channel brings it into view, with its
// settings showing what is wrong
fix: () => {
setCurrent(props.id);
setHide(true);
form.trigger();
},
preview: () => {
setCurrent(props.id);
setHide(true);
},
}),
[value]
);

View File

@ -126,10 +126,6 @@ export const Providers = [
identifier: 'mastodon',
component: MastodonProvider,
},
{
identifier: 'mastodon-custom',
component: MastodonProvider,
},
{
identifier: 'bluesky',
component: BlueskyProvider,

View File

@ -11,7 +11,6 @@ import { useShallow } from 'zustand/react/shallow';
import { GlobalIcon } from '@gitroom/frontend/components/ui/icons';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { Integrations } from '@gitroom/frontend/components/launches/calendar.context';
import { useExistingData } from '@gitroom/frontend/components/launches/helpers/use.existing.data';
import {
useDecisionModal,
useModals,
@ -53,7 +52,6 @@ export function useHasScroll(ref: RefObject<HTMLElement | null>): boolean {
export const SelectCurrent: FC = () => {
const modals = useDecisionModal();
const existingData = useExistingData();
const {
selectedIntegrations,
current,
@ -104,25 +102,22 @@ export const SelectCurrent: FC = () => {
locked && 'opacity-50 pointer-events-none'
)}
>
{/* an existing post opens on its channels, without the global mode */}
{!existingData.integration && (
<div
onClick={() => {
setHide(true);
setCurrent('global');
}}
className={clsx(
'cursor-pointer flex gap-[8px] rounded-[8px] w-[40px] h-[40px] mobile:w-[44px] mobile:h-[44px] mobile:shrink-0 justify-center items-center bg-newBgLineColor mobile:bg-newSettings',
current !== 'global'
? 'text-[#A3A3A3]'
: 'border mobile:border-[1.5px] border-[#FC69FF] text-[#FC69FF]'
)}
>
<div>
<GlobalIcon className="mobile:w-[24px] mobile:h-[24px]" />
</div>
<div
onClick={() => {
setHide(true);
setCurrent('global');
}}
className={clsx(
'cursor-pointer flex gap-[8px] rounded-[8px] w-[40px] h-[40px] mobile:w-[44px] mobile:h-[44px] mobile:shrink-0 justify-center items-center bg-newBgLineColor mobile:bg-newSettings',
current !== 'global'
? 'text-[#A3A3A3]'
: 'border mobile:border-[1.5px] border-[#FC69FF] text-[#FC69FF]'
)}
>
<div>
<GlobalIcon className="mobile:w-[24px] mobile:h-[24px]" />
</div>
)}
</div>
{selectedIntegrations.map(({ integration }) => (
<div
onClick={() => {
@ -137,18 +132,13 @@ export const SelectCurrent: FC = () => {
: 'border-transparent'
)}
>
{/* an existing post keeps its channels, each with its own content */}
{!existingData.integration && (
<>
<div
onClick={removeSocial(integration)}
className="absolute justify-center items-center flex mobile:hidden w-[8px] h-[8px] -top-[1px] -start-[3px] bg-red-500 rounded-full text-white text-[8px]"
>
X
</div>
<IsGlobal id={integration.id} />
</>
)}
<div
onClick={removeSocial(integration)}
className="absolute justify-center items-center flex mobile:hidden w-[8px] h-[8px] -top-[1px] -start-[3px] bg-red-500 rounded-full text-white text-[8px]"
>
X
</div>
<IsGlobal id={integration.id} />
<div
{...{
'data-tooltip-id': 'tooltip',

View File

@ -30,8 +30,6 @@ interface StoreState {
inlineImages: boolean;
loaded: boolean;
date: dayjs.Dayjs;
// the other channels of an existing post, each with its own date
channelDates: Record<string, dayjs.Dayjs>;
postComment: PostComment;
dummy: boolean;
repeater?: number;
@ -115,7 +113,6 @@ interface StoreState {
setTab: (tab: 0 | 1) => void;
setHide: (hide: boolean) => void;
setDate: (date: dayjs.Dayjs) => void;
setChannelDate: (integrationId: string, date: dayjs.Dayjs) => void;
setRepeater: (repeater: number) => void;
setTags: (tags: { label: string; value: string }[]) => void;
setIsCreateSet: (isCreateSet: boolean) => void;
@ -148,7 +145,6 @@ const initialState = {
comments: true,
activateExitButton: true,
date: newDayjs(),
channelDates: {} as Record<string, dayjs.Dayjs>,
postComment: PostComment.ALL,
tags: [] as { label: string; value: string }[],
totalChars: 0,
@ -541,13 +537,6 @@ export const useLaunchStore = create<StoreState>()((set) => ({
set((state) => ({
date,
})),
setChannelDate: (integrationId: string, date: dayjs.Dayjs) =>
set((state) => ({
channelDates: {
...state.channelDates,
[integrationId]: date,
},
})),
setRepeater: (repeater: number) =>
set((state) => ({
repeater,

View File

@ -2,7 +2,7 @@
import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { Logo } from '@gitroom/frontend/components/new-layout/logo';
import { jakartaSans } from '@gitroom/frontend/fonts/plus-jakarta-sans/plus.jakarta.sans.font';
import { Plus_Jakarta_Sans } from 'next/font/google';
const ModeComponent = dynamic(
() => import('@gitroom/frontend/components/layout/mode.component'),
{
@ -44,6 +44,12 @@ import { FirstBillingComponent } from '@gitroom/frontend/components/billing/firs
import { TrialTracker } from '@gitroom/frontend/components/layout/gtm.component';
import { setSentryUser } from '@gitroom/react/sentry/initialize.sentry.client';
const jakartaSans = Plus_Jakarta_Sans({
weight: ['600', '500', '700'],
style: ['normal', 'italic'],
subsets: ['latin'],
});
export const LayoutComponent = ({ children }: { children: ReactNode }) => {
const fetch = useFetch();
@ -125,14 +131,12 @@ export const LayoutComponent = ({ children }: { children: ReactNode }) => {
<div
id="left-menu"
className={clsx(
'fixed h-full w-[64px] start-[20px] flex flex-1 top-0 mobile:static mobile:h-auto mobile:min-h-full mobile:mx-auto',
user?.admin && 'pt-[52px] max-h-[1000px]:w-[500px]'
'fixed h-full w-[64px] start-[17px] flex flex-1 top-0 mobile:static mobile:h-auto mobile:min-h-full mobile:mx-auto',
user?.admin && 'pt-[60px] max-h-[1000px]:w-[500px]'
)}
>
<div className="flex flex-col h-full gap-[32px] mobile:gap-[16px] flex-1 pt-[12px] pb-[20px] mobile:pb-[12px]">
<div className="flex justify-center">
<Logo />
</div>
<div className="flex flex-col h-full gap-[32px] mobile:gap-[16px] flex-1 py-[12px]">
<Logo />
<TopMenu />
</div>
</div>

View File

@ -107,13 +107,13 @@ export const OAuthSelfHosted: FC<{
removeError={true}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="Settings > Agents on your instance"
placeholder="Settings > Developers on your instance"
autoComplete="off"
spellCheck={false}
/>
<div className="text-[12px] text-gray-400">
You can also paste the MCP URL from Settings &gt; Agents (Developers or
Public API on older versions) in the Instance URL, it includes the key.
You can also paste the MCP URL from Settings &gt; Developers in the
Instance URL, it includes the key.
</div>
</div>

View File

@ -629,7 +629,7 @@ const OnboardingStep2: FC<{ onBack: () => void; onNext: () => void }> = ({
<div className="bg-newTableHeader rounded-[8px] p-[16px] text-[14px] text-customColor18 text-center w-full max-w-[860px] mx-auto">
{t(
'agent_access_unavailable',
'Agent access is not available for your current plan or role. You can set it up later under Settings > Agents.'
'Agent access is not available for your current plan or role. You can set it up later under Settings > Developers.'
)}
</div>
)}
@ -660,7 +660,7 @@ const OnboardingStep2: FC<{ onBack: () => void; onNext: () => void }> = ({
<div className="text-[13px] text-customColor18 text-center">
{t(
'agent_settings_later',
'More agents and full instructions are available under Settings > Agents'
'More agents and full instructions are available under Settings > Developers'
)}
</div>
<button

View File

@ -240,7 +240,7 @@ export const PlatformAnalytics = () => {
{(integration.inBetweenSteps ||
integration.refreshNeeded) && (
<div className="absolute start-0 top-0 w-[39px] h-[46px] cursor-pointer">
<div className="bg-red-500 w-[15px] h-[15px] rounded-full start-0 top-[5px] absolute z-[200] text-[10px] flex justify-center items-center">
<div className="bg-red-500 w-[15px] h-[15px] rounded-full start-0 -top-[5px] absolute z-[200] text-[10px] flex justify-center items-center">
!
</div>
<div className="bg-primary/60 w-[39px] h-[46px] start-0 top-0 absolute rounded-full z-[199]" />

View File

@ -14,6 +14,8 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import { PlugsContext } from '@gitroom/frontend/components/plugs/plugs.context';
import { Plug } from '@gitroom/frontend/components/plugs/plug';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import useCookie from 'react-use-cookie';
import { SVGLine } from '@gitroom/frontend/components/launches/launches.component';
import { LoadingComponent } from '@gitroom/frontend/components/layout/loading';
export const Plugs = () => {
const fetch = useFetch();
@ -50,6 +52,8 @@ export const Plugs = () => {
fallbackData: [],
});
const [collapseMenu, setCollapseMenu] = useCookie('collapseMenu', '0');
const t = useT();
const sortedIntegrations = useMemo(() => {
@ -82,40 +86,73 @@ export const Plugs = () => {
if (isLoading || plugLoading) {
return (
<div className="flex flex-col items-center justify-center">
<div className="bg-newBgColorInner p-[20px] flex flex-1 flex-col gap-[15px] transition-all items-center justify-center">
<LoadingComponent />
</div>
);
}
return (
<div className="flex flex-col gap-[20px]">
<div className="flex flex-col">
<h3 className="text-[20px]">{t('plugs', 'Plugs')}</h3>
</div>
{!sortedIntegrations.length ? (
<div className="bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[16px] items-start">
<div className="text-customColor18">
{t(
'there_are_not_plugs_matching_your_channels',
'There are not plugs matching your channels'
)}
<br />
{t(
'you_have_to_add_x_linkedin_page_threads_or_bluesky',
'You have to add: X, LinkedIn Page, Threads or Bluesky'
)}
</div>
<Button onClick={() => router.push('/launches')}>
{t(
'go_to_the_calendar_to_add_channels',
'Go to the calendar to add channels'
)}
</Button>
if (!sortedIntegrations.length && !isLoading) {
return (
<div className="bg-newBgColorInner p-[20px] flex flex-1 flex-col gap-[15px] transition-all items-center justify-center">
<div>
<img src="/peoplemarketplace.svg" />
</div>
) : (
<>
<div className="flex flex-wrap gap-[8px]">
<div className="text-[48px]">
{t(
'there_are_not_plugs_matching_your_channels',
'There are not plugs matching your channels'
)}
<br />
{t(
'you_have_to_add_x_linkedin_page_threads_or_bluesky',
'You have to add: X, LinkedIn Page, Threads or Bluesky'
)}
</div>
<Button onClick={() => router.push('/launches')}>
{t(
'go_to_the_calendar_to_add_channels',
'Go to the calendar to add channels'
)}
</Button>
</div>
);
}
return (
<>
<div
className={clsx(
'bg-newBgColorInner p-[20px] mobile:p-[12px] flex flex-col gap-[15px] transition-all mobile:w-full',
collapseMenu === '1' ? 'group sidebar w-[100px]' : 'w-[260px]'
)}
>
<div className="flex gap-[12px] flex-col">
<div className="flex items-center mobile:hidden">
<h2 className="group-[.sidebar]:hidden flex-1 text-[20px] font-[500]">
{t('channels')}
</h2>
<div
onClick={() => setCollapseMenu(collapseMenu === '1' ? '0' : '1')}
className="group-[.sidebar]:rotate-[180deg] group-[.sidebar]:mx-auto text-btnText bg-btnSimple rounded-[6px] w-[24px] h-[24px] flex items-center justify-center cursor-pointer select-none"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="7"
height="13"
viewBox="0 0 7 13"
fill="none"
>
<path
d="M6 11.5L1 6.5L6 1.5"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
</div>
<div className="flex gap-[15px] mobile:gap-[12px] flex-col mobile:flex-row mobile:overflow-x-auto mobile:ps-[12px] mobile:pt-[6px] mobile:pb-[6px] scrollbar scrollbar-thumb-fifth scrollbar-track-newBgColor">
{sortedIntegrations.map((integration, index) => (
<div
key={integration.id}
@ -134,27 +171,29 @@ export const Plugs = () => {
setCurrent(index);
}}
className={clsx(
'flex gap-[8px] items-center px-[12px] py-[8px] rounded-[8px] hover:bg-boxHover cursor-pointer',
currentIntegration.id === integration.id
? 'bg-boxHover'
: 'opacity-40 hover:opacity-100'
'flex gap-[8px] items-center justify-center group/profile hover:bg-boxHover rounded-e-[8px] mobile:shrink-0',
currentIntegration.id !== integration.id &&
'opacity-20 hover:opacity-100 cursor-pointer'
)}
>
<div
className={clsx(
'relative rounded-full flex justify-center items-center',
'relative rounded-full flex justify-center items-center gap-[8px]',
integration.disabled && 'opacity-50'
)}
>
{(integration.inBetweenSteps ||
integration.refreshNeeded) && (
<div className="absolute start-0 top-0 w-[36px] h-[36px] cursor-pointer">
<div className="absolute start-0 top-0 w-[39px] h-[46px] cursor-pointer">
<div className="bg-red-500 w-[15px] h-[15px] rounded-full start-0 -top-[5px] absolute z-[200] text-[10px] flex justify-center items-center">
!
</div>
<div className="bg-primary/60 w-[36px] h-[36px] start-0 top-0 absolute rounded-full z-[199]" />
<div className="bg-primary/60 w-[39px] h-[46px] start-0 top-0 absolute rounded-full z-[199]" />
</div>
)}
<div className="h-full w-[4px] -ms-[12px] rounded-s-[3px] opacity-0 group-hover/profile:opacity-100 transition-opacity">
<SVGLine />
</div>
<ImageWithFallback
fallbackSrc={`/icons/platforms/${integration.identifier}.png`}
src={integration.picture}
@ -165,7 +204,7 @@ export const Plugs = () => {
/>
<SafeImage
src={`/icons/platforms/${integration.identifier}.png`}
className="rounded-[8px] absolute z-10 bottom-[-5px] -end-[5px] border border-fifth"
className="rounded-[8px] absolute z-10 bottom-[5px] -end-[5px] border border-fifth"
alt={integration.identifier}
width={18.41}
height={18.41}
@ -173,7 +212,7 @@ export const Plugs = () => {
</div>
<div
className={clsx(
'max-w-[160px] whitespace-nowrap text-ellipsis overflow-hidden',
'flex-1 whitespace-nowrap text-ellipsis overflow-hidden group-[.sidebar]:hidden mobile:hidden',
integration.disabled && 'opacity-50'
)}
>
@ -182,11 +221,13 @@ export const Plugs = () => {
</div>
))}
</div>
<PlugsContext.Provider value={currentIntegrationPlug}>
<Plug />
</PlugsContext.Provider>
</>
)}
</div>
</div>
</div>
<div className="bg-newBgColorInner flex-1 flex-col flex p-[20px] mobile:p-[12px] gap-[12px]">
<PlugsContext.Provider value={currentIntegrationPlug}>
<Plug />
</PlugsContext.Provider>
</div>
</>
);
};

View File

@ -5,7 +5,6 @@ import { Button } from '@gitroom/react/form/button';
import { Input } from '@gitroom/react/form/input';
import { Textarea } from '@gitroom/react/form/textarea';
import { FC, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { FormProvider, useForm } from 'react-hook-form';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
@ -130,28 +129,10 @@ const CommentComposer: FC<{
const toast = useToaster();
const modals = useModals();
const { recaptchaSiteKey } = useVariables();
const {
previewId,
pending,
setPending,
mutate,
teamMembers,
canMention,
} = usePreviewComments();
const { previewId, pending, setPending, mutate } = usePreviewComments();
const [loading, setLoading] = useState(false);
const [mentions, setMentions] = useState<string[]>([]);
const [assignedToId, setAssignedToId] = useState('');
const form = useForm({ values: { content: '' } });
const anchor = parentId ? null : pending;
const toggleMention = useCallback(
(id: string) => () =>
setMentions((current) =>
current.includes(id)
? current.filter((existing) => existing !== id)
: [...current, id]
),
[]
);
const askForName = useCallback(
() =>
@ -228,10 +209,6 @@ const CommentComposer: FC<{
: {}),
...(displayName ? { displayName } : {}),
...(recaptchaToken ? { recaptchaToken } : {}),
...(canMention && mentions.length ? { mentions } : {}),
...(canMention && !parentId && assignedToId
? { assignedToId }
: {}),
}),
}
);
@ -247,8 +224,6 @@ const CommentComposer: FC<{
}
form.reset({ content: '' });
setMentions([]);
setAssignedToId('');
if (anchor) {
setPending(null);
}
@ -258,17 +233,7 @@ const CommentComposer: FC<{
setLoading(false);
}
},
[
user?.id,
recaptchaSiteKey,
previewId,
parentId,
anchor,
askForName,
canMention,
mentions,
assignedToId,
]
[user?.id, recaptchaSiteKey, previewId, parentId, anchor, askForName]
);
return (
@ -303,49 +268,6 @@ const CommentComposer: FC<{
}
maxLength={2000}
/>
{canMention && !!teamMembers.length && (
<div className="flex flex-col gap-[10px] text-[12px]">
{!parentId && (
<label className="flex items-center gap-[8px]">
<span className="text-textItemBlur">
{t('preview_assign_to', 'Assign to')}
</span>
<select
className="bg-transparent border border-newTableBorder rounded-[4px] px-[6px] py-[2px]"
value={assignedToId}
onChange={(event) => setAssignedToId(event.target.value)}
>
<option value="">
{t('preview_unassigned', 'Unassigned')}
</option>
{teamMembers.map((member) => (
<option key={member.id} value={member.id}>
{member.name}
</option>
))}
</select>
</label>
)}
<div className="flex flex-wrap items-center gap-[10px]">
<span className="text-textItemBlur">
{t('preview_mention', 'Mention')}
</span>
{teamMembers.map((member) => (
<label
key={member.id}
className="flex items-center gap-[4px] cursor-pointer"
>
<input
type="checkbox"
checked={mentions.includes(member.id)}
onChange={toggleMention(member.id)}
/>
<span>{member.name}</span>
</label>
))}
</div>
</div>
)}
<div className="flex items-center justify-end gap-[10px] -mt-[14px]">
<svg
xmlns="http://www.w3.org/2000/svg"
@ -384,20 +306,11 @@ const CommentComposer: FC<{
const CommentBody: FC<{ comment: PreviewComment }> = ({ comment }) => {
const t = useT();
const { teamMembers } = usePreviewComments();
const mentionedNames = comment.mentionedUserIds
.map((id) => teamMembers.find((member) => member.id === id)?.name)
.filter(Boolean);
return (
<div className="flex flex-col gap-[4px]">
<div className="text-[14px] whitespace-pre-wrap break-words">
{comment.content}
</div>
{!!mentionedNames.length && (
<div className="text-[12px] text-btnPrimary">
{t('preview_cc', 'cc')}: {mentionedNames.join(', ')}
</div>
)}
<div className="text-[12px] text-textItemBlur">
{comment.name || t('reviewer', 'Reviewer')} ·{' '}
{dayjs(comment.createdAt).format('MMM D, YYYY HH:mm')}
@ -424,7 +337,6 @@ const ThreadCard: FC<{
setActiveThread,
hoveredThread,
setHoveredThread,
teamMembers,
} = usePreviewComments();
const resolved = !!comment.resolvedAt;
const anchored = comment.anchorStart !== null && comment.anchorEnd !== null;
@ -454,24 +366,6 @@ const ThreadCard: FC<{
mutate();
}, [comment.id, resolved]);
const changeAssignee = useCallback(
async (event: { target: { value: string } }) => {
const response = await fetch(`/posts/comments/${comment.id}/assign`, {
method: 'PUT',
body: JSON.stringify({ assignedToId: event.target.value || undefined }),
});
if (!response.ok) {
toast.show(
t('preview_comment_failed', 'Could not post the comment'),
'warning'
);
return;
}
mutate();
},
[comment.id]
);
return (
<div
ref={ref}
@ -496,28 +390,6 @@ const ThreadCard: FC<{
{t('preview_comment_text_changed', 'Text changed')}
</div>
)}
{canResolve && !!teamMembers.length ? (
<select
className="text-[11px] bg-transparent border border-newTableBorder rounded-[4px] px-[4px] py-[1px]"
value={comment.assignedToId || ''}
onChange={changeAssignee}
>
<option value="">{t('preview_unassigned', 'Unassigned')}</option>
{teamMembers.map((member) => (
<option key={member.id} value={member.id}>
{member.name}
</option>
))}
</select>
) : (
!!comment.assignedToName && (
<div className="text-[11px] rounded-[4px] px-[6px] py-[2px] bg-btnSimple">
{t('preview_assigned_to', 'Assigned to {{name}}', {
name: comment.assignedToName,
})}
</div>
)
)}
</div>
{!!comment.anchorQuote && (
<div
@ -592,135 +464,6 @@ const ThreadCard: FC<{
);
};
const ApprovalSection: FC = () => {
const t = useT();
const user = useUser();
const fetch = useFetch();
const toast = useToaster();
const modals = useModals();
const router = useRouter();
const { recaptchaSiteKey } = useVariables();
const { previewId, postState, comments, mutate } = usePreviewComments();
const [loading, setLoading] = useState(false);
const approval = useMemo(
() => comments.find((c) => c.isApproval && !c.parentId),
[comments]
);
const askForName = useCallback(
() =>
new Promise<string | null>((resolve) => {
modals.openModal({
classNames: {
modal: 'bg-transparent text-textColor',
},
title: t('preview_comment_your_name', 'Your name'),
withCloseButton: true,
onClose: () => resolve(null),
children: (close) => (
<ReviewerNameForm
onConfirm={(name) => {
resolve(name);
close();
}}
/>
),
});
}),
[t]
);
const approve = useCallback(async () => {
let displayName: string | undefined;
let recaptchaToken: string | undefined;
if (!user?.id) {
const name = await askForName();
if (!name) {
return;
}
displayName = name;
if (recaptchaSiteKey) {
const token = await loadRecaptchaToken(recaptchaSiteKey).catch(() => {
toast.show(
t('preview_approve_failed', 'Could not approve this post'),
'warning'
);
return null;
});
if (!token) {
return;
}
recaptchaToken = token;
}
}
setLoading(true);
try {
const response = await fetch(`/public/posts/${previewId}/approve`, {
method: 'POST',
body: JSON.stringify({
...(displayName ? { displayName } : {}),
...(recaptchaToken ? { recaptchaToken } : {}),
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
toast.show(
body?.message ||
t('preview_approve_failed', 'Could not approve this post'),
'warning'
);
return;
}
toast.show(
t('preview_approved', 'Post approved and scheduled'),
'success'
);
await mutate();
router.refresh();
} finally {
setLoading(false);
}
}, [user?.id, recaptchaSiteKey, previewId]);
if (postState !== 'DRAFT' && !approval) {
return null;
}
return (
<div className="flex flex-col gap-[10px] rounded-[8px] border border-newTableBorder p-[12px]">
{!!approval && (
<div className="text-[13px] text-textItemBlur">
✓{' '}
{t(
'preview_approved_by',
'{{name}} approved this post for publishing.',
{ name: approval.name || t('reviewer', 'Reviewer') }
)}
</div>
)}
{postState === 'DRAFT' && (
<>
<div className="text-[13px] text-textItemBlur">
{t(
'preview_approve_hint',
'Happy with this draft? Approve it to schedule it for publishing.'
)}
</div>
<Button onClick={approve} loading={loading}>
{t('approve_and_schedule', 'Approve & Schedule')}
</Button>
</>
)}
</div>
);
};
export const CommentsComponents: FC<{ previewId: string }> = () => {
const t = useT();
const user = useUser();
@ -757,7 +500,6 @@ export const CommentsComponents: FC<{ previewId: string }> = () => {
return (
<div className="flex flex-col gap-[16px]">
<ApprovalSection />
<div className="text-[18px] font-[600]">{t('comments', 'Comments')}</div>
<CommentComposer />
{!isLoading && !threads.length && (

View File

@ -10,7 +10,6 @@ import {
} from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useUser } from '@gitroom/frontend/components/layout/user.context';
export interface PreviewComment {
id: string;
@ -21,19 +20,8 @@ export interface PreviewComment {
anchorEnd: number | null;
anchorQuote: string | null;
resolvedAt: string | null;
isApproval: boolean;
createdAt: string;
name: string | null;
mentionedUserIds: string[];
assignedToId: string | null;
assignedToName: string | null;
}
export interface CommentTeamMember {
id: string;
name: string;
email: string;
role: string;
}
export interface PendingAnchor {
@ -51,33 +39,13 @@ export interface ActiveThread {
source: 'mark' | 'card';
}
// `useAuthed` picks the authenticated route (org-scoped, so it returns the
// mention/assignment identities) vs. the fully public one (same comments,
// those identities stripped) - see PostsService.getComments's
// includeInternal gate. Matches CommentComposer's own
// user?.id-vs-public branching for which endpoint to POST to.
const useComments = (previewId: string, useAuthed: boolean) => {
const fetch = useFetch();
const path = useAuthed
? `/posts/${previewId}/comments`
: `/public/posts/${previewId}/comments`;
const load = useCallback(async () => {
return (await fetch(path)).json();
}, [path]);
return useSWR<{ comments: PreviewComment[] }>(path, load);
};
// Backs the @mention/assign picker - only fetched for a logged-in team
// member viewing their own org's preview (the public reviewer never needs,
// or is allowed to see, the team list). A disabled SWR key (null) skips the
// request entirely rather than firing it and discarding the result.
const useCommentTeamMembers = (enabled: boolean) => {
const useComments = (previewId: string) => {
const fetch = useFetch();
const load = useCallback(async () => {
return (await fetch('/posts/comments/team-members')).json();
}, []);
return useSWR<CommentTeamMember[]>(
enabled ? '/posts/comments/team-members' : null,
return (await fetch(`/public/posts/${previewId}/comments`)).json();
}, [previewId]);
return useSWR<{ comments: PreviewComment[] }>(
`/public/posts/${previewId}/comments`,
load
);
};
@ -86,7 +54,6 @@ interface PreviewCommentsContextInterface {
previewId: string;
postIds: string[];
organizationId: string;
postState: string;
comments: PreviewComment[];
isLoading: boolean;
mutate: () => Promise<any>;
@ -96,8 +63,6 @@ interface PreviewCommentsContextInterface {
setActiveThread: (thread: ActiveThread | null) => void;
hoveredThread: string | null;
setHoveredThread: (id: string | null) => void;
teamMembers: CommentTeamMember[];
canMention: boolean;
}
const PreviewCommentsContext = createContext<PreviewCommentsContextInterface>(
@ -108,16 +73,12 @@ export const PreviewCommentsProvider: FC<{
previewId: string;
postIds: string[];
organizationId: string;
postState: string;
children: ReactNode;
}> = ({ previewId, postIds, organizationId, postState, children }) => {
}> = ({ previewId, postIds, organizationId, children }) => {
const { data, mutate, isLoading } = useComments(previewId);
const [pending, setPending] = useState<PendingAnchor | null>(null);
const [activeThread, setActiveThread] = useState<ActiveThread | null>(null);
const [hoveredThread, setHoveredThread] = useState<string | null>(null);
const user = useUser();
const canMention = !!user?.id && user?.orgId === organizationId;
const { data, mutate, isLoading } = useComments(previewId, canMention);
const { data: teamMembers } = useCommentTeamMembers(canMention);
return (
<PreviewCommentsContext.Provider
@ -125,7 +86,6 @@ export const PreviewCommentsProvider: FC<{
previewId,
postIds,
organizationId,
postState,
comments: data?.comments || [],
isLoading,
mutate,
@ -135,8 +95,6 @@ export const PreviewCommentsProvider: FC<{
setActiveThread,
hoveredThread,
setHoveredThread,
teamMembers: teamMembers || [],
canMention,
}}
>
{children}

View File

@ -2,7 +2,7 @@
import { FC } from 'react';
// Logos for the MCP clients shown in Settings > Agents and in onboarding.
// Logos for the MCP clients shown in Settings > Developers and in onboarding.
// Monochrome marks use currentColor so they follow the button text color,
// brand marks (Claude, VS Code, Gemini) keep their colors.
const icons: Record<string, FC<{ size: number }>> = {

View File

@ -1,7 +1,7 @@
'use client';
import { useState, useCallback } from 'react';
import { useSWRConfig } from 'swr';
import { useState, useCallback, useMemo } from 'react';
import useSWR, { useSWRConfig } from 'swr';
import { useUser } from '../layout/user.context';
import copy from 'copy-to-clipboard';
import { useToaster } from '@gitroom/react/toaster/toaster';
@ -9,6 +9,7 @@ import { useVariables } from '@gitroom/react/helpers/variable.context';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useDecisionModal } from '@gitroom/frontend/components/layout/new-modal';
import { DeveloperComponent } from '@gitroom/frontend/components/developer/developer.component';
import { McpClientIcon } from '@gitroom/frontend/components/public-api/mcp.client.icons';
import clsx from 'clsx';
@ -923,11 +924,50 @@ const PublicApiContent = () => {
export const PublicComponent = () => {
const t = useT();
const fetch = useFetch();
const user = useUser();
const [subTab, setSubTab] = useState<'api' | 'developer'>('api');
const loadOrganizations = useCallback(async () => {
return await (await fetch('/user/organizations')).json();
}, []);
const { data: organizations } = useSWR('organizations', loadOrganizations, {
revalidateIfStale: false,
revalidateOnFocus: false,
refreshWhenOffline: false,
refreshWhenHidden: false,
revalidateOnReconnect: false,
});
const currentOrg = useMemo(() => {
return organizations?.find((org: any) => org?.id === user?.orgId);
}, [organizations, user?.orgId]);
return (
<div className="flex flex-col gap-[20px]">
<h3 className="text-[20px]">{t('agents', 'Agents')}</h3>
<PublicApiContent />
<h3 className="text-[20px]">
{t('developers', 'Developers')}
{currentOrg?.name ? ` - ${currentOrg.name}` : ''}
</h3>
<div className="flex gap-[6px]">
{(['api', 'developer'] as const).map((tab) => (
<button
key={tab}
type="button"
className={clsx(
'cursor-pointer px-[20px] h-[44px] text-[15px] font-[600] rounded-[8px] transition-colors',
subTab === tab
? 'bg-[#612BD3] text-white'
: 'bg-btnSimple text-customColor18 hover:bg-boxHover hover:text-textColor'
)}
onClick={() => setSubTab(tab)}
>
{tab === 'api'
? t('access', 'Access')
: t('apps', 'Apps')}
</button>
))}
</div>
{subTab === 'api' && <PublicApiContent />}
{subTab === 'developer' && <DeveloperComponent />}
</div>
);
};

View File

@ -1,93 +0,0 @@
'use client';
import React, { useCallback } from 'react';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
import { Checkbox } from '@gitroom/react/form/checkbox';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
interface ApprovalQueueResponse {
requireApprovalForQueue: boolean;
}
export const useApprovalQueuePreference = () => {
const fetch = useFetch();
const load = useCallback(async () => {
return (await fetch('/settings/approval-queue')).json();
}, []);
return useSWR<ApprovalQueueResponse>('approval-queue-preference', load, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
revalidateOnMount: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
});
};
// Admin-only toggle for Organization.requireApprovalForQueue: once on, a
// USER-level member's schedule/publish-now save is held as a draft awaiting
// an ADMIN/SUPERADMIN approval instead of going straight to the queue (see
// PostsService#createPost). Rendered only for ADMIN/SUPERADMIN callers by
// TeamsComponent - the backend also enforces this via the ADMIN policy on
// POST /settings/approval-queue, so this is a UX nicety, not the real gate.
const ApprovalQueuePreferenceComponent = () => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const { data, isLoading, mutate } = useApprovalQueuePreference();
const toggle = useCallback(async () => {
const newValue = !data?.requireApprovalForQueue;
mutate({ requireApprovalForQueue: newValue });
const response = await fetch('/settings/approval-queue', {
method: 'POST',
body: JSON.stringify({ requireApprovalForQueue: newValue }),
});
if (!response.ok) {
mutate({ requireApprovalForQueue: !newValue });
toaster.show(
t('could_not_update_setting', 'Could not update this setting'),
'warning'
);
return;
}
toaster.show(t('settings_updated', 'Settings updated'), 'success');
}, [data, fetch, mutate, toaster, t]);
if (isLoading) {
return null;
}
return (
<div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[24px]">
<div className="flex items-center justify-between gap-[24px]">
<div className="flex flex-col flex-1">
<div className="text-[14px]">
{t('require_approval_for_queue', 'Require approval before posts go live')}
</div>
<div className="text-[12px] text-customColor18">
{t(
'require_approval_for_queue_description',
'When on, a schedule or publish-now save by a regular team member is held as a draft until an admin approves it.'
)}
</div>
</div>
<Checkbox
name="requireApprovalForQueue"
disableForm={true}
checked={!!data?.requireApprovalForQueue}
onChange={toggle}
/>
</div>
</div>
);
};
export default ApprovalQueuePreferenceComponent;

View File

@ -1,44 +0,0 @@
'use client';
import { FC, useState } from 'react';
import clsx from 'clsx';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { DeveloperComponent } from '@gitroom/frontend/components/developer/developer.component';
import { ApprovedAppsComponent } from '@gitroom/frontend/components/approved-apps/approved-apps.component';
export const AppsComponent: FC<{ canManageApps: boolean }> = ({
canManageApps,
}) => {
const t = useT();
const [subTab, setSubTab] = useState<'apps' | 'approved_apps'>('apps');
const current = canManageApps ? subTab : 'approved_apps';
return (
<div className="flex flex-col gap-[20px]">
<h3 className="text-[20px]">{t('apps', 'Apps')}</h3>
{canManageApps && (
<div className="flex gap-[6px]">
{(['apps', 'approved_apps'] as const).map((tab) => (
<button
key={tab}
type="button"
className={clsx(
'cursor-pointer px-[20px] h-[44px] text-[15px] font-[600] rounded-[8px] transition-colors',
current === tab
? 'bg-[#612BD3] text-white'
: 'bg-btnSimple text-customColor18 hover:bg-boxHover hover:text-textColor'
)}
onClick={() => setSubTab(tab)}
>
{tab === 'apps'
? t('apps', 'Apps')
: t('approved_apps', 'Approved Apps')}
</button>
))}
</div>
)}
{current === 'apps' && <DeveloperComponent />}
{current === 'approved_apps' && <ApprovedAppsComponent />}
</div>
);
};

View File

@ -1,7 +1,6 @@
'use client';
import React, { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { Button } from '@gitroom/react/form/button';
@ -11,62 +10,20 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { TrashIcon } from '@gitroom/frontend/components/ui/icons';
interface DeleteAccountInfo {
hasSubscription: boolean;
hasAdditionalMembers: boolean;
}
export const useDeleteAccountInfo = () => {
const fetch = useFetch();
const load = useCallback(async () => {
return (await fetch('/user/delete-account-info')).json();
}, []);
return useSWR<DeleteAccountInfo>('delete-account-info', load, {
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
revalidateOnMount: true,
refreshWhenHidden: false,
refreshWhenOffline: false,
});
};
const DeleteAccountComponent: FC<{ isLink?: boolean }> = ({ isLink }) => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const { isSecured } = useVariables();
const [loading, setLoading] = useState(false);
const { mutate } = useDeleteAccountInfo();
const deleteAccount = useCallback(async () => {
const info = await mutate();
const message =
info?.hasSubscription && info?.hasAdditionalMembers
? t(
'delete_account_confirm_subscription_members',
'Your account, organizations, channels and posts will be deleted, your subscription will be cancelled and the additional team members will be removed from your organization. This action cannot be undone, are you sure?'
)
: info?.hasSubscription
? t(
'delete_account_confirm_subscription',
'Your account, organizations, channels and posts will be deleted and your subscription will be cancelled. This action cannot be undone, are you sure?'
)
: info?.hasAdditionalMembers
? t(
'delete_account_confirm_members',
'Your account, organizations, channels and posts will be deleted and the additional team members will be removed from your organization. This action cannot be undone, are you sure?'
)
: t(
'delete_account_confirm',
'Your account, organizations, channels and posts will be deleted. This action cannot be undone, are you sure?'
);
if (
!(await deleteDialog(
message,
t(
'delete_account_confirm',
'Your account, organizations, channels and posts will be deleted. This action cannot be undone, are you sure?'
),
t('yes_delete_my_account', 'Yes, delete my account')
))
) {

View File

@ -1,124 +0,0 @@
'use client';
import React, { useCallback } from 'react';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import useSWR from 'swr';
import { Button } from '@gitroom/react/form/button';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { newDayjs } from '@gitroom/frontend/components/layout/set.timezone';
interface PendingApprovalPost {
id: string;
content: string;
publishDate: string;
group: string;
integration: {
id: string;
name: string;
picture: string | null;
providerIdentifier: string;
};
createdBy: { id: string; name: string | null; email: string } | null;
}
// ADMIN/SUPERADMIN-only - every post a USER-level member couldn't queue
// directly because the org has Organization.requireApprovalForQueue on
// (see posts.controller.ts GET /posts/pending-approval). Complements the
// per-post approve/reject actions already on the calendar card itself -
// this is the "don't have to go hunting on the calendar" view.
export const PendingApprovalsComponent = () => {
const t = useT();
const fetch = useFetch();
const toaster = useToaster();
const load = useCallback(async () => {
return (await fetch('/posts/pending-approval')).json();
}, []);
const { data, mutate, isLoading } = useSWR<PendingApprovalPost[]>(
'pending-approval-posts',
load,
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
revalidateIfStale: false,
}
);
const decide = useCallback(
(post: PendingApprovalPost, action: 'approve' | 'reject') => async () => {
const response = await fetch(`/posts/${post.id}/${action}-queue`, {
method: 'PUT',
});
if (!response.ok) {
toaster.show(
t(
'could_not_update_post',
'Could not update this post - it may have already been handled'
),
'warning'
);
mutate();
return;
}
toaster.show(
action === 'approve'
? t('post_approved', 'Post approved and queued')
: t('post_rejected', 'Post rejected'),
'success'
);
mutate();
},
[fetch, mutate, toaster, t]
);
if (isLoading || !data?.length) {
return null;
}
return (
<div className="flex flex-col">
<h3 className="text-[20px]">
{t('pending_approvals', 'Pending Approvals')}
</h3>
<div className="text-customColor18 mt-[4px]">
{t(
'pending_approvals_description',
'Posts saved by team members while approval is required, waiting for you'
)}
</div>
<div className="my-[16px] mt-[16px] bg-sixth border-fifth border rounded-[4px] p-[24px] flex flex-col gap-[16px]">
{data.map((post) => (
<div
key={post.id}
className="flex items-center gap-[12px] border-b border-fifth pb-[12px] last:border-0 last:pb-0"
>
<div className="flex-1 flex flex-col">
<div className="text-[12px] text-customColor18">
{post.createdBy?.name || post.createdBy?.email || t('unknown', 'Unknown')}
{' · '}
{newDayjs(post.publishDate).local().format('MMM D, HH:mm')}
{' · '}
{post.integration.name}
</div>
<div className="text-[14px] line-clamp-2">
{post.content || t('no_content', 'no content')}
</div>
</div>
<div className="flex gap-[8px]">
<Button onClick={decide(post, 'approve')}>
{t('approve', 'Approve')}
</Button>
<Button secondary={true} onClick={decide(post, 'reject')}>
{t('reject', 'Reject')}
</Button>
</div>
</div>
))}
</div>
</div>
);
};
export default PendingApprovalsComponent;

View File

@ -17,8 +17,6 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import copy from 'copy-to-clipboard';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import ApprovalQueuePreferenceComponent from '@gitroom/frontend/components/settings/approval-queue-preference.component';
import { PendingApprovalsComponent } from '@gitroom/frontend/components/settings/pending-approvals.component';
const roles = [
{
@ -119,7 +117,6 @@ export const TeamsComponent = () => {
const fetch = useFetch();
const user = useUser();
const modals = useModals();
const toast = useToaster();
const t = useT();
const myLevel = user?.role === 'USER' ? 0 : user?.role === 'ADMIN' ? 1 : 2;
const getLevel = useCallback(
@ -152,40 +149,6 @@ export const TeamsComponent = () => {
revalidateOnReconnect: false,
revalidateIfStale: false,
});
const loadOrganizations = useCallback(async () => {
return await (await fetch('/user/organizations')).json();
}, []);
// Shares the 'organizations' SWR cache key with the organization switcher
// (organization.selector.tsx) instead of fetching the same list twice.
const { data: organizations } = useSWR('organizations', loadOrganizations, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
const canLeave = (organizations?.length || 0) > 1;
const leaveOrganization = useCallback(async () => {
if (
!(await deleteDialog(
t(
'are_you_sure_leave_organization',
'Are you sure you want to leave this organization? You will lose access to it unless invited back.'
)
))
) {
return;
}
const response = await fetch('/settings/team/leave', { method: 'POST' });
if (!response.ok) {
const { message } = await response.json().catch(() => ({} as any));
toast.show(
(Array.isArray(message) ? message[0] : message) ||
t('could_not_leave_organization', 'Could not leave the organization'),
'warning'
);
return;
}
window.location.href = '/';
}, [t]);
const remove = useCallback(
(toRemove: {
user: {
@ -263,23 +226,12 @@ export const TeamsComponent = () => {
</div>
))}
</div>
<div className="flex gap-[12px]">
<div>
<Button onClick={addMember}>
{t('add_another_member', 'Add another member')}
</Button>
{canLeave && (
<Button secondary={true} onClick={leaveOrganization}>
{t('leave_organization', 'Leave organization')}
</Button>
)}
</div>
</div>
{+myLevel >= 1 && (
<>
<ApprovalQueuePreferenceComponent />
<PendingApprovalsComponent />
</>
)}
</div>
);
};

View File

@ -1,5 +1,6 @@
'use client';
import clsx from 'clsx';
import ImageWithFallback from '@gitroom/react/helpers/image.with.fallback';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { ThirdPartyListComponent } from '@gitroom/frontend/components/third-parties/third-party.list.component';
@ -8,6 +9,8 @@ import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import useCookie from 'react-use-cookie';
import { SVGLine } from '@gitroom/frontend/components/launches/launches.component';
export const ThirdPartyMenuComponent: FC<{
reload: () => void;
@ -61,7 +64,7 @@ export const ThirdPartyMenuComponent: FC<{
{show && (
<div
onClick={(e) => e.stopPropagation()}
className={`absolute top-[100%] end-0 p-[8px] px-[20px] bg-fifth flex flex-col gap-[16px] z-[100] rounded-[8px] border border-tableBorder text-nowrap`}
className={`absolute top-[100%] start-0 mobile:start-auto mobile:end-0 p-[8px] px-[20px] bg-fifth flex flex-col gap-[16px] z-[100] rounded-[8px] border border-tableBorder text-nowrap`}
>
<div
className="flex gap-[12px] items-center"
@ -107,47 +110,99 @@ export const ThirdPartyComponent = () => {
refreshWhenHidden: false,
refreshWhenOffline: false,
});
const [collapseMenu, setCollapseMenu] = useCookie('collapseMenu', '0');
return (
<div className="flex flex-col gap-[20px]">
<div className="flex flex-col">
<h3 className="text-[20px]">{t('integrations', 'Integrations')}</h3>
</div>
{!isLoading && (
<div className="bg-sixth border-fifth border rounded-[4px] p-[24px]">
{!data?.length ? (
<div className="text-customColor18">No Integrations Yet</div>
) : (
<div className="flex flex-col gap-[16px]">
{data?.map((p: any) => (
<div
key={p.id}
className="flex items-center justify-between gap-[12px] p-[12px] border border-fifth rounded-[4px]"
>
<div className="flex items-center gap-[12px] min-w-0">
<ImageWithFallback
fallbackSrc={`/icons/third-party/${p.identifier}.png`}
src={`/icons/third-party/${p.identifier}.png`}
className="rounded-full"
alt={p.title}
width={32}
height={32}
/>
<div
className="text-[14px] whitespace-nowrap text-ellipsis overflow-hidden"
data-tooltip-id="tooltip"
data-tooltip-content={p.title}
>
{p.name}
</div>
</div>
<ThirdPartyMenuComponent reload={mutate} tParty={p} />
</div>
))}
<>
<div
className={clsx(
'bg-newBgColorInner p-[20px] mobile:p-[12px] flex flex-col gap-[15px] transition-all mobile:w-full',
collapseMenu === '1' ? 'group sidebar w-[100px]' : 'w-[260px]'
)}
>
<div className="flex gap-[12px] flex-col">
<div className="flex items-center">
<h2 className="group-[.sidebar]:hidden mobile:group-[.sidebar]:block flex-1 text-[20px] mobile:text-[18px] font-[500]">
{t('integrations')}
</h2>
<div
onClick={() => setCollapseMenu(collapseMenu === '1' ? '0' : '1')}
className="group-[.sidebar]:rotate-[180deg] group-[.sidebar]:mx-auto mobile:hidden text-btnText bg-btnSimple rounded-[6px] w-[24px] h-[24px] flex items-center justify-center cursor-pointer select-none"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="7"
height="13"
viewBox="0 0 7 13"
fill="none"
>
<path
d="M6 11.5L1 6.5L6 1.5"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
)}
</div>
<div className="flex flex-col gap-[10px]">
<div className="flex-1 flex flex-col gap-[14px]">
<div
className={clsx(
'gap-[16px] flex flex-col relative justify-center rounded-e-[8px]'
)}
>
{!isLoading && !data?.length ? (
<div>No Integrations Yet</div>
) : (
data?.map((p: any) => (
<div
key={p.id}
className={clsx('flex gap-[8px] items-center group/profile hover:bg-boxHover')}
>
<div className="h-full w-[4px] rounded-s-[3px] opacity-0 group-hover/profile:opacity-100 transition-opacity">
<SVGLine />
</div>
<div
className={clsx(
'relative rounded-full flex justify-center items-center'
)}
data-tooltip-id="tooltip"
data-tooltip-content={p.title}
>
<ImageWithFallback
fallbackSrc={`/icons/third-party/${p.identifier}.png`}
src={`/icons/third-party/${p.identifier}.png`}
className="rounded-full"
alt={p.title}
width={32}
height={32}
/>
</div>
<div
// @ts-ignore
role="Handle"
className={clsx(
'flex-1 whitespace-nowrap text-ellipsis overflow-hidden group-[.sidebar]:hidden mobile:group-[.sidebar]:block'
)}
data-tooltip-id="tooltip"
data-tooltip-content={p.title}
>
{p.name}
</div>
<ThirdPartyMenuComponent reload={mutate} tParty={p} />
</div>
))
)}
</div>
</div>
</div>
</div>
)}
<ThirdPartyListComponent reload={mutate} />
</div>
</div>
<div className="bg-newBgColorInner flex-1 flex-col flex p-[20px] mobile:p-[12px] gap-[12px]">
<ThirdPartyListComponent reload={mutate} />
</div>
</>
);
};

View File

@ -125,24 +125,11 @@ export const ThirdPartyListComponent: FC<{ reload: () => void }> = (props) => {
[]
);
// Installed on the other platform, not connected here with an API key.
// noopener: the page it ends on closes itself when it has an opener
const install = useCallback(
(installUrl: string) => () => {
window.open(installUrl, '_blank', 'noopener,noreferrer');
},
[]
);
return (
<div className="grid grid-cols-4 tablet:grid-cols-3 mobile:!grid-cols-2 gap-[10px] justify-items-center justify-center">
{data?.map((p: any) => (
<div
onClick={
p.installUrl
? install(p.installUrl)
: addApiKey(p.title, p.identifier)
}
onClick={addApiKey(p.title, p.identifier)}
key={p.identifier}
className="w-full h-full p-[20px] mobile:p-[14px] min-h-[100px] text-[14px] bg-newTableHeader hover:bg-newTableBorder rounded-[8px] transition-all text-textColor relative flex flex-col gap-[15px] cursor-pointer"
>

View File

@ -1,6 +1,6 @@
'use client';
import React, { FC, ReactNode, useEffect } from 'react';
import React, { FC, ReactNode } from 'react';
import {
ChevronRightIcon,
CloseIcon,
@ -52,14 +52,6 @@ export const BottomSheet: FC<{
// the main action under the content, like Done or Save
button?: { label: string; onClick: () => void; disabled?: boolean };
}> = ({ title, onClose, children, button }) => {
// the support chat bubble would cover the sheet button
useEffect(() => {
document.querySelector('body')?.classList.add('bottomSheetOpen');
return () => {
document.querySelector('body')?.classList.remove('bottomSheetOpen');
};
}, []);
return (
<div className="fixed inset-0 z-[600] flex flex-col justify-end">
<div

View File

@ -1,157 +0,0 @@
'use client';
import React, { FC, useCallback, useState } from 'react';
import useSWR from 'swr';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { Button } from '@gitroom/react/form/button';
import { useToaster } from '@gitroom/react/toaster/toaster';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
const DELIVERIES_PAGE_SIZE = 25;
interface Delivery {
id: string;
event: string;
postId: string | null;
url: string;
statusCode: number | null;
success: boolean;
attempts: number;
error: string | null;
durationMs: number | null;
createdAt: string;
}
interface DeliveriesResponse {
total: number;
deliveries: Delivery[];
}
const useDeliveries = (webhookId: string, page: number) => {
const fetch = useFetch();
const load = useCallback(async () => {
return (
await fetch(`/webhooks/${webhookId}/deliveries?page=${page}`)
).json();
}, [webhookId, page]);
return useSWR<DeliveriesResponse>(
`webhooks-deliveries-${webhookId}-${page}`,
load
);
};
const statusLabel = (
delivery: Delivery,
t: (key: string, fallback: string) => string
) => {
if (delivery.success) {
return t('delivered', 'Delivered');
}
return t('failed', 'Failed');
};
export const WebhookDeliveries: FC<{ webhookId: string; name: string }> = ({
webhookId,
name,
}) => {
const t = useT();
const toaster = useToaster();
const [page, setPage] = useState(1);
const { data, isLoading, mutate } = useDeliveries(webhookId, page);
const fetch = useFetch();
const redeliver = useCallback(
(deliveryId: string) => async () => {
const result = await (
await fetch(`/webhooks/deliveries/${deliveryId}/redeliver`, {
method: 'POST',
})
).json();
if (result?.success) {
toaster.show(t('delivery_succeeded', 'Delivery succeeded'), 'success');
} else {
toaster.show(
t('delivery_failed_check_the_log', 'Delivery failed, check the log'),
'warning'
);
}
mutate();
},
[mutate]
);
const totalPages = Math.max(
1,
Math.ceil((data?.total || 0) / DELIVERIES_PAGE_SIZE)
);
return (
<div className="flex flex-col gap-[12px] min-w-[600px]">
<div className="text-[14px] opacity-70">
{t(
'recent_delivery_attempts_for',
`Recent delivery attempts for ${name}`,
{ name }
)}
</div>
{!isLoading && !data?.deliveries?.length && (
<div className="text-customColor18">
{t('no_deliveries_yet', 'No deliveries yet.')}
</div>
)}
{!!data?.deliveries?.length && (
<div className="grid grid-cols-[1.2fr,0.8fr,0.6fr,0.6fr,1.6fr,0.8fr] gap-y-[8px] gap-x-[8px] text-[13px]">
<div className="opacity-60">{t('event', 'Event')}</div>
<div className="opacity-60">{t('date', 'Date')}</div>
<div className="opacity-60">{t('status', 'Status')}</div>
<div className="opacity-60">{t('attempts', 'Attempts')}</div>
<div className="opacity-60">{t('error', 'Error')}</div>
<div className="opacity-60">{t('action', 'Action')}</div>
{data.deliveries.map((delivery) => (
<React.Fragment key={delivery.id}>
<div>{delivery.event}</div>
<div>{new Date(delivery.createdAt).toLocaleString()}</div>
<div
className={
delivery.success ? 'text-customColor28' : 'text-red-500'
}
>
{statusLabel(delivery, t)}
{delivery.statusCode ? ` (${delivery.statusCode})` : ''}
</div>
<div>{delivery.attempts}</div>
<div className="break-all opacity-80">
{delivery.error || '—'}
</div>
<div>
<Button secondary onClick={redeliver(delivery.id)}>
{t('redeliver', 'Redeliver')}
</Button>
</div>
</React.Fragment>
))}
</div>
)}
<div className="flex items-center justify-between mt-[8px]">
<div className="text-[13px] opacity-70">
{t('page_of', `Page ${page} of ${totalPages}`, { page, totalPages })}
</div>
<div className="flex gap-[8px]">
<Button
secondary
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
{t('previous', 'Previous')}
</Button>
<Button
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
{t('next', 'Next')}
</Button>
</div>
</div>
</div>
);
};

View File

@ -16,8 +16,6 @@ import { useToaster } from '@gitroom/react/toaster/toaster';
import clsx from 'clsx';
import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';
import { useT } from '@gitroom/react/translation/get.transation.service.client';
import { WebhookDeliveries } from '@gitroom/frontend/components/webhooks/webhook.deliveries';
import { CopyButton } from '@gitroom/frontend/components/public-api/public.component';
export const Webhooks: FC = () => {
const fetch = useFetch();
@ -59,17 +57,6 @@ export const Webhooks: FC = () => {
},
[]
);
const showLogs = useCallback(
(data: any) => () => {
modal.openModal({
title: t('delivery_log', 'Delivery log'),
withCloseButton: true,
classNames: { modal: 'w-[100%] max-w-[900px]' },
children: <WebhookDeliveries webhookId={data.id} name={data.name} />,
});
},
[t]
);
return (
<div className="flex flex-col">
@ -85,11 +72,10 @@ export const Webhooks: FC = () => {
<div className="my-[16px] mt-[16px] bg-sixth border-fifth items-center border rounded-[4px] p-[24px] flex gap-[24px]">
<div className="flex flex-col w-full">
{!!data?.length && (
<div className="grid grid-cols-[1fr,1fr,1fr,1fr,1fr] w-full gap-y-[10px]">
<div className="grid grid-cols-[1fr,1fr,1fr,1fr] w-full gap-y-[10px]">
<div>{t('name', 'Name')}</div>
<div>{t('url', 'URL')}</div>
<div>{t('edit', 'Edit')}</div>
<div>{t('logs', 'Logs')}</div>
<div>{t('delete', 'Delete')}</div>
{data?.map((p: any) => (
<Fragment key={p.id}>
@ -102,13 +88,6 @@ export const Webhooks: FC = () => {
</Button>
</div>
</div>
<div className="flex flex-col justify-center">
<div>
<Button secondary onClick={showLogs(p)}>
{t('logs', 'Logs')}
</Button>
</div>
</div>
<div className="flex flex-col justify-center">
<div>
<Button onClick={deleteHook(p)}>
@ -137,7 +116,6 @@ const details = object().shape({
name: string().required(),
url: string().url().required(),
integrations: array(),
events: array(),
});
const getWebhookOptions = (t: (key: string, fallback: string) => string) => [
{
@ -149,16 +127,6 @@ const getWebhookOptions = (t: (key: string, fallback: string) => string) => [
value: 'specific',
},
];
const getWebhookEventOptions = (t: (key: string, fallback: string) => string) => [
{
value: 'post.published',
label: t('event_post_published', 'A post is published successfully'),
},
{
value: 'post.failed',
label: t('event_post_failed', 'A post fails to publish'),
},
];
export const AddOrEditWebhook: FC<{
data?: any;
reload: () => void;
@ -172,30 +140,15 @@ export const AddOrEditWebhook: FC<{
);
const modal = useModals();
const toast = useToaster();
const eventOptions = getWebhookEventOptions(t);
const form = useForm({
resolver: yupResolver(details),
values: {
name: data?.name || '',
url: data?.url || '',
integrations: data?.integrations?.map((p: any) => p.integration) || [],
events: data?.events || [],
},
});
const integrations = form.watch('integrations');
const events = form.watch('events') as string[];
const toggleEvent = useCallback(
(value: string) => () => {
const current: string[] = form.getValues('events') || [];
form.setValue(
'events',
current.includes(value)
? current.filter((e) => e !== value)
: [...current, value]
);
},
[]
);
const integration = useCallback(async () => {
return (await fetch('/integrations/list')).json();
}, []);
@ -219,46 +172,19 @@ export const AddOrEditWebhook: FC<{
refreshWhenHidden: false,
refreshWhenOffline: false,
});
const revealSecret = useCallback(
(secret: string) => {
modal.openModal({
title: t('webhook_signing_secret', 'Webhook signing secret'),
withCloseButton: true,
children: (
<div className="flex flex-col gap-[12px]">
<div className="text-customColor18">
{t(
'webhook_secret_shown_once',
"Copy this now, it won't be shown again. Use it to verify the X-Postiz-Signature header (HMAC SHA-256 of the raw request body) on incoming requests."
)}
</div>
<div className="flex items-center gap-[8px]">
<div className="break-all font-mono text-[12px] bg-sixth p-[8px] rounded flex-1">
{secret}
</div>
<CopyButton text={secret} label={t('secret', 'Secret')} />
</div>
</div>
),
});
},
[t]
);
const callBack = useCallback(
async (values: any) => {
const result = await (
await fetch('/webhooks', {
method: data?.id ? 'PUT' : 'POST',
body: JSON.stringify({
...(data?.id
? {
id: data.id,
}
: {}),
...values,
}),
})
).json();
await fetch('/webhooks', {
method: data?.id ? 'PUT' : 'POST',
body: JSON.stringify({
...(data?.id
? {
id: data.id,
}
: {}),
...values,
}),
});
toast.show(
data?.id
? t('webhook_updated_successfully', 'Webhook updated successfully')
@ -266,35 +192,10 @@ export const AddOrEditWebhook: FC<{
'success'
);
modal.closeAll();
if (result?.secret) {
revealSecret(result.secret);
}
reload();
},
[data, integrations, revealSecret]
[data, integrations]
);
const regenerateSecret = useCallback(async () => {
if (
!(await deleteDialog(
t(
'regenerate_secret_confirm',
'Regenerating invalidates the current signing secret - any system verifying it will need the new one. Continue?'
),
t('yes_regenerate', 'Yes, regenerate'),
t('regenerate_webhook_secret', 'Regenerate webhook secret')
))
) {
return;
}
const result = await (
await fetch(`/webhooks/${data.id}/secret`, { method: 'POST' })
).json();
modal.closeAll();
if (result?.secret) {
revealSecret(result.secret);
}
reload();
}, [data, revealSecret]);
const sendTest = useCallback(async () => {
const url = form.getValues('url');
toast.show(t('webhook_sent', 'Webhook send'), 'success');
@ -379,32 +280,6 @@ export const AddOrEditWebhook: FC<{
isMain={true}
/>
)}
<div className="mt-[16px]">
<div className="mb-[8px]">
{t('events', 'Events')}
</div>
<div className="text-customColor18 text-[12px] mb-[8px]">
{t(
'webhook_events_hint',
'Leave everything unchecked to receive every event.'
)}
</div>
<div className="flex flex-col gap-[6px]">
{eventOptions.map((option) => (
<label
key={option.value}
className="flex items-center gap-[8px] cursor-pointer"
>
<input
type="checkbox"
checked={(events || []).includes(option.value)}
onChange={toggleEvent(option.value)}
/>
<span>{option.label}</span>
</label>
))}
</div>
</div>
<div className="flex gap-[10px]">
<Button
type="submit"
@ -430,16 +305,6 @@ export const AddOrEditWebhook: FC<{
>
{t('send_test', 'Send Test')}
</Button>
{!!data?.id && (
<Button
type="button"
secondary={true}
className="mt-[24px]"
onClick={regenerateSecret}
>
{t('regenerate_secret', 'Regenerate secret')}
</Button>
)}
</div>
</div>
</div>

View File

@ -1,93 +0,0 @@
Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

Some files were not shown because too many files have changed in this diff Show More