chore: 初始化TikTok短剧后端项目基础架构
创建了完整的NestJS项目结构,包含配置文件、核心模块、工具类、拦截器、过滤器等基础代码,实现了健康检查、用户认证、管理员RBAC、剧集管理、订单支付、媒体管理等核心功能的基础框架,配置了ESLint、TypeScript、Jest等开发工具链。
This commit is contained in:
10
.env
Normal file
10
.env
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
PORT=3030
|
||||||
|
JWT_SECRET=change-me
|
||||||
|
|
||||||
|
# MySQL settings for the production TypeORM layer.
|
||||||
|
# The current scaffold defines entities and API boundaries; repository persistence can be enabled when the database is ready.
|
||||||
|
DB_HOST=sh-cdb-kksiutuw.sql.tencentcdb.com
|
||||||
|
DB_PORT=22246
|
||||||
|
DB_USERNAME=root
|
||||||
|
DB_PASSWORD=zhxiao1124..
|
||||||
|
DB_DATABASE=onion_tiktok
|
||||||
13
.env.example
Normal file
13
.env.example
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
PORT=3000
|
||||||
|
JWT_SECRET=change-me
|
||||||
|
ADMIN_JWT_SECRET=change-me-admin
|
||||||
|
ADMIN_USERNAME=admin
|
||||||
|
ADMIN_PASSWORD=admin123
|
||||||
|
|
||||||
|
# MySQL settings for the production TypeORM layer.
|
||||||
|
# The current scaffold defines entities and API boundaries; repository persistence can be enabled when the database is ready.
|
||||||
|
DB_HOST=127.0.0.1
|
||||||
|
DB_PORT=3306
|
||||||
|
DB_USERNAME=root
|
||||||
|
DB_PASSWORD=
|
||||||
|
DB_DATABASE=cth_tk_backend
|
||||||
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
78
README.md
Normal file
78
README.md
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# TikTok Short Drama Backend
|
||||||
|
|
||||||
|
NestJS backend API for a TikTok Minis short drama app.
|
||||||
|
|
||||||
|
## API Contract
|
||||||
|
|
||||||
|
All endpoints must follow [docs/api-standard.md](./docs/api-standard.md).
|
||||||
|
|
||||||
|
Response shape:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"data": {},
|
||||||
|
"message": "success",
|
||||||
|
"timestamp": "2026-06-30T00:00:00.000Z",
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"cost": "3ms"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Paginated list shape:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"data": {
|
||||||
|
"list": [],
|
||||||
|
"pagination": {
|
||||||
|
"page": 1,
|
||||||
|
"pageSize": 20,
|
||||||
|
"total": 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": "success",
|
||||||
|
"timestamp": "2026-06-30T00:00:00.000Z",
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"cost": "3ms"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implemented Modules
|
||||||
|
|
||||||
|
- `health`: app health check.
|
||||||
|
- `logs`: request log lookup by `requestId` and playback error reporting.
|
||||||
|
- `dramas`: admin drama and episode configuration, app published content listing.
|
||||||
|
- `auth`: TikTok login placeholder that returns a business JWT.
|
||||||
|
- `orders`: paid episode orders, TikTok payment webhook, and playback unlock checks.
|
||||||
|
- `admin`: admin login, RBAC permissions, roles, and admin user management.
|
||||||
|
- `users`: app user listing, detail, and status management for admins.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pnpm install
|
||||||
|
pnpm run start:dev
|
||||||
|
pnpm run build
|
||||||
|
pnpm run test:e2e
|
||||||
|
```
|
||||||
|
|
||||||
|
Swagger is available at:
|
||||||
|
|
||||||
|
```text
|
||||||
|
http://localhost:3000/api/docs
|
||||||
|
```
|
||||||
|
|
||||||
|
Default admin account for local development:
|
||||||
|
|
||||||
|
```text
|
||||||
|
username: admin
|
||||||
|
password: admin123
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- The project currently uses in-memory services so the API contract can be developed and tested before MySQL credentials are available.
|
||||||
|
- TypeORM entity classes are included for the planned MySQL persistence layer.
|
||||||
|
- Replace the TikTok login placeholder with official TikTok Minis login exchange once app credentials are ready.
|
||||||
225
docs/api-standard.md
Normal file
225
docs/api-standard.md
Normal file
@@ -0,0 +1,225 @@
|
|||||||
|
# API Standard
|
||||||
|
|
||||||
|
This document defines the API contract for the TikTok short drama backend.
|
||||||
|
All current and future endpoints must follow this standard.
|
||||||
|
|
||||||
|
## Base Rules
|
||||||
|
|
||||||
|
- API style: RESTful API.
|
||||||
|
- Response content type: `application/json`.
|
||||||
|
- All responses must include `requestId`.
|
||||||
|
- `requestId` must be UUID v4.
|
||||||
|
- The client may pass `X-Request-Id`; if it is a valid UUID v4, the server reuses it.
|
||||||
|
- If `X-Request-Id` is missing or invalid, the server generates a new UUID v4.
|
||||||
|
- `requestId` is the primary lookup key for request logs.
|
||||||
|
- `cost` is the server-side request duration, formatted as a string such as `3ms`.
|
||||||
|
- `timestamp` is the server response time in ISO 8601 format.
|
||||||
|
- `data` must always exist. Use `{}` for empty object responses. Paginated list responses must use `data.list`.
|
||||||
|
|
||||||
|
## Success Response
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"data": {},
|
||||||
|
"message": "success",
|
||||||
|
"timestamp": "2026-06-30T00:00:00.000Z",
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"cost": "3ms"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## List Response
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 0,
|
||||||
|
"data": {
|
||||||
|
"list": [],
|
||||||
|
"pagination": {
|
||||||
|
"page": 1,
|
||||||
|
"pageSize": 20,
|
||||||
|
"total": 100
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"message": "success",
|
||||||
|
"timestamp": "2026-06-30T00:00:00.000Z",
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"cost": "3ms"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Response
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"code": 403,
|
||||||
|
"data": {},
|
||||||
|
"message": "No permission",
|
||||||
|
"timestamp": "2026-06-30T00:00:00.000Z",
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"cost": "3ms"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Code Rules
|
||||||
|
|
||||||
|
- `0`: success.
|
||||||
|
- `400`: invalid request parameters.
|
||||||
|
- `401`: not authenticated.
|
||||||
|
- `403`: no permission.
|
||||||
|
- `404`: resource not found.
|
||||||
|
- `409`: conflict, duplicate operation, or invalid state transition.
|
||||||
|
- `422`: business validation failed.
|
||||||
|
- `429`: too many requests.
|
||||||
|
- `500`: internal server error.
|
||||||
|
|
||||||
|
HTTP status codes should match the response `code` for errors.
|
||||||
|
For successful responses, use the correct HTTP status code such as `200` or `201`, while response `code` remains `0`.
|
||||||
|
|
||||||
|
## Request Log Rules
|
||||||
|
|
||||||
|
Every API request must create one request log record.
|
||||||
|
|
||||||
|
The request log must include:
|
||||||
|
|
||||||
|
- `requestId`
|
||||||
|
- `method`
|
||||||
|
- `path`
|
||||||
|
- `query`
|
||||||
|
- `body`
|
||||||
|
- `statusCode`
|
||||||
|
- `responseCode`
|
||||||
|
- `message`
|
||||||
|
- `costMs`
|
||||||
|
- `userId`
|
||||||
|
- `adminId`
|
||||||
|
- `ip`
|
||||||
|
- `userAgent`
|
||||||
|
- `errorStack`
|
||||||
|
- `createdAt`
|
||||||
|
|
||||||
|
`requestId` must have a unique index in the request log table.
|
||||||
|
|
||||||
|
Admin log endpoints:
|
||||||
|
|
||||||
|
- `GET /api/admin/v1/logs/requests`
|
||||||
|
- `GET /api/admin/v1/logs/requests/:requestId`
|
||||||
|
|
||||||
|
## Playback Error Log Rules
|
||||||
|
|
||||||
|
The app must be able to report video playback errors.
|
||||||
|
|
||||||
|
Endpoint:
|
||||||
|
|
||||||
|
- `POST /api/app/v1/logs/playback-errors`
|
||||||
|
|
||||||
|
Request body:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"requestId": "0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2",
|
||||||
|
"dramaId": 1,
|
||||||
|
"episodeId": 10,
|
||||||
|
"playUrl": "https://cdn.example.com/video.mp4",
|
||||||
|
"playerErrorCode": "MEDIA_DECODE_ERROR",
|
||||||
|
"message": "Video decode failed",
|
||||||
|
"progressSeconds": 128,
|
||||||
|
"networkType": "wifi",
|
||||||
|
"device": {
|
||||||
|
"platform": "ios",
|
||||||
|
"model": "iPhone",
|
||||||
|
"systemVersion": "17.0",
|
||||||
|
"appVersion": "1.0.0"
|
||||||
|
},
|
||||||
|
"occurredAt": "2026-06-30T00:00:00.000Z"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The playback error log must include:
|
||||||
|
|
||||||
|
- `id`
|
||||||
|
- `requestId`
|
||||||
|
- `userId`
|
||||||
|
- `dramaId`
|
||||||
|
- `episodeId`
|
||||||
|
- `playUrl`
|
||||||
|
- `playerErrorCode`
|
||||||
|
- `message`
|
||||||
|
- `progressSeconds`
|
||||||
|
- `networkType`
|
||||||
|
- `device`
|
||||||
|
- `occurredAt`
|
||||||
|
- `createdAt`
|
||||||
|
|
||||||
|
`PlaybackErrorLog.requestId` must have a normal index so playback errors can be linked with request logs.
|
||||||
|
|
||||||
|
Admin playback error endpoints:
|
||||||
|
|
||||||
|
- `GET /api/admin/v1/logs/playback-errors`
|
||||||
|
- `GET /api/admin/v1/logs/playback-errors/:id`
|
||||||
|
|
||||||
|
## Implementation Requirements
|
||||||
|
|
||||||
|
The NestJS implementation must include:
|
||||||
|
|
||||||
|
- `RequestIdMiddleware` to generate or validate `requestId`.
|
||||||
|
- A global response interceptor to wrap successful responses.
|
||||||
|
- A global exception filter to wrap error responses.
|
||||||
|
- A request logging interceptor or middleware to write request logs.
|
||||||
|
- DTO validation with `class-validator`.
|
||||||
|
- Swagger/OpenAPI definitions for all endpoints.
|
||||||
|
- Tests that verify every endpoint includes `code`, `data`, `message`, `timestamp`, `requestId`, and `cost`.
|
||||||
|
|
||||||
|
## Admin Permission Rules
|
||||||
|
|
||||||
|
Admin APIs under `/api/admin/v1/*` must require an admin bearer token, except `/api/admin/v1/auth/login`.
|
||||||
|
|
||||||
|
The backend uses RBAC:
|
||||||
|
|
||||||
|
- `Permission`: atomic capability, such as `drama:create`.
|
||||||
|
- `Role`: a group of permissions.
|
||||||
|
- `AdminUser`: an admin account with one or more roles.
|
||||||
|
- Super admin accounts bypass permission checks.
|
||||||
|
|
||||||
|
Default local super admin:
|
||||||
|
|
||||||
|
```text
|
||||||
|
username: admin
|
||||||
|
password: admin123
|
||||||
|
```
|
||||||
|
|
||||||
|
Core admin endpoints:
|
||||||
|
|
||||||
|
- `POST /api/admin/v1/auth/login`
|
||||||
|
- `GET /api/admin/v1/auth/profile`
|
||||||
|
- `GET /api/admin/v1/permissions`
|
||||||
|
- `POST /api/admin/v1/permissions`
|
||||||
|
- `GET /api/admin/v1/roles`
|
||||||
|
- `POST /api/admin/v1/roles`
|
||||||
|
- `GET /api/admin/v1/admin-users`
|
||||||
|
- `POST /api/admin/v1/admin-users`
|
||||||
|
- `PATCH /api/admin/v1/admin-users/:id/status`
|
||||||
|
- `GET /api/admin/v1/users`
|
||||||
|
- `GET /api/admin/v1/users/:id`
|
||||||
|
- `PATCH /api/admin/v1/users/:id/status`
|
||||||
|
|
||||||
|
## Core Domain Modules
|
||||||
|
|
||||||
|
The backend is organized around these modules:
|
||||||
|
|
||||||
|
- `auth`: TikTok code exchange placeholder, local `user_id` binding, app access token issuing.
|
||||||
|
- `drama`: album list, episode list, free or paid state, review and publish state.
|
||||||
|
- `media`: cover records, video upload jobs, BytePlus `vid`, TikTok album or episode sync placeholders.
|
||||||
|
- `payment`: SKU or unlock price, trade order, TikTok order id, webhook status, unlock records.
|
||||||
|
- `player`: album id, episode id, BytePlus vid, play auth token, and playback permission checks.
|
||||||
|
- `admin`: drama upload, episode edits, review submit, publish or offline, order and playback data.
|
||||||
|
|
||||||
|
Core table targets:
|
||||||
|
|
||||||
|
- `users`: `id`, `tiktok_open_id`, `nickname`, `avatar`, `created_at`.
|
||||||
|
- `drama_albums`: `id`, `tiktok_album_id`, `title`, `description`, `cover_id`, `cover_url`, `status`, `online_version`.
|
||||||
|
- `drama_episodes`: `id`, `album_id`, `tiktok_episode_id`, `seq`, `title`, `byteplus_vid`, `cover_id`, `free_type`, `price`, `review_status`, `publish_status`.
|
||||||
|
- `orders`: `id`, `user_id`, `album_id`, `episode_id`, `tiktok_order_id`, `trade_order_id`, `amount`, `status`.
|
||||||
|
- `unlock_records`: `id`, `user_id`, `episode_id`, `source`, `created_at`.
|
||||||
|
- `media_upload_jobs`: `id`, `job_id`, `byteplus_vid`, `status`, `raw_response`.
|
||||||
17
eslint.config.mjs
Normal file
17
eslint.config.mjs
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import eslint from '@eslint/js';
|
||||||
|
import tseslint from 'typescript-eslint';
|
||||||
|
|
||||||
|
export default tseslint.config(
|
||||||
|
eslint.configs.recommended,
|
||||||
|
...tseslint.configs.recommended,
|
||||||
|
{
|
||||||
|
files: ['src/**/*.ts', 'test/**/*.ts'],
|
||||||
|
rules: {
|
||||||
|
'@typescript-eslint/no-explicit-any': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||||
|
'@typescript-eslint/no-unsafe-return': 'off'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
5
nest-cli.json
Normal file
5
nest-cli.json
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://json.schemastore.org/nest-cli",
|
||||||
|
"collection": "@nestjs/schematics",
|
||||||
|
"sourceRoot": "src"
|
||||||
|
}
|
||||||
58
package.json
Normal file
58
package.json
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
{
|
||||||
|
"name": "cth-tk-backend",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"scripts": {
|
||||||
|
"build": "nest build",
|
||||||
|
"start": "nest start",
|
||||||
|
"start:dev": "nest start --watch",
|
||||||
|
"test": "jest",
|
||||||
|
"test:e2e": "jest --config ./test/jest-e2e.json",
|
||||||
|
"lint": "eslint \"{src,test}/**/*.ts\""
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@nestjs/common": "^11.0.0",
|
||||||
|
"@nestjs/config": "^4.0.0",
|
||||||
|
"@nestjs/core": "^11.0.0",
|
||||||
|
"@nestjs/jwt": "^11.0.0",
|
||||||
|
"@nestjs/mapped-types": "^2.1.0",
|
||||||
|
"@nestjs/passport": "^11.0.0",
|
||||||
|
"@nestjs/platform-express": "^11.0.0",
|
||||||
|
"@nestjs/swagger": "^11.0.0",
|
||||||
|
"@nestjs/typeorm": "^11.0.0",
|
||||||
|
"bcrypt": "^6.0.0",
|
||||||
|
"class-transformer": "^0.5.1",
|
||||||
|
"class-validator": "^0.14.0",
|
||||||
|
"mysql2": "^3.0.0",
|
||||||
|
"passport": "^0.7.0",
|
||||||
|
"passport-jwt": "^4.0.1",
|
||||||
|
"reflect-metadata": "^0.2.2",
|
||||||
|
"rxjs": "^7.8.0",
|
||||||
|
"typeorm": "^0.3.0",
|
||||||
|
"uuid": "^11.0.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/eslintrc": "^3.0.0",
|
||||||
|
"@eslint/js": "^9.0.0",
|
||||||
|
"@nestjs/cli": "^11.0.0",
|
||||||
|
"@nestjs/schematics": "^11.0.0",
|
||||||
|
"@nestjs/testing": "^11.0.0",
|
||||||
|
"@types/bcrypt": "^5.0.2",
|
||||||
|
"@types/express": "^5.0.0",
|
||||||
|
"@types/jest": "^30.0.0",
|
||||||
|
"@types/node": "^24.0.0",
|
||||||
|
"@types/passport-jwt": "^4.0.1",
|
||||||
|
"@types/supertest": "^6.0.0",
|
||||||
|
"@types/uuid": "^10.0.0",
|
||||||
|
"eslint": "^9.0.0",
|
||||||
|
"jest": "^30.0.0",
|
||||||
|
"source-map-support": "^0.5.21",
|
||||||
|
"supertest": "^7.0.0",
|
||||||
|
"ts-jest": "^29.0.0",
|
||||||
|
"ts-loader": "^9.5.0",
|
||||||
|
"ts-node": "^10.9.0",
|
||||||
|
"tsconfig-paths": "^4.2.0",
|
||||||
|
"typescript": "^5.8.0",
|
||||||
|
"typescript-eslint": "^8.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
6929
pnpm-lock.yaml
generated
Normal file
6929
pnpm-lock.yaml
generated
Normal file
File diff suppressed because it is too large
Load Diff
4
pnpm-workspace.yaml
Normal file
4
pnpm-workspace.yaml
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
allowBuilds:
|
||||||
|
'@scarf/scarf': true
|
||||||
|
bcrypt: true
|
||||||
|
unrs-resolver: true
|
||||||
27
src/app.module.ts
Normal file
27
src/app.module.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { ConfigModule } from '@nestjs/config';
|
||||||
|
import { AdminModule } from './modules/admin/admin.module';
|
||||||
|
import { AuthModule } from './modules/auth/auth.module';
|
||||||
|
import { DramasModule } from './modules/dramas/dramas.module';
|
||||||
|
import { HealthModule } from './modules/health/health.module';
|
||||||
|
import { LogsModule } from './modules/logs/logs.module';
|
||||||
|
import { MediaModule } from './modules/media/media.module';
|
||||||
|
import { OrdersModule } from './modules/orders/orders.module';
|
||||||
|
import { PlayerModule } from './modules/player/player.module';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ConfigModule.forRoot({
|
||||||
|
isGlobal: true,
|
||||||
|
}),
|
||||||
|
AdminModule,
|
||||||
|
HealthModule,
|
||||||
|
LogsModule,
|
||||||
|
DramasModule,
|
||||||
|
MediaModule,
|
||||||
|
AuthModule,
|
||||||
|
OrdersModule,
|
||||||
|
PlayerModule,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AppModule {}
|
||||||
42
src/bootstrap.ts
Normal file
42
src/bootstrap.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import { INestApplication, ValidationPipe } from "@nestjs/common";
|
||||||
|
import { Reflector } from "@nestjs/core";
|
||||||
|
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
|
||||||
|
import { HttpExceptionFilter } from "./common/filters/http-exception.filter";
|
||||||
|
import { RequestLoggingInterceptor } from "./common/interceptors/request-logging.interceptor";
|
||||||
|
import { ResponseInterceptor } from "./common/interceptors/response.interceptor";
|
||||||
|
import { RequestIdMiddleware } from "./common/middleware/request-id.middleware";
|
||||||
|
import { LogsService } from "./modules/logs/logs.service";
|
||||||
|
|
||||||
|
export function bootstrapApp(app: INestApplication) {
|
||||||
|
app.enableCors({
|
||||||
|
origin: process.env.CORS_ORIGIN?.split(',') ?? [
|
||||||
|
'http://localhost:5173',
|
||||||
|
'http://127.0.0.1:5173',
|
||||||
|
],
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
app.use(RequestIdMiddleware);
|
||||||
|
app.useGlobalPipes(
|
||||||
|
new ValidationPipe({
|
||||||
|
whitelist: true,
|
||||||
|
transform: true,
|
||||||
|
forbidNonWhitelisted: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const logsService = app.get(LogsService);
|
||||||
|
app.useGlobalFilters(new HttpExceptionFilter(logsService));
|
||||||
|
app.useGlobalInterceptors(
|
||||||
|
new RequestLoggingInterceptor(logsService, app.get(Reflector)),
|
||||||
|
new ResponseInterceptor(),
|
||||||
|
);
|
||||||
|
|
||||||
|
const config = new DocumentBuilder()
|
||||||
|
.setTitle("TikTok Short Drama Backend")
|
||||||
|
.setDescription("RESTful API for TikTok short drama backend services.")
|
||||||
|
.setVersion("1.0")
|
||||||
|
.addBearerAuth()
|
||||||
|
.build();
|
||||||
|
const document = SwaggerModule.createDocument(app, config);
|
||||||
|
SwaggerModule.setup("/api/docs", app, document);
|
||||||
|
}
|
||||||
1
src/common/constants/response-message.constants.ts
Normal file
1
src/common/constants/response-message.constants.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export const SUCCESS_MESSAGE = 'success';
|
||||||
6
src/common/decorators/api-message.decorator.ts
Normal file
6
src/common/decorators/api-message.decorator.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const API_MESSAGE_METADATA = 'api:message';
|
||||||
|
|
||||||
|
export const ApiMessage = (message: string) =>
|
||||||
|
SetMetadata(API_MESSAGE_METADATA, message);
|
||||||
10
src/common/dto/paginated-response.dto.ts
Normal file
10
src/common/dto/paginated-response.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
export interface PaginationMeta {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
list: T[];
|
||||||
|
pagination: PaginationMeta;
|
||||||
|
}
|
||||||
79
src/common/filters/http-exception.filter.ts
Normal file
79
src/common/filters/http-exception.filter.ts
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
import {
|
||||||
|
ArgumentsHost,
|
||||||
|
Catch,
|
||||||
|
ExceptionFilter,
|
||||||
|
HttpException,
|
||||||
|
HttpStatus,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { LogsService } from '../../modules/logs/logs.service';
|
||||||
|
import { getRequestCost } from '../utils/request-context.util';
|
||||||
|
|
||||||
|
@Catch()
|
||||||
|
export class HttpExceptionFilter implements ExceptionFilter {
|
||||||
|
constructor(private readonly logsService: LogsService) {}
|
||||||
|
|
||||||
|
catch(exception: unknown, host: ArgumentsHost) {
|
||||||
|
const ctx = host.switchToHttp();
|
||||||
|
const request = ctx.getRequest<
|
||||||
|
Request & { requestId?: string; adminId?: number; user?: { id: number } }
|
||||||
|
>();
|
||||||
|
const response = ctx.getResponse<Response>();
|
||||||
|
const statusCode =
|
||||||
|
exception instanceof HttpException
|
||||||
|
? exception.getStatus()
|
||||||
|
: HttpStatus.INTERNAL_SERVER_ERROR;
|
||||||
|
const message = this.getMessage(exception, statusCode);
|
||||||
|
const requestId = request.requestId ?? '';
|
||||||
|
const costMs = getRequestCost(request);
|
||||||
|
|
||||||
|
this.logsService.recordRequest({
|
||||||
|
requestId,
|
||||||
|
method: request.method,
|
||||||
|
path: request.originalUrl ?? request.url,
|
||||||
|
query: request.query,
|
||||||
|
body: request.body,
|
||||||
|
statusCode,
|
||||||
|
responseCode: statusCode,
|
||||||
|
message,
|
||||||
|
costMs,
|
||||||
|
userId: request.user?.id,
|
||||||
|
adminId: request.adminId,
|
||||||
|
ip: request.ip,
|
||||||
|
userAgent: request.get('user-agent'),
|
||||||
|
errorStack: exception instanceof Error ? exception.stack : undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
response.status(statusCode).json({
|
||||||
|
code: statusCode,
|
||||||
|
data: {},
|
||||||
|
message,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
requestId,
|
||||||
|
cost: `${costMs}ms`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getMessage(exception: unknown, statusCode: number): string {
|
||||||
|
if (exception instanceof HttpException) {
|
||||||
|
const response = exception.getResponse();
|
||||||
|
if (typeof response === 'string') {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
response &&
|
||||||
|
typeof response === 'object' &&
|
||||||
|
'message' in response
|
||||||
|
) {
|
||||||
|
const message = (response as { message: string | string[] }).message;
|
||||||
|
return Array.isArray(message) ? message.join('; ') : message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (exception instanceof Error && statusCode === HttpStatus.INTERNAL_SERVER_ERROR) {
|
||||||
|
return exception.message || 'Internal server error';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Internal server error';
|
||||||
|
}
|
||||||
|
}
|
||||||
55
src/common/interceptors/request-logging.interceptor.ts
Normal file
55
src/common/interceptors/request-logging.interceptor.ts
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import {
|
||||||
|
CallHandler,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { Request, Response } from 'express';
|
||||||
|
import { Observable, tap } from 'rxjs';
|
||||||
|
import {
|
||||||
|
API_MESSAGE_METADATA,
|
||||||
|
} from '../decorators/api-message.decorator';
|
||||||
|
import { SUCCESS_MESSAGE } from '../constants/response-message.constants';
|
||||||
|
import { getRequestCost } from '../utils/request-context.util';
|
||||||
|
import { LogsService } from '../../modules/logs/logs.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RequestLoggingInterceptor implements NestInterceptor {
|
||||||
|
constructor(
|
||||||
|
private readonly logsService: LogsService,
|
||||||
|
private readonly reflector: Reflector,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
|
const http = context.switchToHttp();
|
||||||
|
const request = http.getRequest<
|
||||||
|
Request & { requestId?: string; adminId?: number; user?: { id: number } }
|
||||||
|
>();
|
||||||
|
const response = http.getResponse<Response>();
|
||||||
|
const message =
|
||||||
|
this.reflector.get<string>(API_MESSAGE_METADATA, context.getHandler()) ??
|
||||||
|
SUCCESS_MESSAGE;
|
||||||
|
|
||||||
|
return next.handle().pipe(
|
||||||
|
tap(() => {
|
||||||
|
this.logsService.recordRequest({
|
||||||
|
requestId: request.requestId ?? '',
|
||||||
|
method: request.method,
|
||||||
|
path: request.originalUrl ?? request.url,
|
||||||
|
query: request.query,
|
||||||
|
body: request.body,
|
||||||
|
statusCode: response.statusCode,
|
||||||
|
responseCode: 0,
|
||||||
|
message,
|
||||||
|
costMs: getRequestCost(request),
|
||||||
|
userId: request.user?.id,
|
||||||
|
adminId: request.adminId,
|
||||||
|
ip: request.ip,
|
||||||
|
userAgent: request.get('user-agent'),
|
||||||
|
errorStack: undefined,
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
39
src/common/interceptors/response.interceptor.ts
Normal file
39
src/common/interceptors/response.interceptor.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import {
|
||||||
|
CallHandler,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
NestInterceptor,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { map, Observable } from 'rxjs';
|
||||||
|
import { SUCCESS_MESSAGE } from '../constants/response-message.constants';
|
||||||
|
import {
|
||||||
|
API_MESSAGE_METADATA,
|
||||||
|
} from '../decorators/api-message.decorator';
|
||||||
|
import { getRequestCost } from '../utils/request-context.util';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ResponseInterceptor implements NestInterceptor {
|
||||||
|
constructor(private readonly reflector = new Reflector()) {}
|
||||||
|
|
||||||
|
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||||
|
const request = context
|
||||||
|
.switchToHttp()
|
||||||
|
.getRequest<Request & { requestId?: string }>();
|
||||||
|
const message =
|
||||||
|
this.reflector.get<string>(API_MESSAGE_METADATA, context.getHandler()) ??
|
||||||
|
SUCCESS_MESSAGE;
|
||||||
|
|
||||||
|
return next.handle().pipe(
|
||||||
|
map((data) => ({
|
||||||
|
code: 0,
|
||||||
|
data: data ?? {},
|
||||||
|
message,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
requestId: request.requestId,
|
||||||
|
cost: `${getRequestCost(request)}ms`,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
21
src/common/middleware/request-id.middleware.ts
Normal file
21
src/common/middleware/request-id.middleware.ts
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
import { NextFunction, Request, Response } from 'express';
|
||||||
|
import { validate as validateUuid, version as uuidVersion, v4 as uuidv4 } from 'uuid';
|
||||||
|
|
||||||
|
export function RequestIdMiddleware(
|
||||||
|
request: Request & { requestId?: string; startTime?: bigint },
|
||||||
|
response: Response,
|
||||||
|
next: NextFunction,
|
||||||
|
) {
|
||||||
|
const incomingRequestId = request.get('x-request-id');
|
||||||
|
const requestId =
|
||||||
|
incomingRequestId &&
|
||||||
|
validateUuid(incomingRequestId) &&
|
||||||
|
uuidVersion(incomingRequestId) === 4
|
||||||
|
? incomingRequestId
|
||||||
|
: uuidv4();
|
||||||
|
|
||||||
|
request.requestId = requestId;
|
||||||
|
request.startTime = process.hrtime.bigint();
|
||||||
|
response.setHeader('X-Request-Id', requestId);
|
||||||
|
next();
|
||||||
|
}
|
||||||
10
src/common/utils/request-context.util.ts
Normal file
10
src/common/utils/request-context.util.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { Request } from 'express';
|
||||||
|
|
||||||
|
export function getRequestCost(request: Request & { startTime?: bigint }) {
|
||||||
|
if (!request.startTime) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const diff = process.hrtime.bigint() - request.startTime;
|
||||||
|
return Number(diff / BigInt(1_000_000));
|
||||||
|
}
|
||||||
11
src/main.ts
Normal file
11
src/main.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { bootstrapApp } from './bootstrap';
|
||||||
|
|
||||||
|
async function bootstrap() {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
|
}
|
||||||
|
|
||||||
|
void bootstrap();
|
||||||
146
src/modules/admin/admin.controller.ts
Normal file
146
src/modules/admin/admin.controller.ts
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { CurrentAdmin } from './decorators/current-admin.decorator';
|
||||||
|
import { RequirePermissions } from './decorators/require-permissions.decorator';
|
||||||
|
import { AdminLoginDto } from './dto/admin-login.dto';
|
||||||
|
import { ChangeAdminPasswordDto } from './dto/change-admin-password.dto';
|
||||||
|
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
|
||||||
|
import { CreatePermissionDto } from './dto/create-permission.dto';
|
||||||
|
import { CreateRoleDto } from './dto/create-role.dto';
|
||||||
|
import { UpdateAdminProfileDto } from './dto/update-admin-profile.dto';
|
||||||
|
import { UpdateAdminRolesDto } from './dto/update-admin-roles.dto';
|
||||||
|
import { UpdateAdminStatusDto } from './dto/update-admin-status.dto';
|
||||||
|
import { UpdateRolePermissionsDto } from './dto/update-role-permissions.dto';
|
||||||
|
import { AdminJwtAuthGuard } from './guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from './guards/permissions.guard';
|
||||||
|
import { AdminUserRecord } from './interfaces/admin-records.interface';
|
||||||
|
import { AdminService } from './admin.service';
|
||||||
|
|
||||||
|
@ApiTags('Admin')
|
||||||
|
@Controller('/api/admin/v1')
|
||||||
|
export class AdminController {
|
||||||
|
constructor(private readonly adminService: AdminService) {}
|
||||||
|
|
||||||
|
@Post('/auth/login')
|
||||||
|
login(@Body() dto: AdminLoginDto) {
|
||||||
|
return this.adminService.login(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/auth/profile')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard)
|
||||||
|
getProfile(@CurrentAdmin() admin: AdminUserRecord) {
|
||||||
|
return this.adminService.toAdminView(admin);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/auth/profile')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard)
|
||||||
|
updateProfile(
|
||||||
|
@CurrentAdmin() admin: AdminUserRecord,
|
||||||
|
@Body() dto: UpdateAdminProfileDto,
|
||||||
|
) {
|
||||||
|
return this.adminService.updateProfile(admin.id, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/auth/password')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard)
|
||||||
|
changePassword(
|
||||||
|
@CurrentAdmin() admin: AdminUserRecord,
|
||||||
|
@Body() dto: ChangeAdminPasswordDto,
|
||||||
|
) {
|
||||||
|
return this.adminService.changePassword(
|
||||||
|
admin.id,
|
||||||
|
dto.oldPassword,
|
||||||
|
dto.newPassword,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/permissions')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('permission:read')
|
||||||
|
listPermissions(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||||
|
return this.adminService.listPermissions({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/permissions')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('permission:create')
|
||||||
|
createPermission(@Body() dto: CreatePermissionDto) {
|
||||||
|
return this.adminService.createPermission(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/roles')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('role:read')
|
||||||
|
listRoles(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||||
|
return this.adminService.listRoles({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/roles')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('role:create')
|
||||||
|
createRole(@Body() dto: CreateRoleDto) {
|
||||||
|
return this.adminService.createRole(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/roles/:id/permissions')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('role:update')
|
||||||
|
updateRolePermissions(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: UpdateRolePermissionsDto,
|
||||||
|
) {
|
||||||
|
return this.adminService.updateRolePermissions(
|
||||||
|
Number(id),
|
||||||
|
dto.permissionIds,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/admin-users')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('admin-user:read')
|
||||||
|
listAdminUsers(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||||
|
return this.adminService.listAdminUsers({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/admin-users')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('admin-user:create')
|
||||||
|
createAdminUser(@Body() dto: CreateAdminUserDto) {
|
||||||
|
return this.adminService.createAdminUser(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/admin-users/:id/roles')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('admin-user:update')
|
||||||
|
updateAdminRoles(@Param('id') id: string, @Body() dto: UpdateAdminRolesDto) {
|
||||||
|
return this.adminService.updateAdminRoles(Number(id), dto.roleIds);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/admin-users/:id/status')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('admin-user:update')
|
||||||
|
updateAdminStatus(@Param('id') id: string, @Body() dto: UpdateAdminStatusDto) {
|
||||||
|
return this.adminService.updateAdminStatus(Number(id), dto.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/modules/admin/admin.module.ts
Normal file
20
src/modules/admin/admin.module.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Global, Module } from '@nestjs/common';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { AdminController } from './admin.controller';
|
||||||
|
import { AdminService } from './admin.service';
|
||||||
|
import { AdminJwtAuthGuard } from './guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from './guards/permissions.guard';
|
||||||
|
|
||||||
|
@Global()
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
JwtModule.register({
|
||||||
|
secret: process.env.ADMIN_JWT_SECRET ?? process.env.JWT_SECRET ?? 'development-secret',
|
||||||
|
signOptions: { expiresIn: '12h' },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AdminController],
|
||||||
|
providers: [AdminService, AdminJwtAuthGuard, PermissionsGuard],
|
||||||
|
exports: [JwtModule, AdminService, AdminJwtAuthGuard, PermissionsGuard],
|
||||||
|
})
|
||||||
|
export class AdminModule {}
|
||||||
318
src/modules/admin/admin.service.ts
Normal file
318
src/modules/admin/admin.service.ts
Normal file
@@ -0,0 +1,318 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
UnauthorizedException,
|
||||||
|
UnprocessableEntityException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import * as bcrypt from 'bcrypt';
|
||||||
|
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||||
|
import { AdminLoginDto } from './dto/admin-login.dto';
|
||||||
|
import { CreateAdminUserDto } from './dto/create-admin-user.dto';
|
||||||
|
import { CreatePermissionDto } from './dto/create-permission.dto';
|
||||||
|
import { CreateRoleDto } from './dto/create-role.dto';
|
||||||
|
import { UpdateAdminProfileDto } from './dto/update-admin-profile.dto';
|
||||||
|
import {
|
||||||
|
AdminUserRecord,
|
||||||
|
AdminUserView,
|
||||||
|
PermissionRecord,
|
||||||
|
RoleRecord,
|
||||||
|
} from './interfaces/admin-records.interface';
|
||||||
|
|
||||||
|
interface PaginationInput {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminService {
|
||||||
|
private permissionSequence = 1;
|
||||||
|
private roleSequence = 1;
|
||||||
|
private adminSequence = 1;
|
||||||
|
private readonly permissions: PermissionRecord[] = [];
|
||||||
|
private readonly roles: RoleRecord[] = [];
|
||||||
|
private readonly admins: AdminUserRecord[] = [];
|
||||||
|
|
||||||
|
constructor(private readonly jwtService: JwtService) {
|
||||||
|
this.seed();
|
||||||
|
}
|
||||||
|
|
||||||
|
async login(dto: AdminLoginDto) {
|
||||||
|
const admin = this.admins.find((item) => item.username === dto.username);
|
||||||
|
if (
|
||||||
|
!admin ||
|
||||||
|
admin.status !== 'active' ||
|
||||||
|
!bcrypt.compareSync(dto.password, admin.passwordHash)
|
||||||
|
) {
|
||||||
|
throw new UnauthorizedException('Invalid username or password');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessToken: await this.jwtService.signAsync({
|
||||||
|
sub: admin.id,
|
||||||
|
username: admin.username,
|
||||||
|
type: 'admin',
|
||||||
|
}),
|
||||||
|
admin: this.toAdminView(admin),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
createPermission(dto: CreatePermissionDto): PermissionRecord {
|
||||||
|
if (this.permissions.some((item) => item.code === dto.code)) {
|
||||||
|
throw new ConflictException('Permission code already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const permission: PermissionRecord = {
|
||||||
|
id: this.permissionSequence++,
|
||||||
|
code: dto.code,
|
||||||
|
name: dto.name,
|
||||||
|
description: dto.description,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.permissions.push(permission);
|
||||||
|
return permission;
|
||||||
|
}
|
||||||
|
|
||||||
|
listPermissions(
|
||||||
|
pagination: PaginationInput,
|
||||||
|
): PaginatedResponse<PermissionRecord> {
|
||||||
|
return this.paginate([...this.permissions], pagination);
|
||||||
|
}
|
||||||
|
|
||||||
|
createRole(dto: CreateRoleDto): RoleRecord {
|
||||||
|
if (this.roles.some((item) => item.code === dto.code)) {
|
||||||
|
throw new ConflictException('Role code already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const permissionIds = dto.permissionIds ?? [];
|
||||||
|
const role: RoleRecord = {
|
||||||
|
id: this.roleSequence++,
|
||||||
|
code: dto.code,
|
||||||
|
name: dto.name,
|
||||||
|
description: dto.description,
|
||||||
|
permissionIds,
|
||||||
|
permissions: this.permissions.filter((permission) =>
|
||||||
|
permissionIds.includes(permission.id),
|
||||||
|
),
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.roles.push(role);
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
listRoles(pagination: PaginationInput): PaginatedResponse<RoleRecord> {
|
||||||
|
return this.paginate([...this.roles], pagination);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateRolePermissions(id: number, permissionIds: number[]): RoleRecord {
|
||||||
|
const role = this.roles.find((item) => item.id === id);
|
||||||
|
if (!role) {
|
||||||
|
throw new NotFoundException('Role not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const uniquePermissionIds = [...new Set(permissionIds)];
|
||||||
|
role.permissionIds = uniquePermissionIds;
|
||||||
|
role.permissions = this.permissions.filter((permission) =>
|
||||||
|
uniquePermissionIds.includes(permission.id),
|
||||||
|
);
|
||||||
|
role.updatedAt = new Date().toISOString();
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
|
||||||
|
createAdminUser(dto: CreateAdminUserDto): AdminUserView {
|
||||||
|
if (this.admins.some((item) => item.username === dto.username)) {
|
||||||
|
throw new ConflictException('Admin username already exists');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const admin: AdminUserRecord = {
|
||||||
|
id: this.adminSequence++,
|
||||||
|
username: dto.username,
|
||||||
|
passwordHash: bcrypt.hashSync(dto.password, 10),
|
||||||
|
nickname: dto.nickname,
|
||||||
|
email: dto.email,
|
||||||
|
status: 'active',
|
||||||
|
isSuperAdmin: false,
|
||||||
|
roleIds: dto.roleIds ?? [],
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.admins.push(admin);
|
||||||
|
return this.toAdminView(admin);
|
||||||
|
}
|
||||||
|
|
||||||
|
listAdminUsers(
|
||||||
|
pagination: PaginationInput,
|
||||||
|
): PaginatedResponse<AdminUserView> {
|
||||||
|
return this.paginate(
|
||||||
|
this.admins.map((admin) => this.toAdminView(admin)),
|
||||||
|
pagination,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateAdminStatus(
|
||||||
|
id: number,
|
||||||
|
status: 'active' | 'disabled',
|
||||||
|
): AdminUserView {
|
||||||
|
const admin = this.findAdminById(id);
|
||||||
|
if (!admin) {
|
||||||
|
throw new NotFoundException('Admin user not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
admin.status = status;
|
||||||
|
admin.updatedAt = new Date().toISOString();
|
||||||
|
return this.toAdminView(admin);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateAdminRoles(id: number, roleIds: number[]): AdminUserView {
|
||||||
|
const admin = this.findAdminById(id);
|
||||||
|
if (!admin) {
|
||||||
|
throw new NotFoundException('Admin user not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
admin.roleIds = [...new Set(roleIds)];
|
||||||
|
admin.updatedAt = new Date().toISOString();
|
||||||
|
return this.toAdminView(admin);
|
||||||
|
}
|
||||||
|
|
||||||
|
updateProfile(
|
||||||
|
adminId: number,
|
||||||
|
dto: UpdateAdminProfileDto,
|
||||||
|
): AdminUserView {
|
||||||
|
const admin = this.findAdminById(adminId);
|
||||||
|
if (!admin) {
|
||||||
|
throw new NotFoundException('Admin user not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
admin.nickname = dto.nickname;
|
||||||
|
admin.email = dto.email;
|
||||||
|
admin.updatedAt = new Date().toISOString();
|
||||||
|
return this.toAdminView(admin);
|
||||||
|
}
|
||||||
|
|
||||||
|
changePassword(
|
||||||
|
adminId: number,
|
||||||
|
oldPassword: string,
|
||||||
|
newPassword: string,
|
||||||
|
): Record<string, never> {
|
||||||
|
const admin = this.findAdminById(adminId);
|
||||||
|
if (!admin) {
|
||||||
|
throw new NotFoundException('Admin user not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!bcrypt.compareSync(oldPassword, admin.passwordHash)) {
|
||||||
|
throw new UnprocessableEntityException('Old password is incorrect');
|
||||||
|
}
|
||||||
|
|
||||||
|
admin.passwordHash = bcrypt.hashSync(newPassword, 10);
|
||||||
|
admin.updatedAt = new Date().toISOString();
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
findAdminById(id: number) {
|
||||||
|
return this.admins.find((admin) => admin.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
getPermissionCodesForAdmin(adminId: number) {
|
||||||
|
const admin = this.findAdminById(adminId);
|
||||||
|
if (!admin) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (admin.isSuperAdmin) {
|
||||||
|
return ['*'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.roles
|
||||||
|
.filter((role) => admin.roleIds.includes(role.id))
|
||||||
|
.flatMap((role) => role.permissions.map((permission) => permission.code));
|
||||||
|
}
|
||||||
|
|
||||||
|
toAdminView(admin: AdminUserRecord): AdminUserView {
|
||||||
|
const roles = this.roles.filter((role) => admin.roleIds.includes(role.id));
|
||||||
|
const permissions: PermissionRecord[] | ['*'] = admin.isSuperAdmin
|
||||||
|
? ['*']
|
||||||
|
: roles.flatMap((role) => role.permissions);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: admin.id,
|
||||||
|
username: admin.username,
|
||||||
|
nickname: admin.nickname,
|
||||||
|
email: admin.email,
|
||||||
|
status: admin.status,
|
||||||
|
isSuperAdmin: admin.isSuperAdmin,
|
||||||
|
roles,
|
||||||
|
permissions,
|
||||||
|
createdAt: admin.createdAt,
|
||||||
|
updatedAt: admin.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private seed() {
|
||||||
|
const codes = [
|
||||||
|
['permission:read', '查看权限'],
|
||||||
|
['permission:create', '创建权限'],
|
||||||
|
['role:read', '查看角色'],
|
||||||
|
['role:create', '创建角色'],
|
||||||
|
['role:update', '更新角色'],
|
||||||
|
['admin-user:read', '查看人员'],
|
||||||
|
['admin-user:create', '创建人员'],
|
||||||
|
['admin-user:update', '更新人员'],
|
||||||
|
['user:read', '查看用户'],
|
||||||
|
['user:update', '更新用户'],
|
||||||
|
['drama:read', '查看短剧'],
|
||||||
|
['drama:create', '创建短剧'],
|
||||||
|
['drama:update', '更新短剧'],
|
||||||
|
['episode:create', '创建剧集'],
|
||||||
|
['episode:update', '更新剧集'],
|
||||||
|
['media:read', '查看媒体'],
|
||||||
|
['media:create', '创建媒体'],
|
||||||
|
['payment:read', '查看支付记录'],
|
||||||
|
['log:read', '查看日志'],
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const [code, name] of codes) {
|
||||||
|
this.createPermission({ code, name });
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
this.admins.push({
|
||||||
|
id: this.adminSequence++,
|
||||||
|
username: process.env.ADMIN_USERNAME ?? 'admin',
|
||||||
|
passwordHash: bcrypt.hashSync(process.env.ADMIN_PASSWORD ?? 'admin123', 10),
|
||||||
|
nickname: 'Super Admin',
|
||||||
|
email: process.env.ADMIN_EMAIL ?? 'admin@example.com',
|
||||||
|
status: 'active',
|
||||||
|
isSuperAdmin: true,
|
||||||
|
roleIds: [],
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private paginate<T>(
|
||||||
|
records: T[],
|
||||||
|
input: PaginationInput,
|
||||||
|
): PaginatedResponse<T> {
|
||||||
|
const page = Math.max(input.page, 1);
|
||||||
|
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: records.slice(start, start + pageSize),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: records.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/modules/admin/decorators/current-admin.decorator.ts
Normal file
12
src/modules/admin/decorators/current-admin.decorator.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||||
|
|
||||||
|
export const CurrentAdmin = createParamDecorator(
|
||||||
|
(_data: unknown, ctx: ExecutionContext): AdminUserRecord | undefined => {
|
||||||
|
const request = ctx
|
||||||
|
.switchToHttp()
|
||||||
|
.getRequest<Request & { adminUser?: AdminUserRecord }>();
|
||||||
|
return request.adminUser;
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
import { SetMetadata } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const REQUIRED_PERMISSIONS_METADATA = 'admin:required-permissions';
|
||||||
|
|
||||||
|
export const RequirePermissions = (...permissions: string[]) =>
|
||||||
|
SetMetadata(REQUIRED_PERMISSIONS_METADATA, permissions);
|
||||||
13
src/modules/admin/dto/admin-login.dto.ts
Normal file
13
src/modules/admin/dto/admin-login.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class AdminLoginDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
username: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(6)
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
13
src/modules/admin/dto/change-admin-password.dto.ts
Normal file
13
src/modules/admin/dto/change-admin-password.dto.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsString, MinLength } from 'class-validator';
|
||||||
|
|
||||||
|
export class ChangeAdminPasswordDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
oldPassword: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(6)
|
||||||
|
newPassword: string;
|
||||||
|
}
|
||||||
38
src/modules/admin/dto/create-admin-user.dto.ts
Normal file
38
src/modules/admin/dto/create-admin-user.dto.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsEmail,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Min,
|
||||||
|
MinLength,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateAdminUserDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
username: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
@MinLength(6)
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
nickname?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsEmail()
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ type: [Number] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsInt({ each: true })
|
||||||
|
@Min(1, { each: true })
|
||||||
|
roleIds?: number[];
|
||||||
|
}
|
||||||
17
src/modules/admin/dto/create-permission.dto.ts
Normal file
17
src/modules/admin/dto/create-permission.dto.ts
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreatePermissionDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
30
src/modules/admin/dto/create-role.dto.ts
Normal file
30
src/modules/admin/dto/create-role.dto.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
Min,
|
||||||
|
} from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateRoleDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ type: [Number] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsInt({ each: true })
|
||||||
|
@Min(1, { each: true })
|
||||||
|
permissionIds?: number[];
|
||||||
|
}
|
||||||
14
src/modules/admin/dto/update-admin-profile.dto.ts
Normal file
14
src/modules/admin/dto/update-admin-profile.dto.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsEmail, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateAdminProfileDto {
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
nickname?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsEmail()
|
||||||
|
email?: string;
|
||||||
|
}
|
||||||
10
src/modules/admin/dto/update-admin-roles.dto.ts
Normal file
10
src/modules/admin/dto/update-admin-roles.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsArray, IsInt, Min } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateAdminRolesDto {
|
||||||
|
@ApiProperty({ type: [Number] })
|
||||||
|
@IsArray()
|
||||||
|
@IsInt({ each: true })
|
||||||
|
@Min(1, { each: true })
|
||||||
|
roleIds: number[];
|
||||||
|
}
|
||||||
8
src/modules/admin/dto/update-admin-status.dto.ts
Normal file
8
src/modules/admin/dto/update-admin-status.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsIn } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateAdminStatusDto {
|
||||||
|
@ApiProperty({ enum: ['active', 'disabled'] })
|
||||||
|
@IsIn(['active', 'disabled'])
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
}
|
||||||
10
src/modules/admin/dto/update-role-permissions.dto.ts
Normal file
10
src/modules/admin/dto/update-role-permissions.dto.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsArray, IsInt, Min } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateRolePermissionsDto {
|
||||||
|
@ApiProperty({ type: [Number] })
|
||||||
|
@IsArray()
|
||||||
|
@IsInt({ each: true })
|
||||||
|
@Min(1, { each: true })
|
||||||
|
permissionIds: number[];
|
||||||
|
}
|
||||||
39
src/modules/admin/entities/admin-user.entity.ts
Normal file
39
src/modules/admin/entities/admin-user.entity.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('admin_users')
|
||||||
|
export class AdminUser {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 64 })
|
||||||
|
username: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 255 })
|
||||||
|
passwordHash: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
nickname?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32, default: 'active' })
|
||||||
|
status: string;
|
||||||
|
|
||||||
|
@Column({ type: 'boolean', default: false })
|
||||||
|
isSuperAdmin: boolean;
|
||||||
|
|
||||||
|
@Column({ type: 'json', nullable: true })
|
||||||
|
roleIds?: number[];
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
30
src/modules/admin/entities/permission.entity.ts
Normal file
30
src/modules/admin/entities/permission.entity.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('permissions')
|
||||||
|
export class Permission {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 512, nullable: true })
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
33
src/modules/admin/entities/role.entity.ts
Normal file
33
src/modules/admin/entities/role.entity.ts
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('roles')
|
||||||
|
export class Role {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
name: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 512, nullable: true })
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'json', nullable: true })
|
||||||
|
permissionIds?: number[];
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
53
src/modules/admin/guards/admin-jwt-auth.guard.ts
Normal file
53
src/modules/admin/guards/admin-jwt-auth.guard.ts
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||||
|
import { AdminService } from '../admin.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AdminJwtAuthGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly adminService: AdminService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context
|
||||||
|
.switchToHttp()
|
||||||
|
.getRequest<Request & { adminUser?: AdminUserRecord; adminId?: number }>();
|
||||||
|
const authHeader = request.get('authorization');
|
||||||
|
const token = authHeader?.startsWith('Bearer ')
|
||||||
|
? authHeader.slice('Bearer '.length)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException('Admin not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = await this.jwtService.verifyAsync<{
|
||||||
|
sub: number;
|
||||||
|
type: string;
|
||||||
|
}>(token);
|
||||||
|
if (payload.type !== 'admin') {
|
||||||
|
throw new UnauthorizedException('Admin not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
const adminUser = this.adminService.findAdminById(payload.sub);
|
||||||
|
if (!adminUser || adminUser.status !== 'active') {
|
||||||
|
throw new UnauthorizedException('Admin not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
request.adminUser = adminUser;
|
||||||
|
request.adminId = adminUser.id;
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Admin not authenticated');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
52
src/modules/admin/guards/permissions.guard.ts
Normal file
52
src/modules/admin/guards/permissions.guard.ts
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from '@nestjs/common';
|
||||||
|
import { Reflector } from '@nestjs/core';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import {
|
||||||
|
REQUIRED_PERMISSIONS_METADATA,
|
||||||
|
} from '../decorators/require-permissions.decorator';
|
||||||
|
import { AdminUserRecord } from '../interfaces/admin-records.interface';
|
||||||
|
import { AdminService } from '../admin.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PermissionsGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private readonly reflector: Reflector,
|
||||||
|
private readonly adminService: AdminService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
canActivate(context: ExecutionContext): boolean {
|
||||||
|
const required =
|
||||||
|
this.reflector.getAllAndOverride<string[]>(
|
||||||
|
REQUIRED_PERMISSIONS_METADATA,
|
||||||
|
[context.getHandler(), context.getClass()],
|
||||||
|
) ?? [];
|
||||||
|
|
||||||
|
if (required.length === 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const request = context
|
||||||
|
.switchToHttp()
|
||||||
|
.getRequest<Request & { adminUser?: AdminUserRecord }>();
|
||||||
|
const adminUser = request.adminUser;
|
||||||
|
|
||||||
|
if (!adminUser) {
|
||||||
|
throw new ForbiddenException('No permission');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adminUser.isSuperAdmin) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = this.adminService.getPermissionCodesForAdmin(adminUser.id);
|
||||||
|
const allowed = required.every((permission) =>
|
||||||
|
permissions.includes(permission),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!allowed) {
|
||||||
|
throw new ForbiddenException('No permission');
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
45
src/modules/admin/interfaces/admin-records.interface.ts
Normal file
45
src/modules/admin/interfaces/admin-records.interface.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
export interface PermissionRecord {
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RoleRecord {
|
||||||
|
id: number;
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
description?: string;
|
||||||
|
permissionIds: number[];
|
||||||
|
permissions: PermissionRecord[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminUserRecord {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
passwordHash: string;
|
||||||
|
nickname?: string;
|
||||||
|
email?: string;
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
isSuperAdmin: boolean;
|
||||||
|
roleIds: number[];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdminUserView {
|
||||||
|
id: number;
|
||||||
|
username: string;
|
||||||
|
nickname?: string;
|
||||||
|
email?: string;
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
isSuperAdmin: boolean;
|
||||||
|
roles: RoleRecord[];
|
||||||
|
permissions: PermissionRecord[] | ['*'];
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
15
src/modules/auth/auth.controller.ts
Normal file
15
src/modules/auth/auth.controller.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Body, Controller, Post } from '@nestjs/common';
|
||||||
|
import { ApiTags } from '@nestjs/swagger';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { TikTokLoginDto } from './dto/tiktok-login.dto';
|
||||||
|
|
||||||
|
@ApiTags('Auth')
|
||||||
|
@Controller('/api/app/v1/auth')
|
||||||
|
export class AuthController {
|
||||||
|
constructor(private readonly authService: AuthService) {}
|
||||||
|
|
||||||
|
@Post('/tiktok-login')
|
||||||
|
loginWithTikTok(@Body() dto: TikTokLoginDto) {
|
||||||
|
return this.authService.loginWithTikTok(dto);
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/modules/auth/auth.module.ts
Normal file
20
src/modules/auth/auth.module.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { JwtModule } from '@nestjs/jwt';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
import { AuthController } from './auth.controller';
|
||||||
|
import { AuthService } from './auth.service';
|
||||||
|
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
UsersModule,
|
||||||
|
JwtModule.register({
|
||||||
|
secret: process.env.JWT_SECRET ?? 'development-secret',
|
||||||
|
signOptions: { expiresIn: '30d' },
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
controllers: [AuthController],
|
||||||
|
providers: [AuthService, JwtAuthGuard],
|
||||||
|
exports: [JwtModule, JwtAuthGuard],
|
||||||
|
})
|
||||||
|
export class AuthModule {}
|
||||||
39
src/modules/auth/auth.service.ts
Normal file
39
src/modules/auth/auth.service.ts
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
import { Injectable, UnprocessableEntityException } from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { UsersService } from '../users/users.service';
|
||||||
|
import { TikTokLoginDto } from './dto/tiktok-login.dto';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AuthService {
|
||||||
|
constructor(
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async loginWithTikTok(dto: TikTokLoginDto) {
|
||||||
|
const tiktokOpenId = dto.mockOpenId ?? this.resolveOpenIdFromCode(dto.code);
|
||||||
|
const result = this.usersService.upsertTikTokUser({
|
||||||
|
tiktokOpenId,
|
||||||
|
tiktokUnionId: dto.tiktokUnionId,
|
||||||
|
nickname: dto.nickname,
|
||||||
|
avatarUrl: dto.avatarUrl,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
accessToken: await this.jwtService.signAsync({
|
||||||
|
sub: result.user.id,
|
||||||
|
tiktokOpenId: result.user.tiktokOpenId,
|
||||||
|
}),
|
||||||
|
user: result.user,
|
||||||
|
isNewUser: result.isNewUser,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveOpenIdFromCode(code: string) {
|
||||||
|
if (!code) {
|
||||||
|
throw new UnprocessableEntityException('TikTok login code is required');
|
||||||
|
}
|
||||||
|
|
||||||
|
return `mock-${code}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
10
src/modules/auth/decorators/current-user.decorator.ts
Normal file
10
src/modules/auth/decorators/current-user.decorator.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { UserRecord } from '../../users/interfaces/user-record.interface';
|
||||||
|
|
||||||
|
export const CurrentUser = createParamDecorator(
|
||||||
|
(_data: unknown, ctx: ExecutionContext): UserRecord | undefined => {
|
||||||
|
const request = ctx.switchToHttp().getRequest<Request & { user?: UserRecord }>();
|
||||||
|
return request.user;
|
||||||
|
},
|
||||||
|
);
|
||||||
30
src/modules/auth/dto/tiktok-login.dto.ts
Normal file
30
src/modules/auth/dto/tiktok-login.dto.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class TikTokLoginDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
code: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Development-only mock open id until TikTok app credentials are configured.',
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
mockOpenId?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
tiktokUnionId?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
nickname?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
avatarUrl?: string;
|
||||||
|
}
|
||||||
42
src/modules/auth/guards/jwt-auth.guard.ts
Normal file
42
src/modules/auth/guards/jwt-auth.guard.ts
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { JwtService } from '@nestjs/jwt';
|
||||||
|
import { Request } from 'express';
|
||||||
|
import { UsersService } from '../../users/users.service';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class JwtAuthGuard implements CanActivate {
|
||||||
|
constructor(
|
||||||
|
private readonly jwtService: JwtService,
|
||||||
|
private readonly usersService: UsersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<Request & { user?: unknown }>();
|
||||||
|
const authHeader = request.get('authorization');
|
||||||
|
const token = authHeader?.startsWith('Bearer ')
|
||||||
|
? authHeader.slice('Bearer '.length)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException('Not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = await this.jwtService.verifyAsync<{ sub: number }>(token);
|
||||||
|
const user = this.usersService.findById(payload.sub);
|
||||||
|
if (!user || user.status !== 'active') {
|
||||||
|
throw new UnauthorizedException('Not authenticated');
|
||||||
|
}
|
||||||
|
|
||||||
|
request.user = user;
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Not authenticated');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
src/modules/dramas/drama-status.enum.ts
Normal file
6
src/modules/dramas/drama-status.enum.ts
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
export enum PublishStatus {
|
||||||
|
Draft = 'draft',
|
||||||
|
Scheduled = 'scheduled',
|
||||||
|
Published = 'published',
|
||||||
|
Offline = 'offline',
|
||||||
|
}
|
||||||
87
src/modules/dramas/dramas.controller.ts
Normal file
87
src/modules/dramas/dramas.controller.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
|
||||||
|
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from '../admin/guards/permissions.guard';
|
||||||
|
import { CreateDramaDto } from './dto/create-drama.dto';
|
||||||
|
import { CreateEpisodeDto } from './dto/create-episode.dto';
|
||||||
|
import { DramasService } from './dramas.service';
|
||||||
|
import { PublishStatus } from './drama-status.enum';
|
||||||
|
|
||||||
|
@ApiTags('Dramas')
|
||||||
|
@Controller()
|
||||||
|
export class DramasController {
|
||||||
|
constructor(private readonly dramasService: DramasService) {}
|
||||||
|
|
||||||
|
@Post('/api/admin/v1/dramas')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('drama:create')
|
||||||
|
createDrama(@Body() dto: CreateDramaDto) {
|
||||||
|
return this.dramasService.createDrama(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/api/admin/v1/dramas')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('drama:read')
|
||||||
|
listAdminDramas(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||||
|
return this.dramasService.listAdminDramas({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/api/admin/v1/episodes')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('episode:create')
|
||||||
|
createEpisode(@Body() dto: CreateEpisodeDto) {
|
||||||
|
return this.dramasService.createEpisode(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/api/admin/v1/dramas/:id/submit-review')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('drama:update')
|
||||||
|
submitReview(@Param('id') id: string) {
|
||||||
|
return this.dramasService.submitReview(Number(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/api/admin/v1/episodes/:id/publish-status')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('episode:update')
|
||||||
|
updatePublishStatus(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Body() dto: { publishStatus: PublishStatus },
|
||||||
|
) {
|
||||||
|
return this.dramasService.updateEpisodePublishStatus(
|
||||||
|
Number(id),
|
||||||
|
dto.publishStatus,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/api/app/v1/dramas')
|
||||||
|
listPublishedDramas(
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.dramasService.listPublishedDramas({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/api/app/v1/dramas/:id/episodes')
|
||||||
|
listPublishedEpisodes(
|
||||||
|
@Param('id') id: string,
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.dramasService.listPublishedEpisodes(Number(id), {
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/modules/dramas/dramas.module.ts
Normal file
12
src/modules/dramas/dramas.module.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AdminModule } from '../admin/admin.module';
|
||||||
|
import { DramasController } from './dramas.controller';
|
||||||
|
import { DramasService } from './dramas.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AdminModule],
|
||||||
|
controllers: [DramasController],
|
||||||
|
providers: [DramasService],
|
||||||
|
exports: [DramasService],
|
||||||
|
})
|
||||||
|
export class DramasModule {}
|
||||||
221
src/modules/dramas/dramas.service.ts
Normal file
221
src/modules/dramas/dramas.service.ts
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
import {
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||||
|
import { CreateDramaDto } from './dto/create-drama.dto';
|
||||||
|
import { CreateEpisodeDto } from './dto/create-episode.dto';
|
||||||
|
import { PublishStatus } from './drama-status.enum';
|
||||||
|
import {
|
||||||
|
DramaRecord,
|
||||||
|
EpisodeRecord,
|
||||||
|
} from './interfaces/drama-records.interface';
|
||||||
|
|
||||||
|
interface PaginationInput {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class DramasService {
|
||||||
|
private dramaSequence = 1;
|
||||||
|
private episodeSequence = 1;
|
||||||
|
private readonly dramas: DramaRecord[] = [];
|
||||||
|
private readonly episodes: EpisodeRecord[] = [];
|
||||||
|
|
||||||
|
createDrama(dto: CreateDramaDto): DramaRecord {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const drama: DramaRecord = {
|
||||||
|
id: this.dramaSequence++,
|
||||||
|
tiktokAlbumId: dto.tiktokAlbumId,
|
||||||
|
title: dto.title,
|
||||||
|
description: dto.description,
|
||||||
|
coverId: dto.coverId,
|
||||||
|
coverUrl: dto.coverUrl,
|
||||||
|
portraitCoverUrl: dto.portraitCoverUrl,
|
||||||
|
landscapeCoverUrl: dto.landscapeCoverUrl,
|
||||||
|
type: dto.type,
|
||||||
|
tags: dto.tags ?? [],
|
||||||
|
region: dto.region,
|
||||||
|
language: dto.language,
|
||||||
|
year: dto.year,
|
||||||
|
status: dto.status ?? PublishStatus.Draft,
|
||||||
|
sortOrder: dto.sortOrder ?? 0,
|
||||||
|
isRecommended: dto.isRecommended ?? false,
|
||||||
|
onlineVersion: dto.onlineVersion ?? 1,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.dramas.push(drama);
|
||||||
|
return drama;
|
||||||
|
}
|
||||||
|
|
||||||
|
listAdminDramas(pagination: PaginationInput): PaginatedResponse<DramaRecord> {
|
||||||
|
return this.paginate(this.sortDramas(this.dramas), pagination);
|
||||||
|
}
|
||||||
|
|
||||||
|
createEpisode(dto: CreateEpisodeDto): EpisodeRecord {
|
||||||
|
const dramaId = dto.dramaId ?? dto.albumId;
|
||||||
|
const episodeNo = dto.episodeNo ?? dto.seq;
|
||||||
|
if (!dramaId || !episodeNo) {
|
||||||
|
throw new NotFoundException('Drama not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const drama = this.dramas.find((item) => item.id === dramaId);
|
||||||
|
if (!drama) {
|
||||||
|
throw new NotFoundException('Drama not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const duplicate = this.episodes.some(
|
||||||
|
(item) =>
|
||||||
|
item.dramaId === dramaId && item.episodeNo === episodeNo,
|
||||||
|
);
|
||||||
|
if (duplicate) {
|
||||||
|
throw new ConflictException('Episode number already exists in this drama');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const freeType = dto.freeType ?? (dto.isPaid ? 'paid' : 'free');
|
||||||
|
const price = dto.price ?? dto.unlockPrice ?? 0;
|
||||||
|
const episode: EpisodeRecord = {
|
||||||
|
id: this.episodeSequence++,
|
||||||
|
dramaId,
|
||||||
|
albumId: dramaId,
|
||||||
|
tiktokEpisodeId: dto.tiktokEpisodeId,
|
||||||
|
episodeNo,
|
||||||
|
seq: episodeNo,
|
||||||
|
title: dto.title,
|
||||||
|
description: dto.description,
|
||||||
|
byteplusVid: dto.byteplusVid,
|
||||||
|
coverId: dto.coverId,
|
||||||
|
coverUrl: dto.coverUrl,
|
||||||
|
videoUrl: dto.videoUrl,
|
||||||
|
trialDurationSeconds: dto.trialDurationSeconds,
|
||||||
|
durationSeconds: dto.durationSeconds,
|
||||||
|
isPaid: freeType === 'paid',
|
||||||
|
freeType,
|
||||||
|
unlockPrice: price,
|
||||||
|
price,
|
||||||
|
publishAt: dto.publishAt,
|
||||||
|
nextReleaseAt: dto.nextReleaseAt,
|
||||||
|
status: dto.status ?? dto.publishStatus ?? PublishStatus.Draft,
|
||||||
|
reviewStatus: dto.reviewStatus ?? 'pending',
|
||||||
|
publishStatus: dto.publishStatus ?? dto.status ?? PublishStatus.Draft,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.episodes.push(episode);
|
||||||
|
return episode;
|
||||||
|
}
|
||||||
|
|
||||||
|
listPublishedDramas(
|
||||||
|
pagination: PaginationInput,
|
||||||
|
): PaginatedResponse<DramaRecord> {
|
||||||
|
return this.paginate(
|
||||||
|
this.sortDramas(
|
||||||
|
this.dramas.filter((item) => item.status === PublishStatus.Published),
|
||||||
|
),
|
||||||
|
pagination,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
listPublishedEpisodes(
|
||||||
|
dramaId: number,
|
||||||
|
pagination: PaginationInput,
|
||||||
|
): PaginatedResponse<EpisodeRecord> {
|
||||||
|
const drama = this.dramas.find((item) => item.id === dramaId);
|
||||||
|
if (!drama || drama.status !== PublishStatus.Published) {
|
||||||
|
throw new NotFoundException('Drama not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const episodes = this.episodes
|
||||||
|
.filter(
|
||||||
|
(item) =>
|
||||||
|
item.dramaId === dramaId && item.status === PublishStatus.Published,
|
||||||
|
)
|
||||||
|
.sort((left, right) => left.episodeNo - right.episodeNo);
|
||||||
|
|
||||||
|
return this.paginate(episodes, pagination);
|
||||||
|
}
|
||||||
|
|
||||||
|
getPublishedEpisodeOrThrow(episodeId: number): EpisodeRecord {
|
||||||
|
const episode = this.episodes.find((item) => item.id === episodeId);
|
||||||
|
if (!episode || episode.status !== PublishStatus.Published) {
|
||||||
|
throw new NotFoundException('Episode not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const drama = this.dramas.find((item) => item.id === episode.dramaId);
|
||||||
|
if (!drama || drama.status !== PublishStatus.Published) {
|
||||||
|
throw new NotFoundException('Episode not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return episode;
|
||||||
|
}
|
||||||
|
|
||||||
|
getEpisodeOrThrow(episodeId: number): EpisodeRecord {
|
||||||
|
const episode = this.episodes.find((item) => item.id === episodeId);
|
||||||
|
if (!episode) {
|
||||||
|
throw new NotFoundException('Episode not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return episode;
|
||||||
|
}
|
||||||
|
|
||||||
|
submitReview(albumId: number) {
|
||||||
|
const album = this.dramas.find((item) => item.id === albumId);
|
||||||
|
if (!album) {
|
||||||
|
throw new NotFoundException('Drama not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.episodes
|
||||||
|
.filter((episode) => episode.albumId === albumId)
|
||||||
|
.forEach((episode) => {
|
||||||
|
episode.reviewStatus = 'pending';
|
||||||
|
episode.updatedAt = new Date().toISOString();
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
albumId,
|
||||||
|
reviewStatus: 'pending',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
updateEpisodePublishStatus(episodeId: number, publishStatus: PublishStatus) {
|
||||||
|
const episode = this.getEpisodeOrThrow(episodeId);
|
||||||
|
episode.publishStatus = publishStatus;
|
||||||
|
episode.status = publishStatus;
|
||||||
|
episode.updatedAt = new Date().toISOString();
|
||||||
|
return episode;
|
||||||
|
}
|
||||||
|
|
||||||
|
private sortDramas(records: DramaRecord[]) {
|
||||||
|
return [...records].sort((left, right) => {
|
||||||
|
if (right.sortOrder !== left.sortOrder) {
|
||||||
|
return right.sortOrder - left.sortOrder;
|
||||||
|
}
|
||||||
|
|
||||||
|
return right.id - left.id;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private paginate<T>(
|
||||||
|
records: T[],
|
||||||
|
input: PaginationInput,
|
||||||
|
): PaginatedResponse<T> {
|
||||||
|
const page = Math.max(input.page, 1);
|
||||||
|
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: records.slice(start, start + pageSize),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: records.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
96
src/modules/dramas/dto/create-drama.dto.ts
Normal file
96
src/modules/dramas/dto/create-drama.dto.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsArray,
|
||||||
|
IsBoolean,
|
||||||
|
IsEnum,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUrl,
|
||||||
|
Min,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { PublishStatus } from '../drama-status.enum';
|
||||||
|
|
||||||
|
export class CreateDramaDto {
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
tiktokAlbumId?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsOptional()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
coverUrl: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
coverId?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
portraitCoverUrl?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
landscapeCoverUrl?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
type: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ type: [String] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsArray()
|
||||||
|
@IsString({ each: true })
|
||||||
|
tags?: string[];
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
region?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
language?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1900)
|
||||||
|
year?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: PublishStatus })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(PublishStatus)
|
||||||
|
status?: PublishStatus;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
sortOrder?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
isRecommended?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
onlineVersion?: number;
|
||||||
|
}
|
||||||
131
src/modules/dramas/dto/create-episode.dto.ts
Normal file
131
src/modules/dramas/dto/create-episode.dto.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsDateString,
|
||||||
|
IsEnum,
|
||||||
|
IsInt,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
IsUrl,
|
||||||
|
Min,
|
||||||
|
} from 'class-validator';
|
||||||
|
import { PublishStatus } from '../drama-status.enum';
|
||||||
|
|
||||||
|
export class CreateEpisodeDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
dramaId?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
albumId?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
tiktokEpisodeId?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
episodeNo?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
seq?: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsOptional()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
coverUrl: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
coverId?: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsOptional()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
videoUrl?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
byteplusVid?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
trialDurationSeconds?: number;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
durationSeconds: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsBoolean()
|
||||||
|
isPaid?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: ['free', 'paid'] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
freeType?: 'free' | 'paid';
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
unlockPrice?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsInt()
|
||||||
|
@Min(0)
|
||||||
|
price?: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
publishAt?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsDateString()
|
||||||
|
nextReleaseAt?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: PublishStatus })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(PublishStatus)
|
||||||
|
status?: PublishStatus;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: ['pending', 'approved', 'rejected'] })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
reviewStatus?: 'pending' | 'approved' | 'rejected';
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ enum: PublishStatus })
|
||||||
|
@IsOptional()
|
||||||
|
@IsEnum(PublishStatus)
|
||||||
|
publishStatus?: PublishStatus;
|
||||||
|
}
|
||||||
59
src/modules/dramas/entities/drama.entity.ts
Normal file
59
src/modules/dramas/entities/drama.entity.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { PublishStatus } from '../drama-status.enum';
|
||||||
|
|
||||||
|
@Entity('dramas')
|
||||||
|
export class Drama {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 255 })
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
@Column({ type: 'text', nullable: true })
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024 })
|
||||||
|
coverUrl: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||||
|
portraitCoverUrl?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||||
|
landscapeCoverUrl?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
type: string;
|
||||||
|
|
||||||
|
@Column({ type: 'json', nullable: true })
|
||||||
|
tags?: string[];
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 64, nullable: true })
|
||||||
|
region?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32, nullable: true })
|
||||||
|
language?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'int', nullable: true })
|
||||||
|
year?: number;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
|
||||||
|
status: PublishStatus;
|
||||||
|
|
||||||
|
@Column({ type: 'int', default: 0 })
|
||||||
|
sortOrder: number;
|
||||||
|
|
||||||
|
@Column({ type: 'boolean', default: false })
|
||||||
|
isRecommended: boolean;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
61
src/modules/dramas/entities/episode.entity.ts
Normal file
61
src/modules/dramas/entities/episode.entity.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
import { PublishStatus } from '../drama-status.enum';
|
||||||
|
|
||||||
|
@Entity('episodes')
|
||||||
|
@Index(['dramaId', 'episodeNo'], { unique: true })
|
||||||
|
export class Episode {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
dramaId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'int' })
|
||||||
|
episodeNo: number;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 255 })
|
||||||
|
title: string;
|
||||||
|
|
||||||
|
@Column({ type: 'text', nullable: true })
|
||||||
|
description?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024 })
|
||||||
|
coverUrl: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024 })
|
||||||
|
videoUrl: string;
|
||||||
|
|
||||||
|
@Column({ type: 'int', nullable: true })
|
||||||
|
trialDurationSeconds?: number;
|
||||||
|
|
||||||
|
@Column({ type: 'int' })
|
||||||
|
durationSeconds: number;
|
||||||
|
|
||||||
|
@Column({ type: 'boolean', default: false })
|
||||||
|
isPaid: boolean;
|
||||||
|
|
||||||
|
@Column({ type: 'int', nullable: true })
|
||||||
|
unlockPrice?: number;
|
||||||
|
|
||||||
|
@Column({ type: 'datetime', nullable: true })
|
||||||
|
publishAt?: Date;
|
||||||
|
|
||||||
|
@Column({ type: 'datetime', nullable: true })
|
||||||
|
nextReleaseAt?: Date;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32, default: PublishStatus.Draft })
|
||||||
|
status: PublishStatus;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
51
src/modules/dramas/interfaces/drama-records.interface.ts
Normal file
51
src/modules/dramas/interfaces/drama-records.interface.ts
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
import { PublishStatus } from '../drama-status.enum';
|
||||||
|
|
||||||
|
export interface DramaRecord {
|
||||||
|
id: number;
|
||||||
|
tiktokAlbumId?: string;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
coverId?: number;
|
||||||
|
coverUrl: string;
|
||||||
|
portraitCoverUrl?: string;
|
||||||
|
landscapeCoverUrl?: string;
|
||||||
|
type: string;
|
||||||
|
tags: string[];
|
||||||
|
region?: string;
|
||||||
|
language?: string;
|
||||||
|
year?: number;
|
||||||
|
status: PublishStatus;
|
||||||
|
sortOrder: number;
|
||||||
|
isRecommended: boolean;
|
||||||
|
onlineVersion: number;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface EpisodeRecord {
|
||||||
|
id: number;
|
||||||
|
dramaId: number;
|
||||||
|
albumId: number;
|
||||||
|
tiktokEpisodeId?: string;
|
||||||
|
episodeNo: number;
|
||||||
|
seq: number;
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
byteplusVid?: string;
|
||||||
|
coverId?: number;
|
||||||
|
coverUrl: string;
|
||||||
|
videoUrl?: string;
|
||||||
|
trialDurationSeconds?: number;
|
||||||
|
durationSeconds: number;
|
||||||
|
isPaid: boolean;
|
||||||
|
freeType: 'free' | 'paid';
|
||||||
|
unlockPrice?: number;
|
||||||
|
price: number;
|
||||||
|
publishAt?: string;
|
||||||
|
nextReleaseAt?: string;
|
||||||
|
status: PublishStatus;
|
||||||
|
reviewStatus: 'pending' | 'approved' | 'rejected';
|
||||||
|
publishStatus: PublishStatus;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
11
src/modules/health/health.controller.ts
Normal file
11
src/modules/health/health.controller.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { Controller, Get } from '@nestjs/common';
|
||||||
|
import { ApiTags } from '@nestjs/swagger';
|
||||||
|
|
||||||
|
@ApiTags('Health')
|
||||||
|
@Controller('/api/app/v1/health')
|
||||||
|
export class HealthController {
|
||||||
|
@Get()
|
||||||
|
getHealth() {
|
||||||
|
return { status: 'ok' };
|
||||||
|
}
|
||||||
|
}
|
||||||
7
src/modules/health/health.module.ts
Normal file
7
src/modules/health/health.module.ts
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { HealthController } from './health.controller';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
controllers: [HealthController],
|
||||||
|
})
|
||||||
|
export class HealthModule {}
|
||||||
12
src/modules/media/dto/create-cover.dto.ts
Normal file
12
src/modules/media/dto/create-cover.dto.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsString, IsUrl } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateCoverDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
fileName: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsUrl({ require_tld: false })
|
||||||
|
url: string;
|
||||||
|
}
|
||||||
22
src/modules/media/dto/create-upload-job.dto.ts
Normal file
22
src/modules/media/dto/create-upload-job.dto.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsObject, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateUploadJobDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
jobId: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
byteplusVid?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
status: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsObject()
|
||||||
|
rawResponse?: Record<string, unknown>;
|
||||||
|
}
|
||||||
34
src/modules/media/entities/media-upload-job.entity.ts
Normal file
34
src/modules/media/entities/media-upload-job.entity.ts
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('media_upload_jobs')
|
||||||
|
export class MediaUploadJob {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
jobId: string;
|
||||||
|
|
||||||
|
@Index()
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
byteplusVid?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 64 })
|
||||||
|
status: string;
|
||||||
|
|
||||||
|
@Column({ type: 'json', nullable: true })
|
||||||
|
rawResponse?: Record<string, unknown>;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
16
src/modules/media/interfaces/media-records.interface.ts
Normal file
16
src/modules/media/interfaces/media-records.interface.ts
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
export interface CoverRecord {
|
||||||
|
id: number;
|
||||||
|
fileName: string;
|
||||||
|
url: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MediaUploadJobRecord {
|
||||||
|
id: number;
|
||||||
|
jobId: string;
|
||||||
|
byteplusVid?: string;
|
||||||
|
status: string;
|
||||||
|
rawResponse?: Record<string, unknown>;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
40
src/modules/media/media.controller.ts
Normal file
40
src/modules/media/media.controller.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
|
||||||
|
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from '../admin/guards/permissions.guard';
|
||||||
|
import { CreateCoverDto } from './dto/create-cover.dto';
|
||||||
|
import { CreateUploadJobDto } from './dto/create-upload-job.dto';
|
||||||
|
import { MediaService } from './media.service';
|
||||||
|
|
||||||
|
@ApiTags('Media')
|
||||||
|
@Controller('/api/admin/v1/media')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
export class MediaController {
|
||||||
|
constructor(private readonly mediaService: MediaService) {}
|
||||||
|
|
||||||
|
@Post('/covers')
|
||||||
|
@RequirePermissions('media:create')
|
||||||
|
createCover(@Body() dto: CreateCoverDto) {
|
||||||
|
return this.mediaService.createCover(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/upload-jobs')
|
||||||
|
@RequirePermissions('media:create')
|
||||||
|
createUploadJob(@Body() dto: CreateUploadJobDto) {
|
||||||
|
return this.mediaService.createUploadJob(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/upload-jobs')
|
||||||
|
@RequirePermissions('media:read')
|
||||||
|
listUploadJobs(
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.mediaService.listUploadJobs({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/modules/media/media.module.ts
Normal file
12
src/modules/media/media.module.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AdminModule } from '../admin/admin.module';
|
||||||
|
import { MediaController } from './media.controller';
|
||||||
|
import { MediaService } from './media.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AdminModule],
|
||||||
|
controllers: [MediaController],
|
||||||
|
providers: [MediaService],
|
||||||
|
exports: [MediaService],
|
||||||
|
})
|
||||||
|
export class MediaModule {}
|
||||||
65
src/modules/media/media.service.ts
Normal file
65
src/modules/media/media.service.ts
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||||
|
import { CreateCoverDto } from './dto/create-cover.dto';
|
||||||
|
import { CreateUploadJobDto } from './dto/create-upload-job.dto';
|
||||||
|
import {
|
||||||
|
CoverRecord,
|
||||||
|
MediaUploadJobRecord,
|
||||||
|
} from './interfaces/media-records.interface';
|
||||||
|
|
||||||
|
interface PaginationInput {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MediaService {
|
||||||
|
private coverSequence = 1;
|
||||||
|
private uploadJobSequence = 1;
|
||||||
|
private readonly covers: CoverRecord[] = [];
|
||||||
|
private readonly uploadJobs: MediaUploadJobRecord[] = [];
|
||||||
|
|
||||||
|
createCover(dto: CreateCoverDto): CoverRecord {
|
||||||
|
const cover: CoverRecord = {
|
||||||
|
id: this.coverSequence++,
|
||||||
|
fileName: dto.fileName,
|
||||||
|
url: dto.url,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
this.covers.push(cover);
|
||||||
|
return cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
createUploadJob(dto: CreateUploadJobDto): MediaUploadJobRecord {
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const job: MediaUploadJobRecord = {
|
||||||
|
id: this.uploadJobSequence++,
|
||||||
|
jobId: dto.jobId,
|
||||||
|
byteplusVid: dto.byteplusVid,
|
||||||
|
status: dto.status,
|
||||||
|
rawResponse: dto.rawResponse,
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
this.uploadJobs.push(job);
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
listUploadJobs(
|
||||||
|
input: PaginationInput,
|
||||||
|
): PaginatedResponse<MediaUploadJobRecord> {
|
||||||
|
const page = Math.max(input.page, 1);
|
||||||
|
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
const records = [...this.uploadJobs].reverse();
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: records.slice(start, start + pageSize),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: records.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/modules/orders/dto/create-order.dto.ts
Normal file
9
src/modules/orders/dto/create-order.dto.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsInt, Min } from 'class-validator';
|
||||||
|
|
||||||
|
export class CreateOrderDto {
|
||||||
|
@ApiProperty()
|
||||||
|
@IsInt()
|
||||||
|
@Min(1)
|
||||||
|
episodeId: number;
|
||||||
|
}
|
||||||
32
src/modules/orders/dto/tiktok-payment-webhook.dto.ts
Normal file
32
src/modules/orders/dto/tiktok-payment-webhook.dto.ts
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||||
|
import { IsIn, IsOptional, IsString } from 'class-validator';
|
||||||
|
|
||||||
|
export class TikTokPaymentWebhookDto {
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
orderNo?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
tradeOrderId?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
tiktokOrderId?: string;
|
||||||
|
|
||||||
|
@ApiProperty()
|
||||||
|
@IsString()
|
||||||
|
providerTransactionId: string;
|
||||||
|
|
||||||
|
@ApiProperty({ enum: ['paid', 'failed'] })
|
||||||
|
@IsIn(['paid', 'failed'])
|
||||||
|
status: 'paid' | 'failed';
|
||||||
|
|
||||||
|
@ApiPropertyOptional()
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
signature?: string;
|
||||||
|
}
|
||||||
49
src/modules/orders/entities/order.entity.ts
Normal file
49
src/modules/orders/entities/order.entity.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('orders')
|
||||||
|
export class Order {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 64 })
|
||||||
|
orderNo: string;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 64 })
|
||||||
|
tradeOrderId: string;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
userId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
albumId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
episodeId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'int' })
|
||||||
|
amount: number;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32 })
|
||||||
|
status: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
providerTransactionId?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
tiktokOrderId?: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
29
src/modules/orders/entities/user-episode-unlock.entity.ts
Normal file
29
src/modules/orders/entities/user-episode-unlock.entity.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('user_episode_unlocks')
|
||||||
|
@Index(['userId', 'episodeId'], { unique: true })
|
||||||
|
export class UserEpisodeUnlock {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
userId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'bigint' })
|
||||||
|
episodeId: number;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 64 })
|
||||||
|
orderNo: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32 })
|
||||||
|
source: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
25
src/modules/orders/interfaces/order-records.interface.ts
Normal file
25
src/modules/orders/interfaces/order-records.interface.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
export type OrderStatus = 'pending' | 'paid' | 'failed';
|
||||||
|
|
||||||
|
export interface OrderRecord {
|
||||||
|
id: number;
|
||||||
|
orderNo: string;
|
||||||
|
tradeOrderId: string;
|
||||||
|
userId: number;
|
||||||
|
albumId: number;
|
||||||
|
episodeId: number;
|
||||||
|
tiktokOrderId?: string;
|
||||||
|
amount: number;
|
||||||
|
status: OrderStatus;
|
||||||
|
providerTransactionId?: string;
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserEpisodeUnlockRecord {
|
||||||
|
id: number;
|
||||||
|
userId: number;
|
||||||
|
episodeId: number;
|
||||||
|
source: 'payment' | 'admin' | 'free';
|
||||||
|
orderNo: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
50
src/modules/orders/orders.controller.ts
Normal file
50
src/modules/orders/orders.controller.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
|
||||||
|
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from '../admin/guards/permissions.guard';
|
||||||
|
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||||
|
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||||
|
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||||
|
import { CreateOrderDto } from './dto/create-order.dto';
|
||||||
|
import { TikTokPaymentWebhookDto } from './dto/tiktok-payment-webhook.dto';
|
||||||
|
import { OrdersService } from './orders.service';
|
||||||
|
|
||||||
|
@ApiTags('Orders')
|
||||||
|
@Controller()
|
||||||
|
export class OrdersController {
|
||||||
|
constructor(private readonly ordersService: OrdersService) {}
|
||||||
|
|
||||||
|
@Post('/api/app/v1/orders')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
createOrder(@CurrentUser() user: UserRecord, @Body() dto: CreateOrderDto) {
|
||||||
|
return this.ordersService.createOrder(user, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/api/app/v1/episodes/:id/play')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
getPlayback(@CurrentUser() user: UserRecord, @Param('id') id: string) {
|
||||||
|
return this.ordersService.getPlayback(user, Number(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('/api/webhooks/tiktok/payments')
|
||||||
|
handlePaymentWebhook(@Body() dto: TikTokPaymentWebhookDto) {
|
||||||
|
return this.ordersService.handlePaymentWebhook(dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/api/admin/v1/unlock-records')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
@RequirePermissions('payment:read')
|
||||||
|
listUnlockRecords(
|
||||||
|
@Query('page') page?: string,
|
||||||
|
@Query('pageSize') pageSize?: string,
|
||||||
|
) {
|
||||||
|
return this.ordersService.listUnlockRecords({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
15
src/modules/orders/orders.module.ts
Normal file
15
src/modules/orders/orders.module.ts
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { AdminModule } from '../admin/admin.module';
|
||||||
|
import { DramasModule } from '../dramas/dramas.module';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
import { OrdersController } from './orders.controller';
|
||||||
|
import { OrdersService } from './orders.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AdminModule, AuthModule, DramasModule, UsersModule],
|
||||||
|
controllers: [OrdersController],
|
||||||
|
providers: [OrdersService],
|
||||||
|
exports: [OrdersService],
|
||||||
|
})
|
||||||
|
export class OrdersModule {}
|
||||||
147
src/modules/orders/orders.service.ts
Normal file
147
src/modules/orders/orders.service.ts
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
import {
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
UnprocessableEntityException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||||
|
import { DramasService } from '../dramas/dramas.service';
|
||||||
|
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||||
|
import { CreateOrderDto } from './dto/create-order.dto';
|
||||||
|
import { TikTokPaymentWebhookDto } from './dto/tiktok-payment-webhook.dto';
|
||||||
|
import {
|
||||||
|
OrderRecord,
|
||||||
|
UserEpisodeUnlockRecord,
|
||||||
|
} from './interfaces/order-records.interface';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class OrdersService {
|
||||||
|
private orderSequence = 1;
|
||||||
|
private unlockSequence = 1;
|
||||||
|
private readonly orders: OrderRecord[] = [];
|
||||||
|
private readonly unlocks: UserEpisodeUnlockRecord[] = [];
|
||||||
|
|
||||||
|
constructor(private readonly dramasService: DramasService) {}
|
||||||
|
|
||||||
|
createOrder(user: UserRecord, dto: CreateOrderDto): OrderRecord {
|
||||||
|
const episode = this.dramasService.getPublishedEpisodeOrThrow(dto.episodeId);
|
||||||
|
if (!episode.isPaid) {
|
||||||
|
throw new UnprocessableEntityException('Episode is free');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
const order: OrderRecord = {
|
||||||
|
id: this.orderSequence++,
|
||||||
|
orderNo: this.createOrderNo(),
|
||||||
|
tradeOrderId: this.createTradeOrderId(),
|
||||||
|
userId: user.id,
|
||||||
|
albumId: episode.albumId,
|
||||||
|
episodeId: episode.id,
|
||||||
|
amount: episode.price ?? episode.unlockPrice ?? 0,
|
||||||
|
status: 'pending',
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.orders.push(order);
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlayback(user: UserRecord, episodeId: number) {
|
||||||
|
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||||
|
const isUnlocked =
|
||||||
|
!episode.isPaid ||
|
||||||
|
this.unlocks.some(
|
||||||
|
(unlock) => unlock.userId === user.id && unlock.episodeId === episodeId,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
episodeId: episode.id,
|
||||||
|
dramaId: episode.dramaId,
|
||||||
|
albumId: episode.albumId,
|
||||||
|
isLocked: !isUnlocked,
|
||||||
|
isPaid: episode.isPaid,
|
||||||
|
trialDurationSeconds: episode.trialDurationSeconds,
|
||||||
|
durationSeconds: episode.durationSeconds,
|
||||||
|
videoUrl: isUnlocked ? episode.videoUrl : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
handlePaymentWebhook(dto: TikTokPaymentWebhookDto) {
|
||||||
|
const order = this.orders.find(
|
||||||
|
(item) =>
|
||||||
|
item.orderNo === dto.orderNo || item.tradeOrderId === dto.tradeOrderId,
|
||||||
|
);
|
||||||
|
if (!order) {
|
||||||
|
throw new NotFoundException('Order not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (order.status === 'paid') {
|
||||||
|
return {
|
||||||
|
orderNo: order.orderNo,
|
||||||
|
status: order.status,
|
||||||
|
unlocked: this.isUnlocked(order.userId, order.episodeId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
order.providerTransactionId = dto.providerTransactionId;
|
||||||
|
order.tiktokOrderId = dto.tiktokOrderId ?? order.tiktokOrderId;
|
||||||
|
order.status = dto.status;
|
||||||
|
order.updatedAt = new Date().toISOString();
|
||||||
|
|
||||||
|
if (dto.status === 'paid' && !this.isUnlocked(order.userId, order.episodeId)) {
|
||||||
|
this.unlocks.push({
|
||||||
|
id: this.unlockSequence++,
|
||||||
|
userId: order.userId,
|
||||||
|
episodeId: order.episodeId,
|
||||||
|
source: 'payment',
|
||||||
|
orderNo: order.orderNo,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
orderNo: order.orderNo,
|
||||||
|
tradeOrderId: order.tradeOrderId,
|
||||||
|
status: order.status,
|
||||||
|
unlocked: this.isUnlocked(order.userId, order.episodeId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
hasEpisodePermission(userId: number, episodeId: number) {
|
||||||
|
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||||
|
return !episode.isPaid || this.isUnlocked(userId, episodeId);
|
||||||
|
}
|
||||||
|
|
||||||
|
listUnlockRecords(input: {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}): PaginatedResponse<UserEpisodeUnlockRecord> {
|
||||||
|
const page = Math.max(input.page, 1);
|
||||||
|
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
const records = [...this.unlocks].reverse();
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: records.slice(start, start + pageSize),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: records.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private isUnlocked(userId: number, episodeId: number) {
|
||||||
|
return this.unlocks.some(
|
||||||
|
(unlock) => unlock.userId === userId && unlock.episodeId === episodeId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private createOrderNo() {
|
||||||
|
return `ORD${Date.now()}${String(this.orderSequence).padStart(6, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private createTradeOrderId() {
|
||||||
|
return `TRADE${Date.now()}${String(this.orderSequence).padStart(6, '0')}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
19
src/modules/player/player.controller.ts
Normal file
19
src/modules/player/player.controller.ts
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||||
|
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||||
|
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||||
|
import { PlayerService } from './player.service';
|
||||||
|
|
||||||
|
@ApiTags('Player')
|
||||||
|
@Controller('/api/app/v1/player')
|
||||||
|
export class PlayerController {
|
||||||
|
constructor(private readonly playerService: PlayerService) {}
|
||||||
|
|
||||||
|
@Get('/episodes/:id')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(JwtAuthGuard)
|
||||||
|
getEpisodePlayer(@CurrentUser() user: UserRecord, @Param('id') id: string) {
|
||||||
|
return this.playerService.getEpisodePlayer(user, Number(id));
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/modules/player/player.module.ts
Normal file
14
src/modules/player/player.module.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AuthModule } from '../auth/auth.module';
|
||||||
|
import { DramasModule } from '../dramas/dramas.module';
|
||||||
|
import { OrdersModule } from '../orders/orders.module';
|
||||||
|
import { UsersModule } from '../users/users.module';
|
||||||
|
import { PlayerController } from './player.controller';
|
||||||
|
import { PlayerService } from './player.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AuthModule, DramasModule, OrdersModule, UsersModule],
|
||||||
|
controllers: [PlayerController],
|
||||||
|
providers: [PlayerService],
|
||||||
|
})
|
||||||
|
export class PlayerModule {}
|
||||||
30
src/modules/player/player.service.ts
Normal file
30
src/modules/player/player.service.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { DramasService } from '../dramas/dramas.service';
|
||||||
|
import { OrdersService } from '../orders/orders.service';
|
||||||
|
import { UserRecord } from '../users/interfaces/user-record.interface';
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class PlayerService {
|
||||||
|
constructor(
|
||||||
|
private readonly dramasService: DramasService,
|
||||||
|
private readonly ordersService: OrdersService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
getEpisodePlayer(user: UserRecord, episodeId: number) {
|
||||||
|
const episode = this.dramasService.getPublishedEpisodeOrThrow(episodeId);
|
||||||
|
const hasPermission = this.ordersService.hasEpisodePermission(
|
||||||
|
user.id,
|
||||||
|
episode.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
albumId: episode.albumId,
|
||||||
|
episodeId: episode.id,
|
||||||
|
vid: episode.byteplusVid,
|
||||||
|
hasPermission,
|
||||||
|
playAuthToken: hasPermission
|
||||||
|
? `play_auth_${episode.byteplusVid ?? episode.id}_${user.id}`
|
||||||
|
: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
8
src/modules/users/dto/update-user-status.dto.ts
Normal file
8
src/modules/users/dto/update-user-status.dto.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { ApiProperty } from '@nestjs/swagger';
|
||||||
|
import { IsIn } from 'class-validator';
|
||||||
|
|
||||||
|
export class UpdateUserStatusDto {
|
||||||
|
@ApiProperty({ enum: ['active', 'disabled'] })
|
||||||
|
@IsIn(['active', 'disabled'])
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
}
|
||||||
37
src/modules/users/entities/user.entity.ts
Normal file
37
src/modules/users/entities/user.entity.ts
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
import {
|
||||||
|
Column,
|
||||||
|
CreateDateColumn,
|
||||||
|
Entity,
|
||||||
|
Index,
|
||||||
|
PrimaryGeneratedColumn,
|
||||||
|
UpdateDateColumn,
|
||||||
|
} from 'typeorm';
|
||||||
|
|
||||||
|
@Entity('users')
|
||||||
|
export class User {
|
||||||
|
@PrimaryGeneratedColumn()
|
||||||
|
id: number;
|
||||||
|
|
||||||
|
@Index({ unique: true })
|
||||||
|
@Column({ type: 'varchar', length: 128 })
|
||||||
|
tiktokOpenId: string;
|
||||||
|
|
||||||
|
@Index()
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
tiktokUnionId?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 128, nullable: true })
|
||||||
|
nickname?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 1024, nullable: true })
|
||||||
|
avatarUrl?: string;
|
||||||
|
|
||||||
|
@Column({ type: 'varchar', length: 32, default: 'active' })
|
||||||
|
status: string;
|
||||||
|
|
||||||
|
@CreateDateColumn()
|
||||||
|
createdAt: Date;
|
||||||
|
|
||||||
|
@UpdateDateColumn()
|
||||||
|
updatedAt: Date;
|
||||||
|
}
|
||||||
10
src/modules/users/interfaces/user-record.interface.ts
Normal file
10
src/modules/users/interfaces/user-record.interface.ts
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
export interface UserRecord {
|
||||||
|
id: number;
|
||||||
|
tiktokOpenId: string;
|
||||||
|
tiktokUnionId?: string;
|
||||||
|
nickname?: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
status: 'active' | 'disabled';
|
||||||
|
createdAt: string;
|
||||||
|
updatedAt: string;
|
||||||
|
}
|
||||||
36
src/modules/users/users.controller.ts
Normal file
36
src/modules/users/users.controller.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { Body, Controller, Get, Param, Patch, Query, UseGuards } from '@nestjs/common';
|
||||||
|
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||||
|
import { RequirePermissions } from '../admin/decorators/require-permissions.decorator';
|
||||||
|
import { AdminJwtAuthGuard } from '../admin/guards/admin-jwt-auth.guard';
|
||||||
|
import { PermissionsGuard } from '../admin/guards/permissions.guard';
|
||||||
|
import { UpdateUserStatusDto } from './dto/update-user-status.dto';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
@ApiTags('Users')
|
||||||
|
@Controller('/api/admin/v1/users')
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AdminJwtAuthGuard, PermissionsGuard)
|
||||||
|
export class UsersController {
|
||||||
|
constructor(private readonly usersService: UsersService) {}
|
||||||
|
|
||||||
|
@Get()
|
||||||
|
@RequirePermissions('user:read')
|
||||||
|
listUsers(@Query('page') page?: string, @Query('pageSize') pageSize?: string) {
|
||||||
|
return this.usersService.listUsers({
|
||||||
|
page: Number(page) || 1,
|
||||||
|
pageSize: Number(pageSize) || 20,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('/:id')
|
||||||
|
@RequirePermissions('user:read')
|
||||||
|
getUser(@Param('id') id: string) {
|
||||||
|
return this.usersService.getUserOrThrow(Number(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch('/:id/status')
|
||||||
|
@RequirePermissions('user:update')
|
||||||
|
updateStatus(@Param('id') id: string, @Body() dto: UpdateUserStatusDto) {
|
||||||
|
return this.usersService.updateStatus(Number(id), dto.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
12
src/modules/users/users.module.ts
Normal file
12
src/modules/users/users.module.ts
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { AdminModule } from '../admin/admin.module';
|
||||||
|
import { UsersController } from './users.controller';
|
||||||
|
import { UsersService } from './users.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [AdminModule],
|
||||||
|
controllers: [UsersController],
|
||||||
|
providers: [UsersService],
|
||||||
|
exports: [UsersService],
|
||||||
|
})
|
||||||
|
export class UsersModule {}
|
||||||
92
src/modules/users/users.service.ts
Normal file
92
src/modules/users/users.service.ts
Normal file
@@ -0,0 +1,92 @@
|
|||||||
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import { PaginatedResponse } from '../../common/dto/paginated-response.dto';
|
||||||
|
import { UserRecord } from './interfaces/user-record.interface';
|
||||||
|
|
||||||
|
interface UpsertTikTokUserInput {
|
||||||
|
tiktokOpenId: string;
|
||||||
|
tiktokUnionId?: string;
|
||||||
|
nickname?: string;
|
||||||
|
avatarUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PaginationInput {
|
||||||
|
page: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class UsersService {
|
||||||
|
private userSequence = 1;
|
||||||
|
private readonly users: UserRecord[] = [];
|
||||||
|
|
||||||
|
upsertTikTokUser(input: UpsertTikTokUserInput) {
|
||||||
|
const existing = this.users.find(
|
||||||
|
(user) => user.tiktokOpenId === input.tiktokOpenId,
|
||||||
|
);
|
||||||
|
const now = new Date().toISOString();
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
existing.tiktokUnionId = input.tiktokUnionId ?? existing.tiktokUnionId;
|
||||||
|
existing.nickname = input.nickname ?? existing.nickname;
|
||||||
|
existing.avatarUrl = input.avatarUrl ?? existing.avatarUrl;
|
||||||
|
existing.updatedAt = now;
|
||||||
|
return { user: existing, isNewUser: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
const user: UserRecord = {
|
||||||
|
id: this.userSequence++,
|
||||||
|
tiktokOpenId: input.tiktokOpenId,
|
||||||
|
tiktokUnionId: input.tiktokUnionId,
|
||||||
|
nickname: input.nickname,
|
||||||
|
avatarUrl: input.avatarUrl,
|
||||||
|
status: 'active',
|
||||||
|
createdAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.users.push(user);
|
||||||
|
return { user, isNewUser: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
findById(id: number) {
|
||||||
|
return this.users.find((user) => user.id === id);
|
||||||
|
}
|
||||||
|
|
||||||
|
listUsers(pagination: PaginationInput): PaginatedResponse<UserRecord> {
|
||||||
|
return this.paginate([...this.users].reverse(), pagination);
|
||||||
|
}
|
||||||
|
|
||||||
|
getUserOrThrow(id: number) {
|
||||||
|
const user = this.findById(id);
|
||||||
|
if (!user) {
|
||||||
|
throw new NotFoundException('User not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
updateStatus(id: number, status: 'active' | 'disabled') {
|
||||||
|
const user = this.getUserOrThrow(id);
|
||||||
|
user.status = status;
|
||||||
|
user.updatedAt = new Date().toISOString();
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
private paginate<T>(
|
||||||
|
records: T[],
|
||||||
|
input: PaginationInput,
|
||||||
|
): PaginatedResponse<T> {
|
||||||
|
const page = Math.max(input.page, 1);
|
||||||
|
const pageSize = Math.min(Math.max(input.pageSize, 1), 100);
|
||||||
|
const start = (page - 1) * pageSize;
|
||||||
|
|
||||||
|
return {
|
||||||
|
list: records.slice(start, start + pageSize),
|
||||||
|
pagination: {
|
||||||
|
page,
|
||||||
|
pageSize,
|
||||||
|
total: records.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
375
test/admin-permissions-users.e2e-spec.ts
Normal file
375
test/admin-permissions-users.e2e-spec.ts
Normal file
@@ -0,0 +1,375 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('Admin permissions and user management', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let superAdminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
superAdminToken = await loginAdmin(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires admin authentication for admin APIs', async () => {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/users')
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
expect(response.body).toMatchObject({
|
||||||
|
code: 401,
|
||||||
|
data: {},
|
||||||
|
message: 'Admin not authenticated',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates permissions, roles, admin users, and enforces permission checks', async () => {
|
||||||
|
const permissions = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/permissions')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
expect(permissions.body.data.list).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
code: 'permission:read',
|
||||||
|
name: '查看权限',
|
||||||
|
}),
|
||||||
|
expect.objectContaining({
|
||||||
|
code: 'permission:create',
|
||||||
|
name: '创建权限',
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const dramaReadPermission = permissions.body.data.list.find(
|
||||||
|
(permission: { code: string }) => permission.code === 'drama:read',
|
||||||
|
);
|
||||||
|
|
||||||
|
const role = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/roles')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
code: 'drama_viewer',
|
||||||
|
name: 'Drama Viewer',
|
||||||
|
description: 'Can only view dramas',
|
||||||
|
permissionIds: [dramaReadPermission.id],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const admin = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/admin-users')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
username: 'viewer',
|
||||||
|
password: 'viewer123',
|
||||||
|
nickname: 'Viewer',
|
||||||
|
email: 'viewer@example.com',
|
||||||
|
roleIds: [role.body.data.id],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(admin.body.data).toMatchObject({
|
||||||
|
username: 'viewer',
|
||||||
|
nickname: 'Viewer',
|
||||||
|
email: 'viewer@example.com',
|
||||||
|
status: 'active',
|
||||||
|
roles: [expect.objectContaining({ code: 'drama_viewer' })],
|
||||||
|
});
|
||||||
|
expect(admin.body.data.passwordHash).toBeUndefined();
|
||||||
|
|
||||||
|
const viewerLogin = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({ username: 'viewer', password: 'viewer123' })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${viewerLogin.body.data.accessToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
const forbidden = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${viewerLogin.body.data.accessToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Forbidden Create',
|
||||||
|
coverUrl: 'https://cdn.example.com/forbidden.jpg',
|
||||||
|
type: 'test',
|
||||||
|
status: 'draft',
|
||||||
|
})
|
||||||
|
.expect(403);
|
||||||
|
|
||||||
|
expect(forbidden.body).toMatchObject({
|
||||||
|
code: 403,
|
||||||
|
data: {},
|
||||||
|
message: 'No permission',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('updates role permissions from the role permission assignment endpoint', async () => {
|
||||||
|
const permissions = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/permissions')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
const dramaReadPermission = permissions.body.data.list.find(
|
||||||
|
(permission: { code: string }) => permission.code === 'drama:read',
|
||||||
|
);
|
||||||
|
|
||||||
|
const role = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/roles')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
code: 'assignable_role',
|
||||||
|
name: 'Assignable Role',
|
||||||
|
description: 'Role permissions can be assigned later',
|
||||||
|
permissionIds: [],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const updatedRole = await request(app.getHttpServer())
|
||||||
|
.patch(`/api/admin/v1/roles/${role.body.data.id}/permissions`)
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({ permissionIds: [dramaReadPermission.id] })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(updatedRole.body.data).toMatchObject({
|
||||||
|
id: role.body.data.id,
|
||||||
|
permissionIds: [dramaReadPermission.id],
|
||||||
|
permissions: [expect.objectContaining({ code: 'drama:read' })],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates roles with assigned permissions and rejects duplicate role codes', async () => {
|
||||||
|
const permissions = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/permissions')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
const roleReadPermission = permissions.body.data.list.find(
|
||||||
|
(permission: { code: string }) => permission.code === 'role:read',
|
||||||
|
);
|
||||||
|
const roleCreatePermission = permissions.body.data.list.find(
|
||||||
|
(permission: { code: string }) => permission.code === 'role:create',
|
||||||
|
);
|
||||||
|
|
||||||
|
const createdRole = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/roles')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
code: 'system_operator',
|
||||||
|
name: 'System Operator',
|
||||||
|
description: 'Can manage system roles',
|
||||||
|
permissionIds: [roleReadPermission.id, roleCreatePermission.id],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(createdRole.body.data).toMatchObject({
|
||||||
|
code: 'system_operator',
|
||||||
|
name: 'System Operator',
|
||||||
|
permissionIds: [roleReadPermission.id, roleCreatePermission.id],
|
||||||
|
permissions: [
|
||||||
|
expect.objectContaining({ code: 'role:read' }),
|
||||||
|
expect.objectContaining({ code: 'role:create' }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const duplicate = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/roles')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
code: 'system_operator',
|
||||||
|
name: 'Duplicated System Operator',
|
||||||
|
})
|
||||||
|
.expect(409);
|
||||||
|
|
||||||
|
expect(duplicate.body).toMatchObject({
|
||||||
|
code: 409,
|
||||||
|
data: {},
|
||||||
|
message: 'Role code already exists',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows the current admin to change password with the old password', async () => {
|
||||||
|
const admin = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/admin-users')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
username: 'password-user',
|
||||||
|
password: 'oldpass123',
|
||||||
|
nickname: 'Password User',
|
||||||
|
email: 'password-user@example.com',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(admin.body.data.passwordHash).toBeUndefined();
|
||||||
|
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({ username: 'password-user', password: 'oldpass123' })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.patch('/api/admin/v1/auth/password')
|
||||||
|
.set('Authorization', `Bearer ${login.body.data.accessToken}`)
|
||||||
|
.send({ oldPassword: 'wrongpass', newPassword: 'newpass123' })
|
||||||
|
.expect(422);
|
||||||
|
|
||||||
|
const changed = await request(app.getHttpServer())
|
||||||
|
.patch('/api/admin/v1/auth/password')
|
||||||
|
.set('Authorization', `Bearer ${login.body.data.accessToken}`)
|
||||||
|
.send({ oldPassword: 'oldpass123', newPassword: 'newpass123' })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(changed.body.data).toEqual({});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({ username: 'password-user', password: 'oldpass123' })
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({ username: 'password-user', password: 'newpass123' })
|
||||||
|
.expect(201);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows the current admin to view and update profile information', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/admin-users')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
username: 'profile-user',
|
||||||
|
password: 'profile123',
|
||||||
|
nickname: 'Profile User',
|
||||||
|
email: 'profile-user@example.com',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({ username: 'profile-user', password: 'profile123' })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const updated = await request(app.getHttpServer())
|
||||||
|
.patch('/api/admin/v1/auth/profile')
|
||||||
|
.set('Authorization', `Bearer ${login.body.data.accessToken}`)
|
||||||
|
.send({
|
||||||
|
nickname: 'Updated Profile User',
|
||||||
|
email: 'updated-profile-user@example.com',
|
||||||
|
})
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(updated.body.data).toMatchObject({
|
||||||
|
username: 'profile-user',
|
||||||
|
nickname: 'Updated Profile User',
|
||||||
|
email: 'updated-profile-user@example.com',
|
||||||
|
});
|
||||||
|
expect(updated.body.data.passwordHash).toBeUndefined();
|
||||||
|
|
||||||
|
const profile = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/auth/profile')
|
||||||
|
.set('Authorization', `Bearer ${login.body.data.accessToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(profile.body.data).toMatchObject({
|
||||||
|
username: 'profile-user',
|
||||||
|
nickname: 'Updated Profile User',
|
||||||
|
email: 'updated-profile-user@example.com',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('assigns roles to existing admin users', async () => {
|
||||||
|
const permissions = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/permissions')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
const userReadPermission = permissions.body.data.list.find(
|
||||||
|
(permission: { code: string }) => permission.code === 'user:read',
|
||||||
|
);
|
||||||
|
|
||||||
|
const role = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/roles')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
code: 'user_reader',
|
||||||
|
name: 'User Reader',
|
||||||
|
permissionIds: [userReadPermission.id],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const admin = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/admin-users')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({
|
||||||
|
username: 'role-assignee',
|
||||||
|
password: 'assign123',
|
||||||
|
nickname: 'Role Assignee',
|
||||||
|
email: 'role-assignee@example.com',
|
||||||
|
roleIds: [],
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const assigned = await request(app.getHttpServer())
|
||||||
|
.patch(`/api/admin/v1/admin-users/${admin.body.data.id}/roles`)
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({ roleIds: [role.body.data.id] })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(assigned.body.data).toMatchObject({
|
||||||
|
id: admin.body.data.id,
|
||||||
|
roles: [expect.objectContaining({ code: 'user_reader' })],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists and updates app users from admin APIs', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/auth/tiktok-login')
|
||||||
|
.send({
|
||||||
|
code: 'user-management-code',
|
||||||
|
mockOpenId: 'open-user-management',
|
||||||
|
nickname: 'Managed User',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const users = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/users')
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(users.body.data.list).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
tiktokOpenId: 'open-user-management',
|
||||||
|
nickname: 'Managed User',
|
||||||
|
status: 'active',
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const managedUser = users.body.data.list.find(
|
||||||
|
(user: { tiktokOpenId: string }) =>
|
||||||
|
user.tiktokOpenId === 'open-user-management',
|
||||||
|
);
|
||||||
|
|
||||||
|
const disabled = await request(app.getHttpServer())
|
||||||
|
.patch(`/api/admin/v1/users/${managedUser.id}/status`)
|
||||||
|
.set('Authorization', `Bearer ${superAdminToken}`)
|
||||||
|
.send({ status: 'disabled' })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(disabled.body.data).toMatchObject({
|
||||||
|
id: managedUser.id,
|
||||||
|
status: 'disabled',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
111
test/api-standard.e2e-spec.ts
Normal file
111
test/api-standard.e2e-spec.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { validate as validateUuid, version as uuidVersion } from 'uuid';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('API standard', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let adminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
adminToken = await loginAdmin(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('wraps successful responses with code, data, message, timestamp, requestId and cost', async () => {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/app/v1/health')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(response.body).toEqual({
|
||||||
|
code: 0,
|
||||||
|
data: { status: 'ok' },
|
||||||
|
message: 'success',
|
||||||
|
timestamp: expect.any(Number),
|
||||||
|
requestId: expect.any(String),
|
||||||
|
cost: expect.stringMatching(/^\d+ms$/),
|
||||||
|
});
|
||||||
|
expect(validateUuid(response.body.requestId)).toBe(true);
|
||||||
|
expect(uuidVersion(response.body.requestId)).toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('reuses a valid X-Request-Id header', async () => {
|
||||||
|
const requestId = '0f5c2e16-1e44-4d55-93a4-ef7c66d9d1f2';
|
||||||
|
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/app/v1/health')
|
||||||
|
.set('X-Request-Id', requestId)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(response.body.requestId).toBe(requestId);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('wraps errors in the standard response shape', async () => {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/app/v1/missing')
|
||||||
|
.expect(404);
|
||||||
|
|
||||||
|
expect(response.body).toEqual({
|
||||||
|
code: 404,
|
||||||
|
data: {},
|
||||||
|
message: expect.any(String),
|
||||||
|
timestamp: expect.any(Number),
|
||||||
|
requestId: expect.any(String),
|
||||||
|
cost: expect.stringMatching(/^\d+ms$/),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns paginated lists using data.list and data.pagination', async () => {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/logs/requests')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(response.body.code).toBe(0);
|
||||||
|
expect(response.body.data).toEqual({
|
||||||
|
list: expect.any(Array),
|
||||||
|
pagination: {
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
total: expect.any(Number),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('can query a request log by requestId', async () => {
|
||||||
|
const requestId = '180facd4-68f9-48c9-b6b1-3d8eab56a681';
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/app/v1/health')
|
||||||
|
.set('X-Request-Id', requestId)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get(`/api/admin/v1/logs/requests/${requestId}`)
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(response.body.data).toMatchObject({
|
||||||
|
requestId,
|
||||||
|
method: 'GET',
|
||||||
|
path: '/api/app/v1/health',
|
||||||
|
statusCode: 200,
|
||||||
|
responseCode: 0,
|
||||||
|
message: 'success',
|
||||||
|
});
|
||||||
|
expect(response.body.data.costMs).toEqual(expect.any(Number));
|
||||||
|
});
|
||||||
|
});
|
||||||
237
test/core-modules.e2e-spec.ts
Normal file
237
test/core-modules.e2e-spec.ts
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('Core drama platform modules', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let adminToken: string;
|
||||||
|
let userToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
adminToken = await loginAdmin(app);
|
||||||
|
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/auth/tiktok-login')
|
||||||
|
.send({
|
||||||
|
code: 'core-modules-code',
|
||||||
|
mockOpenId: 'core-open-id',
|
||||||
|
nickname: 'Core User',
|
||||||
|
avatarUrl: 'https://cdn.example.com/avatar.png',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
userToken = login.body.data.accessToken;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates albums and episodes with TikTok, media, review, publish, and pricing fields', async () => {
|
||||||
|
const cover = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/media/covers')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
fileName: 'cover.jpg',
|
||||||
|
url: 'https://cdn.example.com/cover.jpg',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const uploadJob = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/media/upload-jobs')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
jobId: 'job-001',
|
||||||
|
byteplusVid: 'v02-byteplus-001',
|
||||||
|
status: 'completed',
|
||||||
|
rawResponse: { provider: 'byteplus' },
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(uploadJob.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
jobId: 'job-001',
|
||||||
|
byteplusVid: 'v02-byteplus-001',
|
||||||
|
status: 'completed',
|
||||||
|
rawResponse: { provider: 'byteplus' },
|
||||||
|
});
|
||||||
|
|
||||||
|
const album = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
tiktokAlbumId: 'tk-album-001',
|
||||||
|
title: 'Core Album',
|
||||||
|
description: 'Album for core schema.',
|
||||||
|
coverId: cover.body.data.id,
|
||||||
|
coverUrl: cover.body.data.url,
|
||||||
|
type: 'revenge',
|
||||||
|
status: 'draft',
|
||||||
|
onlineVersion: 1,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(album.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
tiktokAlbumId: 'tk-album-001',
|
||||||
|
title: 'Core Album',
|
||||||
|
coverId: cover.body.data.id,
|
||||||
|
coverUrl: 'https://cdn.example.com/cover.jpg',
|
||||||
|
status: 'draft',
|
||||||
|
onlineVersion: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const episode = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
tiktokEpisodeId: 'tk-episode-001',
|
||||||
|
seq: 1,
|
||||||
|
title: 'Core Episode 1',
|
||||||
|
byteplusVid: 'v02-byteplus-001',
|
||||||
|
coverId: cover.body.data.id,
|
||||||
|
coverUrl: cover.body.data.url,
|
||||||
|
videoUrl: 'https://cdn.example.com/episode.mp4',
|
||||||
|
freeType: 'paid',
|
||||||
|
price: 299,
|
||||||
|
reviewStatus: 'pending',
|
||||||
|
publishStatus: 'draft',
|
||||||
|
durationSeconds: 300,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(episode.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
tiktokEpisodeId: 'tk-episode-001',
|
||||||
|
seq: 1,
|
||||||
|
byteplusVid: 'v02-byteplus-001',
|
||||||
|
coverId: cover.body.data.id,
|
||||||
|
freeType: 'paid',
|
||||||
|
price: 299,
|
||||||
|
reviewStatus: 'pending',
|
||||||
|
publishStatus: 'draft',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('supports review submission, publish status changes, player auth, trade orders, webhook unlocks, and unlock records', async () => {
|
||||||
|
const album = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Player Album',
|
||||||
|
coverUrl: 'https://cdn.example.com/player-cover.jpg',
|
||||||
|
type: 'player',
|
||||||
|
status: 'published',
|
||||||
|
onlineVersion: 1,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const episode = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
seq: 1,
|
||||||
|
title: 'Paid Player Episode',
|
||||||
|
byteplusVid: 'v02-player-001',
|
||||||
|
coverUrl: 'https://cdn.example.com/player-episode.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/player-episode.mp4',
|
||||||
|
freeType: 'paid',
|
||||||
|
price: 399,
|
||||||
|
reviewStatus: 'approved',
|
||||||
|
publishStatus: 'published',
|
||||||
|
durationSeconds: 300,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post(`/api/admin/v1/dramas/${album.body.data.id}/submit-review`)
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.patch(`/api/admin/v1/episodes/${episode.body.data.id}/publish-status`)
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({ publishStatus: 'published' })
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
const lockedPlayer = await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/player/episodes/${episode.body.data.id}`)
|
||||||
|
.set('Authorization', `Bearer ${userToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(lockedPlayer.body.data).toMatchObject({
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
vid: 'v02-player-001',
|
||||||
|
hasPermission: false,
|
||||||
|
playAuthToken: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const order = await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/orders')
|
||||||
|
.set('Authorization', `Bearer ${userToken}`)
|
||||||
|
.send({ episodeId: episode.body.data.id })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(order.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
tradeOrderId: expect.stringMatching(/^TRADE/),
|
||||||
|
amount: 399,
|
||||||
|
status: 'pending',
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/webhooks/tiktok/payments')
|
||||||
|
.send({
|
||||||
|
tradeOrderId: order.body.data.tradeOrderId,
|
||||||
|
tiktokOrderId: 'tk-order-001',
|
||||||
|
providerTransactionId: 'txn-core-001',
|
||||||
|
status: 'paid',
|
||||||
|
signature: 'dev-signature',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const unlockedPlayer = await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/player/episodes/${episode.body.data.id}`)
|
||||||
|
.set('Authorization', `Bearer ${userToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(unlockedPlayer.body.data).toMatchObject({
|
||||||
|
albumId: album.body.data.id,
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
vid: 'v02-player-001',
|
||||||
|
hasPermission: true,
|
||||||
|
playAuthToken: expect.stringMatching(/^play_auth_/),
|
||||||
|
});
|
||||||
|
|
||||||
|
const unlocks = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/unlock-records')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(unlocks.body.data.list).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
userId: expect.any(Number),
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
source: 'payment',
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
200
test/dramas.e2e-spec.ts
Normal file
200
test/dramas.e2e-spec.ts
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('Dramas and episodes', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let adminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
adminToken = await loginAdmin(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows admin APIs to create a drama and episodes with release metadata', async () => {
|
||||||
|
const dramaResponse = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'City Revenge',
|
||||||
|
description: 'A short drama series.',
|
||||||
|
coverUrl: 'https://cdn.example.com/cover.jpg',
|
||||||
|
portraitCoverUrl: 'https://cdn.example.com/portrait.jpg',
|
||||||
|
landscapeCoverUrl: 'https://cdn.example.com/landscape.jpg',
|
||||||
|
type: 'revenge',
|
||||||
|
tags: ['urban', 'revenge'],
|
||||||
|
region: 'US',
|
||||||
|
language: 'en',
|
||||||
|
year: 2026,
|
||||||
|
status: 'published',
|
||||||
|
sortOrder: 10,
|
||||||
|
isRecommended: true,
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(dramaResponse.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
title: 'City Revenge',
|
||||||
|
status: 'published',
|
||||||
|
type: 'revenge',
|
||||||
|
});
|
||||||
|
|
||||||
|
const dramaId = dramaResponse.body.data.id;
|
||||||
|
const episodeResponse = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
dramaId,
|
||||||
|
episodeNo: 1,
|
||||||
|
title: 'Episode 1',
|
||||||
|
description: 'Opening episode.',
|
||||||
|
coverUrl: 'https://cdn.example.com/ep1.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/ep1.mp4',
|
||||||
|
trialDurationSeconds: 60,
|
||||||
|
durationSeconds: 300,
|
||||||
|
isPaid: true,
|
||||||
|
unlockPrice: 199,
|
||||||
|
publishAt: '2026-07-01T00:00:00.000Z',
|
||||||
|
nextReleaseAt: '2026-07-02T00:00:00.000Z',
|
||||||
|
status: 'published',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(episodeResponse.body.data).toMatchObject({
|
||||||
|
id: expect.any(Number),
|
||||||
|
dramaId,
|
||||||
|
episodeNo: 1,
|
||||||
|
nextReleaseAt: '2026-07-02T00:00:00.000Z',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects duplicate episode numbers under the same drama', async () => {
|
||||||
|
const drama = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Duplicate Episode Test',
|
||||||
|
coverUrl: 'https://cdn.example.com/cover.jpg',
|
||||||
|
type: 'romance',
|
||||||
|
status: 'draft',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
dramaId: drama.body.data.id,
|
||||||
|
episodeNo: 1,
|
||||||
|
title: 'Episode 1',
|
||||||
|
coverUrl: 'https://cdn.example.com/ep1.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/ep1.mp4',
|
||||||
|
durationSeconds: 300,
|
||||||
|
status: 'draft',
|
||||||
|
};
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send(payload)
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const duplicate = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send(payload)
|
||||||
|
.expect(409);
|
||||||
|
|
||||||
|
expect(duplicate.body).toMatchObject({
|
||||||
|
code: 409,
|
||||||
|
data: {},
|
||||||
|
message: 'Episode number already exists in this drama',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns only published dramas and published episodes to app APIs', async () => {
|
||||||
|
const published = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Published Drama',
|
||||||
|
coverUrl: 'https://cdn.example.com/pub.jpg',
|
||||||
|
type: 'action',
|
||||||
|
status: 'published',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Draft Drama',
|
||||||
|
coverUrl: 'https://cdn.example.com/draft.jpg',
|
||||||
|
type: 'action',
|
||||||
|
status: 'draft',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
dramaId: published.body.data.id,
|
||||||
|
episodeNo: 1,
|
||||||
|
title: 'Published Episode',
|
||||||
|
coverUrl: 'https://cdn.example.com/ep1.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/ep1.mp4',
|
||||||
|
durationSeconds: 300,
|
||||||
|
status: 'published',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
dramaId: published.body.data.id,
|
||||||
|
episodeNo: 2,
|
||||||
|
title: 'Draft Episode',
|
||||||
|
coverUrl: 'https://cdn.example.com/ep2.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/ep2.mp4',
|
||||||
|
durationSeconds: 300,
|
||||||
|
status: 'draft',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const dramas = await request(app.getHttpServer())
|
||||||
|
.get('/api/app/v1/dramas')
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(dramas.body.data.list).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ title: 'Published Drama' }),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(dramas.body.data.list).not.toEqual(
|
||||||
|
expect.arrayContaining([expect.objectContaining({ title: 'Draft Drama' })]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const episodes = await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/dramas/${published.body.data.id}/episodes`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(episodes.body.data.list).toEqual([
|
||||||
|
expect.objectContaining({
|
||||||
|
episodeNo: 1,
|
||||||
|
title: 'Published Episode',
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
10
test/jest-e2e.json
Normal file
10
test/jest-e2e.json
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"moduleFileExtensions": ["js", "json", "ts"],
|
||||||
|
"rootDir": "..",
|
||||||
|
"testEnvironment": "node",
|
||||||
|
"testRegex": ".e2e-spec.ts$",
|
||||||
|
"watchman": false,
|
||||||
|
"transform": {
|
||||||
|
"^.+\\.(t|j)s$": "ts-jest"
|
||||||
|
}
|
||||||
|
}
|
||||||
131
test/orders-playback.e2e-spec.ts
Normal file
131
test/orders-playback.e2e-spec.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('Auth, orders, and playback', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let adminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
adminToken = await loginAdmin(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('logs in with TikTok identity, creates an order, and unlocks paid playback through an idempotent payment webhook', async () => {
|
||||||
|
const login = await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/auth/tiktok-login')
|
||||||
|
.send({
|
||||||
|
code: 'test-code',
|
||||||
|
mockOpenId: 'open-user-1',
|
||||||
|
nickname: 'Tester',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(login.body.data).toMatchObject({
|
||||||
|
accessToken: expect.any(String),
|
||||||
|
user: {
|
||||||
|
id: expect.any(Number),
|
||||||
|
tiktokOpenId: 'open-user-1',
|
||||||
|
nickname: 'Tester',
|
||||||
|
},
|
||||||
|
isNewUser: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const token = login.body.data.accessToken;
|
||||||
|
const drama = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/dramas')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
title: 'Paid Drama',
|
||||||
|
coverUrl: 'https://cdn.example.com/paid.jpg',
|
||||||
|
type: 'paid',
|
||||||
|
status: 'published',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const episode = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/episodes')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.send({
|
||||||
|
dramaId: drama.body.data.id,
|
||||||
|
episodeNo: 1,
|
||||||
|
title: 'Paid Episode',
|
||||||
|
coverUrl: 'https://cdn.example.com/paid-ep.jpg',
|
||||||
|
videoUrl: 'https://cdn.example.com/paid-ep.mp4',
|
||||||
|
durationSeconds: 300,
|
||||||
|
isPaid: true,
|
||||||
|
unlockPrice: 199,
|
||||||
|
status: 'published',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/episodes/${episode.body.data.id}/play`)
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
const lockedPlay = await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/episodes/${episode.body.data.id}/play`)
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(lockedPlay.body.data).toMatchObject({
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
isLocked: true,
|
||||||
|
videoUrl: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const order = await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/orders')
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.send({ episodeId: episode.body.data.id })
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(order.body.data).toMatchObject({
|
||||||
|
orderNo: expect.any(String),
|
||||||
|
status: 'pending',
|
||||||
|
amount: 199,
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/webhooks/tiktok/payments')
|
||||||
|
.send({
|
||||||
|
orderNo: order.body.data.orderNo,
|
||||||
|
providerTransactionId: 'txn-1',
|
||||||
|
status: 'paid',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/webhooks/tiktok/payments')
|
||||||
|
.send({
|
||||||
|
orderNo: order.body.data.orderNo,
|
||||||
|
providerTransactionId: 'txn-1',
|
||||||
|
status: 'paid',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
const unlockedPlay = await request(app.getHttpServer())
|
||||||
|
.get(`/api/app/v1/episodes/${episode.body.data.id}/play`)
|
||||||
|
.set('Authorization', `Bearer ${token}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(unlockedPlay.body.data).toMatchObject({
|
||||||
|
episodeId: episode.body.data.id,
|
||||||
|
isLocked: false,
|
||||||
|
videoUrl: 'https://cdn.example.com/paid-ep.mp4',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
77
test/playback-error.e2e-spec.ts
Normal file
77
test/playback-error.e2e-spec.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
import { AppModule } from '../src/app.module';
|
||||||
|
import { bootstrapApp } from '../src/bootstrap';
|
||||||
|
import { loginAdmin } from './test-helpers';
|
||||||
|
|
||||||
|
describe('Playback error logs', () => {
|
||||||
|
let app: INestApplication;
|
||||||
|
let adminToken: string;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
}).compile();
|
||||||
|
|
||||||
|
app = moduleRef.createNestApplication();
|
||||||
|
bootstrapApp(app);
|
||||||
|
await app.init();
|
||||||
|
adminToken = await loginAdmin(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts playback error reports and exposes them to admin logs', async () => {
|
||||||
|
const requestId = 'aac95ef4-c546-427d-88c7-25b15b396b91';
|
||||||
|
|
||||||
|
const createResponse = await request(app.getHttpServer())
|
||||||
|
.post('/api/app/v1/logs/playback-errors')
|
||||||
|
.set('X-Request-Id', requestId)
|
||||||
|
.send({
|
||||||
|
requestId,
|
||||||
|
dramaId: 1,
|
||||||
|
episodeId: 10,
|
||||||
|
playUrl: 'https://cdn.example.com/video.mp4',
|
||||||
|
playerErrorCode: 'MEDIA_DECODE_ERROR',
|
||||||
|
message: 'Video decode failed',
|
||||||
|
progressSeconds: 128,
|
||||||
|
networkType: 'wifi',
|
||||||
|
device: {
|
||||||
|
platform: 'ios',
|
||||||
|
model: 'iPhone',
|
||||||
|
systemVersion: '17.0',
|
||||||
|
appVersion: '1.0.0',
|
||||||
|
},
|
||||||
|
occurredAt: '2026-06-30T00:00:00.000Z',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
expect(createResponse.body).toMatchObject({
|
||||||
|
code: 0,
|
||||||
|
data: {
|
||||||
|
id: expect.any(Number),
|
||||||
|
requestId,
|
||||||
|
},
|
||||||
|
message: 'success',
|
||||||
|
requestId,
|
||||||
|
});
|
||||||
|
|
||||||
|
const listResponse = await request(app.getHttpServer())
|
||||||
|
.get('/api/admin/v1/logs/playback-errors')
|
||||||
|
.set('Authorization', `Bearer ${adminToken}`)
|
||||||
|
.expect(200);
|
||||||
|
|
||||||
|
expect(listResponse.body.data.list).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({
|
||||||
|
requestId,
|
||||||
|
playerErrorCode: 'MEDIA_DECODE_ERROR',
|
||||||
|
progressSeconds: 128,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
14
test/test-helpers.ts
Normal file
14
test/test-helpers.ts
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import * as request from 'supertest';
|
||||||
|
|
||||||
|
export async function loginAdmin(app: INestApplication) {
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/v1/auth/login')
|
||||||
|
.send({
|
||||||
|
username: 'admin',
|
||||||
|
password: 'admin123',
|
||||||
|
})
|
||||||
|
.expect(201);
|
||||||
|
|
||||||
|
return response.body.data.accessToken as string;
|
||||||
|
}
|
||||||
4
tsconfig.build.json
Normal file
4
tsconfig.build.json
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"extends": "./tsconfig.json",
|
||||||
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
|
}
|
||||||
19
tsconfig.json
Normal file
19
tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"module": "commonjs",
|
||||||
|
"declaration": true,
|
||||||
|
"removeComments": true,
|
||||||
|
"emitDecoratorMetadata": true,
|
||||||
|
"experimentalDecorators": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"target": "ES2023",
|
||||||
|
"sourceMap": true,
|
||||||
|
"outDir": "./dist",
|
||||||
|
"baseUrl": "./",
|
||||||
|
"incremental": true,
|
||||||
|
"strict": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"strictPropertyInitialization": false,
|
||||||
|
"noImplicitAny": false
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user