Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions app/(dashboard)/credits/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { CreditDashboard } from '@/components/credits/credit-components';
import { getUser, getTeamForUser } from '@/lib/db/queries';
import { redirect } from 'next/navigation';

export default async function CreditsPage() {
const user = await getUser();
if (!user) {
redirect('/sign-in');
}

const team = await getTeamForUser(user.id);
if (!team) {
throw new Error('Team not found');
}

return (
<div className="container mx-auto py-6">
<h1 className="text-3xl font-bold mb-6">Credit Management</h1>
<CreditDashboard teamId={team.id} />
</div>
);
}
16 changes: 14 additions & 2 deletions app/(dashboard)/dashboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { redirect } from 'next/navigation';
import { Settings } from './settings';
import { getTeamForUser, getUser } from '@/lib/db/queries';
import { CreditBalance } from '@/components/credits/credit-components';

export default async function SettingsPage() {
export default async function DashboardPage() {
const user = await getUser();

if (!user) {
Expand All @@ -15,5 +16,16 @@ export default async function SettingsPage() {
throw new Error('Team not found');
}

return <Settings teamData={teamData} />;
return (
<div className="container mx-auto py-6">
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div className="md:col-span-1">
<CreditBalance teamId={teamData.id} />
</div>
<div className="md:col-span-2">
<Settings teamData={teamData} />
</div>
</div>
</div>
);
}
8 changes: 7 additions & 1 deletion app/(dashboard)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import Link from 'next/link';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { CircleIcon, Home, LogOut } from 'lucide-react';
import { CircleIcon, Home, LogOut, CreditCard } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
Expand Down Expand Up @@ -60,6 +60,12 @@ function Header() {
<span>Dashboard</span>
</Link>
</DropdownMenuItem>
<DropdownMenuItem className="cursor-pointer">
<Link href="/credits" className="flex w-full items-center">
<CreditCard className="mr-2 h-4 w-4" />
<span>Credits</span>
</Link>
</DropdownMenuItem>
<form action={handleSignOut} className="w-full">
<button type="submit" className="flex w-full">
<DropdownMenuItem className="w-full flex-1 cursor-pointer">
Expand Down
32 changes: 32 additions & 0 deletions app/api/ai-generation/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { creditService } from '@/lib/services/credit-service';
import { InsufficientCreditsError } from '@/lib/utils';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
const { teamId, prompt } = await request.json();
const requiredCredits = 10; // Define based on your pricing

try {
// Use credits first
await creditService.useCredits(
teamId,
null, // userId if available
requiredCredits,
'ai_generation',
`Generated content for prompt: ${prompt.substring(0, 50)}...`
);

// Then perform the actual operation
// const result = await generateAIContent(prompt);

return NextResponse.json({ result: 'AI content generated' });
} catch (error) {
if (error instanceof InsufficientCreditsError) {
return NextResponse.json(
{ error: 'Insufficient credits' },
{ status: 402 }
);
}
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
16 changes: 16 additions & 0 deletions app/api/credits/balance/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { creditService } from '@/lib/services/credit-service';
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
const teamId = request.nextUrl.searchParams.get('teamId');
if (!teamId) {
return NextResponse.json({ error: 'teamId is required' }, { status: 400 });
}

try {
const balance = await creditService.getCreditBalance(parseInt(teamId));
return NextResponse.json(balance);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
23 changes: 23 additions & 0 deletions app/api/credits/grants-history/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { creditService } from '@/lib/services/credit-service';
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
const teamId = request.nextUrl.searchParams.get('teamId');
const limit = request.nextUrl.searchParams.get('limit');
const offset = request.nextUrl.searchParams.get('offset');

if (!teamId) {
return NextResponse.json({ error: 'teamId is required' }, { status: 400 });
}

try {
const history = await creditService.getGrantsHistory(
parseInt(teamId),
limit ? parseInt(limit) : undefined,
offset ? parseInt(offset) : undefined
);
return NextResponse.json(history);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
23 changes: 23 additions & 0 deletions app/api/credits/usage-history/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { creditService } from '@/lib/services/credit-service';
import { NextRequest, NextResponse } from 'next/server';

export async function GET(request: NextRequest) {
const teamId = request.nextUrl.searchParams.get('teamId');
const limit = request.nextUrl.searchParams.get('limit');
const offset = request.nextUrl.searchParams.get('offset');

if (!teamId) {
return NextResponse.json({ error: 'teamId is required' }, { status: 400 });
}

try {
const history = await creditService.getUsageHistory(
parseInt(teamId),
limit ? parseInt(limit) : undefined,
offset ? parseInt(offset) : undefined
);
return NextResponse.json(history);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
28 changes: 28 additions & 0 deletions app/api/credits/use/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { creditService } from '@/lib/services/credit-service';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
const { teamId, userId, credits, actionType, description, metadata } =
await request.json();

if (!teamId || !credits || !actionType) {
return NextResponse.json(
{ error: 'teamId, credits, and actionType are required' },
{ status: 400 }
);
}

try {
const newBalance = await creditService.useCredits(
teamId,
userId,
credits,
actionType,
description,
metadata
);
return NextResponse.json(newBalance);
} catch (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
}
34 changes: 3 additions & 31 deletions app/api/stripe/webhook/route.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,6 @@
import Stripe from 'stripe';
import { handleSubscriptionChange, stripe } from '@/lib/payments/stripe';
import { NextRequest, NextResponse } from 'next/server';

const webhookSecret = process.env.STRIPE_WEBHOOK_SECRET!;
import { handleStripeWebhook } from '@/lib/services/stripe-webhook-handler';
import { NextRequest } from 'next/server';

export async function POST(request: NextRequest) {
const payload = await request.text();
const signature = request.headers.get('stripe-signature') as string;

let event: Stripe.Event;

try {
event = stripe.webhooks.constructEvent(payload, signature, webhookSecret);
} catch (err) {
console.error('Webhook signature verification failed.', err);
return NextResponse.json(
{ error: 'Webhook signature verification failed.' },
{ status: 400 }
);
}

switch (event.type) {
case 'customer.subscription.updated':
case 'customer.subscription.deleted':
const subscription = event.data.object as Stripe.Subscription;
await handleSubscriptionChange(subscription);
break;
default:
console.log(`Unhandled event type ${event.type}`);
}

return NextResponse.json({ received: true });
return handleStripeWebhook(request);
}
34 changes: 34 additions & 0 deletions components/ai/ai-generation-component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use client';

import { useCreditCheck } from '@/components/credits/credit-components';
import { Button } from '../ui/button';

function AIGenerationComponent({ teamId }: { teamId: number }) {
const { hasSufficientCredits, loading } = useCreditCheck(teamId, 10);

const handleGenerate = async () => {
if (!hasSufficientCredits) {
alert('Insufficient credits');
return;
}

// Proceed with generation
const response = await fetch('/api/ai-generation', {
method: 'POST',
body: JSON.stringify({ teamId, prompt: 'A sample prompt' }),
});

// Handle response
const data = await response.json();
alert(data.result);
};

return (
<Button
onClick={handleGenerate}
disabled={!hasSufficientCredits || loading}
>
Generate (10 credits)
</Button>
);
}
Loading