π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: import post
Nevo David666de6ac063b
diff --git a/apps/backend/src/api/routes/posts.controller.ts b/apps/backend/src/api/routes/posts.controller.tsindex 84b1b7486..790df94f5 100644--- a/apps/backend/src/api/routes/posts.controller.ts+++ b/apps/backend/src/api/routes/posts.controller.ts@@ -3,6 +3,7 @@ import {Controller,Delete,Get,+ HttpException,Param,Post,Put,@@ -144,6 +145,18 @@ export class PostsController {return this._postsService.getOldPosts(org.id, date);}+ @Get('/group/:group/debug-export')+ async getPostGroupDebugExport(+ @GetOrgFromRequest() org: Organization,+ @GetUserFromRequest() user: User,+ @Param('group') group: string+ ) {+ if (!user.isSuperAdmin) {+ throw new HttpException('Forbidden', 403);+ }+ return this._postsService.getPostGroupDebugExport(org.id, group);+ }+@Get('/group/:group')getPostsByGroup(@GetOrgFromRequest() org: Organization, @Param('group') group: string) {return this._postsService.getPostsByGroup(org.id, group);diff --git a/apps/frontend/src/components/launches/calendar.tsx b/apps/frontend/src/components/launches/calendar.tsxindex ca728a4ec..88e3fc4c6 100644--- a/apps/frontend/src/components/launches/calendar.tsx+++ b/apps/frontend/src/components/launches/calendar.tsx@@ -53,6 +53,7 @@ import i18next from 'i18next';import { AddEditModal } from '@gitroom/frontend/components/new-launch/add.edit.modal';import { deleteDialog } from '@gitroom/react/helpers/delete.dialog';import { useVariables } from '@gitroom/react/helpers/variable.context';+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';@@ -171,6 +172,27 @@ const usePostActions = (onMutate?: () => void) => {[integrations, fetch, modal, mutate]);+ const copyDebugJson = useCallback(+ (post: any) => async () => {+ try {+ const data = await (+ await fetch(`/posts/group/${post.group}/debug-export`)+ ).json();+ copy(JSON.stringify(data, null, 2));+ toaster.show(+ t('debug_json_copied', 'Debug JSON copied to clipboard'),+ 'success'+ );+ } catch {+ toaster.show(+ t('debug_json_copy_failed', 'Failed to copy debug data'),+ 'warning'+ );+ }+ },+ [fetch, toaster, t]+ );+const deletePost = useCallback((post: any) => async () => {if (@@ -234,7 +256,7 @@ const usePostActions = (onMutate?: () => void) => {[modal, t, mutate]);- return { editPost, deletePost, openStatistics, openMissingRelease };+ return { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease };};export const DayView = () => {@@ -469,10 +491,11 @@ export const MonthView = () => {};export const ListView = () => {const t = useT();+ const user = useUser();const { integrations, loading, listPosts } = useCalendar();// Use shared post actions hook- const { editPost, deletePost, openStatistics, openMissingRelease } = usePostActions();+ const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease } = usePostActions();// Group posts by dateconst groupedPosts = useMemo(() => {@@ -525,6 +548,7 @@ export const ListView = () => {missingRelease={openMissingRelease(post.id)}editPost={editPost(post, false)}duplicatePost={editPost(post, true)}+ copyDebugJson={user?.admin ? copyDebugJson(post) : undefined}post={post}integrations={integrations}deletePost={deletePost(post)}@@ -578,7 +602,7 @@ export const CalendarColumn: FC<{const fetch = useFetch();// Use shared post actions hook- const { editPost, deletePost, openStatistics, openMissingRelease } = usePostActions();+ const { editPost, deletePost, copyDebugJson, openStatistics, openMissingRelease } = usePostActions();const postList = useMemo(() => {return posts.filter((post) => {const pList = dayjs.utc(post.publishDate).local();@@ -844,6 +868,7 @@ export const CalendarColumn: FC<{missingRelease={openMissingRelease(post.id)}editPost={editPost(post, false)}duplicatePost={editPost(post, true)}+ copyDebugJson={user?.admin ? copyDebugJson(post) : undefined}post={post}integrations={integrations}deletePost={deletePost(post)}@@ -949,6 +974,7 @@ const CalendarItem: FC<{isBeforeNow: boolean;editPost: () => void;duplicatePost: () => void;+ copyDebugJson?: () => void;deletePost: () => void;statistics: () => void;missingRelease?: () => void;@@ -968,6 +994,7 @@ const CalendarItem: FC<{editPost,statistics,duplicatePost,+ copyDebugJson,post,date,isBeforeNow,@@ -1033,6 +1060,17 @@ const CalendarItem: FC<{>{post.tags.map((p) => p.tag.name).join(', ')}</div>+ {copyDebugJson && (+ <div+ className={clsx(+ 'hidden group-hover:block hover:underline cursor-pointer',+ post?.tags?.[0]?.tag?.color && 'mix-blend-difference'+ )}+ onClick={copyDebugJson}+ >+ <CopyDebug />+ </div>+ )}<divclassName={clsx('hidden group-hover:block hover:underline cursor-pointer',@@ -1124,6 +1162,27 @@ const CalendarItem: FC<{</div>);});+const CopyDebug = () => {+ 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"+ strokeLinecap="round"+ strokeLinejoin="round"+ data-tooltip-id="tooltip"+ data-tooltip-content={t('copy_debug_json', 'Copy Debug JSON')}+ >+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ );+};const Duplicate = () => {const t = useT();return (diff --git a/apps/frontend/src/components/launches/import-debug-post.modal.tsx b/apps/frontend/src/components/launches/import-debug-post.modal.tsxnew file mode 100644index 000000000..6a935e33a--- /dev/null+++ b/apps/frontend/src/components/launches/import-debug-post.modal.tsx@@ -0,0 +1,255 @@+'use client';++import { FC, useCallback, useMemo, useState } from 'react';+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 { useIntegrationList } from '@gitroom/frontend/components/launches/helpers/use.integration.list';+import { useSWRConfig } from 'swr';+import clsx from 'clsx';++interface DebugPostData {+ type: string;+ date: string;+ shortLink: boolean;+ tags: Array<{ value: string; label: string }>;+ posts: Array<{+ integration: { id: string };+ group: string;+ settings: { __type: string; [key: string]: any };+ value: Array<{+ content: string;+ image: Array<{ id: string; path: string; alt?: string; thumbnail?: string }>;+ delay: number;+ }>;+ }>;+ _debug: {+ providerIdentifier: string;+ providerName: string;+ state: string;+ error: string | null;+ errors: Array<{+ message: string;+ platform: string;+ body: string;+ createdAt: string;+ }>;+ originalGroup: string;+ originalPublishDate: string;+ exportedAt: string;+ };+}++export const ImportDebugPostModal: FC<{ close: () => void }> = ({ close }) => {+ const fetch = useFetch();+ const toaster = useToaster();+ const t = useT();+ const [jsonInput, setJsonInput] = useState('');+ const [parsed, setParsed] = useState<DebugPostData | null>(null);+ const [parseError, setParseError] = useState('');+ const [selectedIntegrationId, setSelectedIntegrationId] = useState('');+ const [importing, setImporting] = useState(false);+ const { data: integrations } = useIntegrationList();+ const { mutate } = useSWRConfig();++ const handleJsonChange = useCallback((value: string) => {+ setJsonInput(value);+ setParseError('');+ setParsed(null);+ setSelectedIntegrationId('');++ if (!value.trim()) return;++ try {+ const data = JSON.parse(value);+ if (!data.posts || !data._debug?.providerIdentifier) {+ setParseError('Invalid debug JSON format. Missing posts or _debug data.');+ return;+ }+ setParsed(data);+ } catch {+ setParseError('Invalid JSON');+ }+ }, []);++ const matchingIntegrations = useMemo(() => {+ if (!parsed || !integrations?.length) return [];+ return integrations.filter(+ (i: any) => i.identifier === parsed._debug.providerIdentifier+ );+ }, [parsed, integrations]);++ const handleImport = useCallback(async () => {+ if (!parsed || !selectedIntegrationId) return;++ setImporting(true);+ try {+ const { _debug, ...payload } = parsed;+ const importPayload = {+ ...payload,+ type: 'draft',+ date: new Date().toISOString(),+ tags: [],+ posts: payload.posts.map((post) => ({+ ...post,+ integration: { id: selectedIntegrationId },+ })),+ };++ await fetch('/posts', {+ method: 'POST',+ body: JSON.stringify(importPayload),+ });++ await mutate(+ (key: string) =>+ typeof key === 'string' &&+ (key.startsWith('/posts-') || key.startsWith('/posts-list-')),+ undefined,+ { revalidate: true }+ );++ toaster.show(+ t('debug_post_imported', 'Post imported as draft successfully'),+ 'success'+ );+ close();+ } catch {+ toaster.show(+ t('debug_post_import_failed', 'Failed to import post'),+ 'warning'+ );+ } finally {+ setImporting(false);+ }+ }, [parsed, selectedIntegrationId, fetch, toaster, t, close, mutate]);++ return (+ <div className="flex flex-col gap-[16px] min-w-[500px]">+ <textarea+ className="w-full h-[200px] p-[12px] rounded-[8px] bg-input border border-tableBorder text-textColor font-mono text-[13px] resize-y"+ placeholder={t(+ 'paste_debug_json',+ 'Paste the debug JSON copied from a failed post...'+ )}+ value={jsonInput}+ onChange={(e) => handleJsonChange(e.target.value)}+ />++ {parseError && (+ <div className="text-red-500 text-[13px]">{parseError}</div>+ )}++ {parsed && (+ <div className="flex flex-col gap-[12px]">+ <div className="flex flex-col gap-[8px] p-[12px] rounded-[8px] bg-input border border-tableBorder">+ <div className="text-[13px] font-[600] text-textColor">+ {t('debug_info', 'Debug Info')}+ </div>+ <div className="text-[12px] text-textColor/70 flex flex-col gap-[4px]">+ <div>+ <span className="font-[500]">+ {t('provider', 'Provider')}:+ </span>{' '}+ {parsed._debug.providerIdentifier} ({parsed._debug.providerName})+ </div>+ <div>+ <span className="font-[500]">+ {t('state', 'State')}:+ </span>{' '}+ <span className={parsed._debug.state === 'ERROR' ? 'text-red-500' : ''}>+ {parsed._debug.state}+ </span>+ </div>+ {parsed._debug.error && (+ <div>+ <span className="font-[500]">+ {t('error', 'Error')}:+ </span>{' '}+ <span className="text-red-400">{parsed._debug.error}</span>+ </div>+ )}+ {parsed._debug.errors?.length > 0 && (+ <div className="mt-[4px]">+ <span className="font-[500]">+ {t('error_details', 'Error Details')}:+ </span>+ <div className="mt-[4px] max-h-[100px] overflow-y-auto bg-newBgColor p-[8px] rounded-[4px] text-[11px] font-mono">+ {parsed._debug.errors.map((err, i) => (+ <div key={i} className="mb-[4px]">+ [{err.platform}] {err.message}+ </div>+ ))}+ </div>+ </div>+ )}+ <div>+ <span className="font-[500]">+ {t('original_date', 'Original Date')}:+ </span>{' '}+ {new Date(parsed._debug.originalPublishDate).toLocaleString()}+ </div>+ </div>+ </div>++ <div className="flex flex-col gap-[8px]">+ <div className="text-[13px] font-[600] text-textColor">+ {t('select_local_integration', 'Select Local Integration')}+ <span className="text-[12px] font-[400] text-textColor/60 ml-[8px]">+ ({parsed._debug.providerIdentifier})+ </span>+ </div>++ {matchingIntegrations.length === 0 ? (+ <div className="text-[13px] text-red-400">+ {t(+ 'no_matching_integrations',+ `No ${parsed._debug.providerIdentifier} integrations found. Add one first.`+ )}+ </div>+ ) : (+ <div className="flex flex-col gap-[6px]">+ {matchingIntegrations.map((integration) => (+ <div+ key={integration.id}+ className={clsx(+ 'flex items-center gap-[10px] p-[10px] rounded-[8px] border cursor-pointer transition-all',+ selectedIntegrationId === integration.id+ ? 'border-forth bg-forth/10'+ : 'border-tableBorder hover:border-textColor/30'+ )}+ onClick={() => setSelectedIntegrationId(integration.id)}+ >+ <img+ src={integration.picture || '/no-picture.jpg'}+ className="w-[24px] h-[24px] rounded-[6px]"+ alt={integration.name}+ />+ <div className="text-[13px] text-textColor">+ {integration.name}+ </div>+ <img+ src={`/icons/platforms/${integration.identifier}.png`}+ className="w-[14px] h-[14px] rounded-[4px] ml-auto"+ alt={integration.identifier}+ />+ </div>+ ))}+ </div>+ )}+ </div>++ <Button+ onClick={handleImport}+ loading={importing}+ disabled={!selectedIntegrationId}+ className="rounded-[4px]"+ >+ {t('import_as_draft', 'Import as Draft')}+ </Button>+ </div>+ )}+ </div>+ );+};diff --git a/apps/frontend/src/components/layout/impersonate.tsx b/apps/frontend/src/components/layout/impersonate.tsxindex a05eb2d9a..900d8a05d 100644--- a/apps/frontend/src/components/layout/impersonate.tsx+++ b/apps/frontend/src/components/layout/impersonate.tsx@@ -11,6 +11,7 @@ import { setCookie } from '@gitroom/frontend/components/layout/layout.context';import { useT } from '@gitroom/react/translation/get.transation.service.client';import { useModals } from '@gitroom/frontend/components/layout/new-modal';import { Button } from '@gitroom/react/form/button';+import { ImportDebugPostModal } from '@gitroom/frontend/components/launches/import-debug-post.modal';interface Charge {id: string;@@ -272,6 +273,27 @@ export const Subscription = () => {</Select>);};+const ImportDebugPost = () => {+ const { openModal } = useModals();+ const t = useT();++ const handleClick = useCallback(() => {+ openModal({+ title: t('import_debug_post', 'Import Debug Post'),+ children: (close) => <ImportDebugPostModal close={close} />,+ });+ }, []);++ return (+ <div+ className="px-[10px] rounded-[4px] bg-yellow-600 text-white cursor-pointer whitespace-nowrap"+ onClick={handleClick}+ >+ {t('import_debug_post', 'Import Debug Post')}+ </div>+ );+};+export const Impersonate = () => {const fetch = useFetch();const [name, setName] = useState('');@@ -352,16 +374,21 @@ export const Impersonate = () => {{billingEnabled && <ManageBilling />}</div>) : (- <Input- autoComplete="off"- placeholder="Write the user details"- name="impersonate"- disableForm={true}- label=""- removeError={true}- value={name}- onChange={(e) => setName(e.target.value)}- />+ <div className="flex items-center gap-[10px]">+ <div className="flex-1">+ <Input+ autoComplete="off"+ placeholder="Write the user details"+ name="impersonate"+ disableForm={true}+ label=""+ removeError={true}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </div>+ <ImportDebugPost />+ </div>)}</div>{!!data?.length && (diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.tsindex 66b6466f4..1dce22678 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.repository.ts@@ -419,6 +419,15 @@ export class PostsRepository {return update;}+ getErrorsByPostIds(postIds: string[]) {+ return this._errors.model.errors.findMany({+ where: {+ postId: { in: postIds },+ },+ orderBy: { createdAt: 'desc' },+ });+ }+async changeDate(orgId: string,id: string,diff --git a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.tsindex 54d723551..86e53bd67 100644--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts@@ -420,6 +420,53 @@ export class PostsService {}}+ async getPostGroupDebugExport(orgId: string, group: string) {+ const loadAll = await this._postRepository.getPostsByGroup(orgId, group);+ const errors = await this._postRepository.getErrorsByPostIds(+ loadAll.map((p) => p.id)+ );+ const posts = this.arrangePostsByGroup(loadAll, undefined);+ const rootPost = posts[0] as any;++ return {+ type: 'draft' as const,+ shortLink: false,+ date: rootPost.publishDate.toISOString(),+ tags:+ rootPost.tags?.map((t: any) => ({+ value: t.tag.id,+ label: t.tag.name,+ })) || [],+ posts: [+ {+ integration: { id: 'REPLACE_WITH_LOCAL_INTEGRATION_ID' },+ group: rootPost.group,+ settings: JSON.parse(rootPost.settings || '{}'),+ value: posts.map((post) => ({+ content: post.content,+ image: JSON.parse(post.image || '[]'),+ delay: post.delay || 0,+ })),+ },+ ],+ _debug: {+ providerIdentifier: rootPost.integration?.providerIdentifier,+ providerName: rootPost.integration?.name,+ state: rootPost.state,+ error: rootPost.error,+ errors: errors.map((e) => ({+ message: e.message,+ platform: e.platform,+ body: e.body,+ createdAt: e.createdAt,+ })),+ originalGroup: group,+ originalPublishDate: rootPost.publishDate,+ exportedAt: new Date().toISOString(),+ },+ };+ }+async getPostsByGroup(orgId: string, group: string) {const convertToJPEG = false;const loadAll = await this._postRepository.getPostsByGroup(orgId, group);