-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Add Official Provider and Credits System #1024
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
luoling8192
wants to merge
8
commits into
main
Choose a base branch
from
feature/official-provider-and-credits-15068508989857164459
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e0f9686
feat: add official provider and user credits system with stripe integ…
google-labs-jules[bot] 8c0bec6
[autofix.ci] apply automated fixes
autofix-ci[bot] 1f05f48
chore: type
luoling8192 d9e5597
fix: type
luoling8192 20fb2c8
feat: rename to flux
luoling8192 ec9bafa
feat: i18n
luoling8192 0f7beb3
chore: rename
luoling8192 48f6fa8
feat: ui
luoling8192 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| import type { FluxService } from '../services/flux' | ||
| import type { HonoEnv } from '../types/hono' | ||
|
|
||
| import { Hono } from 'hono' | ||
|
|
||
| import { authGuard } from '../middlewares/auth' | ||
|
|
||
| export function createFluxRoutes(fluxService: FluxService) { | ||
| const routes = new Hono<HonoEnv>() | ||
|
|
||
| routes.use('*', authGuard) | ||
|
|
||
| routes.get('/', async (c) => { | ||
| const user = c.get('user')! | ||
| const flux = await fluxService.getFlux(user.id) | ||
| return c.json(flux) | ||
| }) | ||
|
|
||
| return routes | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import type { FluxService } from '../services/flux' | ||
| import type { HonoEnv } from '../types/hono' | ||
|
|
||
| import Stripe from 'stripe' | ||
|
|
||
| import { Hono } from 'hono' | ||
|
|
||
| import { authGuard } from '../middlewares/auth' | ||
|
|
||
| export function createStripeRoutes(fluxService: FluxService, env: any) { | ||
| const stripe = new Stripe(env.STRIPE_SECRET_KEY) | ||
| const routes = new Hono<HonoEnv>() | ||
|
|
||
| routes.post('/checkout', authGuard, async (c) => { | ||
| const user = c.get('user')! | ||
| const { amount } = await c.req.json() | ||
|
|
||
| const session = await stripe.checkout.sessions.create({ | ||
| payment_method_types: ['card'], | ||
| line_items: [ | ||
| { | ||
| price_data: { | ||
| currency: 'usd', | ||
| product_data: { | ||
| name: 'Flux Top-up', | ||
| }, | ||
| unit_amount: amount, | ||
| }, | ||
| quantity: 1, | ||
| }, | ||
| ], | ||
| mode: 'payment', | ||
| success_url: `${env.CLIENT_URL}/settings/flux?success=true`, | ||
| cancel_url: `${env.CLIENT_URL}/settings/flux?canceled=true`, | ||
| customer_email: user.email, | ||
| metadata: { | ||
| userId: user.id, | ||
| }, | ||
| }) | ||
|
|
||
| return c.json({ url: session.url }) | ||
| }) | ||
|
|
||
| routes.post('/webhook', async (c) => { | ||
| const sig = c.req.header('stripe-signature') | ||
| if (!sig) | ||
| return c.json({ error: 'No signature' }, 400) | ||
|
|
||
| let event: Stripe.Event | ||
| try { | ||
| const body = await c.req.text() | ||
| event = stripe.webhooks.constructEvent(body, sig, env.STRIPE_WEBHOOK_SECRET) | ||
| } | ||
| catch (err: any) { | ||
| return c.json({ error: `Webhook Error: ${err.message}` }, 400) | ||
| } | ||
|
|
||
| if (event.type === 'checkout.session.completed') { | ||
| const session = event.data.object as Stripe.Checkout.Session | ||
| const userId = session.metadata?.userId | ||
| const amount = session.amount_total | ||
|
|
||
| if (userId && amount) { | ||
| // Example: 1 flux per cent? | ||
| await fluxService.addFlux(userId, amount) | ||
| } | ||
| } | ||
|
|
||
| return c.json({ received: true }) | ||
| }) | ||
|
|
||
| return routes | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,44 @@ | ||||||
| import type { FluxService } from '../services/flux' | ||||||
| import type { HonoEnv } from '../types/hono' | ||||||
|
|
||||||
| import { Hono } from 'hono' | ||||||
|
|
||||||
| import { authGuard } from '../middlewares/auth' | ||||||
|
|
||||||
| export function createV1Routes(fluxService: FluxService, env: any) { | ||||||
| const v1 = new Hono<HonoEnv>() | ||||||
|
|
||||||
| v1.use('*', authGuard) | ||||||
|
|
||||||
| async function handleCompletion(c: any) { | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The context object import type { Context } from 'hono'
Suggested change
|
||||||
| const user = c.get('user')! | ||||||
| const flux = await fluxService.getFlux(user.id) | ||||||
| if (flux.flux <= 0) { | ||||||
| return c.json({ error: 'Insufficient flux' }, 402) | ||||||
| } | ||||||
|
|
||||||
| const body = await c.req.json() | ||||||
|
|
||||||
| // Consume flux (simplified: 1 per request) | ||||||
| await fluxService.consumeFlux(user.id, 1) | ||||||
|
|
||||||
| const response = await fetch(`${env.BACKEND_LLM_BASE_URL}chat/completions`, { | ||||||
| method: 'POST', | ||||||
| headers: { | ||||||
| 'Content-Type': 'application/json', | ||||||
| 'Authorization': `Bearer ${env.BACKEND_LLM_API_KEY}`, | ||||||
| }, | ||||||
| body: JSON.stringify(body), | ||||||
| }) | ||||||
|
|
||||||
| return new Response(response.body, { | ||||||
| status: response.status, | ||||||
| headers: response.headers, | ||||||
| }) | ||||||
| } | ||||||
|
|
||||||
| v1.post('/chat/completions', handleCompletion) | ||||||
| v1.post('/chat/completion', handleCompletion) | ||||||
|
|
||||||
| return v1 | ||||||
| } | ||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| import { integer, pgTable, text, timestamp } from 'drizzle-orm/pg-core' | ||
|
|
||
| import { user } from './accounts' | ||
|
|
||
| export const userFlux = pgTable('user_credits', { | ||
| userId: text('user_id').primaryKey().references(() => user.id, { onDelete: 'cascade' }), | ||
| flux: integer('credits').notNull().default(0), | ||
| stripeCustomerId: text('stripe_customer_id'), | ||
| updatedAt: timestamp('updated_at').defaultNow().notNull(), | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| export * from './accounts' | ||
| export * from './characters' | ||
| export * from './chats' | ||
| export * from './flux' | ||
| export * from './providers' | ||
| export * from './user-character' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| import type * as fullSchema from '../schemas' | ||
| import type { Database } from './db' | ||
|
|
||
| import { eq } from 'drizzle-orm' | ||
|
|
||
| import * as schema from '../schemas/flux' | ||
|
|
||
| export function createFluxService(db: Database<typeof fullSchema>) { | ||
| return { | ||
| async getFlux(userId: string) { | ||
| let record = await db.query.userFlux.findFirst({ | ||
| where: eq(schema.userFlux.userId, userId), | ||
| }) | ||
|
|
||
| if (!record) { | ||
| [record] = await db.insert(schema.userFlux).values({ | ||
| userId, | ||
| flux: 100, // Default initial flux | ||
| }).returning() | ||
| } | ||
|
|
||
| return record | ||
| }, | ||
|
|
||
| async consumeFlux(userId: string, amount: number) { | ||
| const record = await this.getFlux(userId) | ||
| if (record.flux < amount) { | ||
| throw new Error('Insufficient flux') | ||
| } | ||
|
|
||
| const [updated] = await db.update(schema.userFlux) | ||
| .set({ | ||
| flux: record.flux - amount, | ||
| updatedAt: new Date(), | ||
| }) | ||
| .where(eq(schema.userFlux.userId, userId)) | ||
| .returning() | ||
|
|
||
| return updated | ||
| }, | ||
|
|
||
| async addFlux(userId: string, amount: number) { | ||
| const record = await this.getFlux(userId) | ||
| const [updated] = await db.update(schema.userFlux) | ||
| .set({ | ||
| flux: record.flux + amount, | ||
| updatedAt: new Date(), | ||
| }) | ||
| .where(eq(schema.userFlux.userId, userId)) | ||
| .returning() | ||
|
|
||
| return updated | ||
| }, | ||
|
|
||
| async updateStripeCustomerId(userId: string, stripeCustomerId: string) { | ||
| const [updated] = await db.update(schema.userFlux) | ||
| .set({ | ||
| stripeCustomerId, | ||
| updatedAt: new Date(), | ||
| }) | ||
| .where(eq(schema.userFlux.userId, userId)) | ||
| .returning() | ||
|
|
||
| return updated | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| export type FluxService = ReturnType<typeof createFluxService> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
envparameter is typed asany. For better type safety, it should be typed with theEnvtype from../services/env. You'll need to import it: