From c7cc6f6dfd5b807d9eef801939454e5f95dc1009 Mon Sep 17 00:00:00 2001 From: skycurtain Date: Fri, 9 Oct 2026 22:02:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(db):=20payments=20=E6=8B=86=E4=B8=BA=20sub?= =?UTF-8?q?scriptions=20=E4=B8=8E=20topups?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 订阅权益与充值入账分表;topups 对齐上游充值单(无 quota_granted), paid_at=complete_time;quota_derived 查询层派生。 --- packages/core/src/errors.ts | 3 + packages/core/src/schemas.ts | 92 +- packages/core/src/types.ts | 35 +- packages/core/src/upstream.ts | 73 ++ .../db/drizzle/0000_loose_goblin_queen.sql | 138 +++ packages/db/drizzle/meta/0000_snapshot.json | 1054 +++++++++++++++++ packages/db/drizzle/meta/_journal.json | 13 + packages/db/src/repos.ts | 94 +- packages/db/src/schema.ts | 56 +- 9 files changed, 1474 insertions(+), 84 deletions(-) create mode 100644 packages/db/drizzle/0000_loose_goblin_queen.sql create mode 100644 packages/db/drizzle/meta/0000_snapshot.json create mode 100644 packages/db/drizzle/meta/_journal.json diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts index bfeeec3..d56c464 100644 --- a/packages/core/src/errors.ts +++ b/packages/core/src/errors.ts @@ -27,6 +27,9 @@ export const ERR = { errorBody("invalid_credentials", "用户名或密码错误"), session_expired: () => errorBody("session_expired", "会话已过期,请重新登录"), + /** 上游控制台 token 失效——**不是**管理端会话,禁止走 401 登出 */ + platform_token_invalid: () => + errorBody("platform_token_invalid", "平台登录已失效,请重新登录上游账号"), already_initialized: () => errorBody("already_initialized", "系统已初始化,无法重复引导"), key_already_registered: (key_id: number) => diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.ts index a675cf7..0582f33 100644 --- a/packages/core/src/schemas.ts +++ b/packages/core/src/schemas.ts @@ -130,17 +130,33 @@ export const memberMe = z.object({ name: z.string(), }); -export const paymentItem = z.object({ +export const subscriptionItem = z.object({ id: z.number().int(), - kind: z.enum(["subscription", "topup"]), - paid_at: z.number().int(), - paid_amount: z.number(), - remark: z.string(), - period_start: z.number().int().nullable(), + subscription_id: z.number().int(), + period_start: z.number().int(), period_end: z.number().int().nullable(), - subscription_id: z.number().int().nullable(), - quota_granted: z.number().int().nullable(), + quota_granted: z.number().int(), quota_usd: z.string(), + paid_amount: z.number().nullable(), + paid_at: z.number().int().nullable(), + remark: z.string(), + created_at: z.number().int(), +}); + +export const topupItem = z.object({ + id: z.number().int(), + upstream_id: z.number().int().nullable(), + amount: z.number(), + money: z.number(), + trade_no: z.string().nullable(), + payment_method: z.string().nullable(), + payment_provider: z.string().nullable(), + status: z.string().nullable(), + paid_at: z.number().int(), + quota_derived: z.number().int(), + quota_usd: z.string(), + remark: z.string(), + created_at: z.number().int(), }); export const engineStatus = z.object({ @@ -188,46 +204,33 @@ export const memberOverview = z.object({ usage: usageTotals, }), ), - payments: z.array(z.looseObject({ id: z.number().int() })), + subscriptions: z.array(subscriptionItem), + topups: z.array(topupItem), }); -export const createPaymentBody = z +export const createSubscriptionBody = z .object({ - kind: z.enum(["subscription", "topup"]), - paid_at: z.string().min(1), - paid_amount: z.number(), - remark: z.string().default(""), - period_start: z.string().min(1).nullable().optional(), + subscription_id: z.number().int().positive(), + period_start: z.string().min(1), period_end: z.string().min(1).nullable().optional(), - subscription_id: z.number().int().positive().nullable().optional(), - quota_granted: z.number().int().nullable().optional(), - }) - .superRefine((val, ctx) => { - if (val.kind === "subscription") { - if (!val.period_start) { - ctx.addIssue({ - code: "custom", - message: "订阅必须填写期间起点", - path: ["period_start"], - }); - } - if (val.subscription_id == null) { - ctx.addIssue({ - code: "custom", - message: "订阅必须填写订阅编号", - path: ["subscription_id"], - }); - } - } - if (val.quota_granted == null) { - ctx.addIssue({ - code: "custom", - message: "必须填写本笔额度", - path: ["quota_granted"], - }); - } + quota_granted: z.number().int().positive(), + paid_amount: z.number().nullable().optional(), + paid_at: z.string().min(1).nullable().optional(), + remark: z.string().default(""), }); +export const createTopupBody = z.object({ + upstream_id: z.number().int().nullable().optional(), + amount: z.number().positive(), + money: z.number().positive(), + trade_no: z.string().nullable().optional(), + payment_method: z.string().nullable().optional(), + payment_provider: z.string().nullable().optional(), + status: z.string().nullable().optional(), + paid_at: z.string().min(1), + remark: z.string().default(""), +}); + export { setupBody as setupBodySchema, loginBody as loginBodySchema, @@ -236,7 +239,10 @@ export { patchKeyBody as patchKeyBodySchema, createMemberBody as createMemberBodySchema, patchMemberBody as patchMemberBodySchema, - createPaymentBody as createPaymentBodySchema, + createSubscriptionBody as createSubscriptionBodySchema, + createTopupBody as createTopupBodySchema, + subscriptionItem as subscriptionItemSchema, + topupItem as topupItemSchema, timeRangeQuery as timeRangeQuerySchema, pageQuery as pageQuerySchema, }; diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 75c1dc4..31b6a15 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -11,7 +11,6 @@ export type Quota = number; export type QuotaUsd = string; export type BillingSource = "subscription" | "wallet"; -export type PaymentKind = "subscription" | "topup"; export type KeyStatus = "active" | "disabled"; export type MemberStatus = "active" | "disabled"; @@ -57,17 +56,35 @@ export interface KeyItem { expires_at: UnixSec | null; } -export interface PaymentItem { +/** 订阅权益登记 */ +export interface SubscriptionItem { id: number; - kind: PaymentKind; - paid_at: UnixSec; - paid_amount: PaidAmount; - remark: string; - period_start: UnixSec | null; + subscription_id: number; + period_start: UnixSec; period_end: UnixSec | null; - subscription_id: number | null; - quota_granted: number | null; + quota_granted: Quota; quota_usd: QuotaUsd; + paid_amount: PaidAmount | null; + paid_at: UnixSec | null; + remark: string; + created_at: UnixSec; +} + +/** 充值入账(对齐上游充值单;无 quota_granted 入库列) */ +export interface TopupItem { + id: number; + upstream_id: number | null; + amount: number; + money: PaidAmount; + trade_no: string | null; + payment_method: string | null; + payment_provider: string | null; + status: string | null; + paid_at: UnixSec; + quota_derived: Quota; + quota_usd: QuotaUsd; + remark: string; + created_at: UnixSec; } export interface MemberItem { diff --git a/packages/core/src/upstream.ts b/packages/core/src/upstream.ts index 2707708..f0d86c0 100644 --- a/packages/core/src/upstream.ts +++ b/packages/core/src/upstream.ts @@ -241,3 +241,76 @@ export async function fetchPlatformSubscriptions( clearTimeout(timer); } } + +/** 平台充值单(GET /api/user/topup/self 单页) */ +export interface PlatformTopup { + id: number; + user_id?: number; + amount: number; + money: number; + trade_no?: string; + payment_method?: string; + payment_provider?: string; + create_time?: number; + complete_time?: number; + status?: string; +} + +/** 用控制台 access_token 分页拉充值单(仅 p / page_size,无时间参数) */ +export async function fetchPlatformTopups( + baseUrl: string, + accessToken: string, + page = 1, + pageSize = 10, + timeoutMs = 8_000, +): Promise< + UpstreamResult<{ + items: PlatformTopup[]; + total: number; + page: number; + page_size: number; + }> +> { + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), timeoutMs); + try { + const full = `${joinUrl(baseUrl, "/api/user/topup/self")}?p=${page}&page_size=${pageSize}`; + const res = await fetch(full, { + method: "GET", + headers: { + Authorization: `Bearer ${accessToken}`, + Accept: "application/json", + }, + signal: ac.signal, + }); + if (res.status === 401) return { ok: false, kind: "rejected" }; + if (!res.ok) return { ok: false, kind: "http", status: res.status }; + const body = (await res.json()) as { + code?: boolean | number; + success?: boolean; + data?: { + page?: number; + page_size?: number; + total?: number; + items?: PlatformTopup[]; + }; + }; + if (body.code === false || body.success === false) { + return { ok: false, kind: "rejected" }; + } + const data = body.data ?? {}; + return { + ok: true, + data: { + items: data.items ?? [], + total: data.total ?? 0, + page: data.page ?? page, + page_size: data.page_size ?? pageSize, + }, + }; + } catch { + return { ok: false, kind: "unreachable" }; + } finally { + clearTimeout(timer); + } +} diff --git a/packages/db/drizzle/0000_loose_goblin_queen.sql b/packages/db/drizzle/0000_loose_goblin_queen.sql new file mode 100644 index 0000000..471ce51 --- /dev/null +++ b/packages/db/drizzle/0000_loose_goblin_queen.sql @@ -0,0 +1,138 @@ +CREATE TABLE "api_keys" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "api_keys_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "key_hash" text NOT NULL, + "key_ciphertext" "bytea" NOT NULL, + "status" text DEFAULT 'active' NOT NULL, + "member_id" bigint, + "registered_at" timestamp with time zone DEFAULT now() NOT NULL, + "log_synced_at" timestamp with time zone, + "usage_synced_at" timestamp with time zone, + "token_name" text DEFAULT '' NOT NULL, + "total_granted" bigint DEFAULT 0 NOT NULL, + "total_used" bigint DEFAULT 0 NOT NULL, + "total_available" bigint DEFAULT 0 NOT NULL, + "unlimited_quota" boolean DEFAULT false NOT NULL, + "model_limits" jsonb, + "model_limits_enabled" boolean DEFAULT false NOT NULL, + "expires_at" timestamp with time zone, + CONSTRAINT "api_keys_key_hash_unique" UNIQUE("key_hash") +); +--> statement-breakpoint +CREATE TABLE "audit_logs" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "audit_logs_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "operator" text, + "domain" text NOT NULL, + "action" text NOT NULL, + "summary" text DEFAULT '' NOT NULL +); +--> statement-breakpoint +CREATE TABLE "engine_status" ( + "id" integer PRIMARY KEY DEFAULT 1 NOT NULL, + "running" boolean DEFAULT false NOT NULL, + "sync_interval_ms" bigint DEFAULT 300000 NOT NULL, + "last_round" jsonb, + "updated_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "members" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "members_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "name" text NOT NULL, + "remark" text DEFAULT '' NOT NULL, + "status" text DEFAULT 'active' NOT NULL, + "token_hash" text NOT NULL, + "token_issued_at" timestamp with time zone, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "members_name_unique" UNIQUE("name"), + CONSTRAINT "members_token_hash_unique" UNIQUE("token_hash") +); +--> statement-breakpoint +CREATE TABLE "qpu_history" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "qpu_history_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "qpu" numeric(18, 6) NOT NULL, + "effective_from" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "sessions" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "sessions_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "user_id" bigint NOT NULL, + "token_hash" text NOT NULL, + "expires_at" timestamp with time zone NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "sessions_token_hash_unique" UNIQUE("token_hash") +); +--> statement-breakpoint +CREATE TABLE "subscriptions" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "subscriptions_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "subscription_id" bigint NOT NULL, + "period_start" timestamp with time zone NOT NULL, + "period_end" timestamp with time zone, + "quota_granted" bigint NOT NULL, + "paid_amount" numeric(18, 2), + "paid_at" timestamp with time zone, + "remark" text DEFAULT '' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "subscriptions_subscription_id_unique" UNIQUE("subscription_id") +); +--> statement-breakpoint +CREATE TABLE "topups" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "topups_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "upstream_id" bigint, + "amount" numeric(18, 6) NOT NULL, + "money" numeric(18, 2) NOT NULL, + "trade_no" text, + "payment_method" text, + "payment_provider" text, + "status" text, + "paid_at" timestamp with time zone NOT NULL, + "remark" text DEFAULT '' NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +CREATE TABLE "usage_logs" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "usage_logs_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "api_key_id" bigint NOT NULL, + "dedupe_key" text NOT NULL, + "billing_source" text, + "subscription_id" bigint, + "user_id" bigint DEFAULT 0 NOT NULL, + "created_at" timestamp with time zone NOT NULL, + "type" smallint DEFAULT 2 NOT NULL, + "content" text DEFAULT '' NOT NULL, + "username" text DEFAULT '' NOT NULL, + "token_name" text DEFAULT '' NOT NULL, + "model_name" text DEFAULT '' NOT NULL, + "quota" bigint DEFAULT 0 NOT NULL, + "prompt_tokens" integer DEFAULT 0 NOT NULL, + "completion_tokens" integer DEFAULT 0 NOT NULL, + "use_time" integer DEFAULT 0 NOT NULL, + "is_stream" boolean DEFAULT false NOT NULL, + "channel" integer DEFAULT 0 NOT NULL, + "channel_name" text DEFAULT '' NOT NULL, + "token_id" bigint DEFAULT 0 NOT NULL, + "group_name" text DEFAULT '' NOT NULL, + "ip" text DEFAULT '' NOT NULL, + "request_id" text DEFAULT '' NOT NULL, + "upstream_request_id" text, + "other" jsonb, + CONSTRAINT "usage_logs_dedupe_key_unique" UNIQUE("dedupe_key") +); +--> statement-breakpoint +CREATE TABLE "users" ( + "id" bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "users_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 9223372036854775807 START WITH 1 CACHE 1), + "username" text NOT NULL, + "password_hash" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + CONSTRAINT "users_username_unique" UNIQUE("username") +); +--> statement-breakpoint +ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_member_id_members_id_fk" FOREIGN KEY ("member_id") REFERENCES "public"."members"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "usage_logs" ADD CONSTRAINT "usage_logs_api_key_id_api_keys_id_fk" FOREIGN KEY ("api_key_id") REFERENCES "public"."api_keys"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "api_keys_member_id_idx" ON "api_keys" USING btree ("member_id");--> statement-breakpoint +CREATE INDEX "audit_logs_created_at_idx" ON "audit_logs" USING btree ("created_at");--> statement-breakpoint +CREATE INDEX "sessions_user_id_idx" ON "sessions" USING btree ("user_id");--> statement-breakpoint +CREATE INDEX "subscriptions_period_idx" ON "subscriptions" USING btree ("period_start","period_end");--> statement-breakpoint +CREATE INDEX "usage_logs_created_at_idx" ON "usage_logs" USING btree ("created_at");--> statement-breakpoint +CREATE INDEX "usage_logs_api_key_created_idx" ON "usage_logs" USING btree ("api_key_id","created_at");--> statement-breakpoint +CREATE INDEX "usage_logs_subscription_idx" ON "usage_logs" USING btree ("subscription_id"); \ No newline at end of file diff --git a/packages/db/drizzle/meta/0000_snapshot.json b/packages/db/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000..b5c6381 --- /dev/null +++ b/packages/db/drizzle/meta/0000_snapshot.json @@ -0,0 +1,1054 @@ +{ + "id": "ab6e6c62-7131-480b-9b11-5a386e3c8863", + "prevId": "00000000-0000-0000-0000-000000000000", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.api_keys": { + "name": "api_keys", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "api_keys_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "key_hash": { + "name": "key_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "key_ciphertext": { + "name": "key_ciphertext", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "member_id": { + "name": "member_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "registered_at": { + "name": "registered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "log_synced_at": { + "name": "log_synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "usage_synced_at": { + "name": "usage_synced_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "token_name": { + "name": "token_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "total_granted": { + "name": "total_granted", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "total_used": { + "name": "total_used", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "total_available": { + "name": "total_available", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "unlimited_quota": { + "name": "unlimited_quota", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "model_limits": { + "name": "model_limits", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "model_limits_enabled": { + "name": "model_limits_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "api_keys_member_id_idx": { + "name": "api_keys_member_id_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "api_keys_member_id_members_id_fk": { + "name": "api_keys_member_id_members_id_fk", + "tableFrom": "api_keys", + "tableTo": "members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "api_keys_key_hash_unique": { + "name": "api_keys_key_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "key_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.audit_logs": { + "name": "audit_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "audit_logs_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "operator": { + "name": "operator", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "domain": { + "name": "domain", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "summary": { + "name": "summary", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + } + }, + "indexes": { + "audit_logs_created_at_idx": { + "name": "audit_logs_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.engine_status": { + "name": "engine_status", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "default": 1 + }, + "running": { + "name": "running", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "sync_interval_ms": { + "name": "sync_interval_ms", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 300000 + }, + "last_round": { + "name": "last_round", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.members": { + "name": "members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "members_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_issued_at": { + "name": "token_issued_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "members_name_unique": { + "name": "members_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + }, + "members_token_hash_unique": { + "name": "members_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.qpu_history": { + "name": "qpu_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "qpu_history_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "qpu": { + "name": "qpu", + "type": "numeric(18, 6)", + "primaryKey": false, + "notNull": true + }, + "effective_from": { + "name": "effective_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "sessions_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "user_id": { + "name": "user_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "sessions_user_id_idx": { + "name": "sessions_user_id_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "sessions_token_hash_unique": { + "name": "sessions_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.subscriptions": { + "name": "subscriptions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "subscriptions_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "subscription_id": { + "name": "subscription_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "period_start": { + "name": "period_start", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "period_end": { + "name": "period_end", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "quota_granted": { + "name": "quota_granted", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "paid_amount": { + "name": "paid_amount", + "type": "numeric(18, 2)", + "primaryKey": false, + "notNull": false + }, + "paid_at": { + "name": "paid_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "subscriptions_period_idx": { + "name": "subscriptions_period_idx", + "columns": [ + { + "expression": "period_start", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "period_end", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "subscriptions_subscription_id_unique": { + "name": "subscriptions_subscription_id_unique", + "nullsNotDistinct": false, + "columns": [ + "subscription_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.topups": { + "name": "topups", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "topups_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "upstream_id": { + "name": "upstream_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "amount": { + "name": "amount", + "type": "numeric(18, 6)", + "primaryKey": false, + "notNull": true + }, + "money": { + "name": "money", + "type": "numeric(18, 2)", + "primaryKey": false, + "notNull": true + }, + "trade_no": { + "name": "trade_no", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payment_method": { + "name": "payment_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payment_provider": { + "name": "payment_provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "paid_at": { + "name": "paid_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "remark": { + "name": "remark", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_logs": { + "name": "usage_logs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "usage_logs_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "api_key_id": { + "name": "api_key_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "dedupe_key": { + "name": "dedupe_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "billing_source": { + "name": "billing_source", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "subscription_id": { + "name": "subscription_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "type": { + "name": "type", + "type": "smallint", + "primaryKey": false, + "notNull": true, + "default": 2 + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "token_name": { + "name": "token_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "model_name": { + "name": "model_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "quota": { + "name": "quota", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "prompt_tokens": { + "name": "prompt_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "completion_tokens": { + "name": "completion_tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "use_time": { + "name": "use_time", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "is_stream": { + "name": "is_stream", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "channel": { + "name": "channel", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "channel_name": { + "name": "channel_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "token_id": { + "name": "token_id", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "group_name": { + "name": "group_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "ip": { + "name": "ip", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "request_id": { + "name": "request_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "upstream_request_id": { + "name": "upstream_request_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "other": { + "name": "other", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "usage_logs_created_at_idx": { + "name": "usage_logs_created_at_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_logs_api_key_created_idx": { + "name": "usage_logs_api_key_created_idx", + "columns": [ + { + "expression": "api_key_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "usage_logs_subscription_idx": { + "name": "usage_logs_subscription_idx", + "columns": [ + { + "expression": "subscription_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usage_logs_api_key_id_api_keys_id_fk": { + "name": "usage_logs_api_key_id_api_keys_id_fk", + "tableFrom": "usage_logs", + "tableTo": "api_keys", + "columnsFrom": [ + "api_key_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "usage_logs_dedupe_key_unique": { + "name": "usage_logs_dedupe_key_unique", + "nullsNotDistinct": false, + "columns": [ + "dedupe_key" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "users_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_username_unique": { + "name": "users_username_unique", + "nullsNotDistinct": false, + "columns": [ + "username" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json new file mode 100644 index 0000000..7ce791e --- /dev/null +++ b/packages/db/drizzle/meta/_journal.json @@ -0,0 +1,13 @@ +{ + "version": "7", + "dialect": "postgresql", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1791551016051, + "tag": "0000_loose_goblin_queen", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/packages/db/src/repos.ts b/packages/db/src/repos.ts index 492d9c6..2bc37b4 100644 --- a/packages/db/src/repos.ts +++ b/packages/db/src/repos.ts @@ -4,17 +4,19 @@ import { auditLogs, engineStatus, members, - payments, + subscriptions, qpuHistory, sessions, + topups, usageLogs, users, type ApiKeyRow, type AuditLogRow, type EngineStatusRow, type MemberRow, - type PaymentRow, + type SubscriptionRow, type SessionRow, + type TopupRow, type UsageLogRow, type UserRow, } from "./schema.ts"; @@ -384,41 +386,87 @@ export function createRepos(db: Db) { }, }, - payments: { - async listAll(): Promise { - return db.select().from(payments).orderBy(desc(payments.paid_at)); + subscriptions: { + async listAll(): Promise { + return db + .select() + .from(subscriptions) + .orderBy(desc(subscriptions.period_start)); }, - async findById(id: number): Promise { + async findById(id: number): Promise { const rows = await db .select() - .from(payments) - .where(eq(payments.id, id)) + .from(subscriptions) + .where(eq(subscriptions.id, id)) .limit(1); return rows[0] ?? null; }, - async insert(values: { - kind: string; - paid_at: Date; - paid_amount: number; - remark: string; - period_start: Date | null; - period_end: Date | null; - subscription_id: number | null; - quota_granted: number | null; - }): Promise { - const [row] = await db.insert(payments).values(values).returning(); + async findBySubscriptionId( + subscriptionId: number, + ): Promise { + const rows = await db + .select() + .from(subscriptions) + .where(eq(subscriptions.subscription_id, subscriptionId)) + .limit(1); + return rows[0] ?? null; + }, + async insert( + values: typeof subscriptions.$inferInsert, + ): Promise { + const [row] = await db.insert(subscriptions).values(values).returning(); return row!; }, - async update(id: number, patch: Partial) { + async update( + id: number, + patch: Partial, + ) { const [row] = await db - .update(payments) + .update(subscriptions) .set(patch) - .where(eq(payments.id, id)) + .where(eq(subscriptions.id, id)) .returning(); return row!; }, async remove(id: number): Promise { - await db.delete(payments).where(eq(payments.id, id)); + await db.delete(subscriptions).where(eq(subscriptions.id, id)); + }, + }, + + topups: { + async listAll(): Promise { + return db.select().from(topups).orderBy(desc(topups.paid_at)); + }, + async findById(id: number): Promise { + const rows = await db + .select() + .from(topups) + .where(eq(topups.id, id)) + .limit(1); + return rows[0] ?? null; + }, + async findByUpstreamId(upstreamId: number): Promise { + const rows = await db + .select() + .from(topups) + .where(eq(topups.upstream_id, upstreamId)) + .limit(1); + return rows[0] ?? null; + }, + async insert(values: typeof topups.$inferInsert): Promise { + const [row] = await db.insert(topups).values(values).returning(); + return row!; + }, + async update(id: number, patch: Partial) { + const [row] = await db + .update(topups) + .set(patch) + .where(eq(topups.id, id)) + .returning(); + return row!; + }, + async remove(id: number): Promise { + await db.delete(topups).where(eq(topups.id, id)); }, }, diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 31c0940..037ec04 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -117,20 +117,57 @@ export const usageLogs = pgTable( ], ); -export const payments = pgTable("payments", { +/** 订阅权益登记(原 payments.kind=subscription) */ +export const subscriptions = pgTable( + "subscriptions", + { + id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(), + subscription_id: bigint("subscription_id", { mode: "number" }).notNull().unique(), + period_start: timestamp("period_start", { + withTimezone: true, + mode: "date", + }).notNull(), + period_end: timestamp("period_end", { withTimezone: true, mode: "date" }), + quota_granted: bigint("quota_granted", { mode: "number" }).notNull(), + paid_amount: numeric("paid_amount", { + precision: 18, + scale: 2, + mode: "number", + }), + paid_at: timestamp("paid_at", { withTimezone: true, mode: "date" }), + remark: text("remark").notNull().default(""), + created_at: timestamp("created_at", { + withTimezone: true, + mode: "date", + }) + .notNull() + .defaultNow(), + }, + (t) => [index("subscriptions_period_idx").on(t.period_start, t.period_end)], +); + +/** 充值入账事件(原 payments.kind=topup;无 quota_granted 列) */ +export const topups = pgTable("topups", { id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(), - kind: text("kind").notNull(), - paid_at: timestamp("paid_at", { withTimezone: true, mode: "date" }).notNull(), - paid_amount: numeric("paid_amount", { + upstream_id: bigint("upstream_id", { mode: "number" }), + amount: numeric("amount", { precision: 18, scale: 6, mode: "number" }).notNull(), + money: numeric("money", { precision: 18, scale: 2, mode: "number", }).notNull(), + trade_no: text("trade_no"), + payment_method: text("payment_method"), + payment_provider: text("payment_provider"), + status: text("status"), + paid_at: timestamp("paid_at", { withTimezone: true, mode: "date" }).notNull(), remark: text("remark").notNull().default(""), - period_start: timestamp("period_start", { withTimezone: true, mode: "date" }), - period_end: timestamp("period_end", { withTimezone: true, mode: "date" }), - subscription_id: bigint("subscription_id", { mode: "number" }), - quota_granted: bigint("quota_granted", { mode: "number" }), + created_at: timestamp("created_at", { + withTimezone: true, + mode: "date", + }) + .notNull() + .defaultNow(), }); export const qpuHistory = pgTable("qpu_history", { @@ -207,7 +244,8 @@ export const engineStatus = pgTable("engine_status", { export type MemberRow = typeof members.$inferSelect; export type ApiKeyRow = typeof apiKeys.$inferSelect; export type UsageLogRow = typeof usageLogs.$inferSelect; -export type PaymentRow = typeof payments.$inferSelect; +export type SubscriptionRow = typeof subscriptions.$inferSelect; +export type TopupRow = typeof topups.$inferSelect; export type QpuHistoryRow = typeof qpuHistory.$inferSelect; export type UserRow = typeof users.$inferSelect; export type SessionRow = typeof sessions.$inferSelect;