📨 The ultimate agentic social media scheduling tool 🤖
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: group schedules
Nevo Davida194e3f487da
diff --git a/apps/backend/src/api/routes/public.controller.ts b/apps/backend/src/api/routes/public.controller.tsindex 40cf3542c..235f82a77 100644--- a/apps/backend/src/api/routes/public.controller.ts+++ b/apps/backend/src/api/routes/public.controller.ts@@ -54,8 +54,10 @@ 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 previewreturn (await this._postsService.getPostsRecursively(id, true)).map(- ({ childrenPost, ...p }) => ({+ ({ childrenPost, batchId, ...p }) => ({...p,...(p.integration? {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.tsindex b91591c4a..4f9f9d1ab 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@@ -14,6 +14,7 @@ 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';@@ -134,7 +135,14 @@ export class PublicIntegrationsController {) {Sentry.metrics.count('public_api-request', 1);const body = await this._postsService.mapTypeToPost(- rawBody,+ {+ ...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,+ },org.id,rawBody?.type === 'draft' || true);@@ -598,7 +606,13 @@ export class PublicIntegrationsController {@Body('releaseId') releaseId: string) {Sentry.metrics.count('public_api-request', 1);- return this._postsService.updateReleaseId(org.id, id, releaseId);+ // the batch only links the posts in the dashboard+ const { batchId, ...post } = await this._postsService.updateReleaseId(+ org.id,+ id,+ releaseId+ );+ return post;}@Get('/analytics/:integration')diff --git a/apps/frontend/src/components/launches/helpers/use.existing.data.tsx b/apps/frontend/src/components/launches/helpers/use.existing.data.tsxindex 6b0e96448..5170cbc97 100644--- a/apps/frontend/src/components/launches/helpers/use.existing.data.tsx+++ b/apps/frontend/src/components/launches/helpers/use.existing.data.tsx@@ -5,6 +5,15 @@ 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;diff --git a/apps/frontend/src/components/new-launch/add.edit.modal.tsx b/apps/frontend/src/components/new-launch/add.edit.modal.tsxindex 0e18d4263..aa29e6bbc 100644--- a/apps/frontend/src/components/new-launch/add.edit.modal.tsx+++ b/apps/frontend/src/components/new-launch/add.edit.modal.tsx@@ -12,6 +12,7 @@ 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;@@ -113,6 +114,16 @@ 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) {@@ -132,6 +143,21 @@ 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 {@@ -144,6 +170,8 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {setTags,setEditor,setRepeater,+ selectedIntegrations,+ setChannelDate,} = useLaunchStore(useShallow((state) => ({reset: state.reset,@@ -155,6 +183,8 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {setTags: state.setTags,setEditor: state.setEditor,setRepeater: state.setRepeater,+ selectedIntegrations: state.selectedIntegrations,+ setChannelDate: state.setChannelDate,})));@@ -170,23 +200,28 @@ export const AddEditModalInnerInner: FC<AddEditModalProps> = (props) => {value: p.tag.name,})) || []);+addInternalValue(0,existingData.integration,- 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[],- }))+ postValues(existingData.posts));++ // 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');diff --git a/apps/frontend/src/components/new-launch/manage.modal.tsx b/apps/frontend/src/components/new-launch/manage.modal.tsxindex 2a2d10986..6d466e311 100644--- a/apps/frontend/src/components/new-launch/manage.modal.tsx+++ b/apps/frontend/src/components/new-launch/manage.modal.tsx@@ -103,12 +103,16 @@ 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,@@ -121,9 +125,26 @@ 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 saveconst [dateDraft, setDateDraft] = useState(date);+ // the channels the post already has, each with its own post+ const existingPosts = [existingData, ...(existingData.siblings || [])];+useEffect(() => {if (hide) {setHide(false);@@ -203,6 +224,76 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {const deletePost = useCallback(async () => {setLoading(true);+ if (existingData.siblings?.length) {+ // the channel in view, or the one that was opened+ const channel =+ existingPosts.find((p) => p.integration === current) || existingData;+ 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(@@ -221,19 +312,32 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {mutate();modal.closeAll();return;- }, [existingData, mutate, modal]);+ }, [existingData, mutate, modal, current, integrations]);const schedule = useCallback((type: 'draft' | 'now' | 'schedule' | 'update') => async () => {let republish = false;- if (- (type === 'now' || type === 'schedule') &&- (existingData?.posts?.[0]?.state === 'PUBLISHED' ||- (existingData?.posts?.[0]?.state === 'QUEUE' &&- dayjs().isAfter(date.utc())))- ) {- const channels = selectedIntegrations- .map((p) => p.integration.name)+ // channels saved without changing their state, the rest are saved as `type`+ let updateOnly: string[] = [];+ // 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()))+ );++ if ((type === 'now' || type === 'schedule') && published.length) {+ const channels = published+ .map(+ (p) =>+ `${integrations.find((i) => i.id === p.integration)?.name} ${t(+ 'republish_at',+ 'at'+ )} ${(channelDates[p.integration] || date).format(+ 'DD/MM/YYYY HH:mm'+ )}`+ ).join(', ');const isRecurring =!!repeater || !!existingData?.posts?.[0]?.intervalInDays;@@ -248,8 +352,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {'post_already_published_republish_warning','This post was already published. Republishing will publish it again to')}{' '}- {channels} {t('republish_at', 'at')}{' '}- {date.format('DD/MM/YYYY HH:mm')}.+ {channels}.{isRecurring && (<div className="mt-[10px]">{t(@@ -288,7 +391,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {});if (whatToDo === 'update') {- type = 'update';+ updateOnly = published.map((p) => p.integration);}if (whatToDo === 'republish') {@@ -296,6 +399,29 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {}}+ // another channel whose date already passed would go out right away, it+ // only gets its details saved+ if (type === 'schedule') {+ updateOnly = [+ ...updateOnly,+ ...existingPosts+ .filter(+ (p) =>+ p.integration !== existingData.integration &&+ !published.includes(p) &&+ dayjs().isAfter((channelDates[p.integration] || date).utc())+ )+ .map((p) => p.integration),+ ];+ }++ // a draft of a post with other channels leaves the published ones as they are+ if (type === 'draft' && existingData.siblings?.length) {+ updateOnly = published+ .filter((p) => p.posts[0].state === 'PUBLISHED')+ .map((p) => p.integration);+ }+setLoading(true);// Pull the local values to build the payload, but rely on the server@@ -312,7 +438,14 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {integration: {id: post.id,},- group,+ // 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'),+ }+ : {}),settings: { ...(post.settings || {}) },value: post.values.map((value: any) => ({...(value.id ? { id: value.id } : {}),@@ -473,23 +606,50 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {if (addEditSets) {addEditSets(data);} else {- const response = await fetch('/posts', {- method: 'POST',- body: JSON.stringify(data),- });+ // the channels that only update their details are saved apart, first,+ // since a draft save skips the checks their update still runs+ let saved = false;+ for (const request of [+ {+ type: 'update',+ posts: posts.filter((p: any) =>+ updateOnly.includes(p.integration.id)+ ),+ },+ {+ type,+ posts: posts.filter(+ (p: any) => !updateOnly.includes(p.integration.id)+ ),+ },+ ]) {+ if (!request.posts.length) {+ continue;+ }- 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'- );+ 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;}- setLoading(false);- return;+ saved = true;}}@@ -512,7 +672,17 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {}}},- [ref, repeater, tags, date, addEditSets, dummy, shortlinkPreferenceData]+ [+ ref,+ repeater,+ tags,+ date,+ channelDates,+ integrations,+ addEditSets,+ dummy,+ shortlinkPreferenceData,+ ]);const scheduleLabel = dummy@@ -601,10 +771,10 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {loading={loading}><DatePicker- onChange={setDate}- date={date}+ onChange={setPickerDate}+ date={pickerDate}onOpen={() => {- setDateDraft(date);+ setDateDraft(pickerDate);setMobileSheet('date');}}/>@@ -645,7 +815,8 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {<PicksSocialsComponent toolTip={true} /></div><div className="mobile:hidden">- {!dummy && (+ {/* an existing post keeps its channels */}+ {!dummy && !existingData.integration && (<SelectCustomeronChange={changeCustomer}integrations={integrations}@@ -670,7 +841,8 @@ 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 && <SelectCurrent />}+ {(!existingData.integration ||+ !!existingData.siblings?.length) && <SelectCurrent />}</div>{!existingData.integration && (<>@@ -826,7 +998,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {<div>{t('delete_post', 'Delete Post')}</div></button>)}- <DatePicker onChange={setDate} date={date} />+ <DatePicker onChange={setPickerDate} date={pickerDate} />{!addEditSets && (<buttondisabled={@@ -1014,7 +1186,7 @@ export const ManageModal: FC<AddEditModalProps> = (props) => {button={{label: t('save', 'Save'),onClick: () => {- setDate(dateDraft);+ setPickerDate(dateDraft);setMobileSheet(null);},}}diff --git a/apps/frontend/src/components/new-launch/picks.socials.component.tsx b/apps/frontend/src/components/new-launch/picks.socials.component.tsxindex 0979a1931..caae02537 100644--- a/apps/frontend/src/components/new-launch/picks.socials.component.tsx+++ b/apps/frontend/src/components/new-launch/picks.socials.component.tsx@@ -50,7 +50,10 @@ export const PicksSocialsComponent: FC<{const availableIntegrations = integrations.filter((f) => {if (exising.integration) {- return f.id === exising.integration;+ return (+ f.id === exising.integration ||+ !!exising.siblings?.some((sibling) => sibling.integration === f.id)+ );}return !f.inBetweenSteps && !f.disabled;});diff --git a/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx b/apps/frontend/src/components/new-launch/providers/high.order.provider.tsxindex 93d29f2b2..71fb27786 100644--- a/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx+++ b/apps/frontend/src/components/new-launch/providers/high.order.provider.tsx@@ -83,7 +83,7 @@ export const withProvider = function <T extends object>(params: {setHide,} = useLaunchStore(useShallow((state) => ({- date: state.date,+ date: state.channelDates[props.id] || state.date,tab: state.tab,global: state.global,dummy: state.dummy,diff --git a/apps/frontend/src/components/new-launch/select.current.tsx b/apps/frontend/src/components/new-launch/select.current.tsxindex bea6d8edf..de1b857dc 100644--- a/apps/frontend/src/components/new-launch/select.current.tsx+++ b/apps/frontend/src/components/new-launch/select.current.tsx@@ -11,6 +11,7 @@ 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,@@ -52,6 +53,7 @@ export function useHasScroll(ref: RefObject<HTMLElement | null>): boolean {export const SelectCurrent: FC = () => {const modals = useDecisionModal();+ const existingData = useExistingData();const {selectedIntegrations,current,@@ -102,22 +104,25 @@ export const SelectCurrent: FC = () => {locked && 'opacity-50 pointer-events-none')}>- <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]" />+ {/* 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>- </div>+ )}{selectedIntegrations.map(({ integration }) => (<divonClick={() => {@@ -132,13 +137,18 @@ export const SelectCurrent: FC = () => {: 'border-transparent')}>- <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} />+ {/* 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{...{'data-tooltip-id': 'tooltip',diff --git a/apps/frontend/src/components/new-launch/store.ts b/apps/frontend/src/components/new-launch/store.tsindex 1c0f51796..706350719 100644--- a/apps/frontend/src/components/new-launch/store.ts+++ b/apps/frontend/src/components/new-launch/store.ts@@ -30,6 +30,8 @@ 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;@@ -113,6 +115,7 @@ 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;@@ -145,6 +148,7 @@ 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,@@ -537,6 +541,13 @@ 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,diff --git a/i18n.lock b/i18n.lockindex 92839f772..aa0003366 100644--- a/i18n.lock+++ b/i18n.lock@@ -833,3 +833,6 @@ checksums:channels_settings: 770e5ae7cec0a83e1454246b52591093delete_selected: adad57b0659260858fbf786ef31e9612are_you_sure_you_want_to_delete_selected_media: 2fcf9a6ddcd40aa74d2cf914730ecc4b+ delete_post_from_all_channels_question: f37374b458fa43056a019397f342ea04+ delete_from_all_channels: 39a7f754c6a1f730cd511307e483e13d+ delete_only_from: 819a30bf30916eba1d5ced11efc16fdediff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.tsindex eedb18687..c2830afdd 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts@@ -405,6 +405,26 @@ export class PostsRepository {});}+ // the posts of the other channels in the batch, without the given group+ getPostsByBatch(orgId: string, batchId: string, exceptGroup: string) {+ return this._post.model.post.findMany({+ where: {+ organizationId: orgId,+ batchId,+ group: {+ not: exceptGroup,+ },+ deletedAt: null,+ integration: {+ deletedAt: null,+ },+ },+ orderBy: {+ createdAt: 'asc',+ },+ });+ }+getPost(id: string,includeIntegration = false,@@ -594,12 +614,40 @@ export class PostsRepository {// 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+ keepGroup = false,+ // Shared by the posts saved together for several channels, so opening one+ // of them in the editor brings the others.+ batchId?: string) {const posts: Post[] = [];const uuid = uuidv4();const group = keepGroup && body.group ? body.group : uuid;+ // an edited post stays in the batch it was created in, even when it is+ // saved on its own or with a group that was rotated since+ const ids = body.value.map((value) => value.id).filter(Boolean);+ const existingBatchId =+ body.group || ids.length+ ? (+ await this._post.model.post.findFirst({+ where: {+ organizationId: orgId,+ deletedAt: null,+ batchId: {+ not: null,+ },+ OR: [+ ...(body.group ? [{ group: body.group }] : []),+ ...(ids.length ? [{ id: { in: ids } }] : []),+ ],+ },+ select: {+ batchId: true,+ },+ })+ )?.batchId+ : undefined;+for (const value of body.value) {const updateData = (type: 'create' | 'update') => ({publishDate: dayjs(date).toDate(),@@ -627,6 +675,7 @@ export class PostsRepository {content: value.content,delay: value.delay || 0,group,+ batchId: existingBatchId || batchId,intervalInDays: inter ? +inter : null,approvedSubmitForOrder: APPROVED_SUBMIT_FOR_ORDER.NO,...(type === 'create' ? { creationMethod } : {}),diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 5dc2fe559..b3e168d70 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -18,7 +18,8 @@ import {} from '@prisma/client';import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';import { GetPostsListDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.list.dto';-import { shuffle } from 'lodash';+import { groupBy, shuffle, uniqBy } from 'lodash';+import { v4 as uuidv4 } from 'uuid';import { CreateGeneratedPostsDto } from '@gitroom/nestjs-libraries/dtos/generator/create.generated.posts.dto';import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';import { makeId } from '@gitroom/nestjs-libraries/services/make.is';@@ -646,18 +647,63 @@ export class PostsService {}async getPostsByGroup(orgId: string, group: string) {- const convertToJPEG = false;const loadAll = await this._postRepository.getPostsByGroup(orgId, group);const posts = this.arrangePostsByGroup(loadAll, undefined);if (!posts.length) {throw new NotFoundException('Post not found');}+ const batch = posts[0].batchId+ ? await this._postRepository.getPostsByBatch(+ orgId,+ posts[0].batchId,+ group+ )+ : [];++ // the other channels the post was created with, the editor holds one+ // post per channel, and a channel that repeats differently is its own post+ const siblings = uniqBy(+ Object.values(groupBy(batch, (post) => post.group))+ .map((batchPosts) => this.arrangePostsByGroup(batchPosts, undefined))+ .filter(+ (batchPosts) =>+ batchPosts.length &&+ batchPosts[0].integrationId !== posts[0].integrationId &&+ batchPosts[0].intervalInDays === posts[0].intervalInDays+ ),+ (batchPosts) => batchPosts[0].integrationId+ );++ return {+ ...(await this.groupForEditor(posts)),+ siblings: await Promise.all(+ siblings.map((batchPosts) => this.groupForEditor(batchPosts))+ ),+ };+ }++ // the post as the editor loads it, its channel without the tokens+ private async groupForEditor(+ posts: PostWithConditionals[],+ convertToJPEG = false+ ) {return {group: posts?.[0]?.group,posts: await Promise.all(- (posts || []).map(async (post) => ({+ (posts || []).map(async ({ integration, ...post }) => ({...post,+ ...(integration+ ? {+ integration: {+ id: integration.id,+ name: integration.name,+ picture: integration.picture,+ providerIdentifier: integration.providerIdentifier,+ profile: integration.profile,+ },+ }+ : {}),image: await this.updateMedia(post.id,JSON.parse(post.image || '[]'),@@ -695,24 +741,7 @@ export class PostsService {throw new NotFoundException('Post not found');}- const list = {- group: posts?.[0]?.group,- posts: await Promise.all(- (posts || []).map(async (post) => ({- ...post,- image: await this.updateMedia(- post.id,- JSON.parse(post.image || '[]'),- convertToJPEG- ),- }))- ),- integrationPicture: posts[0]?.integration?.picture,- integration: posts[0].integrationId,- settings: JSON.parse(posts[0].settings || '{}'),- };-- return list;+ return this.groupForEditor(posts, convertToJPEG);}async getOldPosts(orgId: string, date: string) {@@ -1074,6 +1103,7 @@ export class PostsService {keepGroup = false): Promise<any[]> {const postList = [];+ const batchId = uuidv4();for (const post of body.posts) {if ((body.type === 'schedule' || body.type === 'now') &&@@ -1108,12 +1138,15 @@ export class PostsService {const { posts } = await this._postRepository.createOrUpdatePost(body.type,orgId,- body.type === 'now' ? dayjs().format('YYYY-MM-DDTHH:mm:00') : body.date,+ body.type === 'now'+ ? dayjs().format('YYYY-MM-DDTHH:mm:00')+ : post.date || body.date,post,body.tags,creationMethod,body.inter,- keepGroup+ keepGroup,+ batchId);if (!posts?.length) {diff --git a/libraries/nestjs-libraries/src/database/prisma/schema.prisma b/libraries/nestjs-libraries/src/database/prisma/schema.prismaindex 39165caf3..f3feb10aa 100644--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma@@ -463,6 +463,7 @@ model Post {content Stringdelay Int @default(0)group String+ batchId String?title String?description String?parentPostId String?@@ -493,6 +494,7 @@ model Post {tags TagsPosts[]@@index([group])+ @@index([batchId])@@index([deletedAt])@@index([publishDate])@@index([state])diff --git a/libraries/nestjs-libraries/src/dtos/posts/create.post.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/create.post.dto.tsindex b7c82c8bf..471e3d609 100644--- a/libraries/nestjs-libraries/src/dtos/posts/create.post.dto.ts+++ b/libraries/nestjs-libraries/src/dtos/posts/create.post.dto.ts@@ -68,6 +68,11 @@ export class Post {@IsString()group: string;+ // a channel that keeps a date of its own, the others use the post date+ @IsOptional()+ @IsDateString()+ date?: string;+@ValidateIf((o) => o.type !== 'draft')@ValidateNested()@Type(() => EmptySettings, {diff --git a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json b/libraries/react-shared-libraries/src/translation/locales/ar/translation.jsonindex 4e86e0452..c3a231462 100644--- a/libraries/react-shared-libraries/src/translation/locales/ar/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ar/translation.json@@ -828,5 +828,8 @@"time": "الوقت","channels_settings": "إعدادات القناة","delete_selected": "حذف المحدد",- "are_you_sure_you_want_to_delete_selected_media": "هل أنت متأكد أنك تريد حذف الوسائط المحددة؟"+ "are_you_sure_you_want_to_delete_selected_media": "هل أنت متأكد أنك تريد حذف الوسائط المحددة؟",+ "delete_post_from_all_channels_question": "تم إنشاء هذا المنشور لأكثر من قناة. هل تريد حذفه منها جميعًا؟",+ "delete_from_all_channels": "حذف من جميع القنوات",+ "delete_only_from": "فقط من"}diff --git a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json b/libraries/react-shared-libraries/src/translation/locales/bn/translation.jsonindex 6a2c1e39c..0fd0db229 100644--- a/libraries/react-shared-libraries/src/translation/locales/bn/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/bn/translation.json@@ -828,5 +828,8 @@"time": "সময়","channels_settings": "চ্যানেল সেটিংস","delete_selected": "নির্বাচিতগুলো মুছে ফেলুন",- "are_you_sure_you_want_to_delete_selected_media": "আপনি কি নিশ্চিত যে আপনি নির্বাচিত মিডিয়া মুছে ফেলতে চান?"+ "are_you_sure_you_want_to_delete_selected_media": "আপনি কি নিশ্চিত যে আপনি নির্বাচিত মিডিয়া মুছে ফেলতে চান?",+ "delete_post_from_all_channels_question": "এই পোস্টটি একাধিক চ্যানেলের জন্য তৈরি করা হয়েছে। আপনি কি এটি সবগুলো থেকে মুছে ফেলতে চান?",+ "delete_from_all_channels": "সব চ্যানেল থেকে মুছে ফেলুন",+ "delete_only_from": "শুধুমাত্র চ্যানেল থেকে:"}diff --git a/libraries/react-shared-libraries/src/translation/locales/de/translation.json b/libraries/react-shared-libraries/src/translation/locales/de/translation.jsonindex 3a05675d0..ba7c2ada7 100644--- a/libraries/react-shared-libraries/src/translation/locales/de/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/de/translation.json@@ -828,5 +828,8 @@"time": "Uhrzeit","channels_settings": "Kanaleinstellungen","delete_selected": "Ausgewählte löschen",- "are_you_sure_you_want_to_delete_selected_media": "Bist du sicher, dass du die ausgewählten Medien löschen möchtest?"+ "are_you_sure_you_want_to_delete_selected_media": "Bist du sicher, dass du die ausgewählten Medien löschen möchtest?",+ "delete_post_from_all_channels_question": "Dieser Beitrag wurde für mehr als einen Kanal erstellt. Möchtest du ihn aus allen löschen?",+ "delete_from_all_channels": "Aus allen Kanälen löschen",+ "delete_only_from": "Nur aus"}diff --git a/libraries/react-shared-libraries/src/translation/locales/en/translation.json b/libraries/react-shared-libraries/src/translation/locales/en/translation.jsonindex a1b777060..f67281438 100644--- a/libraries/react-shared-libraries/src/translation/locales/en/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/en/translation.json@@ -830,5 +830,8 @@"time": "Time","channels_settings": "Channel Settings","delete_selected": "Delete Selected",- "are_you_sure_you_want_to_delete_selected_media": "Are you sure you want to delete the selected media?"+ "are_you_sure_you_want_to_delete_selected_media": "Are you sure you want to delete the selected media?",+ "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?",+ "delete_from_all_channels": "Delete from all channels",+ "delete_only_from": "Only from"}diff --git a/libraries/react-shared-libraries/src/translation/locales/es/translation.json b/libraries/react-shared-libraries/src/translation/locales/es/translation.jsonindex 18b229da9..a1c10d0af 100644--- a/libraries/react-shared-libraries/src/translation/locales/es/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/es/translation.json@@ -828,5 +828,8 @@"time": "Hora","channels_settings": "Configuración del canal","delete_selected": "Eliminar seleccionados",- "are_you_sure_you_want_to_delete_selected_media": "¿Estás seguro de que quieres eliminar los medios seleccionados?"+ "are_you_sure_you_want_to_delete_selected_media": "¿Estás seguro de que quieres eliminar los medios seleccionados?",+ "delete_post_from_all_channels_question": "Esta publicación se creó para más de un canal. ¿Quieres eliminarla de todos?",+ "delete_from_all_channels": "Eliminar de todos los canales",+ "delete_only_from": "Solo de"}diff --git a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json b/libraries/react-shared-libraries/src/translation/locales/fr/translation.jsonindex cc77b63b3..2ff94b3e1 100644--- a/libraries/react-shared-libraries/src/translation/locales/fr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/fr/translation.json@@ -828,5 +828,8 @@"time": "Heure","channels_settings": "Paramètres des canaux","delete_selected": "Supprimer la sélection",- "are_you_sure_you_want_to_delete_selected_media": "Êtes-vous sûr de vouloir supprimer les médias sélectionnés ?"+ "are_you_sure_you_want_to_delete_selected_media": "Êtes-vous sûr de vouloir supprimer les médias sélectionnés ?",+ "delete_post_from_all_channels_question": "Ce post a été créé pour plusieurs canaux. Voulez-vous le supprimer de tous ?",+ "delete_from_all_channels": "Supprimer de tous les canaux",+ "delete_only_from": "Uniquement sur"}diff --git a/libraries/react-shared-libraries/src/translation/locales/he/translation.json b/libraries/react-shared-libraries/src/translation/locales/he/translation.jsonindex b9a98344c..c0e6332c6 100644--- a/libraries/react-shared-libraries/src/translation/locales/he/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/he/translation.json@@ -828,5 +828,8 @@"time": "שעה","channels_settings": "הגדרות ערוץ","delete_selected": "מחק את הנבחרים",- "are_you_sure_you_want_to_delete_selected_media": "האם אתה בטוח שברצונך למחוק את המדיה שנבחרה?"+ "are_you_sure_you_want_to_delete_selected_media": "האם אתה בטוח שברצונך למחוק את המדיה שנבחרה?",+ "delete_post_from_all_channels_question": "הפוסט הזה נוצר עבור יותר מערוץ אחד. האם ברצונך למחוק אותו מכולם?",+ "delete_from_all_channels": "מחק מכל הערוצים",+ "delete_only_from": "רק מהערוץ"}diff --git a/libraries/react-shared-libraries/src/translation/locales/it/translation.json b/libraries/react-shared-libraries/src/translation/locales/it/translation.jsonindex cf9cbc3e7..b105b053a 100644--- a/libraries/react-shared-libraries/src/translation/locales/it/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/it/translation.json@@ -828,5 +828,8 @@"time": "Ora","channels_settings": "Impostazioni del canale","delete_selected": "Elimina selezionati",- "are_you_sure_you_want_to_delete_selected_media": "Sei sicuro di voler eliminare i media selezionati?"+ "are_you_sure_you_want_to_delete_selected_media": "Sei sicuro di voler eliminare i media selezionati?",+ "delete_post_from_all_channels_question": "Questo post è stato creato per più di un canale. Vuoi eliminarlo da tutti?",+ "delete_from_all_channels": "Elimina da tutti i canali",+ "delete_only_from": "Solo da"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json b/libraries/react-shared-libraries/src/translation/locales/ja/translation.jsonindex 16f9fef3d..c8e2c1a59 100644--- a/libraries/react-shared-libraries/src/translation/locales/ja/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ja/translation.json@@ -828,5 +828,8 @@"time": "時刻","channels_settings": "チャンネル設定","delete_selected": "選択したものを削除",- "are_you_sure_you_want_to_delete_selected_media": "選択したメディアを削除してもよろしいですか?"+ "are_you_sure_you_want_to_delete_selected_media": "選択したメディアを削除してもよろしいですか?",+ "delete_post_from_all_channels_question": "この投稿は複数のチャンネル向けに作成されました。すべてのチャンネルから削除しますか?",+ "delete_from_all_channels": "すべてのチャンネルから削除",+ "delete_only_from": "このチャンネルのみ:"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json b/libraries/react-shared-libraries/src/translation/locales/ko/translation.jsonindex d1ffbf15c..af29a940e 100644--- a/libraries/react-shared-libraries/src/translation/locales/ko/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ko/translation.json@@ -828,5 +828,8 @@"time": "시간","channels_settings": "채널 설정","delete_selected": "선택 항목 삭제",- "are_you_sure_you_want_to_delete_selected_media": "선택한 미디어를 삭제하시겠습니까?"+ "are_you_sure_you_want_to_delete_selected_media": "선택한 미디어를 삭제하시겠습니까?",+ "delete_post_from_all_channels_question": "이 게시글은 여러 채널용으로 만들어졌습니다. 모든 채널에서 삭제하시겠습니까?",+ "delete_from_all_channels": "모든 채널에서 삭제",+ "delete_only_from": "다음 채널에서만:"}diff --git a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json b/libraries/react-shared-libraries/src/translation/locales/pt/translation.jsonindex 2e573e5c7..ca4ed8e0d 100644--- a/libraries/react-shared-libraries/src/translation/locales/pt/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/pt/translation.json@@ -828,5 +828,8 @@"time": "Hora","channels_settings": "Configurações do canal","delete_selected": "Excluir selecionados",- "are_you_sure_you_want_to_delete_selected_media": "Tem certeza de que deseja excluir as mídias selecionadas?"+ "are_you_sure_you_want_to_delete_selected_media": "Tem certeza de que deseja excluir as mídias selecionadas?",+ "delete_post_from_all_channels_question": "Esta publicação foi criada para mais de um canal. Deseja excluí-la de todos?",+ "delete_from_all_channels": "Excluir de todos os canais",+ "delete_only_from": "Apenas de"}diff --git a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json b/libraries/react-shared-libraries/src/translation/locales/ru/translation.jsonindex 6343ebfa4..de9cfd54c 100644--- a/libraries/react-shared-libraries/src/translation/locales/ru/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/ru/translation.json@@ -828,5 +828,8 @@"time": "Время","channels_settings": "Настройки канала","delete_selected": "Удалить выбранные",- "are_you_sure_you_want_to_delete_selected_media": "Вы уверены, что хотите удалить выбранные медиа?"+ "are_you_sure_you_want_to_delete_selected_media": "Вы уверены, что хотите удалить выбранные медиа?",+ "delete_post_from_all_channels_question": "Этот пост создан для нескольких каналов. Удалить его из всех?",+ "delete_from_all_channels": "Удалить из всех каналов",+ "delete_only_from": "Только из канала"}diff --git a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json b/libraries/react-shared-libraries/src/translation/locales/tr/translation.jsonindex 4b316cd53..f89f805f6 100644--- a/libraries/react-shared-libraries/src/translation/locales/tr/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/tr/translation.json@@ -828,5 +828,8 @@"time": "Saat","channels_settings": "Kanal Ayarları","delete_selected": "Seçilenleri sil",- "are_you_sure_you_want_to_delete_selected_media": "Seçili medyayı silmek istediğinizden emin misiniz?"+ "are_you_sure_you_want_to_delete_selected_media": "Seçili medyayı silmek istediğinizden emin misiniz?",+ "delete_post_from_all_channels_question": "Bu gönderi birden fazla kanal için oluşturuldu. Hepsinden silmek istiyor musunuz?",+ "delete_from_all_channels": "Tüm kanallardan sil",+ "delete_only_from": "Yalnızca şu kanaldan:"}diff --git a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json b/libraries/react-shared-libraries/src/translation/locales/vi/translation.jsonindex f08cd77aa..185309cad 100644--- a/libraries/react-shared-libraries/src/translation/locales/vi/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/vi/translation.json@@ -828,5 +828,8 @@"time": "Giờ","channels_settings": "Cài đặt kênh","delete_selected": "Xóa mục đã chọn",- "are_you_sure_you_want_to_delete_selected_media": "Bạn có chắc muốn xóa phương tiện đã chọn không?"+ "are_you_sure_you_want_to_delete_selected_media": "Bạn có chắc muốn xóa phương tiện đã chọn không?",+ "delete_post_from_all_channels_question": "Bài đăng này được tạo cho nhiều kênh. Bạn có muốn xóa nó khỏi tất cả các kênh không?",+ "delete_from_all_channels": "Xóa khỏi tất cả các kênh",+ "delete_only_from": "Chỉ từ"}diff --git a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json b/libraries/react-shared-libraries/src/translation/locales/zh/translation.jsonindex 780ea3904..e65d065ac 100644--- a/libraries/react-shared-libraries/src/translation/locales/zh/translation.json+++ b/libraries/react-shared-libraries/src/translation/locales/zh/translation.json@@ -828,5 +828,8 @@"time": "时间","channels_settings": "频道设置","delete_selected": "删除所选",- "are_you_sure_you_want_to_delete_selected_media": "你确定要删除所选媒体吗?"+ "are_you_sure_you_want_to_delete_selected_media": "你确定要删除所选媒体吗?",+ "delete_post_from_all_channels_question": "此帖子是为多个频道创建的。要从所有频道中删除它吗?",+ "delete_from_all_channels": "从所有频道删除",+ "delete_only_from": "只删除"}