Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat(api): add PUT /public/v1/posts/:id/settings to update post settings

Gilad Resisi48ab8df07705
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index 5cb53b90d..5c569e8a0 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -27,6 +27,7 @@ import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.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 {
AuthorizationActions,
Sections,
@@ -474,6 +475,21 @@ export class PublicIntegrationsController {
return this._postsService.getMissingContent(org.id, id);
}
+ @Put('/posts/:id/settings')
+ async updatePostSettings(
+ @GetOrgFromRequest() org: Organization,
+ @Param('id') id: string,
+ @Body() body: UpdatePostSettingsDto
+ ) {
+ Sentry.metrics.count('public_api-request', 1);
+ return this._postsService.updatePostSettings(
+ org.id,
+ id,
+ body.settings,
+ 'API'
+ );
+ }
+
@Put('/posts/:id/status')
async changePostStatus(
@GetOrgFromRequest() org: Organization,
diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
index 2a3b2b205..c88850735 100644
--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts
@@ -517,10 +517,15 @@ export class PostsRepository {
body: PostBody,
tags: { value: string; label: string }[],
creationMethod: CreationMethod,
- inter?: number
+ inter?: number,
+ // Keep the existing group instead of rotating it, so open clients
+ // (calendar) holding the group stay valid. Used by out-of-band updates
+ // (agent / MCP / public API); the dashboard keeps the rotate-and-sweep.
+ keepGroup = false
) {
const posts: Post[] = [];
const uuid = uuidv4();
+ const group = keepGroup && body.group ? body.group : uuid;
for (const value of body.value) {
const updateData = (type: 'create' | 'update') => ({
@@ -548,7 +553,7 @@ export class PostsRepository {
: {}),
content: value.content,
delay: value.delay || 0,
- group: uuid,
+ group,
intervalInDays: inter ? +inter : null,
approvedSubmitForOrder: APPROVED_SUBMIT_FOR_ORDER.NO,
...(type === 'create' ? { creationMethod } : {}),
@@ -639,11 +644,29 @@ export class PostsRepository {
)?.id!
: undefined;
- if (body.group) {
+ if (body.group && !keepGroup) {
+ await this._post.model.post.updateMany({
+ where: {
+ group: body.group,
+ deletedAt: null,
+ },
+ data: {
+ parentPostId: null,
+ deletedAt: new Date(),
+ },
+ });
+ }
+
+ // keepGroup: the updated rows still carry the old group, so sweep only the
+ // rows dropped from it (removed comments) by id instead of by group.
+ if (body.group && keepGroup) {
await this._post.model.post.updateMany({
where: {
group: body.group,
deletedAt: null,
+ id: {
+ notIn: posts.map((p) => p.id),
+ },
},
data: {
parentPostId: null,
diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
index 57f73373e..d52dd3fcd 100644
--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
@@ -1,6 +1,7 @@
import {
BadRequestException,
Injectable,
+ NotFoundException,
ValidationPipe,
} from '@nestjs/common';
import { PostsRepository } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.repository';
@@ -876,7 +877,8 @@ export class PostsService {
async createPost(
orgId: string,
body: CreatePostDto,
- creationMethod: CreationMethod
+ creationMethod: CreationMethod,
+ keepGroup = false
): Promise<any[]> {
const postList = [];
for (const post of body.posts) {
@@ -907,7 +909,8 @@ export class PostsService {
post,
body.tags,
creationMethod,
- body.inter
+ body.inter,
+ keepGroup
);
if (!posts?.length) {
@@ -933,6 +936,153 @@ export class PostsService {
return postList;
}
+ // Update ONLY the provider settings of a not-yet-published post (scheduled or
+ // draft). The passed keys are merged into the existing settings; content and
+ // publish date stay as they are, so the running publish workflow is left
+ // untouched (type "update"). Shared by the agent/MCP tool and the public API
+ // PUT /posts/:id/settings so both go through one path.
+ async updatePostSettings(
+ orgId: string,
+ postId: string,
+ settings: Record<string, any>,
+ creationMethod: CreationMethod
+ ): Promise<{ postId: string; publishDate: string }> {
+ // Ordered as post -> comments, root includes integration and tags.
+ const ordered = await this.getPostsRecursively(postId, true, orgId, true);
+
+ const [root] = ordered;
+ if (!root) {
+ throw new NotFoundException('Post not found');
+ }
+
+ if (root.parentPostId) {
+ throw new BadRequestException(
+ 'This id belongs to a comment, pass the id of the main post'
+ );
+ }
+
+ if (root.state !== 'QUEUE' && root.state !== 'DRAFT') {
+ throw new BadRequestException(
+ 'Only scheduled posts that were not published yet (or drafts) can be updated'
+ );
+ }
+
+ if (
+ root.state === 'QUEUE' &&
+ dayjs.utc(root.publishDate).isBefore(dayjs.utc())
+ ) {
+ throw new BadRequestException(
+ 'The publish time of this post already passed, it cannot be updated'
+ );
+ }
+
+ const integration = (root as any).integration;
+
+ let existingSettings: Record<string, any>;
+ try {
+ existingSettings = JSON.parse(root.settings || '{}');
+ } catch (err) {
+ existingSettings = {};
+ }
+
+ // Merge: only the passed keys change, everything else stays.
+ const mergedSettings = {
+ ...existingSettings,
+ ...(settings || {}),
+ __type: integration.providerIdentifier,
+ };
+
+ // Keep the existing content/ids so the posts are updated in place (the
+ // workflow identity is preserved) - only the settings differ.
+ const value = ordered.map((p) => {
+ let image = [];
+ try {
+ image = JSON.parse(p.image || '[]');
+ } catch (err) {}
+ return {
+ id: p.id,
+ content: p.content,
+ delay: p.delay || 0,
+ image,
+ };
+ });
+
+ // Same server-side validation as the dashboard / public create route.
+ const [validation] = await this.validatePosts(orgId, [
+ {
+ integration: { id: integration.id },
+ settings: mergedSettings,
+ value: value.map((p) => ({ content: p.content, image: p.image })),
+ },
+ ]);
+
+ if (validation.emptyContent) {
+ throw new BadRequestException(
+ `${validation.name}: Your post should have at least one character or one image.`
+ );
+ }
+
+ if (root.state !== 'DRAFT') {
+ if (!validation.valid) {
+ throw new BadRequestException(
+ `${validation.name}: ${
+ validation.settingsError || 'Please fix your settings'
+ }`
+ );
+ }
+
+ if (validation.errors !== true) {
+ throw new BadRequestException(
+ `${validation.name}: ${validation.errors}`
+ );
+ }
+
+ if (validation.tooLong) {
+ throw new BadRequestException(
+ `${validation.name}: The maximum characters is ${validation.maximumCharacters}`
+ );
+ }
+ }
+
+ const date = dayjs.utc(root.publishDate).format('YYYY-MM-DDTHH:mm:ss');
+
+ const [output] = await this.createPost(
+ orgId,
+ {
+ date,
+ // Settings-only update: keep the current state and leave the running
+ // publish workflow alone.
+ type: 'update',
+ shortLink: false,
+ tags: ((root as any).tags || []).map((t: any) => ({
+ value: t.tag.name,
+ label: t.tag.name,
+ })),
+ posts: [
+ {
+ integration,
+ group: root.group,
+ settings: mergedSettings,
+ value,
+ },
+ ],
+ } as any,
+ creationMethod,
+ // Keep the group stable: a client may have the calendar open while the
+ // settings are updated out of band, and the calendar links posts by group.
+ true
+ );
+
+ if (!output) {
+ throw new BadRequestException('Failed to update the post');
+ }
+
+ return {
+ postId: output.postId,
+ publishDate: date,
+ };
+ }
+
async separatePosts(content: string, len: number) {
return this._openaiService.separatePosts(content, len);
}
diff --git a/libraries/nestjs-libraries/src/dtos/posts/update.post.settings.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/update.post.settings.dto.ts
new file mode 100644
index 000000000..5ecfd8586
--- /dev/null
+++ b/libraries/nestjs-libraries/src/dtos/posts/update.post.settings.dto.ts
@@ -0,0 +1,7 @@
+import { IsDefined, IsObject } from 'class-validator';
+
+export class UpdatePostSettingsDto {
+ @IsDefined()
+ @IsObject()
+ settings: Record<string, any>;
+}