diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3bf624f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,49 @@ +name: CI + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main, develop ] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '20' + cache: 'pnpm' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Lint + run: pnpm run lint + + - name: Typecheck + run: pnpm run typecheck + + - name: Run unit tests + run: pnpm run test + + - name: Build + run: pnpm run build + + - name: Install Playwright browsers + run: npx playwright install --with-deps + + - name: Run E2E tests + run: pnpm run test:e2e + + - name: Health check + run: | + pnpm run start & + sleep 10 + curl -f http://localhost:3000/api/health || exit 1 + pkill -f "next start" || true \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..1b52559 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "chrome", + "request": "launch", + "name": "Launch Chrome against localhost", + "url": "http://localhost:3000", + "webRoot": "${workspaceFolder}" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..eb66b02 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "chatgpt.openOnStartup": true +} diff --git a/AI_INTEGRATION_README.md b/AI_INTEGRATION_README.md new file mode 100644 index 0000000..3026adf --- /dev/null +++ b/AI_INTEGRATION_README.md @@ -0,0 +1,246 @@ +# AI Services Integration for AiM + +This document describes the AI services integration implemented in the AiM (AI Marketing) platform. + +## Overview + +The AI integration provides the following services: + +- **Content Generation**: Generate new content based on prompts +- **Content Summarization**: Summarize long-form content +- **Content Translation**: Translate content to different languages +- **Idea Generation**: Generate creative ideas for content topics + +## Setup + +### Environment Variables + +Add the following to your `.env` file: + +```env +# OpenAI +OPENAI_API_KEY="your-openai-api-key-here" +``` + +### Dependencies + +The following packages are required: + +- `openai`: OpenAI SDK for API integration + +Install with: + +```bash +pnpm add openai +``` + +## API Endpoints + +### Content Generation + +**POST** `/api/[orgId]/content/generate` + +Generates new content using AI based on a prompt. + +**Request Body:** + +```json +{ + "prompt": "Write a social media post about summer fashion", + "campaignId": "campaign-uuid" +} +``` + +**Response:** + +```json +{ + "id": "content-uuid", + "title": "AI Generated: Write a social media post about summer fashion...", + "body": "Generated content here...", + "campaignId": "campaign-uuid", + "createdAt": "2024-01-01T00:00:00.000Z" +} +``` + +### Content Summarization + +**POST** `/api/[orgId]/content/summarize` + +Summarizes provided content. + +**Request Body:** + +```json +{ + "content": "Long text to summarize...", + "length": "brief" | "detailed" +} +``` + +**Response:** + +```json +{ + "summary": "Summarized content here..." +} +``` + +### Content Translation + +**POST** `/api/[orgId]/content/translate` + +Translates content to a target language. + +**Request Body:** + +```json +{ + "content": "Text to translate", + "targetLanguage": "Spanish", + "sourceLanguage": "English" // optional +} +``` + +**Response:** + +```json +{ + "translatedContent": "Texto traducido" +} +``` + +### Idea Generation + +**POST** `/api/[orgId]/content/ideas` + +Generates creative ideas for content topics. + +**Request Body:** + +```json +{ + "topic": "social media marketing", + "count": 5, + "type": "general" | "titles" | "hashtags" | "campaigns" +} +``` + +**Response:** + +```json +{ + "ideas": ["Idea 1", "Idea 2", "Idea 3"] +} +``` + +## UI Integration + +### Creator Dashboard + +The AI features are integrated into the Creator Dashboard with three main sections: + +1. **AI Assistant Tab**: Contains forms for all AI services +2. **Content Studio**: AI-powered content creation dialog +3. **Idea Generation**: Generate content ideas based on topics + +### Features + +- **Real-time AI Generation**: Generate content instantly +- **Campaign Integration**: Associate generated content with campaigns +- **Multi-language Support**: Translate content to various languages +- **Idea Brainstorming**: Generate multiple ideas for content topics +- **Content Optimization**: Summarize and improve existing content + +## Usage Examples + +### Generating Content + +```typescript +import { generateContent } from '@/lib/openai'; + +const content = await generateContent({ + prompt: 'Write a blog post about AI in marketing', + type: 'blog', + tone: 'professional', + length: 'medium', +}); +``` + +### Summarizing Content + +```typescript +import { summarizeContent } from '@/lib/openai'; + +const summary = await summarizeContent({ + content: 'Long article text...', + length: 'brief', +}); +``` + +### Translating Content + +```typescript +import { translateContent } from '@/lib/openai'; + +const translation = await translateContent({ + content: 'Hello world', + targetLanguage: 'Spanish', +}); +``` + +### Generating Ideas + +```typescript +import { generateIdeas } from '@/lib/openai'; + +const ideas = await generateIdeas({ + topic: 'content marketing', + count: 5, + type: 'general', +}); +``` + +## Error Handling + +All AI functions include proper error handling: + +- API key validation +- Network error handling +- Rate limiting considerations +- Fallback responses for failed requests + +## Security + +- API keys are stored as environment variables +- All endpoints require authentication +- RBAC permissions are enforced +- Input validation using Zod schemas + +## Testing + +Run the AI integration tests: + +```typescript +import { runAITests } from '@/lib/ai-test'; + +// Run all tests +const results = await runAITests(); +``` + +## Future Enhancements + +- Support for additional AI models +- Batch processing for multiple content items +- Advanced content optimization features +- Integration with other AI services +- Custom AI model training + +## Support + +For issues or questions about the AI integration: + +1. Check the API key is valid and has sufficient credits +2. Verify network connectivity +3. Review error logs in the console +4. Ensure proper permissions are set for the user diff --git a/DEPLOYMENT_README.md b/DEPLOYMENT_README.md new file mode 100644 index 0000000..21a09a4 --- /dev/null +++ b/DEPLOYMENT_README.md @@ -0,0 +1,57 @@ +# Deployment and Monitoring Guide + +## Containerization + +### Docker + +- Build: `docker build -t aim-platform .` +- Run: `docker run -p 3000:3000 aim-platform` + +### Docker Compose (Development) + +- Start: `docker-compose up` +- Stop: `docker-compose down` + +## Deployment + +### Vercel + +1. Connect repository to Vercel +2. Set environment variables in Vercel dashboard: + - `DATABASE_URL` + - `NEXTAUTH_SECRET` + - `NEXTAUTH_URL` + - `OPENAI_API_KEY` +3. Deploy + +### AWS Amplify + +1. Connect repository to Amplify +2. Configure build settings (amplify.yml provided) +3. Set environment variables +4. Deploy + +## Environment Variables + +### Production (.env.production) + +- Update with production values +- Use secure secrets for sensitive data + +## Monitoring + +### Health Check + +- Endpoint: `/api/health` +- Returns status of services (database, OpenAI) +- Use for load balancer health checks + +### Logs + +- Application logs available in deployment platform +- Database logs via PostgreSQL + +### Performance + +- Next.js analytics in production +- Monitor API response times diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4da00ea --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +# Use the official Node.js 20 image as the base image +FROM node:20-alpine + +# Set the working directory inside the container +WORKDIR /app + +# Copy package.json and package-lock.json (or pnpm-lock.yaml) +COPY package.json pnpm-lock.yaml ./ + +# Install dependencies +RUN npm install -g pnpm && pnpm install --frozen-lockfile + +# Copy the rest of the application code +COPY . . + +# Generate Prisma client +RUN pnpm run db:generate + +# Build the Next.js application +RUN pnpm run build + +# Expose the port the app runs on +EXPOSE 3000 + +# Set environment variables +ENV NODE_ENV=production + +# Start the application +CMD ["pnpm", "start"] \ No newline at end of file diff --git a/README.md b/README.md index 5e73163..aa75f35 100644 --- a/README.md +++ b/README.md @@ -45,3 +45,36 @@ pnpm dev Star History Chart + +## Auth + DB + Onboarding + +- Credentials login for development only (NextAuth v5) +- Prisma + Postgres schema for User/Organization/Brand/Membership/CreatorProfile +- Health check at /api/health +- Onboarding flow to choose Creator or Brand and set internal role +- Seed script with demo org, brand, and users + +### Environment + +Copy .env.example to .env.local and adjust values: + +`DATABASE_URL="postgresql://postgres:postgres@localhost:5432/circle_dev?schema=public" +NEXTAUTH_URL="http://localhost:3000" +NEXTAUTH_SECRET="changeme-in-local" +DEV_LOGIN_PASSWORD="dev"` + +Ensure Postgres is running and accessible by DATABASE_URL. + +### Database + +Generate and push schema, then seed (optional): + +`pnpm db:generate +pnpm db:push +pnpm db:seed` + +### Dev Login + +- Visit /auth/signin +- Use any email and password equal to DEV_LOGIN_PASSWORD +- After first login, go to /onboarding to set role diff --git a/Repo analysis and plan.docx b/Repo analysis and plan.docx new file mode 100644 index 0000000..d4097e6 Binary files /dev/null and b/Repo analysis and plan.docx differ diff --git a/__mocks__/next-intl.ts b/__mocks__/next-intl.ts new file mode 100644 index 0000000..c09b69e --- /dev/null +++ b/__mocks__/next-intl.ts @@ -0,0 +1,26 @@ +export const useTranslations = () => (key: string) => { + const translations: Record = { + admin_title: 'Admin Dashboard', + admin_description: 'Manage your organization and users', + total_users: 'Total Users', + active_users: 'active', + active_campaigns: 'Active Campaigns', + total_campaigns: 'of', + total: 'total', + content_pieces: 'Content Pieces', + pending_approvals: 'Pending Approvals', + user_management: 'User Management', + organization: 'Organization', + system: 'System', + system_settings: 'System Settings', + }; + + return translations[key] || key; +}; + +export const useFormatter = () => ({ + dateTime: (date: Date) => date.toISOString(), + number: (num: number) => num.toString(), +}); + +export const NextIntlClientProvider = ({ children }: { children: React.ReactNode }) => children; diff --git a/amplify.yml b/amplify.yml new file mode 100644 index 0000000..a5d35f3 --- /dev/null +++ b/amplify.yml @@ -0,0 +1,19 @@ +version: 1 +frontend: + phases: + preBuild: + commands: + - npm install -g pnpm + - pnpm install + - pnpm run db:generate + build: + commands: + - pnpm run build + artifacts: + baseDirectory: .next + files: + - '**/*' + cache: + paths: + - node_modules/**/* + - .next/cache/**/* \ No newline at end of file diff --git a/app/[orgId]/assets/page.tsx b/app/[orgId]/assets/page.tsx new file mode 100644 index 0000000..f4d5bad --- /dev/null +++ b/app/[orgId]/assets/page.tsx @@ -0,0 +1,17 @@ +import { AssetLibrary } from '@/components/assets/asset-library'; + +interface AssetsPageProps { + params: { + orgId: string; + }; +} + +export default function AssetsPage({ params }: AssetsPageProps) { + const { orgId } = params; + + return ( +
+ +
+ ); +} diff --git a/app/[orgId]/content/page.tsx b/app/[orgId]/content/page.tsx new file mode 100644 index 0000000..ed1b580 --- /dev/null +++ b/app/[orgId]/content/page.tsx @@ -0,0 +1,17 @@ +import { ContentEditor } from '@/components/content/content-editor'; + +interface ContentPageProps { + params: { + orgId: string; + }; +} + +export default function ContentPage({ params }: ContentPageProps) { + const { orgId } = params; + + return ( +
+ +
+ ); +} diff --git a/app/[orgId]/page.tsx b/app/[orgId]/page.tsx index afd7d1b..e684177 100644 --- a/app/[orgId]/page.tsx +++ b/app/[orgId]/page.tsx @@ -1,5 +1,55 @@ +import { Suspense } from 'react'; +import { getUserRole } from '@/lib/rbac'; +import { CreatorDashboard } from '@/components/dashboards/creator-dashboard'; +import { BrandDashboard } from '@/components/dashboards/brand-dashboard'; +import { AdminDashboard } from '@/components/dashboards/admin-dashboard'; import { redirect } from 'next/navigation'; +import { OrgRole } from '@prisma/client'; -export default function OrgIdPage() { - redirect('lndev-ui/team/CORE/all'); +interface OrgIdPageProps { + params: Promise<{ + orgId: string; + }>; +} + +async function DashboardContent({ orgId }: { orgId: string }) { + const userRole = await getUserRole(orgId); + + if (!userRole) { + // User doesn't have access to this organization + redirect('/auth/signin'); + } + + switch (userRole) { + case OrgRole.CREATOR: + return ; + case OrgRole.BRAND_OWNER: + return ; + case OrgRole.ADMIN: + return ; + default: + redirect('/auth/signin'); + } +} + +export default async function OrgIdPage({ params }: OrgIdPageProps) { + const resolvedParams = await params; + + return ( + +
+
+
Loading dashboard...
+
+ Please wait while we set up your workspace +
+
+ + } + > + +
+ ); } diff --git a/app/[orgId]/schedules/page.tsx b/app/[orgId]/schedules/page.tsx new file mode 100644 index 0000000..2972be9 --- /dev/null +++ b/app/[orgId]/schedules/page.tsx @@ -0,0 +1,27 @@ +import { Suspense } from 'react'; +import { ScheduleCalendar } from '@/components/schedules/schedule-calendar'; + +interface SchedulesPageProps { + params: { + orgId: string; + }; +} + +export default function SchedulesPage({ params }: SchedulesPageProps) { + const { orgId } = params; + + return ( +
+
+

Content Scheduling

+

+ Schedule your content for publication and manage your posting calendar. +

+
+ + Loading calendar...
}> + + + + ); +} diff --git a/app/api/[orgId]/analytics/events/route.ts b/app/api/[orgId]/analytics/events/route.ts new file mode 100644 index 0000000..79d1b24 --- /dev/null +++ b/app/api/[orgId]/analytics/events/route.ts @@ -0,0 +1,66 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { createAnalyticsEventSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.VIEW_ANALYTICS); + + const events = await (prisma as any).analyticsEvent.findMany({ + where: { userId: session.user.id }, + orderBy: { createdAt: 'desc' }, + }); + + return NextResponse.json(events); + } catch (error) { + console.error('Error fetching analytics events:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.VIEW_ANALYTICS); + + const body = await request.json(); + const validatedData = createAnalyticsEventSchema.parse(body); + + const event = await (prisma as any).analyticsEvent.create({ + data: { + ...validatedData, + userId: session.user.id, + organizationId: params.orgId, + }, + }); + + return NextResponse.json(event, { status: 201 }); + } catch (error) { + console.error('Error creating analytics event:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/analytics/metrics/route.ts b/app/api/[orgId]/analytics/metrics/route.ts new file mode 100644 index 0000000..03f0e45 --- /dev/null +++ b/app/api/[orgId]/analytics/metrics/route.ts @@ -0,0 +1,88 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.VIEW_ANALYTICS); + + // Get metrics for the org - count events by type + const eventCounts = await prisma.analyticsEvent.groupBy({ + by: ['event'], + where: { organizationId: params.orgId }, + _count: { + event: true, + }, + }); + + // Get campaign-specific metrics + const campaignMetrics = await prisma.campaign.findMany({ + where: { organizationId: params.orgId }, + include: { + contents: { + include: { + analyticsEvents: true, + }, + }, + analyticsEvents: true, + }, + }); + + // Calculate aggregated metrics + const totalImpressions = eventCounts.find((e) => e.event === 'impression')?._count.event || 0; + const totalClicks = eventCounts.find((e) => e.event === 'click')?._count.event || 0; + const totalViews = eventCounts.find((e) => e.event === 'view')?._count.event || 0; + + const ctr = totalImpressions > 0 ? (totalClicks / totalImpressions) * 100 : 0; + + // Calculate ROI (simplified - assuming some conversion value) + const conversions = eventCounts.find((e) => e.event === 'conversion')?._count.event || 0; + const roi = conversions > 0 ? ((conversions * 100) / totalClicks) * 100 : 0; // Assuming $100 per conversion + + const metrics = { + totalEvents: eventCounts.reduce((sum, item) => sum + item._count.event, 0), + eventsByType: eventCounts.reduce( + (acc, item) => { + acc[item.event] = item._count.event; + return acc; + }, + {} as Record + ), + impressions: totalImpressions, + clicks: totalClicks, + views: totalViews, + ctr: ctr, + roi: roi, + campaignMetrics: campaignMetrics.map((campaign) => ({ + id: campaign.id, + name: campaign.name, + totalEvents: campaign.analyticsEvents.length, + contentCount: campaign.contents.length, + contentMetrics: campaign.contents.map((content) => ({ + id: content.id, + title: content.title, + events: content.analyticsEvents.length, + impressions: content.analyticsEvents.filter((e) => e.event === 'impression').length, + clicks: content.analyticsEvents.filter((e) => e.event === 'click').length, + views: content.analyticsEvents.filter((e) => e.event === 'view').length, + })), + })), + }; + + return NextResponse.json(metrics); + } catch (error) { + console.error('Error fetching analytics metrics:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/analytics/track/route.ts b/app/api/[orgId]/analytics/track/route.ts new file mode 100644 index 0000000..e4c2fd2 --- /dev/null +++ b/app/api/[orgId]/analytics/track/route.ts @@ -0,0 +1,73 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.VIEW_ANALYTICS); + + const body = await request.json(); + const { event, campaignId, contentId, data } = body; + + if (!event) { + return NextResponse.json({ error: 'Event type is required' }, { status: 400 }); + } + + // Validate that campaign and content belong to the organization + if (campaignId) { + const campaign = await prisma.campaign.findFirst({ + where: { + id: campaignId, + organizationId: orgId, + }, + }); + if (!campaign) { + return NextResponse.json({ error: 'Campaign not found' }, { status: 404 }); + } + } + + if (contentId) { + const content = await prisma.content.findFirst({ + where: { + id: contentId, + campaign: { + organizationId: orgId, + }, + }, + }); + if (!content) { + return NextResponse.json({ error: 'Content not found' }, { status: 404 }); + } + } + + const analyticsEvent = await prisma.analyticsEvent.create({ + data: { + event, + data, + userId: session.user.id, + organizationId: orgId, + campaignId: campaignId || null, + contentId: contentId || null, + }, + }); + + return NextResponse.json(analyticsEvent, { status: 201 }); + } catch (error) { + console.error('Error tracking analytics event:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/assets/[id]/route.ts b/app/api/[orgId]/assets/[id]/route.ts new file mode 100644 index 0000000..bdf4772 --- /dev/null +++ b/app/api/[orgId]/assets/[id]/route.ts @@ -0,0 +1,136 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const asset = await prisma.asset.findFirst({ + where: { + id, + content: { campaign: { organizationId: orgId } }, + }, + include: { + content: true, + }, + }); + + if (!asset) { + return NextResponse.json({ error: 'Asset not found' }, { status: 404 }); + } + + return NextResponse.json(asset); + } catch (error) { + console.error('Error fetching asset:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function PUT( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + const body = await request.json(); + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + // Verify asset belongs to org + const existingAsset = await prisma.asset.findFirst({ + where: { + id, + content: { campaign: { organizationId: orgId } }, + }, + }); + + if (!existingAsset) { + return NextResponse.json({ error: 'Asset not found' }, { status: 404 }); + } + + const updatedAsset = await prisma.asset.update({ + where: { id }, + data: { + url: body.url, + type: body.type, + }, + include: { + content: true, + }, + }); + + return NextResponse.json(updatedAsset); + } catch (error) { + console.error('Error updating asset:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + // Verify asset belongs to org + const existingAsset = await prisma.asset.findFirst({ + where: { + id, + content: { campaign: { organizationId: orgId } }, + }, + }); + + if (!existingAsset) { + return NextResponse.json({ error: 'Asset not found' }, { status: 404 }); + } + + await prisma.asset.delete({ + where: { id }, + }); + + return NextResponse.json({ message: 'Asset deleted successfully' }); + } catch (error) { + console.error('Error deleting asset:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/assets/route.ts b/app/api/[orgId]/assets/route.ts new file mode 100644 index 0000000..9a5d6c9 --- /dev/null +++ b/app/api/[orgId]/assets/route.ts @@ -0,0 +1,38 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + const { searchParams } = new URL(request.url); + const contentId = searchParams.get('contentId'); + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const where = contentId + ? { content: { campaign: { organizationId: orgId } }, contentId } + : { content: { campaign: { organizationId: orgId } } }; + + const assets = await prisma.asset.findMany({ + where, + include: { + content: true, + }, + }); + + return NextResponse.json(assets); + } catch (error) { + console.error('Error fetching assets:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/assets/upload/route.ts b/app/api/[orgId]/assets/upload/route.ts new file mode 100644 index 0000000..fec30c4 --- /dev/null +++ b/app/api/[orgId]/assets/upload/route.ts @@ -0,0 +1,69 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; +import formidable from 'formidable'; +import { promises as fs } from 'fs'; +import path from 'path'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + // Parse multipart form data + const form = formidable({ + uploadDir: path.join(process.cwd(), 'public/uploads'), + keepExtensions: true, + }); + + const [fields, files] = await form.parse(request as any); + + const contentId = fields.contentId?.[0]; + const file = files.file?.[0]; + + if (!contentId || !file) { + return NextResponse.json({ error: 'Missing contentId or file' }, { status: 400 }); + } + + // Verify content belongs to org + const content = await prisma.content.findFirst({ + where: { id: contentId, campaign: { organizationId: orgId } }, + }); + if (!content) { + return NextResponse.json({ error: 'Content not found' }, { status: 404 }); + } + + // Mock URL - in real implementation, upload to cloud storage + const mockUrl = `/uploads/${file.newFilename}`; + + const asset = await prisma.asset.create({ + data: { + url: mockUrl, + name: fields.name?.[0] || file.originalFilename || 'Untitled', + type: file.mimetype || 'unknown', + size: file.size, + description: fields.description?.[0], + tags: fields.tags?.[0] ? JSON.parse(fields.tags[0]) : [], + contentId, + }, + }); + + return NextResponse.json(asset, { status: 201 }); + } catch (error) { + console.error('Error uploading asset:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/campaigns/[id]/route.ts b/app/api/[orgId]/campaigns/[id]/route.ts new file mode 100644 index 0000000..291c2fb --- /dev/null +++ b/app/api/[orgId]/campaigns/[id]/route.ts @@ -0,0 +1,110 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { updateCampaignSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + // Check access + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const campaign = await prisma.campaign.findFirst({ + where: { id, organizationId: orgId }, + include: { + contents: true, + schedules: true, + }, + }); + + if (!campaign) { + return NextResponse.json({ error: 'Campaign not found' }, { status: 404 }); + } + + return NextResponse.json(campaign); + } catch (error) { + console.error('Error fetching campaign:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function PUT( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + // Require permission + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CAMPAIGNS); + + const body = await request.json(); + const validatedData = updateCampaignSchema.parse(body); + + const campaign = await prisma.campaign.update({ + where: { id }, + data: validatedData, + }); + + return NextResponse.json(campaign); + } catch (error) { + console.error('Error updating campaign:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + // Require permission + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CAMPAIGNS); + + await prisma.campaign.delete({ + where: { id }, + }); + + return NextResponse.json({ message: 'Campaign deleted' }); + } catch (error) { + console.error('Error deleting campaign:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/campaigns/route.ts b/app/api/[orgId]/campaigns/route.ts new file mode 100644 index 0000000..f88462d --- /dev/null +++ b/app/api/[orgId]/campaigns/route.ts @@ -0,0 +1,70 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { createCampaignSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + // Check if user has access to the org (at least CREATOR) + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const campaigns = await prisma.campaign.findMany({ + where: { organizationId: orgId }, + include: { + contents: true, + schedules: true, + }, + }); + + return NextResponse.json(campaigns); + } catch (error) { + console.error('Error fetching campaigns:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + // Require BRAND_OWNER or ADMIN to create campaigns + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CAMPAIGNS); + + const body = await request.json(); + const validatedData = createCampaignSchema.parse(body); + + const campaign = await prisma.campaign.create({ + data: { + ...validatedData, + organizationId: orgId, + }, + }); + + return NextResponse.json(campaign, { status: 201 }); + } catch (error) { + console.error('Error creating campaign:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/[id]/route.ts b/app/api/[orgId]/content/[id]/route.ts new file mode 100644 index 0000000..9c4ce17 --- /dev/null +++ b/app/api/[orgId]/content/[id]/route.ts @@ -0,0 +1,111 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { updateContentSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const content = await prisma.content.findFirst({ + where: { id, campaign: { organizationId: orgId } }, + include: { + campaign: true, + assets: true, + }, + }); + + if (!content) { + return NextResponse.json({ error: 'Content not found' }, { status: 404 }); + } + + return NextResponse.json(content); + } catch (error) { + console.error('Error fetching content:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function PUT( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const validatedData = updateContentSchema.parse(body); + + const content = await prisma.content.update({ + where: { id }, + data: validatedData, + include: { + campaign: true, + assets: true, + }, + }); + + return NextResponse.json(content); + } catch (error) { + console.error('Error updating content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + await prisma.content.delete({ + where: { id }, + }); + + return NextResponse.json({ message: 'Content deleted' }); + } catch (error) { + console.error('Error deleting content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/generate/route.ts b/app/api/[orgId]/content/generate/route.ts new file mode 100644 index 0000000..0ccb686 --- /dev/null +++ b/app/api/[orgId]/content/generate/route.ts @@ -0,0 +1,61 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { generateContentSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; +import { generateContent } from '@/lib/openai'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const validatedData = generateContentSchema.parse(body); + + // Verify campaign belongs to org + const campaign = await prisma.campaign.findFirst({ + where: { id: validatedData.campaignId, organizationId: orgId }, + }); + if (!campaign) { + return NextResponse.json({ error: 'Campaign not found' }, { status: 404 }); + } + + // Generate content using OpenAI + const generatedBody = await generateContent({ + prompt: validatedData.prompt, + type: 'general', + tone: 'professional', + length: 'medium', + }); + + const content = await prisma.content.create({ + data: { + title: `AI Generated: ${validatedData.prompt.slice(0, 50)}...`, + body: generatedBody, + campaignId: validatedData.campaignId, + }, + include: { + campaign: true, + assets: true, + }, + }); + + return NextResponse.json(content, { status: 201 }); + } catch (error) { + console.error('Error generating content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/ideas/route.ts b/app/api/[orgId]/content/ideas/route.ts new file mode 100644 index 0000000..18f83c1 --- /dev/null +++ b/app/api/[orgId]/content/ideas/route.ts @@ -0,0 +1,41 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import { generateIdeas } from '@/lib/openai'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const { topic, count = 5, type = 'general' } = body; + + if (!topic) { + return NextResponse.json({ error: 'Topic is required' }, { status: 400 }); + } + + const ideas = await generateIdeas({ + topic, + count, + type, + }); + + return NextResponse.json({ ideas }, { status: 200 }); + } catch (error) { + console.error('Error generating ideas:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/route.ts b/app/api/[orgId]/content/route.ts new file mode 100644 index 0000000..a912ddc --- /dev/null +++ b/app/api/[orgId]/content/route.ts @@ -0,0 +1,83 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { createContentSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + const { searchParams } = new URL(request.url); + const campaignId = searchParams.get('campaignId'); + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const where = campaignId + ? { campaign: { organizationId: orgId }, campaignId } + : { campaign: { organizationId: orgId } }; + + const contents = await prisma.content.findMany({ + where, + include: { + campaign: true, + assets: true, + }, + }); + + return NextResponse.json(contents); + } catch (error) { + console.error('Error fetching contents:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const validatedData = createContentSchema.parse(body); + + // Verify campaign belongs to org + const campaign = await prisma.campaign.findFirst({ + where: { id: validatedData.campaignId, organizationId: orgId }, + }); + if (!campaign) { + return NextResponse.json({ error: 'Campaign not found' }, { status: 404 }); + } + + const content = await prisma.content.create({ + data: validatedData, + include: { + campaign: true, + assets: true, + }, + }); + + return NextResponse.json(content, { status: 201 }); + } catch (error) { + console.error('Error creating content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/summarize/route.ts b/app/api/[orgId]/content/summarize/route.ts new file mode 100644 index 0000000..e6de906 --- /dev/null +++ b/app/api/[orgId]/content/summarize/route.ts @@ -0,0 +1,40 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import { summarizeContent } from '@/lib/openai'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const { content, length = 'brief' } = body; + + if (!content) { + return NextResponse.json({ error: 'Content is required' }, { status: 400 }); + } + + const summary = await summarizeContent({ + content, + length, + }); + + return NextResponse.json({ summary }, { status: 200 }); + } catch (error) { + console.error('Error summarizing content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/content/translate/route.ts b/app/api/[orgId]/content/translate/route.ts new file mode 100644 index 0000000..29c528a --- /dev/null +++ b/app/api/[orgId]/content/translate/route.ts @@ -0,0 +1,44 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import { translateContent } from '@/lib/openai'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_CONTENT); + + const body = await request.json(); + const { content, targetLanguage, sourceLanguage } = body; + + if (!content || !targetLanguage) { + return NextResponse.json( + { error: 'Content and target language are required' }, + { status: 400 } + ); + } + + const translatedContent = await translateContent({ + content, + targetLanguage, + sourceLanguage, + }); + + return NextResponse.json({ translatedContent }, { status: 200 }); + } catch (error) { + console.error('Error translating content:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/schedules/[id]/route.ts b/app/api/[orgId]/schedules/[id]/route.ts new file mode 100644 index 0000000..ff8e691 --- /dev/null +++ b/app/api/[orgId]/schedules/[id]/route.ts @@ -0,0 +1,110 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { updateScheduleSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_SCHEDULES); + + const schedule = await prisma.schedule.findFirst({ + where: { id, campaign: { organizationId: orgId } }, + include: { + campaign: true, + content: true, + }, + }); + + if (!schedule) { + return NextResponse.json({ error: 'Schedule not found' }, { status: 404 }); + } + + return NextResponse.json(schedule); + } catch (error) { + console.error('Error fetching schedule:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function PUT( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_SCHEDULES); + + const body = await request.json(); + const validatedData = updateScheduleSchema.parse(body); + + const schedule = await prisma.schedule.update({ + where: { id }, + data: validatedData, + include: { + campaign: true, + }, + }); + + return NextResponse.json(schedule); + } catch (error) { + console.error('Error updating schedule:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function DELETE( + request: NextRequest, + { params }: { params: { orgId: string; id: string } } +) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId, id } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_SCHEDULES); + + await prisma.schedule.delete({ + where: { id }, + }); + + return NextResponse.json({ message: 'Schedule deleted' }); + } catch (error) { + console.error('Error deleting schedule:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/[orgId]/schedules/route.ts b/app/api/[orgId]/schedules/route.ts new file mode 100644 index 0000000..af9afec --- /dev/null +++ b/app/api/[orgId]/schedules/route.ts @@ -0,0 +1,82 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; +import { createScheduleSchema } from '@/lib/schemas'; +import { requirePermission, PERMISSIONS } from '@/lib/rbac'; + +export async function GET(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + const { searchParams } = new URL(request.url); + const campaignId = searchParams.get('campaignId'); + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_SCHEDULES); + + const where = campaignId + ? { campaign: { organizationId: orgId }, campaignId } + : { campaign: { organizationId: orgId } }; + + const schedules = await prisma.schedule.findMany({ + where, + include: { + campaign: true, + content: true, + }, + }); + + return NextResponse.json(schedules); + } catch (error) { + console.error('Error fetching schedules:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} + +export async function POST(request: NextRequest, { params }: { params: { orgId: string } }) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { orgId } = params; + + await requirePermission(session.user.id, orgId, PERMISSIONS.MANAGE_SCHEDULES); + + const body = await request.json(); + const validatedData = createScheduleSchema.parse(body); + + // Verify campaign belongs to org + const campaign = await prisma.campaign.findFirst({ + where: { id: validatedData.campaignId, organizationId: orgId }, + }); + if (!campaign) { + return NextResponse.json({ error: 'Campaign not found' }, { status: 404 }); + } + + const schedule = await prisma.schedule.create({ + data: validatedData, + include: { + campaign: true, + }, + }); + + return NextResponse.json(schedule, { status: 201 }); + } catch (error) { + console.error('Error creating schedule:', error); + if (error instanceof Error && error.message === 'Insufficient permissions') { + return NextResponse.json({ error: 'Forbidden' }, { status: 403 }); + } + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/auth/[...nextauth]/route.ts b/app/api/auth/[...nextauth]/route.ts new file mode 100644 index 0000000..bf39beb --- /dev/null +++ b/app/api/auth/[...nextauth]/route.ts @@ -0,0 +1,3 @@ +import { authHandlers } from '@/lib/auth'; + +export const { GET, POST } = authHandlers; diff --git a/app/api/cron/publish/route.ts b/app/api/cron/publish/route.ts new file mode 100644 index 0000000..d423438 --- /dev/null +++ b/app/api/cron/publish/route.ts @@ -0,0 +1,32 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { runCronJob } from '@/lib/cron-worker'; + +export async function POST(request: NextRequest) { + try { + // You might want to add authentication/authorization here + // to prevent unauthorized access to the cron endpoint + + const result = await runCronJob(); + + if (result.success) { + return NextResponse.json({ + message: 'Cron job executed successfully', + published: result.published, + }); + } else { + return NextResponse.json({ error: result.error }, { status: 500 }); + } + } catch (error) { + console.error('Error running cron job:', error); + return NextResponse.json({ error: 'Internal server error' }, { status: 500 }); + } +} + +// Optional: GET endpoint to check cron status +export async function GET() { + return NextResponse.json({ + message: 'Cron endpoint is available', + endpoint: '/api/cron/publish', + method: 'POST', + }); +} diff --git a/app/api/health/route.ts b/app/api/health/route.ts new file mode 100644 index 0000000..ec94527 --- /dev/null +++ b/app/api/health/route.ts @@ -0,0 +1,38 @@ +import { NextResponse } from 'next/server'; +import { PrismaClient } from '@prisma/client'; + +const prisma = new PrismaClient(); + +export async function GET() { + try { + // Check database connection + await prisma.$queryRaw`SELECT 1`; + + // Check OpenAI API key (basic check) + const openaiKey = process.env.OPENAI_API_KEY; + const openaiOk = openaiKey && openaiKey.startsWith('sk-'); + + return NextResponse.json({ + ok: true, + status: 'healthy', + timestamp: new Date().toISOString(), + services: { + database: 'connected', + openai: openaiOk ? 'configured' : 'not configured', + }, + }); + } catch (error) { + console.error('Health check failed:', error); + return NextResponse.json( + { + ok: false, + status: 'unhealthy', + timestamp: new Date().toISOString(), + error: error instanceof Error ? error.message : 'Unknown error', + }, + { status: 503 } + ); + } finally { + await prisma.$disconnect(); + } +} diff --git a/app/api/me/role/route.ts b/app/api/me/role/route.ts new file mode 100644 index 0000000..39c390b --- /dev/null +++ b/app/api/me/role/route.ts @@ -0,0 +1,36 @@ +import { NextRequest, NextResponse } from 'next/server'; +import { auth } from '@/lib/auth'; +import { getUserRole } from '@/lib/rbac'; + +export async function GET(request: NextRequest) { + try { + const session = await auth(); + if (!session?.user?.id) { + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + } + + const { searchParams } = new URL(request.url); + const orgId = searchParams.get('orgId'); + + if (!orgId) { + return NextResponse.json({ error: 'Organization ID required' }, { status: 400 }); + } + + const userRole = await getUserRole(orgId); + + if (!userRole) { + return NextResponse.json( + { error: 'No role found for this organization' }, + { status: 403 } + ); + } + + return NextResponse.json({ role: userRole }); + } catch (error) { + console.error('Error fetching user role:', error); + return NextResponse.json( + { error: error instanceof Error ? error.message : 'Internal server error' }, + { status: 500 } + ); + } +} diff --git a/app/api/me/route.ts b/app/api/me/route.ts new file mode 100644 index 0000000..cef8894 --- /dev/null +++ b/app/api/me/route.ts @@ -0,0 +1,13 @@ +import { NextResponse } from 'next/server'; +import prisma from '@/lib/prisma'; +import { auth } from '@/lib/auth'; + +export async function GET() { + const session = await auth(); + if (!session?.user?.id) return NextResponse.json({ hasMembership: false }); + const membership = await prisma.membership.findFirst({ where: { userId: session.user.id } }); + return NextResponse.json({ + hasMembership: !!membership, + organizationId: membership?.organizationId, + }); +} diff --git a/app/api/onboarding/brand/route.ts b/app/api/onboarding/brand/route.ts new file mode 100644 index 0000000..e5ebb9a --- /dev/null +++ b/app/api/onboarding/brand/route.ts @@ -0,0 +1,88 @@ +import { NextResponse } from 'next/server'; +import { z } from 'zod'; +import prisma from '@/lib/prisma'; +import type { InternalRole } from '@prisma/client'; +import { auth } from '@/lib/auth'; + +const bodySchema = z.object({ + brandName: z.string().min(2).max(100), + inviteCreatorEmail: z.string().email().optional(), + internalRole: z + .union([ + z.literal('DESIGNER'), + z.literal('CONTENT'), + z.literal('ACCOUNT'), + z.literal('MANAGER'), + ]) + .nullish(), +}); + +export async function POST(req: Request) { + const session = await auth(); + if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + const userId = session.user.id; + + const json = await req.json().catch(() => ({})); + const parsed = bodySchema.safeParse(json); + if (!parsed.success) { + return NextResponse.json({ error: 'Invalid request' }, { status: 400 }); + } + const { brandName, inviteCreatorEmail, internalRole } = parsed.data; + + // Resolve or create default organization + const existingMembership = await prisma.membership.findFirst({ where: { userId } }); + let organizationId: string; + if (existingMembership) { + organizationId = existingMembership.organizationId; + } else { + const user = await prisma.user.findUnique({ where: { id: userId } }); + const org = await prisma.organization.create({ + data: { name: `Workspace for ${user?.name || user?.email || 'user'}` }, + }); + organizationId = org.id; + } + + const brand = await prisma.brand.create({ data: { name: brandName, organizationId } }); + + // Ensure membership for current user as BRAND_OWNER + await prisma.membership.upsert({ + where: { userId_organizationId: { userId, organizationId } }, + update: { role: 'BRAND_OWNER', internalRole: (internalRole as InternalRole | null) ?? null }, + create: { + userId, + organizationId, + role: 'BRAND_OWNER', + internalRole: (internalRole as InternalRole | null) ?? null, + }, + }); + + if (inviteCreatorEmail) { + // Create or find creator user + let invited = await prisma.user.findUnique({ where: { email: inviteCreatorEmail } }); + if (!invited) { + invited = await prisma.user.create({ + data: { email: inviteCreatorEmail, name: inviteCreatorEmail.split('@')[0] }, + }); + } + // Ensure creator profile + const creator = await prisma.creatorProfile.upsert({ + where: { userId: invited.id }, + update: {}, + create: { userId: invited.id }, + }); + // Ensure membership of invited creator to org + await prisma.membership.upsert({ + where: { userId_organizationId: { userId: invited.id, organizationId } }, + update: { role: 'CREATOR' }, + create: { userId: invited.id, organizationId, role: 'CREATOR' }, + }); + // Link creator to brand + await prisma.creatorBrand.upsert({ + where: { brandId_creatorProfileId: { brandId: brand.id, creatorProfileId: creator.id } }, + update: {}, + create: { brandId: brand.id, creatorProfileId: creator.id }, + }); + } + + return NextResponse.json({ ok: true, organizationId }); +} diff --git a/app/api/onboarding/creator/route.ts b/app/api/onboarding/creator/route.ts new file mode 100644 index 0000000..456e849 --- /dev/null +++ b/app/api/onboarding/creator/route.ts @@ -0,0 +1,77 @@ +import { NextResponse } from 'next/server'; +import { z } from 'zod'; +import prisma from '@/lib/prisma'; +import type { InternalRole } from '@prisma/client'; +import { auth } from '@/lib/auth'; + +const bodySchema = z.object({ + createBrand: z + .object({ + name: z.string().min(2).max(100), + }) + .optional(), + internalRole: z + .union([ + z.literal('DESIGNER'), + z.literal('CONTENT'), + z.literal('ACCOUNT'), + z.literal('MANAGER'), + ]) + .nullish(), +}); + +export async function POST(req: Request) { + const session = await auth(); + if (!session?.user?.id) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); + const userId = session.user.id; + + const json = await req.json().catch(() => ({})); + const parsed = bodySchema.safeParse(json); + if (!parsed.success) { + return NextResponse.json({ error: 'Invalid request' }, { status: 400 }); + } + const { createBrand, internalRole } = parsed.data; + + // Resolve or create default organization + const existingMembership = await prisma.membership.findFirst({ where: { userId } }); + let organizationId: string; + if (existingMembership) { + organizationId = existingMembership.organizationId; + } else { + const user = await prisma.user.findUnique({ where: { id: userId } }); + const org = await prisma.organization.create({ + data: { name: `Workspace for ${user?.name || user?.email || 'user'}` }, + }); + organizationId = org.id; + } + + const creator = await prisma.creatorProfile.upsert({ + where: { userId }, + update: {}, + create: { userId }, + }); + + // Ensure membership with CREATOR role + await prisma.membership.upsert({ + where: { userId_organizationId: { userId, organizationId } }, + update: { role: 'CREATOR', internalRole: (internalRole as InternalRole | null) ?? null }, + create: { + userId, + organizationId, + role: 'CREATOR', + internalRole: (internalRole as InternalRole | null) ?? null, + }, + }); + + if (createBrand) { + const brand = await prisma.brand.create({ data: { name: createBrand.name, organizationId } }); + // Link creator to brand + await prisma.creatorBrand.upsert({ + where: { brandId_creatorProfileId: { brandId: brand.id, creatorProfileId: creator.id } }, + update: {}, + create: { brandId: brand.id, creatorProfileId: creator.id }, + }); + } + + return NextResponse.json({ ok: true, organizationId }); +} diff --git a/app/auth/signin/page.tsx b/app/auth/signin/page.tsx new file mode 100644 index 0000000..47d4f1e --- /dev/null +++ b/app/auth/signin/page.tsx @@ -0,0 +1,110 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import { useRouter } from 'next/navigation'; +import { signIn } from 'next-auth/react'; +import { Input } from '@/components/ui/input'; +import { Button } from '@/components/ui/button'; + +export default function SignInPage() { + const [email, setEmail] = useState(''); + const [password, setPassword] = useState(''); + const [loading, setLoading] = useState(false); + const [callbackUrl, setCallbackUrl] = useState('/'); + const router = useRouter(); + + useEffect(() => { + if (typeof window !== 'undefined') { + try { + const url = new URL(window.location.href); + const cb = url.searchParams.get('callbackUrl'); + if (cb) setCallbackUrl(cb); + } catch {} + } + }, []); + + async function onSubmit(e: React.FormEvent) { + e.preventDefault(); + setLoading(true); + const res = await signIn('credentials', { + email, + password, + redirect: false, + callbackUrl, + }); + setLoading(false); + if (res?.ok) { + try { + const me = await fetch('/api/me').then((r) => + r.ok ? r.json() : { hasMembership: false } + ); + + if (!me.hasMembership) { + router.push('/onboarding'); + return; + } + + // If user has membership, check if callbackUrl is valid + // If callbackUrl is from an org route but user doesn't have access, use their actual org + let targetUrl = callbackUrl; + + if (callbackUrl) { + // Check if callbackUrl is an org route (contains orgId) + const urlParts = callbackUrl.split('/').filter(Boolean); + if ( + urlParts.length >= 1 && + urlParts[0] !== 'auth' && + urlParts[0] !== 'api' && + urlParts[0] !== '_next' + ) { + // This looks like an org route, verify it matches user's org + const callbackOrgId = urlParts[0]; + if (callbackOrgId !== me.organizationId) { + targetUrl = `/${me.organizationId}/projects`; + } + } + } + + targetUrl = targetUrl || `/${me.organizationId}/projects`; + router.push(targetUrl); + } catch (error) { + router.push('/onboarding'); + } + } else { + alert('Invalid credentials (dev: check DEV_LOGIN_PASSWORD)'); + } + } + + return ( +
+
+

Sign in

+ + setEmail(e.target.value)} + required + placeholder="you@aim.local" + /> + + setPassword(e.target.value)} + required + placeholder="DEV_LOGIN_PASSWORD" + /> + +
+
+ ); +} diff --git a/app/layout.tsx b/app/layout.tsx index 5572a57..e8c7441 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,6 +1,9 @@ import type { Metadata } from 'next'; import { Geist, Geist_Mono } from 'next/font/google'; import { Toaster } from '@/components/ui/sonner'; +import { NextIntlClientProvider } from 'next-intl'; +import { getMessages } from 'next-intl/server'; +import { SessionProvider } from 'next-auth/react'; import './globals.css'; const geistSans = Geist({ @@ -55,21 +58,30 @@ export const metadata: Metadata = { import { ThemeProvider } from '@/components/layout/theme-provider'; -export default function RootLayout({ +export default async function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { + const messages = await getMessages(); + return ( - - - {children} - - + + + + + {children} + + + + ); diff --git a/app/onboarding/page.tsx b/app/onboarding/page.tsx new file mode 100644 index 0000000..025460a --- /dev/null +++ b/app/onboarding/page.tsx @@ -0,0 +1,127 @@ +import { redirect } from 'next/navigation'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; + +export default async function OnboardingPage() { + try { + const session = await auth(); + + if (!session?.user?.id) { + redirect('/auth/signin'); + } + + console.log('Onboarding - User ID:', session.user.id); + console.log('Onboarding - User email:', session.user.email); + + // First, check if user exists by ID + let user = await prisma.user.findUnique({ + where: { id: session.user.id }, + }); + + if (!user) { + // Check if user exists by email (might have different ID) + const existingUserByEmail = await prisma.user.findUnique({ + where: { email: session.user.email! }, + }); + + if (existingUserByEmail) { + console.log('Onboarding - User found by email with different ID:', existingUserByEmail); + + // Check if this user already has membership + const existingMembership = await prisma.membership.findFirst({ + where: { userId: existingUserByEmail.id }, + }); + + if (existingMembership) { + console.log('Onboarding - Existing user has membership, redirecting'); + redirect(`/${existingMembership.organizationId}/projects`); + } + + // Use the existing user ID for membership creation + user = existingUserByEmail; + } else { + console.log('Onboarding - User not found in DB, creating...'); + // Create user if it doesn't exist + user = await prisma.user.create({ + data: { + id: session.user.id, + email: session.user.email!, + name: session.user.name || 'Unknown User', + }, + }); + console.log('Onboarding - User created:', user); + } + } else { + console.log('Onboarding - User found in DB:', user); + } + + // Check if user already has membership + const membership = await prisma.membership.findFirst({ + where: { userId: user.id }, + }); + + if (membership) { + console.log('Onboarding - User already has membership, redirecting'); + // User already has membership, redirect to their org + redirect(`/${membership.organizationId}/projects`); + } + + console.log('Onboarding - Creating organization and membership...'); + + // Create default organization and membership for the user + const org = await prisma.organization.create({ + data: { + name: `${user.name || 'My'}'s Organization`, + }, + }); + + console.log('Onboarding - Organization created:', org); + + const newMembership = await prisma.membership.create({ + data: { + userId: user.id, + organizationId: org.id, + role: 'ADMIN', + }, + }); + + console.log('Onboarding - Membership created:', newMembership); + + // Redirect to the new organization + redirect(`/${org.id}/projects`); + } catch (error) { + console.error('Onboarding error:', error); + return ( +
+
+

🎯 Welcome to AiM!

+ +
+
+

❌ Setup Error

+

+ {error instanceof Error ? error.message : 'Unknown error occurred'} +

+
+ +
+

🔍 Debug Info

+

+ Check the server console for detailed error information. +

+
+
+ + +
+
+ ); + } +} diff --git a/app/page.tsx b/app/page.tsx index 62fccc7..9527b67 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -1,5 +1,77 @@ import { redirect } from 'next/navigation'; +import { auth } from '@/lib/auth'; +import prisma from '@/lib/prisma'; -export default function Home() { - redirect('lndev-ui/team/CORE/all'); +export default async function Home() { + try { + const session = await auth(); + console.log('Home page - Session:', session); + + if (!session?.user?.id) { + console.log('Home page - No session, redirecting to signin'); + redirect('/auth/signin'); + } + + // Check if user has membership by session user ID first + let membership = await prisma.membership.findFirst({ + where: { userId: session.user.id }, + }); + + // If no membership found by session ID, check by email + if (!membership && session.user.email) { + console.log('Home page - No membership by ID, checking by email...'); + const userByEmail = await prisma.user.findUnique({ + where: { email: session.user.email }, + }); + + if (userByEmail) { + console.log('Home page - User found by email:', userByEmail); + membership = await prisma.membership.findFirst({ + where: { userId: userByEmail.id }, + }); + } + } + + console.log('Home page - Membership:', membership); + + if (!membership) { + console.log('Home page - No membership, redirecting to onboarding'); + redirect('/onboarding'); + } + + // User has membership, redirect to their organization + const redirectUrl = `/${membership.organizationId}/projects`; + console.log('Home page - Redirecting to:', redirectUrl); + redirect(redirectUrl); + } catch (error) { + // Don't log NEXT_REDIRECT errors as they are expected + if (error instanceof Error && error.message.includes('NEXT_REDIRECT')) { + // This is expected behavior, not an error + throw error; // Re-throw to let Next.js handle the redirect + } + + console.error('Home page - Actual error:', error); + return ( +
+
+

❌ Error Loading Page

+ +
+
+

Error Details

+

+ {error instanceof Error ? error.message : 'Unknown error'} +

+ + Try Again + +
+
+
+
+ ); + } } diff --git a/app/test/page.tsx b/app/test/page.tsx new file mode 100644 index 0000000..f09d843 --- /dev/null +++ b/app/test/page.tsx @@ -0,0 +1,33 @@ +export default function TestPage() { + return ( +
+
+

Test Page

+

+ This page bypasses authentication to test if the app works. +

+
+
+

✅ App is Working

+

The basic Next.js app is functioning correctly.

+
+
+

🔐 Authentication Issue

+

+ The problem is likely in the authentication flow or redirects. +

+
+
+

📝 Next Steps

+

Check the browser console for error messages.

+
+
+ +
+
+ ); +} diff --git a/components/__tests__/admin-dashboard.test.tsx b/components/__tests__/admin-dashboard.test.tsx new file mode 100644 index 0000000..35439d8 --- /dev/null +++ b/components/__tests__/admin-dashboard.test.tsx @@ -0,0 +1,45 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { AdminDashboard } from '../dashboards/admin-dashboard'; + +describe('AdminDashboard', () => { + const mockOrgId = 'test-org-123'; + + it('renders the dashboard title', () => { + render(); + expect(screen.getByText('Admin Dashboard')).toBeInTheDocument(); + }); + + it('renders organization statistics', () => { + render(); + + expect(screen.getByText('Total Users')).toBeInTheDocument(); + expect(screen.getByText('45')).toBeInTheDocument(); // totalUsers + expect(screen.getByText('38 active')).toBeInTheDocument(); // activeUsers + + expect(screen.getByText('Active Campaigns')).toBeInTheDocument(); + expect(screen.getByText('8')).toBeInTheDocument(); // activeCampaigns + expect(screen.getByText('of 12 total')).toBeInTheDocument(); // totalCampaigns + + expect(screen.getByText('Content Pieces')).toBeInTheDocument(); + expect(screen.getByText('156')).toBeInTheDocument(); // totalContent + + expect(screen.getByText('Pending Approvals')).toBeInTheDocument(); + expect(screen.getByText('23')).toBeInTheDocument(); // pendingApprovals + }); + + it('renders tabs', () => { + render(); + + expect(screen.getByText('User Management')).toBeInTheDocument(); + expect(screen.getByText('Organization')).toBeInTheDocument(); + expect(screen.getByText('System')).toBeInTheDocument(); + }); + + it('renders system settings button', () => { + render(); + + expect(screen.getByText('System Settings')).toBeInTheDocument(); + }); +}); diff --git a/components/analytics/analytics-charts.tsx b/components/analytics/analytics-charts.tsx new file mode 100644 index 0000000..a98da55 --- /dev/null +++ b/components/analytics/analytics-charts.tsx @@ -0,0 +1,149 @@ +'use client'; + +import React from 'react'; +import { + BarChart, + Bar, + XAxis, + YAxis, + CartesianGrid, + Tooltip, + ResponsiveContainer, + PieChart, + Pie, + Cell, + LineChart, + Line, +} from 'recharts'; + +interface AnalyticsChartsProps { + metrics: { + totalEvents: number; + eventsByType: Record; + impressions: number; + clicks: number; + views: number; + ctr: number; + roi: number; + campaignMetrics: Array<{ + id: string; + name: string; + totalEvents: number; + contentCount: number; + contentMetrics: Array<{ + id: string; + title: string; + events: number; + impressions: number; + clicks: number; + views: number; + }>; + }>; + }; +} + +const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042', '#8884D8']; + +export function AnalyticsCharts({ metrics }: AnalyticsChartsProps) { + // Prepare data for event types pie chart + const eventTypesData = Object.entries(metrics.eventsByType).map(([type, count]) => ({ + name: type.charAt(0).toUpperCase() + type.slice(1), + value: count, + })); + + // Prepare data for campaign performance bar chart + const campaignData = metrics.campaignMetrics.map((campaign) => ({ + name: campaign.name.length > 15 ? campaign.name.substring(0, 15) + '...' : campaign.name, + events: campaign.totalEvents, + content: campaign.contentCount, + })); + + // Prepare data for performance metrics line chart + const performanceData = [ + { name: 'Impressions', value: metrics.impressions }, + { name: 'Clicks', value: metrics.clicks }, + { name: 'Views', value: metrics.views }, + ]; + + return ( +
+ {/* Event Types Distribution */} +
+

Event Types Distribution

+ + + `${name} ${(percent * 100).toFixed(0)}%`} + outerRadius={80} + fill="#8884d8" + dataKey="value" + > + {eventTypesData.map((entry, index) => ( + + ))} + + + + +
+ + {/* Campaign Performance */} +
+

Campaign Performance

+ + + + + + + + + +
+ + {/* Performance Metrics */} +
+

Key Performance Metrics

+
+
+
+ {metrics.impressions.toLocaleString()} +
+
Impressions
+
+
+
+ {metrics.clicks.toLocaleString()} +
+
Clicks
+
+
+
+ {metrics.ctr.toFixed(2)}% +
+
CTR
+
+
+ + + + + + + + + +
+
+ ); +} diff --git a/components/analytics/analytics-example.tsx b/components/analytics/analytics-example.tsx new file mode 100644 index 0000000..b38adfc --- /dev/null +++ b/components/analytics/analytics-example.tsx @@ -0,0 +1,119 @@ +'use client'; + +import React from 'react'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { useAnalytics } from '@/hooks/use-analytics'; +import { Eye, MousePointer, ThumbsUp, Share2 } from 'lucide-react'; + +interface AnalyticsExampleProps { + orgId: string; + campaignId?: string; + contentId?: string; +} + +export function AnalyticsExample({ orgId, campaignId, contentId }: AnalyticsExampleProps) { + const { trackEvent } = useAnalytics(orgId); + + const handleView = async () => { + try { + await trackEvent('view', campaignId, contentId, { + source: 'example_component', + timestamp: new Date().toISOString(), + }); + console.log('View event tracked'); + } catch (error) { + console.error('Failed to track view:', error); + } + }; + + const handleClick = async () => { + try { + await trackEvent('click', campaignId, contentId, { + element: 'example_button', + position: 'center', + }); + console.log('Click event tracked'); + } catch (error) { + console.error('Failed to track click:', error); + } + }; + + const handleLike = async () => { + try { + await trackEvent('like', campaignId, contentId, { + reaction_type: 'thumbs_up', + }); + console.log('Like event tracked'); + } catch (error) { + console.error('Failed to track like:', error); + } + }; + + const handleShare = async () => { + try { + await trackEvent('share', campaignId, contentId, { + platform: 'social_media', + }); + console.log('Share event tracked'); + } catch (error) { + console.error('Failed to track share:', error); + } + }; + + return ( + + + Analytics Event Tracking Example + + Click buttons to track different types of analytics events + + + +
+ + + + +
+ +
+

+ Campaign ID: {campaignId || 'Not set'} +

+

+ Content ID: {contentId || 'Not set'} +

+

+ Organization ID: {orgId} +

+
+ +
+

+ Usage: +

+
+                  {`const { trackEvent } = useAnalytics(orgId);
+
+await trackEvent('event_type', campaignId, contentId, {
+  custom_data: 'value'
+});`}
+               
+
+
+
+ ); +} diff --git a/components/assets/asset-library.tsx b/components/assets/asset-library.tsx new file mode 100644 index 0000000..e0d301b --- /dev/null +++ b/components/assets/asset-library.tsx @@ -0,0 +1,312 @@ +'use client'; + +import { useState, useEffect } from 'react'; +import { useSession } from 'next-auth/react'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { Input } from '@/components/ui/input'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogTrigger, +} from '@/components/ui/dialog'; +import { Upload, Search, Image, Video, FileText, Music, Trash2, Eye } from 'lucide-react'; +import { AssetUpload } from './asset-upload'; +import { AssetPreview } from './asset-preview'; + +interface Asset { + id: string; + url: string; + name?: string; + type: string; + size?: number; + description?: string; + tags?: string[]; + createdAt: string; + content: { + id: string; + title: string; + }; +} + +interface AssetLibraryProps { + orgId: string; + contentId?: string; + onAssetSelect?: (asset: Asset) => void; +} + +export function AssetLibrary({ orgId, contentId, onAssetSelect }: AssetLibraryProps) { + const { data: session } = useSession(); + const [assets, setAssets] = useState([]); + const [loading, setLoading] = useState(true); + const [searchTerm, setSearchTerm] = useState(''); + const [selectedType, setSelectedType] = useState('all'); + const [selectedTags, setSelectedTags] = useState([]); + const [sortBy, setSortBy] = useState('newest'); + const [uploadDialogOpen, setUploadDialogOpen] = useState(false); + const [previewAsset, setPreviewAsset] = useState(null); + + const fetchAssets = async () => { + try { + const params = new URLSearchParams(); + if (contentId) params.append('contentId', contentId); + + const response = await fetch(`/api/${orgId}/assets?${params}`); + if (response.ok) { + const data = await response.json(); + setAssets(data); + } + } catch (error) { + console.error('Error fetching assets:', error); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + if (session?.user) { + fetchAssets(); + } + }, [session, orgId, contentId]); + + const filteredAssets = assets + .filter((asset) => { + const matchesSearch = + !searchTerm || + asset.name?.toLowerCase().includes(searchTerm.toLowerCase()) || + asset.content.title.toLowerCase().includes(searchTerm.toLowerCase()) || + asset.type.toLowerCase().includes(searchTerm.toLowerCase()) || + asset.description?.toLowerCase().includes(searchTerm.toLowerCase()) || + asset.tags?.some((tag) => tag.toLowerCase().includes(searchTerm.toLowerCase())); + + const matchesType = selectedType === 'all' || asset.type.startsWith(selectedType); + const matchesTags = + selectedTags.length === 0 || selectedTags.every((tag) => asset.tags?.includes(tag)); + + return matchesSearch && matchesType && matchesTags; + }) + .sort((a, b) => { + switch (sortBy) { + case 'newest': + return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(); + case 'oldest': + return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(); + case 'name': + return (a.name || a.content.title).localeCompare(b.name || b.content.title); + case 'size': + return (b.size || 0) - (a.size || 0); + default: + return 0; + } + }); + + const getAssetIcon = (type: string) => { + if (type.startsWith('image/')) return ; + if (type.startsWith('video/')) return