first commit
This commit is contained in:
commit
3307ca6359
40
AGENTS.md
Normal file
40
AGENTS.md
Normal file
@ -0,0 +1,40 @@
|
||||
# 仓库指南
|
||||
|
||||
## 项目结构与模块划分
|
||||
本仓库分为 `frontend/` 和 `backend/` 两部分。业务代码只放在 `frontend/src/` 与 `backend/src/`;`dist/`、`node_modules/` 视为生成产物,不要在里面改业务逻辑。前端主要目录有 `src/views/`、`src/components/`、`src/api/`、`src/stores/`、`src/router/`。后端按 Express 常见分层组织:`src/routes/`、`src/controllers/`、`src/middleware/`、`src/utils/`。数据库结构在 `backend/prisma/schema.prisma`。
|
||||
|
||||
## 构建、运行与验证命令
|
||||
- `cd frontend && npm run dev`:启动前端开发服务,默认地址 `http://localhost:5173`
|
||||
- `cd frontend && npm run build`:执行前端类型检查并构建
|
||||
- `cd backend && npm run dev`:启动后端开发服务
|
||||
- `cd backend && npm run build`:编译后端 TypeScript
|
||||
- `cd backend && npm run prisma:generate`:生成 Prisma Client
|
||||
- `cd backend && npm run prisma:migrate`:执行本地数据库迁移
|
||||
- `docker-compose up -d`:同时启动 MySQL、后端、前端
|
||||
|
||||
## 代码风格与命名规范
|
||||
统一使用 TypeScript,缩进保持 2 个空格。Vue 组件使用 PascalCase,例如 `EquipmentList.vue`;接口模块、工具函数、状态文件使用 camelCase,例如 `equipment.ts`、`format.ts`。后端保持“路由进 `routes/`、处理进 `controllers/`、公共逻辑进 `utils/`”的现有结构。Prisma 模型名保持 PascalCase,数据库字段保持 snake_case。
|
||||
|
||||
## 测试与验证要求
|
||||
当前仓库没有正式的自动化测试体系。每次改动后,至少执行 `frontend` 和 `backend` 的构建检查,并手工验证受影响流程,重点关注登录、设备增删改查、借出扫码、归还扫码、统计页面。以后如果补测试,建议放在对应功能旁边或单独的 `tests/` 目录,并使用 `*.spec.ts` 命名。
|
||||
|
||||
## 提交与合并请求规范
|
||||
当前工作区看不到完整 Git 历史,提交信息建议使用“范围 + 动作”的简短格式,例如:`前端:修复借出页跳转`、`后端:校验设备编码唯一性`。每次提交尽量只做一类事情。提交合并请求时,应写明改动范围、是否涉及 Prisma 或环境变量、手工验证步骤;如果改了界面,附截图。
|
||||
|
||||
## 小团队多代理角色
|
||||
本项目建议使用小团队模式,不要把角色拆得过细。
|
||||
|
||||
- `结构分析代理`:只读分析 `frontend/src`、`backend/src`、`backend/prisma`,负责找页面入口、接口调用链、控制器位置、数据表关系和影响范围。
|
||||
- `前端执行代理`:只改 `frontend/`,负责页面、表单、路由、状态管理、前端接口接入。
|
||||
- `后端执行代理`:只改 `backend/src/`,负责路由、控制器、中间件、权限和返回结构。
|
||||
- `数据结构代理`:只在确实要改表结构或字段时使用,主要负责 `backend/prisma` 和直接相关的后端代码。
|
||||
|
||||
本项目的多代理协作规则:
|
||||
|
||||
- 跨前后端任务,先让 `结构分析代理` 把调用链和接口契约查清楚,再拆实现。
|
||||
- 不要让两个执行代理同时改同一层,避免互相覆盖。
|
||||
- 普通缺陷和页面调整不要动 `数据结构代理`。
|
||||
- 最终集成、构建检查和手工验证由主代理负责。
|
||||
|
||||
## 安全与配置提醒
|
||||
不要提交真实密钥或生产环境配置。后端配置放在 `backend/.env`,前端配置放在根目录或前端的 Vite 环境文件。共享或部署前,先检查 `docker-compose.yml` 里的端口和默认账号信息是否适合当前环境。
|
||||
106
README.md
Normal file
106
README.md
Normal file
@ -0,0 +1,106 @@
|
||||
# 摄影设备借还管理系统
|
||||
|
||||
## 项目简介
|
||||
|
||||
摄影设备借还管理系统是一个用于管理摄影设备库存、借用、归还的Web应用系统。系统提供设备信息管理、借用归还流程、库存统计、条码打印等功能,帮助管理人员高效管理摄影设备资源。
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 前端
|
||||
- **框架**: Vue.js 3 + TypeScript
|
||||
- **UI设计**: Apple Design System (Tailwind CSS)
|
||||
- **状态管理**: Pinia
|
||||
- **路由**: Vue Router 4
|
||||
- **HTTP客户端**: Axios
|
||||
- **图表库**: ECharts
|
||||
- **条码生成**: JsBarcode
|
||||
- **构建工具**: Vite
|
||||
|
||||
### 后端
|
||||
- **框架**: Node.js + Express + TypeScript
|
||||
- **数据库**: MySQL 8.0
|
||||
- **ORM**: Prisma
|
||||
- **身份认证**: Keycloak (待集成)
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
shebeiguanli/
|
||||
├── frontend/ # 前端项目
|
||||
│ ├── src/
|
||||
│ │ ├── api/ # API接口
|
||||
│ │ ├── components/# 组件
|
||||
│ │ ├── router/ # 路由配置
|
||||
│ │ ├── stores/ # 状态管理
|
||||
│ │ ├── views/ # 页面
|
||||
│ │ └── utils/ # 工具函数
|
||||
│ └── package.json
|
||||
├── backend/ # 后端项目
|
||||
│ ├── src/
|
||||
│ │ ├── controllers/# 控制器
|
||||
│ │ ├── routes/ # 路由
|
||||
│ │ ├── utils/ # 工具函数
|
||||
│ │ └── index.ts # 入口文件
|
||||
│ ├── prisma/ # Prisma配置
|
||||
│ └── package.json
|
||||
└── 开发文档.md # 开发文档
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 前端开发
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端服务运行在: http://localhost:5173
|
||||
|
||||
### 后端开发
|
||||
|
||||
1. 配置数据库连接(修改 `.env` 文件)
|
||||
2. 初始化数据库
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm install
|
||||
npx prisma generate
|
||||
npx prisma migrate dev
|
||||
npm run dev
|
||||
```
|
||||
|
||||
后端服务运行在: http://localhost:3000
|
||||
|
||||
### 数据库配置
|
||||
|
||||
在 `backend/.env` 文件中配置数据库连接:
|
||||
|
||||
```
|
||||
DATABASE_URL="mysql://root:password@localhost:3306/equipment_management?charset=utf8mb4"
|
||||
```
|
||||
|
||||
## 功能特性
|
||||
|
||||
- ✅ 设备管理(增删改查)
|
||||
- ✅ 设备编码自动生成和自定义录入
|
||||
- ✅ 设备价格信息管理
|
||||
- ✅ 扫码出库/入库功能
|
||||
- ✅ 借用归还管理
|
||||
- ✅ 统计分析(设备状态、价值统计)
|
||||
- ✅ Apple Design System UI设计
|
||||
- ⏳ 条码打印功能(待实现)
|
||||
- ⏳ Keycloak认证集成(待实现)
|
||||
|
||||
## 开发规范
|
||||
|
||||
- 前端严格遵循Apple官方UI设计规范
|
||||
- 使用TypeScript进行类型检查
|
||||
- 代码遵循ESLint规范
|
||||
- 使用Git进行版本控制
|
||||
|
||||
## 许可证
|
||||
|
||||
ISC
|
||||
|
||||
5
backend/.gitignore
vendored
Normal file
5
backend/.gitignore
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
.DS_Store
|
||||
*.log
|
||||
39
backend/Dockerfile
Normal file
39
backend/Dockerfile
Normal file
@ -0,0 +1,39 @@
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 安装 OpenSSL
|
||||
RUN apk add --no-cache openssl
|
||||
|
||||
# 安装所有依赖(包括 devDependencies 用于构建)
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
# 复制 Prisma 文件并生成客户端
|
||||
COPY prisma ./prisma
|
||||
RUN npx prisma generate
|
||||
|
||||
# 复制源代码并构建
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
# 生产镜像
|
||||
FROM node:20-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 安装 OpenSSL
|
||||
RUN apk add --no-cache openssl
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci --only=production
|
||||
|
||||
COPY --from=builder /app/dist ./dist
|
||||
COPY --from=builder /app/prisma ./prisma
|
||||
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
|
||||
|
||||
RUN npx prisma generate
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["sh", "-c", "npx prisma db push --accept-data-loss && node dist/index.js"]
|
||||
82
backend/README.md
Normal file
82
backend/README.md
Normal file
@ -0,0 +1,82 @@
|
||||
# 摄影设备借还系统 - 后端
|
||||
|
||||
## 技术栈
|
||||
|
||||
- Node.js + Express
|
||||
- TypeScript
|
||||
- Prisma ORM
|
||||
- MySQL 8.0
|
||||
|
||||
## 开发
|
||||
|
||||
1. 安装依赖
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. 配置数据库
|
||||
编辑 `.env` 文件,设置数据库连接:
|
||||
```
|
||||
DATABASE_URL="mysql://root:password@localhost:3306/equipment_management?charset=utf8mb4"
|
||||
```
|
||||
|
||||
3. 初始化数据库
|
||||
```bash
|
||||
npx prisma generate
|
||||
npx prisma migrate dev
|
||||
```
|
||||
|
||||
4. 启动开发服务器
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## API文档
|
||||
|
||||
API基础路径: `http://localhost:3000/api`
|
||||
|
||||
### 主要接口
|
||||
|
||||
- `/api/equipment` - 设备管理
|
||||
- `/api/borrow` - 借用管理
|
||||
- `/api/return` - 归还管理
|
||||
- `/api/statistics` - 统计分析
|
||||
- `/api/barcode` - 条码生成
|
||||
- `/api/auth` - 用户认证
|
||||
|
||||
## 环境变量
|
||||
|
||||
`.env` 文件示例:
|
||||
|
||||
```
|
||||
DATABASE_URL="mysql://root:password@localhost:3306/equipment_management?charset=utf8mb4"
|
||||
SESSION_SECRET=equipment-management-secret
|
||||
KEYCLOAK_URL=http://localhost:8080
|
||||
KEYCLOAK_REALM=equipment-management
|
||||
KEYCLOAK_CLIENT_ID=equipment-client
|
||||
# 可选:若为机密客户端
|
||||
# KEYCLOAK_CLIENT_SECRET=your-client-secret
|
||||
```
|
||||
|
||||
## Keycloak 集成
|
||||
|
||||
后端使用 `keycloak-connect` 保护接口、管理用户信息。部署步骤:
|
||||
|
||||
1. 使用 Docker 启动 Keycloak(示例):
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name keycloak \
|
||||
-p 8080:8080 \
|
||||
-e KEYCLOAK_ADMIN=admin \
|
||||
-e KEYCLOAK_ADMIN_PASSWORD=admin \
|
||||
quay.io/keycloak/keycloak:23.0.7 start-dev
|
||||
```
|
||||
|
||||
2. 在 Keycloak 中创建 Realm `equipment-management`
|
||||
3. 创建客户端 `equipment-client`
|
||||
- 类型:Public Client(或使用 Confidential 并设置 `KEYCLOAK_CLIENT_SECRET`)
|
||||
- 有效重定向 URI:`http://localhost:5173/*`
|
||||
4. 创建用户并分配角色(如 `admin`、`user`)
|
||||
|
||||
后端接口自动验证 Bearer Token,无需额外登录接口。
|
||||
2868
backend/package-lock.json
generated
Normal file
2868
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
40
backend/package.json
Normal file
40
backend/package.json
Normal file
@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.0.0",
|
||||
"description": "摄影设备借还系统后端",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"dev": "nodemon --exec ts-node src/index.ts",
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:migrate": "prisma migrate dev",
|
||||
"prisma:studio": "prisma studio"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@prisma/client": "^5.0.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.0.0",
|
||||
"express": "^4.18.0",
|
||||
"express-session": "^1.17.3",
|
||||
"keycloak-connect": "^23.0.7",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"mysql2": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/cors": "^2.8.0",
|
||||
"@types/express": "^4.17.0",
|
||||
"@types/express-session": "^1.17.7",
|
||||
"@types/bcryptjs": "^2.4.2",
|
||||
"@types/multer": "^1.4.7",
|
||||
"@types/node": "^20.0.0",
|
||||
"nodemon": "^3.0.0",
|
||||
"prisma": "^5.0.0",
|
||||
"ts-node": "^10.9.0",
|
||||
"typescript": "^5.0.0"
|
||||
}
|
||||
}
|
||||
12
backend/prisma.config.ts
Normal file
12
backend/prisma.config.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { defineConfig, env } from "prisma/config";
|
||||
|
||||
export default defineConfig({
|
||||
schema: "prisma/schema.prisma",
|
||||
migrations: {
|
||||
path: "prisma/migrations",
|
||||
},
|
||||
engine: "classic",
|
||||
datasource: {
|
||||
url: env("DATABASE_URL"),
|
||||
},
|
||||
});
|
||||
164
backend/prisma/schema.prisma
Normal file
164
backend/prisma/schema.prisma
Normal file
@ -0,0 +1,164 @@
|
||||
// This is your Prisma schema file,
|
||||
// learn more about it in the docs: https://pris.ly/d/prisma-schema
|
||||
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "mysql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
model Equipment {
|
||||
id Int @id @default(autoincrement())
|
||||
equipment_code String @unique @db.VarChar(50)
|
||||
equipment_name String @db.VarChar(100)
|
||||
equipment_model String? @db.VarChar(100)
|
||||
equipment_type String @db.VarChar(50)
|
||||
code_generation_mode String @default("auto") @db.VarChar(20)
|
||||
status String @default("可用") @db.VarChar(20)
|
||||
total_quantity Int @default(0)
|
||||
remaining_quantity Int @default(0)
|
||||
unit_price Decimal @default(0.00) @db.Decimal(10, 2)
|
||||
total_value Decimal @default(0.00) @db.Decimal(12, 2)
|
||||
borrowed_value Decimal @default(0.00) @db.Decimal(12, 2)
|
||||
available_value Decimal @default(0.00) @db.Decimal(12, 2)
|
||||
description String? @db.Text
|
||||
purchase_date DateTime? @db.Date
|
||||
supplier String? @db.VarChar(100)
|
||||
storage_location_id Int?
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
borrow_records BorrowRecord[]
|
||||
storageLocation StorageLocation? @relation(fields: [storage_location_id], references: [id])
|
||||
|
||||
@@index([equipment_code])
|
||||
@@index([equipment_type])
|
||||
@@index([status])
|
||||
@@index([code_generation_mode])
|
||||
@@index([unit_price])
|
||||
@@index([storage_location_id])
|
||||
@@map("equipment")
|
||||
}
|
||||
|
||||
model BorrowRecord {
|
||||
id Int @id @default(autoincrement())
|
||||
equipment_id Int
|
||||
equipment_code String @db.VarChar(50)
|
||||
person_id Int
|
||||
person_name String @db.VarChar(50)
|
||||
person_nickname String @db.VarChar(50)
|
||||
person_identifier String? @db.VarChar(50)
|
||||
borrow_time DateTime @default(now())
|
||||
expected_return_time DateTime?
|
||||
is_long_term Boolean @default(false)
|
||||
return_time DateTime?
|
||||
status String @default("已借出") @db.VarChar(20)
|
||||
return_condition String @default("正常") @db.VarChar(20)
|
||||
notes String? @db.Text
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
equipment Equipment @relation(fields: [equipment_id], references: [id])
|
||||
person Person @relation(fields: [person_id], references: [id])
|
||||
|
||||
@@index([equipment_id])
|
||||
@@index([person_id])
|
||||
@@index([status])
|
||||
@@index([borrow_time])
|
||||
@@map("borrow_record")
|
||||
}
|
||||
|
||||
model User {
|
||||
id Int @id @default(autoincrement())
|
||||
username String @unique @db.VarChar(50)
|
||||
password String @db.VarChar(255)
|
||||
name String @db.VarChar(50)
|
||||
email String? @db.VarChar(100)
|
||||
phone String? @db.VarChar(20)
|
||||
role String @default("user") @db.VarChar(20)
|
||||
status String @default("active") @db.VarChar(20)
|
||||
last_login_at DateTime? @db.DateTime
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
operation_logs OperationLog[]
|
||||
site_configs SiteConfig[] @relation("SiteConfigUpdatedBy")
|
||||
|
||||
@@index([role])
|
||||
@@index([status])
|
||||
@@map("user")
|
||||
}
|
||||
|
||||
model SiteConfig {
|
||||
id Int @id @default(autoincrement())
|
||||
site_name String @db.VarChar(100)
|
||||
logo_url String? @db.VarChar(255)
|
||||
favicon_url String? @db.VarChar(255)
|
||||
theme_color String? @db.VarChar(20)
|
||||
updated_by Int?
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @default(now())
|
||||
|
||||
updatedBy User? @relation("SiteConfigUpdatedBy", fields: [updated_by], references: [id])
|
||||
|
||||
@@map("site_config")
|
||||
}
|
||||
|
||||
model Person {
|
||||
id Int @id @default(autoincrement())
|
||||
nickname String @db.VarChar(50)
|
||||
real_name String @db.VarChar(50)
|
||||
id_number String? @unique @db.VarChar(50)
|
||||
department String? @db.VarChar(100)
|
||||
position String? @db.VarChar(100)
|
||||
phone String? @db.VarChar(20)
|
||||
email String? @db.VarChar(100)
|
||||
status String @default("active") @db.VarChar(20)
|
||||
remarks String? @db.Text
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
borrow_records BorrowRecord[]
|
||||
|
||||
@@index([nickname])
|
||||
@@index([real_name])
|
||||
@@index([status])
|
||||
@@map("person")
|
||||
}
|
||||
|
||||
model StorageLocation {
|
||||
id Int @id @default(autoincrement())
|
||||
name String @db.VarChar(100)
|
||||
code String? @db.VarChar(50)
|
||||
status String @default("active") @db.VarChar(20)
|
||||
description String? @db.Text
|
||||
created_at DateTime @default(now())
|
||||
updated_at DateTime @updatedAt
|
||||
|
||||
equipments Equipment[]
|
||||
|
||||
@@index([status])
|
||||
@@map("storage_location")
|
||||
}
|
||||
|
||||
model OperationLog {
|
||||
id Int @id @default(autoincrement())
|
||||
user_id Int?
|
||||
username String? @db.VarChar(50)
|
||||
operation_type String @db.VarChar(50)
|
||||
equipment_id Int?
|
||||
equipment_code String? @db.VarChar(50)
|
||||
operation_details String? @db.Text
|
||||
ip_address String? @db.VarChar(50)
|
||||
created_at DateTime @default(now())
|
||||
|
||||
user User? @relation(fields: [user_id], references: [id])
|
||||
|
||||
@@index([user_id])
|
||||
@@index([operation_type])
|
||||
@@index([created_at])
|
||||
@@map("operation_log")
|
||||
}
|
||||
103
backend/src/controllers/barcodeController.ts
Normal file
103
backend/src/controllers/barcodeController.ts
Normal file
@ -0,0 +1,103 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
// 获取设备信息用于生成条码(条码在前端生成)
|
||||
export const getEquipmentForBarcode = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_code } = req.params
|
||||
|
||||
const equipment = await prisma.equipment.findUnique({
|
||||
where: { equipment_code },
|
||||
select: {
|
||||
id: true,
|
||||
equipment_code: true,
|
||||
equipment_name: true,
|
||||
equipment_model: true,
|
||||
equipment_type: true
|
||||
}
|
||||
})
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
successResponse(res, {
|
||||
equipment_code: equipment.equipment_code,
|
||||
equipment_name: equipment.equipment_name,
|
||||
equipment_model: equipment.equipment_model,
|
||||
equipment_type: equipment.equipment_type
|
||||
}, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取设备信息失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 批量获取设备信息用于生成条码
|
||||
export const getEquipmentBatchForBarcode = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_ids } = req.body
|
||||
|
||||
// 使用 select 明确指定所有需要的字段,包括关联数据
|
||||
const equipmentList = await prisma.equipment.findMany({
|
||||
where: {
|
||||
id: {
|
||||
in: equipment_ids.map((id: number) => Number(id))
|
||||
}
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
equipment_code: true,
|
||||
equipment_name: true,
|
||||
equipment_model: true,
|
||||
equipment_type: true,
|
||||
storage_location_id: true,
|
||||
storageLocation: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// 调试:打印原始查询结果
|
||||
console.log('条码打印 - 原始查询结果:', JSON.stringify(equipmentList, null, 2))
|
||||
equipmentList.forEach((eq, index) => {
|
||||
console.log(`原始设备 ${index + 1} (ID: ${eq.id}):`, {
|
||||
name: eq.equipment_name,
|
||||
storage_location_id: eq.storage_location_id,
|
||||
storageLocation: eq.storageLocation,
|
||||
allKeys: Object.keys(eq)
|
||||
})
|
||||
})
|
||||
|
||||
// 直接返回查询结果,不需要再次映射
|
||||
const result = equipmentList.map(eq => ({
|
||||
id: eq.id,
|
||||
equipment_code: eq.equipment_code,
|
||||
equipment_name: eq.equipment_name,
|
||||
equipment_model: eq.equipment_model,
|
||||
equipment_type: eq.equipment_type,
|
||||
storage_location_id: eq.storage_location_id,
|
||||
storageLocation: eq.storageLocation
|
||||
}))
|
||||
|
||||
// 调试:打印返回的数据
|
||||
console.log('条码打印 - 最终返回结果:', JSON.stringify(result, null, 2))
|
||||
result.forEach((eq, index) => {
|
||||
console.log(`设备 ${index + 1} (ID: ${eq.id}):`, {
|
||||
name: eq.equipment_name,
|
||||
storage_location_id: eq.storage_location_id,
|
||||
storageLocation: eq.storageLocation
|
||||
})
|
||||
})
|
||||
|
||||
successResponse(res, result, '获取成功')
|
||||
} catch (error: any) {
|
||||
console.error('批量获取设备信息失败:', error)
|
||||
errorResponse(res, error.message || '批量获取设备信息失败')
|
||||
}
|
||||
}
|
||||
|
||||
744
backend/src/controllers/borrowController.ts
Normal file
744
backend/src/controllers/borrowController.ts
Normal file
@ -0,0 +1,744 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
const parseNumber = (value: any): number | undefined => {
|
||||
const num = Number(value)
|
||||
return Number.isNaN(num) ? undefined : num
|
||||
}
|
||||
|
||||
const parseDate = (value?: any): Date | null => {
|
||||
if (!value) return null
|
||||
const date = new Date(value)
|
||||
return Number.isNaN(date.getTime()) ? null : date
|
||||
}
|
||||
|
||||
const equipmentInclude = {
|
||||
storageLocation: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const getEquipmentByIdentifier = async (equipmentId?: number, equipmentCode?: string) => {
|
||||
if (equipmentId) {
|
||||
return prisma.equipment.findUnique({ where: { id: equipmentId }, include: equipmentInclude })
|
||||
}
|
||||
if (equipmentCode) {
|
||||
return prisma.equipment.findUnique({ where: { equipment_code: equipmentCode }, include: equipmentInclude })
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const ensurePersonAvailable = async (personId?: number) => {
|
||||
if (!personId) {
|
||||
throw new Error('使用者ID不能为空')
|
||||
}
|
||||
const person = await prisma.person.findUnique({ where: { id: personId } })
|
||||
if (!person || person.status !== 'active') {
|
||||
throw new Error('使用者不存在或已禁用')
|
||||
}
|
||||
return person
|
||||
}
|
||||
|
||||
const ensureEquipmentBorrowable = (equipment: any) => {
|
||||
if (equipment.status !== '可用') {
|
||||
throw new Error('设备状态不可借用')
|
||||
}
|
||||
if (equipment.remaining_quantity <= 0) {
|
||||
throw new Error('设备库存不足')
|
||||
}
|
||||
}
|
||||
|
||||
const updateEquipmentAfterBorrow = async (equipment: any) => {
|
||||
const newRemainingQuantity = equipment.remaining_quantity - 1
|
||||
if (newRemainingQuantity < 0) {
|
||||
throw new Error('设备库存不足')
|
||||
}
|
||||
const borrowedQuantity = equipment.total_quantity - newRemainingQuantity
|
||||
await prisma.equipment.update({
|
||||
where: { id: equipment.id },
|
||||
data: {
|
||||
remaining_quantity: newRemainingQuantity,
|
||||
status: newRemainingQuantity === 0 ? '已借出' : '可用',
|
||||
borrowed_value: Number(equipment.unit_price) * borrowedQuantity,
|
||||
available_value: Number(equipment.unit_price) * newRemainingQuantity
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const updateEquipmentAfterReturn = async (equipment: any) => {
|
||||
const newRemainingQuantity = equipment.remaining_quantity + 1
|
||||
const borrowedQuantity = equipment.total_quantity - newRemainingQuantity
|
||||
await prisma.equipment.update({
|
||||
where: { id: equipment.id },
|
||||
data: {
|
||||
remaining_quantity: newRemainingQuantity,
|
||||
status: '可用',
|
||||
borrowed_value: Number(equipment.unit_price) * borrowedQuantity,
|
||||
available_value: Number(equipment.unit_price) * newRemainingQuantity
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const mapBorrowRecord = (record: any) => ({
|
||||
id: record.id,
|
||||
equipment_id: record.equipment_id,
|
||||
equipment_code: record.equipment_code,
|
||||
equipment_name: record.equipment?.equipment_name,
|
||||
storage_location_id: record.equipment?.storage_location_id ?? null,
|
||||
storageLocation: record.equipment?.storageLocation ?? null,
|
||||
person: record.person
|
||||
? {
|
||||
id: record.person.id,
|
||||
nickname: record.person.nickname,
|
||||
real_name: record.person.real_name,
|
||||
department: record.person.department,
|
||||
phone: record.person.phone
|
||||
}
|
||||
: {
|
||||
id: record.person_id,
|
||||
nickname: record.person_nickname,
|
||||
real_name: record.person_name
|
||||
},
|
||||
person_id: record.person_id,
|
||||
person_name: record.person_name,
|
||||
person_nickname: record.person_nickname,
|
||||
person_identifier: record.person_identifier,
|
||||
borrow_time: record.borrow_time,
|
||||
expected_return_time: record.expected_return_time,
|
||||
is_long_term: record.is_long_term,
|
||||
return_time: record.return_time,
|
||||
status: record.status,
|
||||
return_condition: record.return_condition,
|
||||
notes: record.notes
|
||||
})
|
||||
|
||||
// 借用设备
|
||||
export const borrowEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_id, equipment_code, person_id, expected_return_time, notes, is_long_term } =
|
||||
req.body
|
||||
|
||||
const equipmentIdNum = parseNumber(equipment_id)
|
||||
const equipment = await getEquipmentByIdentifier(equipmentIdNum, equipment_code)
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
if (equipmentIdNum && equipment_code && equipment.equipment_code !== equipment_code) {
|
||||
return errorResponse(res, '设备编号与ID不匹配', 422)
|
||||
}
|
||||
|
||||
let person
|
||||
try {
|
||||
person = await ensurePersonAvailable(parseNumber(person_id))
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message || '使用者验证失败', 422)
|
||||
}
|
||||
|
||||
try {
|
||||
ensureEquipmentBorrowable(equipment)
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message)
|
||||
}
|
||||
|
||||
const longTerm = Boolean(is_long_term)
|
||||
const expectedReturn = longTerm ? null : parseDate(expected_return_time)
|
||||
|
||||
const combinedNotes =
|
||||
longTerm && notes
|
||||
? `${notes};在职长期`
|
||||
: longTerm
|
||||
? '在职长期'
|
||||
: notes || undefined
|
||||
|
||||
const borrowRecord = await prisma.borrowRecord.create({
|
||||
data: {
|
||||
equipment_id: equipment.id,
|
||||
equipment_code: equipment.equipment_code,
|
||||
person_id: person.id,
|
||||
person_name: person.real_name,
|
||||
person_nickname: person.nickname,
|
||||
person_identifier: person.id_number,
|
||||
expected_return_time: expectedReturn,
|
||||
is_long_term: longTerm,
|
||||
notes: combinedNotes,
|
||||
status: '已借出'
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterBorrow(equipment)
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
id: borrowRecord.id,
|
||||
borrow_time: borrowRecord.borrow_time
|
||||
},
|
||||
'借用成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[借用设备失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '借用设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 扫码出库
|
||||
export const scanBorrow = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_code, person_id, expected_return_time, notes, is_long_term } = req.body
|
||||
|
||||
const equipment = await getEquipmentByIdentifier(undefined, equipment_code)
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
let person
|
||||
try {
|
||||
person = await ensurePersonAvailable(parseNumber(person_id))
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message || '使用者验证失败', 422)
|
||||
}
|
||||
|
||||
try {
|
||||
ensureEquipmentBorrowable(equipment)
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message)
|
||||
}
|
||||
|
||||
const longTerm = Boolean(is_long_term)
|
||||
const expectedReturn = longTerm ? null : parseDate(expected_return_time)
|
||||
const combinedNotes =
|
||||
longTerm && notes
|
||||
? `${notes};在职长期`
|
||||
: longTerm
|
||||
? '在职长期'
|
||||
: notes || undefined
|
||||
|
||||
const borrowRecord = await prisma.borrowRecord.create({
|
||||
data: {
|
||||
equipment_id: equipment.id,
|
||||
equipment_code: equipment.equipment_code,
|
||||
person_id: person.id,
|
||||
person_name: person.real_name,
|
||||
person_nickname: person.nickname,
|
||||
person_identifier: person.id_number,
|
||||
expected_return_time: expectedReturn,
|
||||
is_long_term: longTerm,
|
||||
notes: combinedNotes,
|
||||
status: '已借出'
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterBorrow(equipment)
|
||||
const updatedEquipment = await prisma.equipment.findUnique({
|
||||
where: { id: equipment.id },
|
||||
include: equipmentInclude
|
||||
})
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
id: borrowRecord.id,
|
||||
equipment_code: equipment.equipment_code,
|
||||
equipment_name: equipment.equipment_name,
|
||||
borrow_time: borrowRecord.borrow_time,
|
||||
status: '已借出',
|
||||
remaining_quantity: updatedEquipment?.remaining_quantity ?? 0,
|
||||
equipment_status: updatedEquipment?.status ?? '已借出',
|
||||
storage_location_id: equipment.storage_location_id,
|
||||
storageLocation: equipment.storageLocation
|
||||
},
|
||||
'出库成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[扫码出库失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '出库失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 批量扫码出库
|
||||
export const scanBorrowBatch = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_codes, person_id, expected_return_time, notes, is_long_term } = req.body as {
|
||||
equipment_codes: string[]
|
||||
person_id: number
|
||||
expected_return_time?: string
|
||||
notes?: string
|
||||
is_long_term?: boolean
|
||||
}
|
||||
|
||||
if (!Array.isArray(equipment_codes) || equipment_codes.length === 0) {
|
||||
return errorResponse(res, '设备编码列表不能为空', 422)
|
||||
}
|
||||
|
||||
let person
|
||||
try {
|
||||
person = await ensurePersonAvailable(parseNumber(person_id))
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message || '使用者验证失败', 422)
|
||||
}
|
||||
|
||||
const longTerm = Boolean(is_long_term)
|
||||
const expectedReturn = longTerm ? null : parseDate(expected_return_time)
|
||||
const combinedNotes =
|
||||
longTerm && notes
|
||||
? `${notes};在职长期`
|
||||
: longTerm
|
||||
? '在职长期'
|
||||
: notes || undefined
|
||||
const results: any[] = []
|
||||
let successCount = 0
|
||||
let failedCount = 0
|
||||
|
||||
for (const code of equipment_codes) {
|
||||
try {
|
||||
const equipment = await getEquipmentByIdentifier(undefined, code)
|
||||
if (!equipment) {
|
||||
results.push({ equipment_code: code, status: 'failed', message: '设备不存在' })
|
||||
failedCount++
|
||||
continue
|
||||
}
|
||||
|
||||
try {
|
||||
ensureEquipmentBorrowable(equipment)
|
||||
} catch (err: any) {
|
||||
results.push({ equipment_code: code, status: 'failed', message: err.message })
|
||||
failedCount++
|
||||
continue
|
||||
}
|
||||
|
||||
await prisma.borrowRecord.create({
|
||||
data: {
|
||||
equipment_id: equipment.id,
|
||||
equipment_code: equipment.equipment_code,
|
||||
person_id: person.id,
|
||||
person_name: person.real_name,
|
||||
person_nickname: person.nickname,
|
||||
person_identifier: person.id_number,
|
||||
expected_return_time: expectedReturn,
|
||||
is_long_term: longTerm,
|
||||
notes: combinedNotes,
|
||||
status: '已借出'
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterBorrow(equipment)
|
||||
|
||||
results.push({ equipment_code: code, status: 'success', message: '出库成功' })
|
||||
successCount++
|
||||
} catch (error: any) {
|
||||
results.push({
|
||||
equipment_code: code,
|
||||
status: 'failed',
|
||||
message: error.message || '出库失败'
|
||||
})
|
||||
failedCount++
|
||||
}
|
||||
}
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
success_count: successCount,
|
||||
failed_count: failedCount,
|
||||
results
|
||||
},
|
||||
'批量出库完成'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[批量出库失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '批量出库失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 归还设备
|
||||
export const returnEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
equipment_id,
|
||||
equipment_code,
|
||||
return_condition = '正常',
|
||||
notes
|
||||
} = req.body as Record<string, any>
|
||||
|
||||
const equipmentIdNum = parseNumber(equipment_id)
|
||||
const equipment = await getEquipmentByIdentifier(equipmentIdNum, equipment_code)
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
const borrowRecord = await prisma.borrowRecord.findFirst({
|
||||
where: {
|
||||
equipment_id: equipment.id,
|
||||
status: '已借出'
|
||||
},
|
||||
orderBy: { borrow_time: 'desc' }
|
||||
})
|
||||
|
||||
if (!borrowRecord) {
|
||||
return errorResponse(res, '未找到对应的借用记录')
|
||||
}
|
||||
|
||||
await prisma.borrowRecord.update({
|
||||
where: { id: borrowRecord.id },
|
||||
data: {
|
||||
return_time: new Date(),
|
||||
status: '已归还',
|
||||
return_condition,
|
||||
notes
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterReturn(equipment)
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
id: borrowRecord.id,
|
||||
return_time: new Date()
|
||||
},
|
||||
'归还成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[归还设备失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '归还设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 扫码入库
|
||||
export const scanReturn = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
equipment_code,
|
||||
return_condition = '正常',
|
||||
notes,
|
||||
person_id,
|
||||
borrow_record_id
|
||||
} = req.body as Record<string, any>
|
||||
|
||||
const equipment = await getEquipmentByIdentifier(undefined, equipment_code)
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
const personIdNum = parseNumber(person_id)
|
||||
const borrowRecordIdNum = parseNumber(borrow_record_id)
|
||||
|
||||
let borrowRecord = null
|
||||
|
||||
if (borrowRecordIdNum) {
|
||||
borrowRecord = await prisma.borrowRecord.findFirst({
|
||||
where: {
|
||||
id: borrowRecordIdNum,
|
||||
equipment_id: equipment.id,
|
||||
status: '已借出'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (!borrowRecord && personIdNum) {
|
||||
borrowRecord = await prisma.borrowRecord.findFirst({
|
||||
where: {
|
||||
equipment_id: equipment.id,
|
||||
person_id: personIdNum,
|
||||
status: '已借出'
|
||||
},
|
||||
orderBy: { borrow_time: 'desc' }
|
||||
})
|
||||
}
|
||||
|
||||
if (!borrowRecord) {
|
||||
borrowRecord = await prisma.borrowRecord.findFirst({
|
||||
where: {
|
||||
equipment_id: equipment.id,
|
||||
status: '已借出'
|
||||
},
|
||||
orderBy: { borrow_time: 'desc' }
|
||||
})
|
||||
}
|
||||
|
||||
if (!borrowRecord) {
|
||||
return errorResponse(res, '未找到对应的借用记录,请选择正确的使用者', 404)
|
||||
}
|
||||
|
||||
const updatedRecord = await prisma.borrowRecord.update({
|
||||
where: { id: borrowRecord.id },
|
||||
data: {
|
||||
return_time: new Date(),
|
||||
status: '已归还',
|
||||
return_condition,
|
||||
notes
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterReturn(equipment)
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
id: updatedRecord.id,
|
||||
equipment_code: equipment.equipment_code,
|
||||
equipment_name: equipment.equipment_name,
|
||||
return_time: updatedRecord.return_time,
|
||||
status: '已归还',
|
||||
person_id: updatedRecord.person_id
|
||||
},
|
||||
'入库成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[扫码入库失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '入库失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 批量扫码入库
|
||||
export const scanReturnBatch = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
equipment_codes,
|
||||
return_condition = '正常',
|
||||
notes
|
||||
} = req.body as { equipment_codes: string[]; return_condition?: string; notes?: string }
|
||||
|
||||
if (!Array.isArray(equipment_codes) || equipment_codes.length === 0) {
|
||||
return errorResponse(res, '设备编码列表不能为空', 422)
|
||||
}
|
||||
|
||||
const results: any[] = []
|
||||
let successCount = 0
|
||||
let failedCount = 0
|
||||
|
||||
for (const code of equipment_codes) {
|
||||
try {
|
||||
const equipment = await getEquipmentByIdentifier(undefined, code)
|
||||
|
||||
if (!equipment) {
|
||||
results.push({ equipment_code: code, status: 'failed', message: '设备不存在' })
|
||||
failedCount++
|
||||
continue
|
||||
}
|
||||
|
||||
const borrowRecord = await prisma.borrowRecord.findFirst({
|
||||
where: {
|
||||
equipment_id: equipment.id,
|
||||
status: '已借出'
|
||||
},
|
||||
orderBy: { borrow_time: 'desc' }
|
||||
})
|
||||
|
||||
if (!borrowRecord) {
|
||||
results.push({ equipment_code: code, status: 'failed', message: '未找到对应的借用记录' })
|
||||
failedCount++
|
||||
continue
|
||||
}
|
||||
|
||||
await prisma.borrowRecord.update({
|
||||
where: { id: borrowRecord.id },
|
||||
data: {
|
||||
return_time: new Date(),
|
||||
status: '已归还',
|
||||
return_condition,
|
||||
notes
|
||||
}
|
||||
})
|
||||
|
||||
await updateEquipmentAfterReturn(equipment)
|
||||
|
||||
results.push({ equipment_code: code, status: 'success', message: '入库成功' })
|
||||
successCount++
|
||||
} catch (error: any) {
|
||||
results.push({
|
||||
equipment_code: code,
|
||||
status: 'failed',
|
||||
message: error.message || '入库失败'
|
||||
})
|
||||
failedCount++
|
||||
}
|
||||
}
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
success_count: successCount,
|
||||
failed_count: failedCount,
|
||||
results
|
||||
},
|
||||
'批量入库完成'
|
||||
)
|
||||
} catch (error: any) {
|
||||
console.error('[批量入库失败]', {
|
||||
error: error?.message || error,
|
||||
stack: error?.stack,
|
||||
body: req.body,
|
||||
user: res.locals.user
|
||||
})
|
||||
errorResponse(res, error.message || '批量入库失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 根据设备编码查询借用记录
|
||||
export const getBorrowRecordByCode = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_code } = req.params
|
||||
|
||||
const equipment = await getEquipmentByIdentifier(undefined, equipment_code)
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
const borrowRecords = await prisma.borrowRecord.findMany({
|
||||
where: {
|
||||
equipment_id: equipment.id,
|
||||
status: '已借出'
|
||||
},
|
||||
orderBy: { borrow_time: 'desc' },
|
||||
include: {
|
||||
person: true,
|
||||
equipment: {
|
||||
select: {
|
||||
equipment_name: true,
|
||||
storage_location_id: true,
|
||||
storageLocation: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (borrowRecords.length === 0) {
|
||||
return errorResponse(res, '未找到对应的借用记录', 404)
|
||||
}
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
equipment_code: equipment.equipment_code,
|
||||
equipment_name: equipment.equipment_name,
|
||||
unit_price: Number(equipment.unit_price),
|
||||
equipment_value: Number(equipment.unit_price),
|
||||
storage_location_id: equipment.storage_location_id,
|
||||
storageLocation: equipment.storageLocation,
|
||||
borrow_records: borrowRecords.map(mapBorrowRecord),
|
||||
can_return: true,
|
||||
message: '设备已借出,可以选择对应使用者归还'
|
||||
},
|
||||
'查询成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '查询借用记录失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 获取借用记录列表
|
||||
export const getBorrowRecordList = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { page = 1, pageSize = 10, status, person_name, person_id } = req.query
|
||||
|
||||
const filters: any[] = []
|
||||
|
||||
if (status) {
|
||||
filters.push({ status })
|
||||
}
|
||||
|
||||
const personIdNum = parseNumber(person_id)
|
||||
if (personIdNum) {
|
||||
filters.push({ person_id: personIdNum })
|
||||
}
|
||||
|
||||
if (person_name) {
|
||||
const kw = person_name as string
|
||||
filters.push({
|
||||
OR: [
|
||||
{ person_name: { contains: kw } },
|
||||
{ person_nickname: { contains: kw } },
|
||||
{ person_identifier: { contains: kw } }
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
const where = filters.length ? { AND: filters } : undefined
|
||||
const skip = (Number(page) - 1) * Number(pageSize)
|
||||
|
||||
const [list, total] = await Promise.all([
|
||||
prisma.borrowRecord.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(pageSize),
|
||||
orderBy: { borrow_time: 'desc' },
|
||||
include: {
|
||||
person: true,
|
||||
equipment: {
|
||||
select: {
|
||||
equipment_name: true,
|
||||
storage_location_id: true,
|
||||
storageLocation: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
prisma.borrowRecord.count({ where })
|
||||
])
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
list: list.map(mapBorrowRecord),
|
||||
total,
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize)
|
||||
},
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取借用记录列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
463
backend/src/controllers/equipmentController.ts
Normal file
463
backend/src/controllers/equipmentController.ts
Normal file
@ -0,0 +1,463 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
import { generateEquipmentCode, validateEquipmentCode } from '../utils/equipmentCode'
|
||||
|
||||
// 计算设备价值
|
||||
const calculateEquipmentValues = (unitPrice: number, totalQuantity: number, remainingQuantity: number) => {
|
||||
const totalValue = Number(unitPrice) * totalQuantity
|
||||
const borrowedQuantity = totalQuantity - remainingQuantity
|
||||
const borrowedValue = Number(unitPrice) * borrowedQuantity
|
||||
const availableValue = Number(unitPrice) * remainingQuantity
|
||||
|
||||
return {
|
||||
total_value: totalValue,
|
||||
borrowed_value: borrowedValue,
|
||||
available_value: availableValue
|
||||
}
|
||||
}
|
||||
|
||||
const includeStorageLocation = {
|
||||
storageLocation: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
status: true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ensureLocationExists = async (locationId?: number | null) => {
|
||||
if (!locationId) {
|
||||
throw new Error('库位信息不能为空')
|
||||
}
|
||||
|
||||
const location = await prisma.storageLocation.findUnique({
|
||||
where: { id: locationId }
|
||||
})
|
||||
|
||||
if (!location || location.status !== 'active') {
|
||||
throw new Error('所选库位不存在或已停用')
|
||||
}
|
||||
|
||||
return location
|
||||
}
|
||||
|
||||
// 获取设备列表
|
||||
export const getEquipmentList = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { page = 1, pageSize = 10, equipmentType, status, keyword, storage_location_id } = req.query
|
||||
|
||||
const where: any = {}
|
||||
|
||||
if (equipmentType) {
|
||||
where.equipment_type = equipmentType
|
||||
}
|
||||
|
||||
if (status) {
|
||||
where.status = status
|
||||
}
|
||||
|
||||
if (keyword) {
|
||||
where.OR = [
|
||||
{ equipment_name: { contains: keyword as string } },
|
||||
{ equipment_code: { contains: keyword as string } },
|
||||
{ equipment_model: { contains: keyword as string } }
|
||||
]
|
||||
}
|
||||
|
||||
const locationId = Number(storage_location_id)
|
||||
if (!Number.isNaN(locationId) && storage_location_id) {
|
||||
where.storage_location_id = locationId
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(pageSize)
|
||||
|
||||
const [list, total] = await Promise.all([
|
||||
prisma.equipment.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(pageSize),
|
||||
orderBy: { created_at: 'desc' },
|
||||
include: includeStorageLocation
|
||||
}),
|
||||
prisma.equipment.count({ where })
|
||||
])
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
list,
|
||||
total,
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize)
|
||||
},
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取设备列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 获取设备详情
|
||||
export const getEquipmentDetail = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
|
||||
const equipment = await prisma.equipment.findUnique({
|
||||
where: { id: Number(id) },
|
||||
include: includeStorageLocation
|
||||
})
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
successResponse(res, equipment, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取设备详情失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 新增设备
|
||||
export const createEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
equipment_code,
|
||||
equipment_name,
|
||||
equipment_model,
|
||||
equipment_type,
|
||||
code_generation_mode = 'auto',
|
||||
unit_price,
|
||||
total_quantity,
|
||||
purchase_date,
|
||||
supplier,
|
||||
description,
|
||||
storage_location_id
|
||||
} = req.body
|
||||
|
||||
// 生成或验证设备编码
|
||||
let finalCode = equipment_code
|
||||
|
||||
const locationId = storage_location_id ? Number(storage_location_id) : null
|
||||
|
||||
if (code_generation_mode === 'auto') {
|
||||
// 自动生成编码,确保唯一性(generateEquipmentCode内部已处理唯一性检查)
|
||||
finalCode = await generateEquipmentCode(equipment_type, prisma, locationId)
|
||||
|
||||
// 再次检查编码唯一性(双重保险)
|
||||
const existingCheck = await prisma.equipment.findUnique({
|
||||
where: { equipment_code: finalCode }
|
||||
})
|
||||
|
||||
if (existingCheck) {
|
||||
// 如果编码已存在,重新生成(这种情况理论上不应该发生,但作为安全措施)
|
||||
finalCode = await generateEquipmentCode(equipment_type, prisma, locationId)
|
||||
}
|
||||
} else {
|
||||
if (!equipment_code) {
|
||||
return errorResponse(res, '自定义录入模式下设备编码不能为空')
|
||||
}
|
||||
|
||||
if (!validateEquipmentCode(equipment_code)) {
|
||||
return errorResponse(res, '设备编码格式不正确')
|
||||
}
|
||||
|
||||
// 检查编码是否已存在
|
||||
const existing = await prisma.equipment.findUnique({
|
||||
where: { equipment_code }
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
return errorResponse(res, '设备编码已存在')
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureLocationExists(locationId)
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message || '库位无效', 422)
|
||||
}
|
||||
|
||||
// 计算价值
|
||||
const remaining_quantity = total_quantity || 1
|
||||
const values = calculateEquipmentValues(
|
||||
Number(unit_price) || 0,
|
||||
Number(total_quantity) || 1,
|
||||
remaining_quantity
|
||||
)
|
||||
|
||||
const created = await prisma.equipment.create({
|
||||
data: {
|
||||
equipment_code: finalCode,
|
||||
equipment_name,
|
||||
equipment_model,
|
||||
equipment_type,
|
||||
code_generation_mode,
|
||||
unit_price: Number(unit_price) || 0,
|
||||
total_quantity: Number(total_quantity) || 1,
|
||||
remaining_quantity,
|
||||
total_value: values.total_value,
|
||||
borrowed_value: values.borrowed_value,
|
||||
available_value: values.available_value,
|
||||
purchase_date: purchase_date ? new Date(purchase_date) : null,
|
||||
supplier,
|
||||
description,
|
||||
status: '可用',
|
||||
storage_location_id: locationId || undefined
|
||||
}
|
||||
})
|
||||
|
||||
const equipment = await prisma.equipment.findUnique({
|
||||
where: { id: created.id },
|
||||
include: includeStorageLocation
|
||||
})
|
||||
|
||||
successResponse(res, equipment, '新增成功')
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') {
|
||||
return errorResponse(res, '设备编码已存在')
|
||||
}
|
||||
errorResponse(res, error.message || '新增设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 更新设备
|
||||
export const updateEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const {
|
||||
equipment_name,
|
||||
equipment_model,
|
||||
equipment_type,
|
||||
unit_price,
|
||||
total_quantity,
|
||||
status,
|
||||
purchase_date,
|
||||
supplier,
|
||||
description,
|
||||
storage_location_id
|
||||
} = req.body
|
||||
|
||||
// 获取当前设备信息
|
||||
const currentEquipment = await prisma.equipment.findUnique({
|
||||
where: { id: Number(id) }
|
||||
})
|
||||
|
||||
if (!currentEquipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
let targetLocationId = currentEquipment.storage_location_id
|
||||
if (storage_location_id !== undefined) {
|
||||
const normalizedLocationId = Number(storage_location_id)
|
||||
try {
|
||||
await ensureLocationExists(normalizedLocationId)
|
||||
} catch (error: any) {
|
||||
return errorResponse(res, error.message || '库位无效', 422)
|
||||
}
|
||||
targetLocationId = normalizedLocationId
|
||||
}
|
||||
|
||||
// 计算价值与剩余库存同步逻辑
|
||||
const finalTotalQuantity = total_quantity !== undefined ? Number(total_quantity) : currentEquipment.total_quantity
|
||||
const finalUnitPrice = unit_price !== undefined ? Number(unit_price) : Number(currentEquipment.unit_price)
|
||||
// 已借数量 = 原总数 - 原剩余数(保证不为负)
|
||||
const borrowedQuantity = Math.max(currentEquipment.total_quantity - currentEquipment.remaining_quantity, 0)
|
||||
// 若修改了总库存,则根据已借数量同步计算新的剩余库存;否则保持原剩余库存
|
||||
const newRemainingQuantity =
|
||||
total_quantity !== undefined
|
||||
? Math.max(finalTotalQuantity - borrowedQuantity, 0)
|
||||
: currentEquipment.remaining_quantity
|
||||
const values = calculateEquipmentValues(finalUnitPrice, finalTotalQuantity, newRemainingQuantity)
|
||||
|
||||
// 调试日志:观察请求与计算过程
|
||||
console.log('[更新设备] 输入参数:', {
|
||||
id,
|
||||
body: {
|
||||
equipment_name,
|
||||
equipment_model,
|
||||
equipment_type,
|
||||
unit_price,
|
||||
total_quantity,
|
||||
status,
|
||||
purchase_date,
|
||||
supplier,
|
||||
description,
|
||||
storage_location_id
|
||||
}
|
||||
})
|
||||
console.log('[更新设备] 当前设备:', {
|
||||
current_total: currentEquipment.total_quantity,
|
||||
current_remaining: currentEquipment.remaining_quantity,
|
||||
current_status: currentEquipment.status
|
||||
})
|
||||
console.log('[更新设备] 计算结果:', {
|
||||
borrowedQuantity,
|
||||
finalTotalQuantity,
|
||||
newRemainingQuantity,
|
||||
finalUnitPrice,
|
||||
total_value: values.total_value,
|
||||
borrowed_value: values.borrowed_value,
|
||||
available_value: values.available_value
|
||||
})
|
||||
|
||||
await prisma.equipment.update({
|
||||
where: { id: Number(id) },
|
||||
data: {
|
||||
equipment_name,
|
||||
equipment_model,
|
||||
equipment_type,
|
||||
unit_price: finalUnitPrice,
|
||||
total_quantity: finalTotalQuantity,
|
||||
total_value: values.total_value,
|
||||
borrowed_value: values.borrowed_value,
|
||||
available_value: values.available_value,
|
||||
// 若未显式传入状态,则根据剩余库存自动设定
|
||||
status: status ?? (newRemainingQuantity > 0 ? '可用' : '已借出'),
|
||||
purchase_date: purchase_date ? new Date(purchase_date) : currentEquipment.purchase_date,
|
||||
supplier,
|
||||
description,
|
||||
storage_location_id: targetLocationId,
|
||||
remaining_quantity: newRemainingQuantity
|
||||
}
|
||||
})
|
||||
|
||||
console.log('[更新设备] 已写入:', {
|
||||
id,
|
||||
total_quantity: finalTotalQuantity,
|
||||
remaining_quantity: newRemainingQuantity
|
||||
})
|
||||
|
||||
const equipment = await prisma.equipment.findUnique({
|
||||
where: { id: Number(id) },
|
||||
include: includeStorageLocation
|
||||
})
|
||||
|
||||
successResponse(res, equipment, '更新成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 删除设备
|
||||
export const deleteEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
|
||||
const equipmentId = Number(id)
|
||||
|
||||
// 检查是否有未归还的借用记录
|
||||
const activeBorrowCount = await prisma.borrowRecord.count({
|
||||
where: {
|
||||
equipment_id: equipmentId,
|
||||
status: '已借出'
|
||||
}
|
||||
})
|
||||
|
||||
if (activeBorrowCount > 0) {
|
||||
return errorResponse(res, '该设备存在未归还的借用记录,无法删除')
|
||||
}
|
||||
|
||||
// 清理历史借用记录,避免外键约束阻止删除
|
||||
await prisma.borrowRecord.deleteMany({
|
||||
where: {
|
||||
equipment_id: equipmentId
|
||||
}
|
||||
})
|
||||
|
||||
await prisma.equipment.delete({
|
||||
where: { id: equipmentId }
|
||||
})
|
||||
|
||||
successResponse(res, null, '删除成功')
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2025') {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
errorResponse(res, error.message || '删除设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 生成设备编码
|
||||
export const generateCode = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_type, code_generation_mode = 'auto', storage_location_id } = req.body
|
||||
|
||||
if (code_generation_mode === 'auto') {
|
||||
const locationId = storage_location_id ? Number(storage_location_id) : null
|
||||
const code = await generateEquipmentCode(equipment_type, prisma, locationId)
|
||||
successResponse(res, {
|
||||
equipment_code: code,
|
||||
code_format: '{类型数字}{库位ID(4位)}{序号(5位)}'
|
||||
}, '生成成功')
|
||||
} else {
|
||||
errorResponse(res, '自定义录入模式不需要生成编码')
|
||||
}
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '生成编码失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 验证设备编码
|
||||
export const verifyCode = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_code } = req.body
|
||||
|
||||
if (!validateEquipmentCode(equipment_code)) {
|
||||
return successResponse(res, {
|
||||
is_valid: false,
|
||||
is_unique: false,
|
||||
message: '编码格式不正确'
|
||||
}, '验证成功')
|
||||
}
|
||||
|
||||
const existing = await prisma.equipment.findUnique({
|
||||
where: { equipment_code }
|
||||
})
|
||||
|
||||
if (existing) {
|
||||
return successResponse(res, {
|
||||
is_valid: true,
|
||||
is_unique: false,
|
||||
message: '编码已存在'
|
||||
}, '验证成功')
|
||||
}
|
||||
|
||||
successResponse(res, {
|
||||
is_valid: true,
|
||||
is_unique: true,
|
||||
message: '编码可用'
|
||||
}, '验证成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '验证编码失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 根据设备编码查询设备信息(扫码)
|
||||
export const scanEquipment = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_code } = req.params
|
||||
|
||||
const equipment = await prisma.equipment.findUnique({
|
||||
where: { equipment_code },
|
||||
include: includeStorageLocation
|
||||
})
|
||||
|
||||
if (!equipment) {
|
||||
return errorResponse(res, '设备不存在', 404)
|
||||
}
|
||||
|
||||
const is_available = equipment.status === '可用' && equipment.remaining_quantity > 0
|
||||
|
||||
successResponse(res, {
|
||||
...equipment,
|
||||
is_available,
|
||||
message: is_available ? '设备可用' : '设备不可用'
|
||||
}, '查询成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '查询设备失败')
|
||||
}
|
||||
}
|
||||
|
||||
201
backend/src/controllers/personController.ts
Normal file
201
backend/src/controllers/personController.ts
Normal file
@ -0,0 +1,201 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
const sanitizePerson = (person: any) => ({
|
||||
id: person.id,
|
||||
nickname: person.nickname,
|
||||
real_name: person.real_name,
|
||||
id_number: person.id_number,
|
||||
department: person.department,
|
||||
position: person.position,
|
||||
phone: person.phone,
|
||||
email: person.email,
|
||||
status: person.status,
|
||||
remarks: person.remarks,
|
||||
created_at: person.created_at,
|
||||
updated_at: person.updated_at
|
||||
})
|
||||
|
||||
export const getPersonList = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { page = 1, pageSize = 10, keyword, status } = req.query
|
||||
|
||||
const where: any = {}
|
||||
|
||||
if (keyword) {
|
||||
const kw = keyword as string
|
||||
where.OR = [
|
||||
{ nickname: { contains: kw } },
|
||||
{ real_name: { contains: kw } },
|
||||
{ id_number: { contains: kw } }
|
||||
]
|
||||
}
|
||||
|
||||
if (status) {
|
||||
where.status = status
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(pageSize)
|
||||
|
||||
const [list, total] = await Promise.all([
|
||||
prisma.person.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(pageSize),
|
||||
orderBy: { created_at: 'desc' }
|
||||
}),
|
||||
prisma.person.count({ where })
|
||||
])
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
list: list.map(sanitizePerson),
|
||||
total,
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize)
|
||||
},
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取使用者列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const getPersonDetail = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const person = await prisma.person.findUnique({ where: { id: Number(id) } })
|
||||
if (!person) {
|
||||
return errorResponse(res, '使用者不存在', 404)
|
||||
}
|
||||
successResponse(res, sanitizePerson(person), '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取使用者详情失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const createPerson = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const {
|
||||
nickname,
|
||||
real_name,
|
||||
id_number,
|
||||
department,
|
||||
position,
|
||||
phone,
|
||||
email,
|
||||
status = 'active',
|
||||
remarks
|
||||
} = req.body as Record<string, any>
|
||||
|
||||
if (!nickname || !real_name) {
|
||||
return errorResponse(res, '花名与真实姓名为必填项', 422)
|
||||
}
|
||||
|
||||
if (id_number) {
|
||||
const exists = await prisma.person.findUnique({ where: { id_number } })
|
||||
if (exists) {
|
||||
return errorResponse(res, '证件编号已存在', 409)
|
||||
}
|
||||
}
|
||||
|
||||
const created = await prisma.person.create({
|
||||
data: {
|
||||
nickname,
|
||||
real_name,
|
||||
id_number,
|
||||
department,
|
||||
position,
|
||||
phone,
|
||||
email,
|
||||
status,
|
||||
remarks
|
||||
}
|
||||
})
|
||||
|
||||
successResponse(res, sanitizePerson(created), '创建成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '创建使用者失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updatePerson = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const {
|
||||
nickname,
|
||||
real_name,
|
||||
id_number,
|
||||
department,
|
||||
position,
|
||||
phone,
|
||||
email,
|
||||
status,
|
||||
remarks
|
||||
} = req.body as Record<string, any>
|
||||
|
||||
const person = await prisma.person.findUnique({ where: { id: Number(id) } })
|
||||
if (!person) {
|
||||
return errorResponse(res, '使用者不存在', 404)
|
||||
}
|
||||
|
||||
if (id_number && id_number !== person.id_number) {
|
||||
const exists = await prisma.person.findUnique({ where: { id_number } })
|
||||
if (exists) {
|
||||
return errorResponse(res, '证件编号已存在', 409)
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prisma.person.update({
|
||||
where: { id: Number(id) },
|
||||
data: {
|
||||
nickname: nickname ?? person.nickname,
|
||||
real_name: real_name ?? person.real_name,
|
||||
id_number: id_number ?? person.id_number,
|
||||
department,
|
||||
position,
|
||||
phone,
|
||||
email,
|
||||
status: status ?? person.status,
|
||||
remarks
|
||||
}
|
||||
})
|
||||
|
||||
successResponse(res, sanitizePerson(updated), '更新成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新使用者失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updatePersonStatus = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { status } = req.body as { status?: string }
|
||||
|
||||
if (!status) {
|
||||
return errorResponse(res, '状态不能为空', 422)
|
||||
}
|
||||
|
||||
const allowed = ['active', 'inactive']
|
||||
if (!allowed.includes(status)) {
|
||||
return errorResponse(res, '状态值无效', 422)
|
||||
}
|
||||
|
||||
const person = await prisma.person.findUnique({ where: { id: Number(id) } })
|
||||
if (!person) {
|
||||
return errorResponse(res, '使用者不存在', 404)
|
||||
}
|
||||
|
||||
const updated = await prisma.person.update({
|
||||
where: { id: Number(id) },
|
||||
data: { status }
|
||||
})
|
||||
|
||||
successResponse(res, sanitizePerson(updated), '状态更新成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新使用者状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
108
backend/src/controllers/settingsController.ts
Normal file
108
backend/src/controllers/settingsController.ts
Normal file
@ -0,0 +1,108 @@
|
||||
import type { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
const DEFAULT_SITE_NAME = '摄影设备借还系统'
|
||||
const DEFAULT_THEME_COLOR = '#409EFF'
|
||||
const DEFAULT_LOGO_URL = 'https://s3.1080p.hk/shuzhou/2025/05/18/8ebadf0a7cc34eaea00e8619b8efb827.png'
|
||||
|
||||
const mapConfigResponse = (config: any) => {
|
||||
if (!config) {
|
||||
return {
|
||||
site_name: DEFAULT_SITE_NAME,
|
||||
logo_url: DEFAULT_LOGO_URL,
|
||||
favicon_url: '',
|
||||
theme_color: DEFAULT_THEME_COLOR,
|
||||
updated_at: null,
|
||||
updated_by: null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
site_name: config.site_name || DEFAULT_SITE_NAME,
|
||||
logo_url: DEFAULT_LOGO_URL,
|
||||
favicon_url: '',
|
||||
theme_color: config.theme_color || DEFAULT_THEME_COLOR,
|
||||
updated_at: config.updated_at,
|
||||
updated_by: config.updatedBy
|
||||
? {
|
||||
id: config.updatedBy.id,
|
||||
username: config.updatedBy.username,
|
||||
name: config.updatedBy.name
|
||||
}
|
||||
: null
|
||||
}
|
||||
}
|
||||
|
||||
export const getSiteConfig = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const config = await prisma.siteConfig.findFirst({
|
||||
orderBy: { updated_at: 'desc' },
|
||||
include: {
|
||||
updatedBy: {
|
||||
select: {
|
||||
id: true,
|
||||
username: true,
|
||||
name: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
successResponse(res, mapConfigResponse(config), '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取站点配置失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updateSiteConfig = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { site_name, theme_color } = req.body as { site_name?: string; theme_color?: string }
|
||||
|
||||
if (!site_name) {
|
||||
return errorResponse(res, '网站名称不能为空', 422)
|
||||
}
|
||||
|
||||
const existing = await prisma.siteConfig.findFirst({
|
||||
orderBy: { updated_at: 'desc' }
|
||||
})
|
||||
|
||||
const data: any = {
|
||||
site_name: site_name.trim(),
|
||||
theme_color: theme_color || DEFAULT_THEME_COLOR,
|
||||
updated_at: new Date(),
|
||||
updated_by: res.locals.user?.id ?? null,
|
||||
logo_url: DEFAULT_LOGO_URL,
|
||||
favicon_url: null
|
||||
}
|
||||
|
||||
const result = existing
|
||||
? await prisma.siteConfig.update({
|
||||
where: { id: existing.id },
|
||||
data
|
||||
})
|
||||
: await prisma.siteConfig.create({
|
||||
data: {
|
||||
site_name: data.site_name,
|
||||
theme_color: data.theme_color,
|
||||
logo_url: data.logo_url,
|
||||
favicon_url: data.favicon_url,
|
||||
updated_by: data.updated_by
|
||||
}
|
||||
})
|
||||
|
||||
const response = await prisma.siteConfig.findUnique({
|
||||
where: { id: result.id },
|
||||
include: {
|
||||
updatedBy: {
|
||||
select: { id: true, username: true, name: true }
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
successResponse(res, mapConfigResponse(response), '保存成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新站点配置失败')
|
||||
}
|
||||
}
|
||||
|
||||
202
backend/src/controllers/statisticsController.ts
Normal file
202
backend/src/controllers/statisticsController.ts
Normal file
@ -0,0 +1,202 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
// 获取首页统计数据
|
||||
export const getDashboardStats = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const startOfToday = new Date(new Date().setHours(0, 0, 0, 0))
|
||||
|
||||
const [equipmentList, todayBorrowCount, todayReturnCount] = await Promise.all([
|
||||
prisma.equipment.findMany(),
|
||||
prisma.borrowRecord.count({
|
||||
where: {
|
||||
borrow_time: {
|
||||
gte: startOfToday
|
||||
}
|
||||
}
|
||||
}),
|
||||
prisma.borrowRecord.count({
|
||||
where: {
|
||||
return_time: {
|
||||
gte: startOfToday
|
||||
}
|
||||
}
|
||||
})
|
||||
])
|
||||
|
||||
const totalEquipmentQuantity = equipmentList.reduce((sum, eq) => sum + (eq.total_quantity || 0), 0)
|
||||
const availableEquipmentQuantity = equipmentList.reduce(
|
||||
(sum, eq) => sum + (eq.remaining_quantity || 0),
|
||||
0
|
||||
)
|
||||
const borrowedEquipmentQuantity = equipmentList.reduce(
|
||||
(sum, eq) => sum + Math.max((eq.total_quantity || 0) - (eq.remaining_quantity || 0), 0),
|
||||
0
|
||||
)
|
||||
const maintenanceEquipmentQuantity = equipmentList
|
||||
.filter((eq) => eq.status === '维护中')
|
||||
.reduce((sum, eq) => sum + (eq.total_quantity || 0), 0)
|
||||
|
||||
const inventoryByTypeMap = equipmentList.reduce((acc, eq) => {
|
||||
const type = eq.equipment_type || '其他'
|
||||
if (!acc[type]) {
|
||||
acc[type] = {
|
||||
equipment_type: type,
|
||||
total_quantity: 0,
|
||||
available_quantity: 0,
|
||||
borrowed_quantity: 0
|
||||
}
|
||||
}
|
||||
const availableQuantity = eq.remaining_quantity || 0
|
||||
const totalQuantity = eq.total_quantity || 0
|
||||
acc[type].total_quantity += totalQuantity
|
||||
acc[type].available_quantity += availableQuantity
|
||||
acc[type].borrowed_quantity += Math.max(totalQuantity - availableQuantity, 0)
|
||||
return acc
|
||||
}, {} as Record<
|
||||
string,
|
||||
{
|
||||
equipment_type: string
|
||||
total_quantity: number
|
||||
available_quantity: number
|
||||
borrowed_quantity: number
|
||||
}
|
||||
>)
|
||||
|
||||
const inventoryByType = Object.values(inventoryByTypeMap).filter(
|
||||
(item) => item.total_quantity > 0
|
||||
)
|
||||
|
||||
const totalValue = equipmentList.reduce((sum, eq) => sum + Number(eq.total_value), 0)
|
||||
const borrowedValue = equipmentList.reduce((sum, eq) => sum + Number(eq.borrowed_value), 0)
|
||||
const availableValue = equipmentList.reduce((sum, eq) => sum + Number(eq.available_value), 0)
|
||||
const maintenanceValue = equipmentList
|
||||
.filter(eq => eq.status === '维护中')
|
||||
.reduce((sum, eq) => sum + Number(eq.available_value), 0)
|
||||
|
||||
// 获取今日借用/归还价值
|
||||
const todayBorrowRecords = await prisma.borrowRecord.findMany({
|
||||
where: {
|
||||
borrow_time: {
|
||||
gte: startOfToday
|
||||
}
|
||||
},
|
||||
include: {
|
||||
equipment: true
|
||||
}
|
||||
})
|
||||
|
||||
const todayBorrowValue = todayBorrowRecords.reduce(
|
||||
(sum, record) => sum + Number(record.equipment.unit_price),
|
||||
0
|
||||
)
|
||||
|
||||
const todayReturnRecords = await prisma.borrowRecord.findMany({
|
||||
where: {
|
||||
return_time: {
|
||||
gte: startOfToday
|
||||
}
|
||||
},
|
||||
include: {
|
||||
equipment: true
|
||||
}
|
||||
})
|
||||
|
||||
const todayReturnValue = todayReturnRecords.reduce(
|
||||
(sum, record) => sum + Number(record.equipment.unit_price),
|
||||
0
|
||||
)
|
||||
|
||||
const usageRate =
|
||||
totalEquipmentQuantity > 0 ? (borrowedEquipmentQuantity / totalEquipmentQuantity) * 100 : 0
|
||||
const valueUsageRate = totalValue > 0 ? (borrowedValue / totalValue) * 100 : 0
|
||||
|
||||
successResponse(res, {
|
||||
total_equipment: totalEquipmentQuantity,
|
||||
available_equipment: availableEquipmentQuantity,
|
||||
borrowed_equipment: borrowedEquipmentQuantity,
|
||||
maintenance_equipment: maintenanceEquipmentQuantity,
|
||||
usage_rate: usageRate,
|
||||
today_borrow: todayBorrowCount,
|
||||
today_return: todayReturnCount,
|
||||
total_value: totalValue,
|
||||
borrowed_value: borrowedValue,
|
||||
available_value: availableValue,
|
||||
maintenance_value: maintenanceValue,
|
||||
value_usage_rate: valueUsageRate,
|
||||
today_borrow_value: todayBorrowValue,
|
||||
today_return_value: todayReturnValue,
|
||||
inventory_by_type: inventoryByType
|
||||
}, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取统计数据失败')
|
||||
}
|
||||
}
|
||||
|
||||
// 获取设备价值统计
|
||||
export const getValueStatistics = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { equipment_type, start_date, end_date } = req.query
|
||||
|
||||
const where: any = {}
|
||||
|
||||
if (equipment_type) {
|
||||
where.equipment_type = equipment_type
|
||||
}
|
||||
|
||||
if (start_date || end_date) {
|
||||
where.created_at = {}
|
||||
if (start_date) {
|
||||
where.created_at.gte = new Date(start_date as string)
|
||||
}
|
||||
if (end_date) {
|
||||
where.created_at.lte = new Date(end_date as string)
|
||||
}
|
||||
}
|
||||
|
||||
const equipmentList = await prisma.equipment.findMany({ where })
|
||||
|
||||
const totalValue = equipmentList.reduce((sum, eq) => sum + Number(eq.total_value), 0)
|
||||
const borrowedValue = equipmentList.reduce((sum, eq) => sum + Number(eq.borrowed_value), 0)
|
||||
const availableValue = equipmentList.reduce((sum, eq) => sum + Number(eq.available_value), 0)
|
||||
const maintenanceValue = equipmentList
|
||||
.filter(eq => eq.status === '维护中')
|
||||
.reduce((sum, eq) => sum + Number(eq.available_value), 0)
|
||||
|
||||
// 按设备类型统计
|
||||
const valueByType = ['相机', '镜头', '三脚架', '闪光灯', '摄影配饰品'].map(type => {
|
||||
const typeEquipment = equipmentList.filter(eq => eq.equipment_type === type)
|
||||
return {
|
||||
equipment_type: type,
|
||||
total_value: typeEquipment.reduce((sum, eq) => sum + Number(eq.total_value), 0),
|
||||
borrowed_value: typeEquipment.reduce((sum, eq) => sum + Number(eq.borrowed_value), 0),
|
||||
available_value: typeEquipment.reduce((sum, eq) => sum + Number(eq.available_value), 0)
|
||||
}
|
||||
}).filter(item => item.total_value > 0)
|
||||
|
||||
// 价值最高的设备(Top 10)
|
||||
const topEquipment = equipmentList
|
||||
.map(eq => ({
|
||||
equipment_name: eq.equipment_name,
|
||||
unit_price: Number(eq.unit_price),
|
||||
total_value: Number(eq.total_value),
|
||||
borrowed_value: Number(eq.borrowed_value),
|
||||
available_value: Number(eq.available_value)
|
||||
}))
|
||||
.sort((a, b) => b.total_value - a.total_value)
|
||||
.slice(0, 10)
|
||||
|
||||
successResponse(res, {
|
||||
total_value: totalValue,
|
||||
borrowed_value: borrowedValue,
|
||||
available_value: availableValue,
|
||||
maintenance_value: maintenanceValue,
|
||||
value_by_type: valueByType,
|
||||
top_equipment: topEquipment
|
||||
}, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取价值统计失败')
|
||||
}
|
||||
}
|
||||
|
||||
166
backend/src/controllers/storageLocationController.ts
Normal file
166
backend/src/controllers/storageLocationController.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import { Request, Response } from 'express'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
const baseSelect = {
|
||||
id: true,
|
||||
name: true,
|
||||
code: true,
|
||||
status: true,
|
||||
description: true,
|
||||
created_at: true,
|
||||
updated_at: true
|
||||
}
|
||||
|
||||
export const getStorageLocationOptions = async (_req: Request, res: Response) => {
|
||||
try {
|
||||
const locations = await prisma.storageLocation.findMany({
|
||||
where: { status: 'active' },
|
||||
orderBy: { name: 'asc' },
|
||||
select: baseSelect
|
||||
})
|
||||
|
||||
successResponse(res, locations, '获取成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取库位列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const getStorageLocationList = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { page = 1, pageSize = 10, keyword, status } = req.query
|
||||
|
||||
const where: any = {}
|
||||
if (status) {
|
||||
where.status = status
|
||||
}
|
||||
if (keyword) {
|
||||
where.OR = [
|
||||
{ name: { contains: keyword as string } },
|
||||
{ code: { contains: keyword as string } },
|
||||
{ description: { contains: keyword as string } }
|
||||
]
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(pageSize)
|
||||
|
||||
const [list, total] = await Promise.all([
|
||||
prisma.storageLocation.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(pageSize),
|
||||
orderBy: { updated_at: 'desc' },
|
||||
select: {
|
||||
...baseSelect,
|
||||
_count: {
|
||||
select: { equipments: true }
|
||||
}
|
||||
}
|
||||
}),
|
||||
prisma.storageLocation.count({ where })
|
||||
])
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
list,
|
||||
total,
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize)
|
||||
},
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取库位列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const createStorageLocation = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { name, code, description } = req.body as {
|
||||
name?: string
|
||||
code?: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
if (!name || !name.trim()) {
|
||||
return errorResponse(res, '库位名称不能为空', 422)
|
||||
}
|
||||
|
||||
const location = await prisma.storageLocation.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
code: code?.trim() || null,
|
||||
description: description?.trim() || null
|
||||
},
|
||||
select: baseSelect
|
||||
})
|
||||
|
||||
successResponse(res, location, '新增库位成功')
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') {
|
||||
return errorResponse(res, '库位编码已存在')
|
||||
}
|
||||
errorResponse(res, error.message || '新增库位失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updateStorageLocation = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { name, code, description, status } = req.body as {
|
||||
name?: string
|
||||
code?: string
|
||||
description?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
const existing = await prisma.storageLocation.findUnique({
|
||||
where: { id: Number(id) }
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
return errorResponse(res, '库位不存在', 404)
|
||||
}
|
||||
|
||||
const updated = await prisma.storageLocation.update({
|
||||
where: { id: Number(id) },
|
||||
data: {
|
||||
name: name?.trim() || existing.name,
|
||||
code: code?.trim() || null,
|
||||
description: description?.trim() || null,
|
||||
status: status || existing.status
|
||||
},
|
||||
select: baseSelect
|
||||
})
|
||||
|
||||
successResponse(res, updated, '更新库位成功')
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') {
|
||||
return errorResponse(res, '库位编码已存在')
|
||||
}
|
||||
errorResponse(res, error.message || '更新库位失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updateStorageLocationStatus = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { status } = req.body as { status?: string }
|
||||
|
||||
if (!status) {
|
||||
return errorResponse(res, '状态不能为空', 422)
|
||||
}
|
||||
|
||||
const location = await prisma.storageLocation.update({
|
||||
where: { id: Number(id) },
|
||||
data: { status },
|
||||
select: baseSelect
|
||||
})
|
||||
|
||||
successResponse(res, location, '更新状态成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
197
backend/src/controllers/userController.ts
Normal file
197
backend/src/controllers/userController.ts
Normal file
@ -0,0 +1,197 @@
|
||||
import { Request, Response } from 'express'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import prisma from '../utils/prisma'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
|
||||
const SALT_ROUNDS = 10
|
||||
|
||||
const sanitizeUser = (user: any) => ({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
phone: user.phone,
|
||||
role: user.role,
|
||||
roles: [user.role],
|
||||
status: user.status,
|
||||
last_login_at: user.last_login_at,
|
||||
created_at: user.created_at,
|
||||
updated_at: user.updated_at
|
||||
})
|
||||
|
||||
export const getUserList = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { page = 1, pageSize = 10, keyword, role, status } = req.query
|
||||
|
||||
const where: any = {}
|
||||
|
||||
if (keyword) {
|
||||
where.OR = [
|
||||
{ username: { contains: keyword as string } },
|
||||
{ name: { contains: keyword as string } },
|
||||
{ email: { contains: keyword as string } }
|
||||
]
|
||||
}
|
||||
|
||||
if (role) {
|
||||
where.role = role
|
||||
}
|
||||
|
||||
if (status) {
|
||||
where.status = status
|
||||
}
|
||||
|
||||
const skip = (Number(page) - 1) * Number(pageSize)
|
||||
|
||||
const [list, total] = await Promise.all([
|
||||
prisma.user.findMany({
|
||||
where,
|
||||
skip,
|
||||
take: Number(pageSize),
|
||||
orderBy: { created_at: 'desc' }
|
||||
}),
|
||||
prisma.user.count({ where })
|
||||
])
|
||||
|
||||
successResponse(
|
||||
res,
|
||||
{
|
||||
list: list.map(sanitizeUser),
|
||||
total,
|
||||
page: Number(page),
|
||||
pageSize: Number(pageSize)
|
||||
},
|
||||
'获取成功'
|
||||
)
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '获取用户列表失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const createUser = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { username, password, name, email, phone, roles, role, status } = req.body as Record<
|
||||
string,
|
||||
any
|
||||
>
|
||||
|
||||
if (!username || !password || !name) {
|
||||
return errorResponse(res, '用户名、姓名和密码为必填项', 422)
|
||||
}
|
||||
|
||||
const existing = await prisma.user.findUnique({ where: { username } })
|
||||
if (existing) {
|
||||
return errorResponse(res, '用户名已存在', 409)
|
||||
}
|
||||
|
||||
const primaryRole =
|
||||
(Array.isArray(roles) ? roles[0] : roles) || role || (username === 'admin' ? 'admin' : 'user')
|
||||
|
||||
const hashedPassword = await bcrypt.hash(password, SALT_ROUNDS)
|
||||
|
||||
const created = await prisma.user.create({
|
||||
data: {
|
||||
username,
|
||||
password: hashedPassword,
|
||||
name,
|
||||
email,
|
||||
phone,
|
||||
role: primaryRole,
|
||||
status: status || 'active'
|
||||
}
|
||||
})
|
||||
|
||||
successResponse(res, sanitizeUser(created), '创建成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '创建用户失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updateUser = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { name, email, phone, roles, role, status } = req.body as Record<string, any>
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: Number(id) } })
|
||||
if (!user) {
|
||||
return errorResponse(res, '用户不存在', 404)
|
||||
}
|
||||
|
||||
const updateData: any = {
|
||||
name: name ?? user.name,
|
||||
email: email ?? user.email,
|
||||
phone: phone ?? user.phone
|
||||
}
|
||||
|
||||
const newRole = (Array.isArray(roles) ? roles[0] : roles) || role
|
||||
if (newRole) {
|
||||
updateData.role = newRole
|
||||
}
|
||||
|
||||
if (status) {
|
||||
updateData.status = status
|
||||
}
|
||||
|
||||
const updated = await prisma.user.update({
|
||||
where: { id: Number(id) },
|
||||
data: updateData
|
||||
})
|
||||
|
||||
successResponse(res, sanitizeUser(updated), '更新成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新用户失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const resetPassword = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { new_password } = req.body as { new_password?: string }
|
||||
|
||||
if (!new_password) {
|
||||
return errorResponse(res, '新密码不能为空', 422)
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: Number(id) } })
|
||||
if (!user) {
|
||||
return errorResponse(res, '用户不存在', 404)
|
||||
}
|
||||
|
||||
const hashedPassword = await bcrypt.hash(new_password, SALT_ROUNDS)
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: Number(id) },
|
||||
data: { password: hashedPassword }
|
||||
})
|
||||
|
||||
successResponse(res, null, '密码重置成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '重置密码失败')
|
||||
}
|
||||
}
|
||||
|
||||
export const updateUserStatus = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { id } = req.params
|
||||
const { status } = req.body as { status?: string }
|
||||
|
||||
if (!status) {
|
||||
return errorResponse(res, '状态不能为空', 422)
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { id: Number(id) } })
|
||||
if (!user) {
|
||||
return errorResponse(res, '用户不存在', 404)
|
||||
}
|
||||
|
||||
const updated = await prisma.user.update({
|
||||
where: { id: Number(id) },
|
||||
data: { status }
|
||||
})
|
||||
|
||||
successResponse(res, sanitizeUser(updated), '状态更新成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error.message || '更新用户状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
77
backend/src/index.ts
Normal file
77
backend/src/index.ts
Normal file
@ -0,0 +1,77 @@
|
||||
import path from 'path'
|
||||
import express from 'express'
|
||||
import cors from 'cors'
|
||||
import dotenv from 'dotenv'
|
||||
import session from 'express-session'
|
||||
import equipmentRoutes from './routes/equipment'
|
||||
import { scanEquipment } from './controllers/equipmentController'
|
||||
import borrowRoutes, { returnRouter } from './routes/borrow'
|
||||
import statisticsRoutes from './routes/statistics'
|
||||
import authRoutes from './routes/auth'
|
||||
import barcodeRoutes from './routes/barcode'
|
||||
import settingsRoutes from './routes/settings'
|
||||
import usersRoutes from './routes/users'
|
||||
import personRoutes from './routes/persons'
|
||||
import storageLocationRoutes from './routes/storageLocations'
|
||||
import { keycloak, memoryStore } from './utils/keycloak'
|
||||
import { protect, requireAdmin } from './middleware/auth'
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const app = express()
|
||||
const PORT = process.env.PORT || 3000
|
||||
const SESSION_SECRET = process.env.SESSION_SECRET || 'equipment-management-secret'
|
||||
|
||||
// Middleware
|
||||
app.use(cors({ origin: true, credentials: true }))
|
||||
app.use(express.json())
|
||||
app.use(express.urlencoded({ extended: true }))
|
||||
app.use(
|
||||
session({
|
||||
secret: SESSION_SECRET,
|
||||
resave: false,
|
||||
saveUninitialized: false,
|
||||
store: memoryStore,
|
||||
cookie: {
|
||||
secure: false,
|
||||
maxAge: 1000 * 60 * 60 // 1 hour
|
||||
}
|
||||
})
|
||||
)
|
||||
if (process.env.AUTH_MODE !== 'local') {
|
||||
app.use(keycloak.middleware({ logout: '/api/auth/logout', admin: '/keycloak' }))
|
||||
}
|
||||
|
||||
app.use('/uploads', express.static(path.resolve(__dirname, '..', 'uploads')))
|
||||
|
||||
// Routes
|
||||
app.get('/api/equipment/scan/:equipment_code', protect(), scanEquipment)
|
||||
app.use('/api/equipment', protect(), requireAdmin(), equipmentRoutes)
|
||||
app.use('/api/borrow', protect(), borrowRoutes)
|
||||
app.use('/api/return', protect(), returnRouter)
|
||||
app.use('/api/statistics', protect(), statisticsRoutes)
|
||||
app.use('/api/barcode', protect(), barcodeRoutes)
|
||||
app.use('/api/auth', authRoutes)
|
||||
app.use('/api/settings', protect(), requireAdmin(), settingsRoutes)
|
||||
app.use('/api/users', protect(), requireAdmin(), usersRoutes)
|
||||
app.use('/api/persons', personRoutes)
|
||||
app.use('/api/storage-locations', storageLocationRoutes)
|
||||
|
||||
// Health check
|
||||
app.get('/api/health', (req, res) => {
|
||||
res.json({ status: 'ok', message: 'Server is running' })
|
||||
})
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
console.error('Error:', err)
|
||||
res.status(err.status || 500).json({
|
||||
code: err.status || 500,
|
||||
message: err.message || 'Internal Server Error',
|
||||
data: null
|
||||
})
|
||||
})
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on http://localhost:${PORT}`)
|
||||
})
|
||||
58
backend/src/middleware/auth.ts
Normal file
58
backend/src/middleware/auth.ts
Normal file
@ -0,0 +1,58 @@
|
||||
import type { Request, Response, NextFunction, RequestHandler } from 'express'
|
||||
import { keycloak } from '../utils/keycloak'
|
||||
|
||||
const isLocalAuth = () => process.env.AUTH_MODE === 'local'
|
||||
|
||||
// 选择保护策略:local 使用会话校验;默认使用 Keycloak 保护
|
||||
export function protect(): RequestHandler {
|
||||
if (isLocalAuth()) {
|
||||
return function localSessionProtect(req: Request, res: Response, next: NextFunction) {
|
||||
const sessionUser = (req as any).session?.user
|
||||
if (sessionUser) {
|
||||
res.locals.user = sessionUser
|
||||
return next()
|
||||
}
|
||||
return res.status(401).json({ code: 401, message: '未登录', data: null })
|
||||
}
|
||||
}
|
||||
|
||||
const keycloakMiddleware = keycloak.protect()
|
||||
|
||||
return function keycloakWrapper(req: Request, res: Response, next: NextFunction) {
|
||||
keycloakMiddleware(req, res, (err?: any) => {
|
||||
if (err) {
|
||||
return next(err)
|
||||
}
|
||||
const tokenContent = (req as any).kauth?.grant?.access_token?.content as Record<string, any> | undefined
|
||||
if (tokenContent) {
|
||||
res.locals.user = {
|
||||
id: tokenContent.sub,
|
||||
username: tokenContent.preferred_username,
|
||||
name: tokenContent.name || tokenContent.preferred_username,
|
||||
roles: tokenContent.realm_access?.roles || []
|
||||
}
|
||||
}
|
||||
next()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function requireAdmin(): RequestHandler {
|
||||
return function adminGuard(req: Request, res: Response, next: NextFunction) {
|
||||
if (isLocalAuth()) {
|
||||
const sessionUser = (req as any).session?.user
|
||||
if (sessionUser && (sessionUser.role === 'admin' || sessionUser.roles?.includes('admin'))) {
|
||||
res.locals.user = sessionUser
|
||||
return next()
|
||||
}
|
||||
return res.status(403).json({ code: 403, message: '权限不足', data: null })
|
||||
}
|
||||
|
||||
const roles: string[] =
|
||||
((req as any).kauth?.grant?.access_token?.content?.realm_access?.roles as string[]) || []
|
||||
if (roles.includes('admin')) {
|
||||
return next()
|
||||
}
|
||||
return res.status(403).json({ code: 403, message: '权限不足', data: null })
|
||||
}
|
||||
}
|
||||
117
backend/src/routes/auth.ts
Normal file
117
backend/src/routes/auth.ts
Normal file
@ -0,0 +1,117 @@
|
||||
import { Router } from 'express'
|
||||
import { successResponse, errorResponse } from '../utils/response'
|
||||
import { keycloak } from '../utils/keycloak'
|
||||
import type { Request, Response } from 'express'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import prisma from '../utils/prisma'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 获取当前用户信息
|
||||
router.get('/user', (req, res) => {
|
||||
if (process.env.AUTH_MODE === 'local') {
|
||||
const user = (req as any).session?.user
|
||||
if (!user) {
|
||||
return errorResponse(res, '未登录', 401)
|
||||
}
|
||||
return successResponse(res, user, '获取成功')
|
||||
}
|
||||
const grant = (req as any).kauth?.grant
|
||||
const token = grant?.access_token
|
||||
|
||||
if (!token) {
|
||||
return errorResponse(res, '无法获取用户信息', 401)
|
||||
}
|
||||
|
||||
const tokenContent = token.content as Record<string, any>
|
||||
|
||||
successResponse(res, {
|
||||
id: tokenContent.sub,
|
||||
username: tokenContent.preferred_username,
|
||||
name: tokenContent.name || tokenContent.preferred_username,
|
||||
email: tokenContent.email,
|
||||
roles: tokenContent.realm_access?.roles || []
|
||||
}, '获取成功')
|
||||
})
|
||||
|
||||
// Keycloak 配置信息(前端使用)
|
||||
router.get('/config', (req, res) => {
|
||||
successResponse(res, {
|
||||
url: process.env.KEYCLOAK_URL || 'http://localhost:8080',
|
||||
realm: process.env.KEYCLOAK_REALM || 'equipment-management',
|
||||
clientId: process.env.KEYCLOAK_CLIENT_ID || 'equipment-client'
|
||||
}, '获取成功')
|
||||
})
|
||||
|
||||
// 退出登录
|
||||
router.post('/logout', async (req, res) => {
|
||||
try {
|
||||
if (process.env.AUTH_MODE === 'local') {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
req.session?.destroy((err) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
return
|
||||
}
|
||||
resolve()
|
||||
})
|
||||
})
|
||||
return successResponse(res, null, '退出成功')
|
||||
}
|
||||
// Keycloak 模式下仅返回成功,由前端触发 keycloak.logout()
|
||||
return successResponse(res, null, '退出成功')
|
||||
} catch (error: any) {
|
||||
errorResponse(res, error?.message || '退出失败')
|
||||
}
|
||||
})
|
||||
|
||||
// 本地登录模式(不跳转 Keycloak)
|
||||
router.post('/local/login', async (req: Request, res: Response) => {
|
||||
if (process.env.AUTH_MODE !== 'local') {
|
||||
return errorResponse(res, '本地登录未启用', 400)
|
||||
}
|
||||
const { username, password } = req.body as { username?: string; password?: string }
|
||||
if (!username || !password) {
|
||||
return errorResponse(res, '用户名与密码必填', 422)
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { username } })
|
||||
if (!user || user.status !== 'active') {
|
||||
return errorResponse(res, '用户名或密码错误', 401)
|
||||
}
|
||||
|
||||
const validPassword = await bcrypt.compare(password, user.password)
|
||||
if (!validPassword) {
|
||||
return errorResponse(res, '用户名或密码错误', 401)
|
||||
}
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { last_login_at: new Date() }
|
||||
})
|
||||
|
||||
const userPayload = {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
phone: user.phone,
|
||||
role: user.role,
|
||||
roles: [user.role],
|
||||
status: user.status
|
||||
}
|
||||
|
||||
;(req as any).session.user = userPayload
|
||||
|
||||
return successResponse(
|
||||
res,
|
||||
{
|
||||
token: 'session',
|
||||
user: userPayload
|
||||
},
|
||||
'登录成功'
|
||||
)
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
13
backend/src/routes/barcode.ts
Normal file
13
backend/src/routes/barcode.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getEquipmentForBarcode,
|
||||
getEquipmentBatchForBarcode
|
||||
} from '../controllers/barcodeController'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/:equipment_code', getEquipmentForBarcode)
|
||||
router.post('/batch', getEquipmentBatchForBarcode)
|
||||
|
||||
export default router
|
||||
|
||||
32
backend/src/routes/borrow.ts
Normal file
32
backend/src/routes/borrow.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
borrowEquipment,
|
||||
scanBorrow,
|
||||
scanBorrowBatch,
|
||||
getBorrowRecordByCode,
|
||||
getBorrowRecordList
|
||||
} from '../controllers/borrowController'
|
||||
|
||||
const router = Router()
|
||||
|
||||
// 借用相关
|
||||
router.post('/', borrowEquipment)
|
||||
router.post('/scan', scanBorrow)
|
||||
router.post('/scan-batch', scanBorrowBatch)
|
||||
router.get('/scan/:equipment_code', getBorrowRecordByCode)
|
||||
router.get('/records', getBorrowRecordList)
|
||||
|
||||
export default router
|
||||
|
||||
// 归还路由单独导出
|
||||
export const returnRouter = Router()
|
||||
|
||||
import {
|
||||
returnEquipment,
|
||||
scanReturn,
|
||||
scanReturnBatch
|
||||
} from '../controllers/borrowController'
|
||||
|
||||
returnRouter.post('/', returnEquipment)
|
||||
returnRouter.post('/scan', scanReturn)
|
||||
returnRouter.post('/scan-batch', scanReturnBatch)
|
||||
29
backend/src/routes/equipment.ts
Normal file
29
backend/src/routes/equipment.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getEquipmentList,
|
||||
getEquipmentDetail,
|
||||
createEquipment,
|
||||
updateEquipment,
|
||||
deleteEquipment,
|
||||
generateCode,
|
||||
verifyCode,
|
||||
scanEquipment
|
||||
} from '../controllers/equipmentController'
|
||||
import { requireAdmin } from '../middleware/auth'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/scan/:equipment_code', scanEquipment)
|
||||
|
||||
router.use(requireAdmin())
|
||||
|
||||
router.get('/list', getEquipmentList)
|
||||
router.get('/:id', getEquipmentDetail)
|
||||
router.post('/', createEquipment)
|
||||
router.put('/:id', updateEquipment)
|
||||
router.delete('/:id', deleteEquipment)
|
||||
router.post('/generate-code', generateCode)
|
||||
router.post('/verify-code', verifyCode)
|
||||
|
||||
export default router
|
||||
|
||||
23
backend/src/routes/persons.ts
Normal file
23
backend/src/routes/persons.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getPersonList,
|
||||
createPerson,
|
||||
updatePerson,
|
||||
updatePersonStatus,
|
||||
getPersonDetail
|
||||
} from '../controllers/personController'
|
||||
import { protect, requireAdmin } from '../middleware/auth'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.use(protect())
|
||||
|
||||
router.get('/', getPersonList)
|
||||
router.get('/:id', getPersonDetail)
|
||||
|
||||
router.post('/', requireAdmin(), createPerson)
|
||||
router.put('/:id', requireAdmin(), updatePerson)
|
||||
router.patch('/:id/status', requireAdmin(), updatePersonStatus)
|
||||
|
||||
export default router
|
||||
|
||||
17
backend/src/routes/settings.ts
Normal file
17
backend/src/routes/settings.ts
Normal file
@ -0,0 +1,17 @@
|
||||
import { Router } from 'express'
|
||||
import { getSiteConfig, updateSiteConfig } from '../controllers/settingsController'
|
||||
import { protect, requireAdmin } from '../middleware/auth'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/site', getSiteConfig)
|
||||
|
||||
router.put(
|
||||
'/site',
|
||||
protect(),
|
||||
requireAdmin(),
|
||||
updateSiteConfig
|
||||
)
|
||||
|
||||
export default router
|
||||
|
||||
13
backend/src/routes/statistics.ts
Normal file
13
backend/src/routes/statistics.ts
Normal file
@ -0,0 +1,13 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getDashboardStats,
|
||||
getValueStatistics
|
||||
} from '../controllers/statisticsController'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/dashboard', getDashboardStats)
|
||||
router.get('/value', getValueStatistics)
|
||||
|
||||
export default router
|
||||
|
||||
20
backend/src/routes/storageLocations.ts
Normal file
20
backend/src/routes/storageLocations.ts
Normal file
@ -0,0 +1,20 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getStorageLocationOptions,
|
||||
getStorageLocationList,
|
||||
createStorageLocation,
|
||||
updateStorageLocation,
|
||||
updateStorageLocationStatus
|
||||
} from '../controllers/storageLocationController'
|
||||
import { protect, requireAdmin } from '../middleware/auth'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/options', protect(), getStorageLocationOptions)
|
||||
router.get('/list', protect(), requireAdmin(), getStorageLocationList)
|
||||
router.post('/', protect(), requireAdmin(), createStorageLocation)
|
||||
router.put('/:id', protect(), requireAdmin(), updateStorageLocation)
|
||||
router.patch('/:id/status', protect(), requireAdmin(), updateStorageLocationStatus)
|
||||
|
||||
export default router
|
||||
|
||||
19
backend/src/routes/users.ts
Normal file
19
backend/src/routes/users.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
getUserList,
|
||||
createUser,
|
||||
updateUser,
|
||||
resetPassword,
|
||||
updateUserStatus
|
||||
} from '../controllers/userController'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/', getUserList)
|
||||
router.post('/', createUser)
|
||||
router.put('/:id', updateUser)
|
||||
router.post('/:id/reset-password', resetPassword)
|
||||
router.patch('/:id/status', updateUserStatus)
|
||||
|
||||
export default router
|
||||
|
||||
42
backend/src/types/express-session.d.ts
vendored
Normal file
42
backend/src/types/express-session.d.ts
vendored
Normal file
@ -0,0 +1,42 @@
|
||||
declare module 'express-session' {
|
||||
import { RequestHandler } from 'express'
|
||||
|
||||
interface SessionOptions {
|
||||
secret: string
|
||||
resave?: boolean
|
||||
saveUninitialized?: boolean
|
||||
store?: Store
|
||||
cookie?: {
|
||||
secure?: boolean
|
||||
maxAge?: number
|
||||
}
|
||||
}
|
||||
|
||||
interface Store {
|
||||
get: (sid: string, callback: (err: any, sess: any | null) => void) => void
|
||||
set: (sid: string, sess: any, callback?: (err?: any) => void) => void
|
||||
destroy: (sid: string, callback?: (err?: any) => void) => void
|
||||
}
|
||||
|
||||
class MemoryStore implements Store {
|
||||
get: Store['get']
|
||||
set: Store['set']
|
||||
destroy: Store['destroy']
|
||||
}
|
||||
|
||||
interface Session {
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
interface SessionRequest extends Express.Request {
|
||||
session?: Session
|
||||
}
|
||||
|
||||
function session(options: SessionOptions): RequestHandler
|
||||
|
||||
namespace session {
|
||||
export { MemoryStore }
|
||||
}
|
||||
|
||||
export = session
|
||||
}
|
||||
106
backend/src/utils/equipmentCode.ts
Normal file
106
backend/src/utils/equipmentCode.ts
Normal file
@ -0,0 +1,106 @@
|
||||
// 设备类型数字代码映射(纯数字编码)
|
||||
const EQUIPMENT_TYPE_NUMBERS: Record<string, number> = {
|
||||
'相机': 1,
|
||||
'镜头': 2,
|
||||
'三脚架': 3,
|
||||
'闪光灯': 4,
|
||||
'摄影配饰品': 5
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成设备编码(纯数字格式)
|
||||
* 格式: {类型数字}{库位ID(4位)}{序号(5位)}
|
||||
* 例如: 1000100001 (类型1,库位1,序号00001)
|
||||
* 如果没有库位,库位ID为0000
|
||||
*
|
||||
* 确保唯一性:
|
||||
* 1. 查找该类型和库位的最大序号,避免并发问题
|
||||
* 2. 检查生成的编码是否已存在,如果存在则递增序号重试
|
||||
* 3. 最多重试10次,防止无限循环
|
||||
*/
|
||||
export const generateEquipmentCode = async (
|
||||
equipmentType: string,
|
||||
prisma: any,
|
||||
storageLocationId?: number | null
|
||||
): Promise<string> => {
|
||||
const typeNumber = EQUIPMENT_TYPE_NUMBERS[equipmentType] || 0
|
||||
|
||||
// 获取库位ID,如果没有库位则为0
|
||||
const locationId = storageLocationId || 0
|
||||
|
||||
// 格式前缀:{类型数字}{库位ID(4位)}
|
||||
const typeCode = String(typeNumber)
|
||||
const locationCode = String(locationId).padStart(4, '0')
|
||||
const prefix = `${typeCode}${locationCode}`
|
||||
|
||||
// 查找该类型和库位的所有设备,提取最大序号
|
||||
// 使用这种方式比count更安全,可以处理并发情况
|
||||
const existingEquipment = await prisma.equipment.findMany({
|
||||
where: {
|
||||
equipment_type: equipmentType,
|
||||
storage_location_id: storageLocationId || null,
|
||||
equipment_code: {
|
||||
startsWith: prefix
|
||||
}
|
||||
},
|
||||
select: {
|
||||
equipment_code: true
|
||||
},
|
||||
orderBy: {
|
||||
equipment_code: 'desc'
|
||||
},
|
||||
take: 1 // 只取最大的一条
|
||||
})
|
||||
|
||||
// 计算起始序号
|
||||
let startSequence = 1
|
||||
if (existingEquipment.length > 0) {
|
||||
// 从最大编码中提取序号
|
||||
const maxCode = existingEquipment[0].equipment_code
|
||||
if (maxCode.startsWith(prefix)) {
|
||||
const sequencePart = maxCode.substring(prefix.length)
|
||||
const maxSequence = parseInt(sequencePart, 10)
|
||||
if (!isNaN(maxSequence)) {
|
||||
startSequence = maxSequence + 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 检查序号是否溢出(5位数字最大99999)
|
||||
if (startSequence > 99999) {
|
||||
throw new Error(`设备编码序号已溢出,该类型和库位的设备数量已超过99999`)
|
||||
}
|
||||
|
||||
// 生成编码并检查唯一性,最多重试10次
|
||||
const maxRetries = 10
|
||||
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
||||
const sequence = String(startSequence + attempt).padStart(5, '0')
|
||||
const code = `${prefix}${sequence}`
|
||||
|
||||
// 检查编码是否已存在
|
||||
const existing = await prisma.equipment.findUnique({
|
||||
where: { equipment_code: code }
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
// 编码唯一,返回
|
||||
return code
|
||||
}
|
||||
|
||||
// 如果编码已存在,继续尝试下一个序号
|
||||
console.warn(`设备编码 ${code} 已存在,尝试下一个序号`)
|
||||
}
|
||||
|
||||
// 如果重试10次后仍然冲突,抛出错误
|
||||
throw new Error(`无法生成唯一的设备编码,已重试${maxRetries}次`)
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证设备编码格式(纯数字)
|
||||
*/
|
||||
export const validateEquipmentCode = (code: string): boolean => {
|
||||
// 纯数字格式,长度10位:{类型1位}{库位4位}{序号5位}
|
||||
const pattern = /^\d{10}$/
|
||||
return pattern.test(code)
|
||||
}
|
||||
|
||||
49
backend/src/utils/keycloak.ts
Normal file
49
backend/src/utils/keycloak.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import session from 'express-session'
|
||||
import Keycloak from 'keycloak-connect'
|
||||
|
||||
type KeycloakEnvConfig = {
|
||||
serverUrl: string
|
||||
realm: string
|
||||
clientId: string
|
||||
clientSecret?: string
|
||||
}
|
||||
|
||||
const requiredEnv = ['KEYCLOAK_URL', 'KEYCLOAK_REALM', 'KEYCLOAK_CLIENT_ID'] as const
|
||||
|
||||
requiredEnv.forEach((key) => {
|
||||
if (!process.env[key]) {
|
||||
console.warn(`[Keycloak] 环境变量 ${key} 未设置,Keycloak 认证可能无法正常工作。`)
|
||||
}
|
||||
})
|
||||
|
||||
const keycloakConfig: KeycloakEnvConfig = {
|
||||
serverUrl: process.env.KEYCLOAK_URL || 'http://localhost:8080',
|
||||
realm: process.env.KEYCLOAK_REALM || 'equipment-management',
|
||||
clientId: process.env.KEYCLOAK_CLIENT_ID || 'equipment-client',
|
||||
clientSecret: process.env.KEYCLOAK_CLIENT_SECRET
|
||||
}
|
||||
|
||||
const memoryStore = new session.MemoryStore()
|
||||
|
||||
const keycloak = new Keycloak(
|
||||
{
|
||||
store: memoryStore,
|
||||
scope: 'openid profile email'
|
||||
},
|
||||
{
|
||||
realm: keycloakConfig.realm,
|
||||
'auth-server-url': keycloakConfig.serverUrl,
|
||||
'ssl-required': 'external',
|
||||
resource: keycloakConfig.clientId,
|
||||
'public-client': !keycloakConfig.clientSecret,
|
||||
credentials: keycloakConfig.clientSecret
|
||||
? { secret: keycloakConfig.clientSecret }
|
||||
: undefined,
|
||||
'confidential-port': 0,
|
||||
'bearer-only': false,
|
||||
'verify-token-audience': true,
|
||||
'use-resource-role-mappings': true
|
||||
} as any
|
||||
)
|
||||
|
||||
export { keycloak, memoryStore }
|
||||
8
backend/src/utils/prisma.ts
Normal file
8
backend/src/utils/prisma.ts
Normal file
@ -0,0 +1,8 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const prisma = new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error']
|
||||
})
|
||||
|
||||
export default prisma
|
||||
|
||||
24
backend/src/utils/response.ts
Normal file
24
backend/src/utils/response.ts
Normal file
@ -0,0 +1,24 @@
|
||||
import { Response } from 'express'
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
}
|
||||
|
||||
export const successResponse = <T>(res: Response, data: T, message: string = '操作成功'): void => {
|
||||
res.json({
|
||||
code: 200,
|
||||
message,
|
||||
data
|
||||
})
|
||||
}
|
||||
|
||||
export const errorResponse = (res: Response, message: string = '操作失败', code: number = 400): void => {
|
||||
res.status(code).json({
|
||||
code,
|
||||
message,
|
||||
data: null
|
||||
})
|
||||
}
|
||||
|
||||
22
backend/tsconfig.json
Normal file
22
backend/tsconfig.json
Normal file
@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "commonjs",
|
||||
"lib": ["ES2020"],
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"resolveJsonModule": true,
|
||||
"moduleResolution": "node",
|
||||
"declaration": true,
|
||||
"declarationMap": true,
|
||||
"sourceMap": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
|
||||
24
create-admin.js
Normal file
24
create-admin.js
Normal file
@ -0,0 +1,24 @@
|
||||
const bcrypt = require('bcryptjs');
|
||||
const { PrismaClient } = require('@prisma/client');
|
||||
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
async function main() {
|
||||
const hashedPassword = bcrypt.hashSync('admin123', 10);
|
||||
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
username: 'admin',
|
||||
password: hashedPassword,
|
||||
name: '管理员',
|
||||
role: 'admin',
|
||||
status: 'active'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Created admin user:', user.id);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(console.error)
|
||||
.finally(() => prisma.$disconnect());
|
||||
33
deploy.sh
Normal file
33
deploy.sh
Normal file
@ -0,0 +1,33 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 摄影设备借还管理系统 - 部署脚本
|
||||
|
||||
set -e
|
||||
|
||||
echo "=== 开始部署摄影设备借还管理系统 ==="
|
||||
|
||||
# 停止并删除旧容器(如果存在)
|
||||
echo "清理旧容器..."
|
||||
docker-compose down 2>/dev/null || true
|
||||
|
||||
# 构建镜像
|
||||
echo "构建 Docker 镜像..."
|
||||
docker-compose build --no-cache
|
||||
|
||||
# 启动服务
|
||||
echo "启动服务..."
|
||||
docker-compose up -d
|
||||
|
||||
# 等待服务启动
|
||||
echo "等待服务启动..."
|
||||
sleep 10
|
||||
|
||||
# 检查服务状态
|
||||
echo "检查服务状态..."
|
||||
docker-compose ps
|
||||
|
||||
echo ""
|
||||
echo "=== 部署完成 ==="
|
||||
echo "前端访问地址: http://$(hostname -I | awk '{print $1}'):8080"
|
||||
echo "后端 API 地址: http://$(hostname -I | awk '{print $1}'):3001/api"
|
||||
echo "MySQL 端口: 3307"
|
||||
66
docker-compose.yml
Normal file
66
docker-compose.yml
Normal file
@ -0,0 +1,66 @@
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
mysql:
|
||||
image: mysql:8.0
|
||||
container_name: shebeiguanli-mysql
|
||||
restart: always
|
||||
environment:
|
||||
MYSQL_ROOT_PASSWORD: jsjj8888
|
||||
MYSQL_DATABASE: shebeiguanli
|
||||
MYSQL_CHARSET: utf8mb4
|
||||
MYSQL_COLLATION: utf8mb4_unicode_ci
|
||||
ports:
|
||||
- "3307:3306"
|
||||
volumes:
|
||||
- shebeiguanli-mysql-data:/var/lib/mysql
|
||||
command:
|
||||
- --default-authentication-plugin=mysql_native_password
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_unicode_ci
|
||||
healthcheck:
|
||||
test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-pjsjj8888"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
networks:
|
||||
- shebeiguanli-network
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: shebeiguanli-backend
|
||||
restart: always
|
||||
ports:
|
||||
- "3001:3000"
|
||||
environment:
|
||||
DATABASE_URL: mysql://root:jsjj8888@mysql:3306/shebeiguanli?charset=utf8mb4
|
||||
SESSION_SECRET: shebeiguanli-secret-key
|
||||
AUTH_MODE: local
|
||||
PORT: 3000
|
||||
depends_on:
|
||||
mysql:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- shebeiguanli-network
|
||||
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: shebeiguanli-frontend
|
||||
restart: always
|
||||
ports:
|
||||
- "8081:80"
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
- shebeiguanli-network
|
||||
|
||||
volumes:
|
||||
shebeiguanli-mysql-data:
|
||||
|
||||
networks:
|
||||
shebeiguanli-network:
|
||||
driver: bridge
|
||||
27
frontend/.gitignore
vendored
Normal file
27
frontend/.gitignore
vendored
Normal file
@ -0,0 +1,27 @@
|
||||
# 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?
|
||||
|
||||
.env
|
||||
.env.local
|
||||
3
frontend/.vscode/extensions.json
vendored
Normal file
3
frontend/.vscode/extensions.json
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
{
|
||||
"recommendations": ["Vue.volar"]
|
||||
}
|
||||
27
frontend/Dockerfile
Normal file
27
frontend/Dockerfile
Normal file
@ -0,0 +1,27 @@
|
||||
FROM node:20-alpine AS builder
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
|
||||
# 设置构建时环境变量
|
||||
ENV VITE_API_BASE_URL=/api
|
||||
ENV VITE_AUTH_MODE=local
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# 生产镜像
|
||||
FROM nginx:alpine
|
||||
|
||||
# 复制构建产物
|
||||
COPY --from=builder /app/dist /usr/share/nginx/html
|
||||
|
||||
# 复制 nginx 配置
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
|
||||
EXPOSE 80
|
||||
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
56
frontend/README.md
Normal file
56
frontend/README.md
Normal file
@ -0,0 +1,56 @@
|
||||
# 摄影设备借还系统 - 前端
|
||||
|
||||
## 技术栈
|
||||
|
||||
- Vue.js 3 + TypeScript
|
||||
- Vite
|
||||
- Tailwind CSS (Apple Design System)
|
||||
- Pinia
|
||||
- Vue Router 4
|
||||
- Axios
|
||||
- ECharts
|
||||
- JsBarcode
|
||||
|
||||
## 开发
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 构建
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
## UI设计规范
|
||||
|
||||
本项目严格遵循Apple官方UI设计规范(Human Interface Guidelines),包括:
|
||||
|
||||
- 使用系统字体(SF Pro)
|
||||
- Apple色彩系统
|
||||
- 圆角、阴影、毛玻璃效果
|
||||
- 响应式设计
|
||||
- 流畅的动画和过渡效果
|
||||
|
||||
## 环境变量
|
||||
|
||||
请在项目根目录创建 `.env` 文件并配置以下变量:
|
||||
|
||||
```
|
||||
VITE_API_BASE_URL=http://localhost:3000/api
|
||||
VITE_KEYCLOAK_URL=http://localhost:8080
|
||||
VITE_KEYCLOAK_REALM=equipment-management
|
||||
VITE_KEYCLOAK_CLIENT_ID=equipment-client
|
||||
```
|
||||
|
||||
## 用户认证
|
||||
|
||||
前端通过 `keycloak-js` 与 Keycloak 进行集成:
|
||||
|
||||
- 首次进入系统时会自动跳转至 Keycloak 登录页
|
||||
- 登录成功后自动刷新 Token,支持角色识别(admin/user)
|
||||
- 退出登录会调用 Keycloak 的注销流程
|
||||
|
||||
确保后端已经正确配置 Keycloak,并且客户端 `equipment-client` 允许浏览器应用访问。
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>摄影设备借还系统</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
34
frontend/nginx.conf
Normal file
34
frontend/nginx.conf
Normal file
@ -0,0 +1,34 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
|
||||
# Gzip 压缩
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
|
||||
|
||||
# 前端路由 - SPA 支持
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
}
|
||||
|
||||
# API 代理到后端
|
||||
location /api/ {
|
||||
proxy_pass http://shebeiguanli-backend:3000/api/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
}
|
||||
|
||||
# 静态资源缓存
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ {
|
||||
expires 1y;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
}
|
||||
3909
frontend/package-lock.json
generated
Normal file
3909
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
34
frontend/package.json
Normal file
34
frontend/package.json
Normal file
@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc -b && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@heroicons/vue": "^2.2.0",
|
||||
"axios": "^1.13.2",
|
||||
"echarts": "^6.0.0",
|
||||
"html2canvas": "^1.4.1",
|
||||
"jsbarcode": "^3.12.1",
|
||||
"keycloak-js": "^23.0.7",
|
||||
"pinia": "^3.0.4",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^4.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/forms": "^0.5.10",
|
||||
"@types/node": "^24.10.0",
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"autoprefixer": "^10.4.22",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "^3.4.15",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.2.2",
|
||||
"vue-tsc": "^3.1.3"
|
||||
}
|
||||
}
|
||||
10
frontend/postcss.config.js
Normal file
10
frontend/postcss.config.js
Normal file
@ -0,0 +1,10 @@
|
||||
import tailwindcss from 'tailwindcss'
|
||||
import autoprefixer from 'autoprefixer'
|
||||
|
||||
export default {
|
||||
plugins: [
|
||||
tailwindcss(),
|
||||
autoprefixer(),
|
||||
],
|
||||
}
|
||||
|
||||
1
frontend/public/vite.svg
Normal file
1
frontend/public/vite.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
15
frontend/src/App.vue
Normal file
15
frontend/src/App.vue
Normal file
@ -0,0 +1,15 @@
|
||||
<template>
|
||||
<div id="app" class="min-h-screen bg-system-background-secondary">
|
||||
<router-view />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// App root component
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
#app {
|
||||
min-height: 100vh;
|
||||
}
|
||||
</style>
|
||||
41
frontend/src/api/barcode.ts
Normal file
41
frontend/src/api/barcode.ts
Normal file
@ -0,0 +1,41 @@
|
||||
import api from './index'
|
||||
import type { ApiResponse } from '@/types'
|
||||
|
||||
// 获取设备信息用于生成条码
|
||||
export const getEquipmentForBarcode = async (equipmentCode: string) => {
|
||||
const response = await api.get<
|
||||
ApiResponse<{
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
equipment_model?: string
|
||||
equipment_type: string
|
||||
}>
|
||||
>(`/barcode/${equipmentCode}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 批量获取设备信息用于生成条码
|
||||
export const getEquipmentBatchForBarcode = async (equipmentIds: number[]) => {
|
||||
const response = await api.post<
|
||||
ApiResponse<
|
||||
Array<{
|
||||
id: number
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
equipment_model?: string
|
||||
equipment_type: string
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: {
|
||||
id: number
|
||||
name: string
|
||||
code?: string | null
|
||||
} | null
|
||||
}>
|
||||
>
|
||||
>(`/barcode/batch`, {
|
||||
equipment_ids: equipmentIds
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
|
||||
146
frontend/src/api/borrow.ts
Normal file
146
frontend/src/api/borrow.ts
Normal file
@ -0,0 +1,146 @@
|
||||
import api from './index'
|
||||
import type {
|
||||
BorrowRecord,
|
||||
PaginatedResponse,
|
||||
ApiResponse,
|
||||
EquipmentStatus,
|
||||
StorageLocation
|
||||
} from '@/types'
|
||||
|
||||
export interface ScanBorrowResult {
|
||||
id: number
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
borrow_time: string
|
||||
status: string
|
||||
remaining_quantity?: number
|
||||
equipment_status?: EquipmentStatus
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: StorageLocation | null
|
||||
}
|
||||
|
||||
// 借用设备
|
||||
export const borrowEquipment = async (data: {
|
||||
equipment_id?: number
|
||||
equipment_code?: string
|
||||
person_id: number
|
||||
expected_return_time?: string
|
||||
notes?: string
|
||||
is_long_term?: boolean
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<BorrowRecord>>('/borrow', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 扫码出库
|
||||
export const scanBorrow = async (data: {
|
||||
equipment_code: string
|
||||
person_id: number
|
||||
expected_return_time?: string
|
||||
notes?: string
|
||||
is_long_term?: boolean
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<ScanBorrowResult>>('/borrow/scan', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 批量扫码出库
|
||||
export const scanBorrowBatch = async (data: {
|
||||
equipment_codes: string[]
|
||||
person_id: number
|
||||
expected_return_time?: string
|
||||
notes?: string
|
||||
is_long_term?: boolean
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<{
|
||||
success_count: number
|
||||
failed_count: number
|
||||
results: Array<{
|
||||
equipment_code: string
|
||||
status: string
|
||||
message: string
|
||||
}>
|
||||
}>>('/borrow/scan-batch', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 归还设备
|
||||
export const returnEquipment = async (data: {
|
||||
equipment_id: number
|
||||
equipment_code: string
|
||||
return_condition?: string
|
||||
notes?: string
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<BorrowRecord>>('/return', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 扫码入库
|
||||
export const scanReturn = async (data: {
|
||||
equipment_code: string
|
||||
return_condition?: string
|
||||
notes?: string
|
||||
person_id?: number
|
||||
borrow_record_id?: number
|
||||
}) => {
|
||||
const response = await api.post<
|
||||
ApiResponse<{
|
||||
id: number
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
return_time: string
|
||||
status: string
|
||||
person_id?: number
|
||||
}>
|
||||
>('/return/scan', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 批量扫码入库
|
||||
export const scanReturnBatch = async (data: {
|
||||
equipment_codes: string[]
|
||||
return_condition?: string
|
||||
notes?: string
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<{
|
||||
success_count: number
|
||||
failed_count: number
|
||||
results: Array<{
|
||||
equipment_code: string
|
||||
status: string
|
||||
message: string
|
||||
}>
|
||||
}>>('/return/scan-batch', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 根据设备编码查询借用记录
|
||||
export const getBorrowRecordByCode = async (equipmentCode: string) => {
|
||||
const response = await api.get<ApiResponse<{
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
unit_price: number
|
||||
equipment_value: number
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: StorageLocation | null
|
||||
borrow_records: BorrowRecord[]
|
||||
can_return: boolean
|
||||
message: string
|
||||
}>>(`/borrow/scan/${equipmentCode}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 获取借用记录列表
|
||||
export const getBorrowRecordList = async (params: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
status?: string
|
||||
person_name?: string
|
||||
person_id?: number
|
||||
}) => {
|
||||
const response = await api.get<ApiResponse<PaginatedResponse<BorrowRecord>>>('/borrow/records', {
|
||||
params
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
94
frontend/src/api/equipment.ts
Normal file
94
frontend/src/api/equipment.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import api from './index'
|
||||
import type { Equipment, PaginatedResponse, ApiResponse } from '@/types'
|
||||
|
||||
const transformEquipmentPayload = (data: Partial<Equipment>) => {
|
||||
const payload: Record<string, any> = { ...data }
|
||||
if (payload.storageLocation) {
|
||||
payload.storage_location_id = payload.storageLocation?.id
|
||||
delete payload.storageLocation
|
||||
}
|
||||
if (payload.storage_location_id !== undefined && payload.storage_location_id !== null) {
|
||||
payload.storage_location_id = Number(payload.storage_location_id)
|
||||
} else {
|
||||
delete payload.storage_location_id
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
// 获取设备列表
|
||||
export const getEquipmentList = async (params: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
equipmentType?: string
|
||||
status?: string
|
||||
keyword?: string
|
||||
storageLocationId?: number
|
||||
}) => {
|
||||
const { storageLocationId, ...rest } = params
|
||||
const response = await api.get<ApiResponse<PaginatedResponse<Equipment>>>('/equipment/list', {
|
||||
params: {
|
||||
...rest,
|
||||
storage_location_id: storageLocationId
|
||||
}
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 获取设备详情
|
||||
export const getEquipmentDetail = async (id: number) => {
|
||||
const response = await api.get<ApiResponse<Equipment>>(`/equipment/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 新增设备
|
||||
export const createEquipment = async (data: Partial<Equipment>) => {
|
||||
const response = await api.post<ApiResponse<Equipment>>('/equipment', transformEquipmentPayload(data))
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 更新设备
|
||||
export const updateEquipment = async (id: number, data: Partial<Equipment>) => {
|
||||
const response = await api.put<ApiResponse<Equipment>>(`/equipment/${id}`, transformEquipmentPayload(data))
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 删除设备
|
||||
export const deleteEquipment = async (id: number) => {
|
||||
const response = await api.delete<ApiResponse<void>>(`/equipment/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 生成设备编码
|
||||
export const generateEquipmentCode = async (
|
||||
equipmentType: string,
|
||||
codeGenerationMode: string = 'auto',
|
||||
storageLocationId?: number | null
|
||||
) => {
|
||||
const response = await api.post<ApiResponse<{ equipment_code: string; code_format: string }>>(
|
||||
'/equipment/generate-code',
|
||||
{
|
||||
equipment_type: equipmentType,
|
||||
code_generation_mode: codeGenerationMode,
|
||||
storage_location_id: storageLocationId
|
||||
}
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 验证设备编码
|
||||
export const verifyEquipmentCode = async (equipmentCode: string) => {
|
||||
const response = await api.post<ApiResponse<{ is_valid: boolean; is_unique: boolean; message: string }>>(
|
||||
'/equipment/verify-code',
|
||||
{
|
||||
equipment_code: equipmentCode
|
||||
}
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 根据设备编码查询设备信息(扫码)
|
||||
export const scanEquipment = async (equipmentCode: string) => {
|
||||
const response = await api.get<ApiResponse<Equipment>>(`/equipment/scan/${equipmentCode}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
81
frontend/src/api/index.ts
Normal file
81
frontend/src/api/index.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import axios from 'axios'
|
||||
import type { AxiosInstance, AxiosResponse } from 'axios'
|
||||
import type { ApiResponse } from '@/types'
|
||||
|
||||
// 创建axios实例
|
||||
const api: AxiosInstance = axios.create({
|
||||
baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api',
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
})
|
||||
|
||||
api.defaults.withCredentials = true
|
||||
|
||||
// 请求拦截器
|
||||
api.interceptors.request.use(
|
||||
(config) => {
|
||||
// 从localStorage获取token
|
||||
const token = localStorage.getItem('token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
const authMode = import.meta.env.VITE_AUTH_MODE || 'keycloak'
|
||||
|
||||
// 响应拦截器
|
||||
api.interceptors.response.use(
|
||||
(response: AxiosResponse<ApiResponse>) => {
|
||||
const data = response.data as ApiResponse
|
||||
if (data?.code === 200) {
|
||||
return response
|
||||
}
|
||||
return Promise.reject(new Error(data?.message || '请求失败'))
|
||||
},
|
||||
(error) => {
|
||||
// 处理HTTP错误
|
||||
if (error.response) {
|
||||
const requestUrl: string = error.config?.url || ''
|
||||
switch (error.response.status) {
|
||||
case 401:
|
||||
// 未授权,跳转到登录页
|
||||
localStorage.removeItem('token')
|
||||
{
|
||||
const isAuthStatusCheck = requestUrl.includes('/auth/user')
|
||||
const isLoginAttempt = requestUrl.includes('/auth/local/login')
|
||||
const shouldRedirect =
|
||||
authMode !== 'local' || (!isAuthStatusCheck && !isLoginAttempt)
|
||||
if (shouldRedirect && window.location.pathname !== '/login') {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
break
|
||||
case 403:
|
||||
// 禁止访问
|
||||
console.error('禁止访问')
|
||||
break
|
||||
case 404:
|
||||
// 资源不存在
|
||||
console.error('资源不存在')
|
||||
break
|
||||
case 500:
|
||||
// 服务器错误
|
||||
console.error('服务器错误')
|
||||
break
|
||||
default:
|
||||
console.error('请求失败')
|
||||
}
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export default api
|
||||
|
||||
56
frontend/src/api/person.ts
Normal file
56
frontend/src/api/person.ts
Normal file
@ -0,0 +1,56 @@
|
||||
import api from './index'
|
||||
import type { ApiResponse, PaginatedResponse, Person } from '@/types'
|
||||
|
||||
export const getPersonList = async (params: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
keyword?: string
|
||||
status?: string
|
||||
}) => {
|
||||
const response = await api.get<ApiResponse<PaginatedResponse<Person>>>('/persons', { params })
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const getPersonDetail = async (id: number) => {
|
||||
const response = await api.get<ApiResponse<Person>>(`/persons/${id}`)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const createPerson = async (data: {
|
||||
nickname: string
|
||||
real_name: string
|
||||
id_number?: string
|
||||
department?: string
|
||||
position?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
status?: string
|
||||
remarks?: string
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<Person>>('/persons', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updatePerson = async (
|
||||
id: number,
|
||||
data: {
|
||||
nickname?: string
|
||||
real_name?: string
|
||||
id_number?: string
|
||||
department?: string
|
||||
position?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
status?: string
|
||||
remarks?: string
|
||||
}
|
||||
) => {
|
||||
const response = await api.put<ApiResponse<Person>>(`/persons/${id}`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updatePersonStatus = async (id: number, status: 'active' | 'inactive') => {
|
||||
const response = await api.patch<ApiResponse<Person>>(`/persons/${id}/status`, { status })
|
||||
return response.data
|
||||
}
|
||||
|
||||
26
frontend/src/api/settings.ts
Normal file
26
frontend/src/api/settings.ts
Normal file
@ -0,0 +1,26 @@
|
||||
import api from './index'
|
||||
import type { ApiResponse } from '@/types'
|
||||
|
||||
export interface SiteConfigResponse {
|
||||
site_name: string
|
||||
logo_url: string
|
||||
favicon_url: string
|
||||
theme_color: string
|
||||
updated_at: string | null
|
||||
updated_by: {
|
||||
id: number
|
||||
username: string
|
||||
name: string
|
||||
} | null
|
||||
}
|
||||
|
||||
export const getSiteConfig = async () => {
|
||||
const response = await api.get<ApiResponse<SiteConfigResponse>>('/settings/site')
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updateSiteConfig = async (data: { site_name: string; theme_color?: string }) => {
|
||||
const response = await api.put<ApiResponse<SiteConfigResponse>>('/settings/site', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
19
frontend/src/api/statistics.ts
Normal file
19
frontend/src/api/statistics.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import api from './index'
|
||||
import type { DashboardStats, ValueStatistics, ApiResponse } from '@/types'
|
||||
|
||||
// 获取首页统计数据
|
||||
export const getDashboardStats = async () => {
|
||||
const response = await api.get<ApiResponse<DashboardStats>>('/statistics/dashboard')
|
||||
return response.data
|
||||
}
|
||||
|
||||
// 获取设备价值统计
|
||||
export const getValueStatistics = async (params?: {
|
||||
equipment_type?: string
|
||||
start_date?: string
|
||||
end_date?: string
|
||||
}) => {
|
||||
const response = await api.get<ApiResponse<ValueStatistics>>('/statistics/value', { params })
|
||||
return response.data
|
||||
}
|
||||
|
||||
37
frontend/src/api/storageLocation.ts
Normal file
37
frontend/src/api/storageLocation.ts
Normal file
@ -0,0 +1,37 @@
|
||||
import api from './index'
|
||||
import type { ApiResponse, PaginatedResponse, StorageLocation } from '@/types'
|
||||
|
||||
export const getStorageLocationOptions = async () => {
|
||||
const response = await api.get<ApiResponse<StorageLocation[]>>('/storage-locations/options')
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const getStorageLocationList = async (params: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
keyword?: string
|
||||
status?: string
|
||||
}) => {
|
||||
const response = await api.get<ApiResponse<PaginatedResponse<StorageLocation>>>('/storage-locations/list', {
|
||||
params
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const createStorageLocation = async (data: Partial<StorageLocation>) => {
|
||||
const response = await api.post<ApiResponse<StorageLocation>>('/storage-locations', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updateStorageLocation = async (id: number, data: Partial<StorageLocation>) => {
|
||||
const response = await api.put<ApiResponse<StorageLocation>>(`/storage-locations/${id}`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updateStorageLocationStatus = async (id: number, status: 'active' | 'inactive') => {
|
||||
const response = await api.patch<ApiResponse<StorageLocation>>(`/storage-locations/${id}/status`, {
|
||||
status
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
57
frontend/src/api/users.ts
Normal file
57
frontend/src/api/users.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import api from './index'
|
||||
import type { ApiResponse, PaginatedResponse, User } from '@/types'
|
||||
|
||||
export interface UserListParams {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
keyword?: string
|
||||
role?: string
|
||||
status?: string
|
||||
}
|
||||
|
||||
export const getUserList = async (params: UserListParams = {}) => {
|
||||
const response = await api.get<ApiResponse<PaginatedResponse<User>>>('/users', { params })
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const createUser = async (data: {
|
||||
username: string
|
||||
password: string
|
||||
name: string
|
||||
email?: string
|
||||
phone?: string
|
||||
roles?: string[]
|
||||
role?: string
|
||||
status?: string
|
||||
}) => {
|
||||
const response = await api.post<ApiResponse<User>>('/users', data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updateUser = async (
|
||||
id: number | string,
|
||||
data: {
|
||||
name?: string
|
||||
email?: string
|
||||
phone?: string
|
||||
roles?: string[]
|
||||
role?: string
|
||||
status?: string
|
||||
}
|
||||
) => {
|
||||
const response = await api.put<ApiResponse<User>>(`/users/${id}`, data)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const updateUserStatus = async (id: number | string, status: 'active' | 'inactive') => {
|
||||
const response = await api.patch<ApiResponse<User>>(`/users/${id}/status`, { status })
|
||||
return response.data
|
||||
}
|
||||
|
||||
export const resetUserPassword = async (id: number | string, newPassword: string) => {
|
||||
const response = await api.post<ApiResponse<null>>(`/users/${id}/reset-password`, {
|
||||
new_password: newPassword
|
||||
})
|
||||
return response.data
|
||||
}
|
||||
|
||||
1
frontend/src/assets/vue.svg
Normal file
1
frontend/src/assets/vue.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 496 B |
9
frontend/src/auth/keycloak.ts
Normal file
9
frontend/src/auth/keycloak.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import Keycloak from 'keycloak-js'
|
||||
|
||||
const keycloak = new Keycloak({
|
||||
url: import.meta.env.VITE_KEYCLOAK_URL || 'http://localhost:8080',
|
||||
realm: import.meta.env.VITE_KEYCLOAK_REALM || 'equipment-management',
|
||||
clientId: import.meta.env.VITE_KEYCLOAK_CLIENT_ID || 'equipment-client'
|
||||
})
|
||||
|
||||
export default keycloak
|
||||
400
frontend/src/components/BarcodePrint.vue
Normal file
400
frontend/src/components/BarcodePrint.vue
Normal file
@ -0,0 +1,400 @@
|
||||
<template>
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">条码打印</h2>
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-for="equipment in equipmentList"
|
||||
:key="equipment.equipment_code"
|
||||
class="barcode-card"
|
||||
>
|
||||
<div class="barcode-canvas">
|
||||
<svg :id="`barcode-${equipment.id}`"></svg>
|
||||
</div>
|
||||
<p class="barcode-text-overlay">
|
||||
{{ equipment.equipment_name }}
|
||||
<span v-if="equipment.equipment_model"> / {{ equipment.equipment_model }}</span>
|
||||
<span v-if="equipment.storageLocation" class="storage-location">
|
||||
/ {{ equipment.storageLocation.name }}{{ equipment.storageLocation.code ? ' (' + equipment.storageLocation.code + ')' : '' }}
|
||||
</span>
|
||||
<span v-else-if="equipment.storage_location_id" class="storage-location">
|
||||
/ 库位ID:{{ equipment.storage_location_id }}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button @click="handlePrint" class="btn-apple-primary flex-1" :disabled="loading">
|
||||
{{ loading ? '生成中...' : '打印条码' }}
|
||||
</button>
|
||||
<button @click="handleDownload" class="btn-apple-secondary flex-1" :disabled="loading">
|
||||
{{ loading ? '生成中...' : '下载图片' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, nextTick } from 'vue'
|
||||
import { getEquipmentBatchForBarcode } from '@/api/barcode'
|
||||
import JsBarcode from 'jsbarcode'
|
||||
import html2canvas from 'html2canvas'
|
||||
|
||||
interface EquipmentBarcode {
|
||||
id: number
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
equipment_model?: string
|
||||
equipment_type: string
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: {
|
||||
id: number
|
||||
name: string
|
||||
code?: string | null
|
||||
} | null
|
||||
}
|
||||
|
||||
interface Props {
|
||||
equipmentIds: number[]
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
|
||||
const equipmentList = ref<EquipmentBarcode[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
const fetchEquipment = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await getEquipmentBatchForBarcode(props.equipmentIds)
|
||||
console.log('原始响应数据:', response)
|
||||
console.log('响应数据类型:', typeof response)
|
||||
console.log('响应数据内容:', JSON.stringify(response, null, 2))
|
||||
|
||||
// response 本身就是 ApiResponse,data 字段包含实际数据
|
||||
const data = response.data || response
|
||||
console.log('提取的数据:', data)
|
||||
console.log('数据类型:', Array.isArray(data))
|
||||
|
||||
if (data && Array.isArray(data)) {
|
||||
equipmentList.value = data
|
||||
// 调试:打印设备信息,检查库位数据
|
||||
console.log('设备列表:', equipmentList.value)
|
||||
console.log('设备列表类型:', Array.isArray(equipmentList.value))
|
||||
equipmentList.value.forEach((eq, index) => {
|
||||
console.log(`设备 ${index + 1} 完整数据:`, eq)
|
||||
console.log(`设备 ${index + 1}:`, {
|
||||
name: eq.equipment_name,
|
||||
storageLocation: eq.storageLocation,
|
||||
storage_location_id: eq.storage_location_id,
|
||||
hasStorageLocation: !!eq.storageLocation,
|
||||
storageLocationType: typeof eq.storageLocation,
|
||||
allKeys: Object.keys(eq)
|
||||
})
|
||||
})
|
||||
await nextTick()
|
||||
generateBarcodes()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备信息失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const generateBarcodes = () => {
|
||||
equipmentList.value.forEach((equipment) => {
|
||||
const svgElement = document.getElementById(`barcode-${equipment.id}`)
|
||||
if (svgElement) {
|
||||
// 清空SVG元素,避免重复生成
|
||||
svgElement.innerHTML = ''
|
||||
|
||||
// 验证编码必须是纯数字(符合中国标准要求)
|
||||
let codeToEncode = equipment.equipment_code
|
||||
|
||||
// 严格验证:编码必须是纯数字
|
||||
if (!/^\d+$/.test(codeToEncode)) {
|
||||
// 如果编码包含非数字字符,尝试提取纯数字部分
|
||||
const numericCode = codeToEncode.replace(/\D/g, '')
|
||||
if (numericCode && numericCode.length >= 6) {
|
||||
// 如果提取的数字长度足够,使用提取的数字
|
||||
codeToEncode = numericCode
|
||||
console.warn('编码包含非数字字符,已提取纯数字部分:', equipment.equipment_code, '->', codeToEncode)
|
||||
} else {
|
||||
console.error('设备编码不是纯数字格式,无法生成条码:', equipment.equipment_code)
|
||||
// 显示错误信息
|
||||
svgElement.innerHTML = `<text x="50%" y="50%" text-anchor="middle" fill="red" font-size="12">编码格式错误</text>`
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 验证编码长度(应该是10位数字,但允许6-20位)
|
||||
if (codeToEncode.length < 6 || codeToEncode.length > 20) {
|
||||
console.warn('编码长度不符合标准(6-20位):', codeToEncode.length, codeToEncode)
|
||||
}
|
||||
|
||||
// 根据中国标准(GB/T 12908-2002)和ISO/IEC 15417配置参数
|
||||
// X尺寸:每个模块的像素宽度(在96 DPI下,4像素≈1.06mm,符合0.25-0.66mm标准范围)
|
||||
const xDimension = 4 // X尺寸(像素),符合中国标准
|
||||
|
||||
// 条码高度:增大条码尺寸,尽量铺满可用空间
|
||||
const barcodeHeight = 300 // 条码高度(像素),从200增加到300,让条码更大
|
||||
// 注意:左右静默区(40像素 = 10个X尺寸)通过CSS的padding添加,符合GB/T 12908-2002标准
|
||||
|
||||
JsBarcode(svgElement, codeToEncode, {
|
||||
format: 'CODE128', // 使用CODE128(自动选择最佳子集,支持纯数字)
|
||||
width: xDimension, // 条码模块宽度(X尺寸),符合中国标准
|
||||
height: barcodeHeight, // 条码高度(像素),符合标准(至少15倍X尺寸)
|
||||
displayValue: false, // 关闭条码下方文字显示(我们会在底部单独显示)
|
||||
margin: 0, // 设置为0,避免上下空白,左右静默区通过CSS添加
|
||||
background: 'transparent', // 设置为透明,让容器背景显示,避免额外的白色背景
|
||||
lineColor: '#000000', // 确保条码是纯黑色,高对比度(至少75%对比度,符合标准)
|
||||
// 确保SVG正确渲染
|
||||
xmlDocument: document,
|
||||
valid: function(valid) {
|
||||
if (!valid) {
|
||||
console.error('条码生成失败,编码可能不符合CODE128标准:', codeToEncode)
|
||||
} else {
|
||||
// 移除SVG内部的白色背景rect(如果有)
|
||||
const svg = svgElement.querySelector('svg')
|
||||
if (svg) {
|
||||
const bgRect = svg.querySelector('rect[fill="#ffffff"]')
|
||||
if (bgRect) {
|
||||
bgRect.remove()
|
||||
}
|
||||
}
|
||||
console.log('条码生成成功(纯数字,符合中国标准):', codeToEncode)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 生成条码图片的通用函数
|
||||
const generateImages = async (): Promise<string[]> => {
|
||||
const images: string[] = []
|
||||
const cardElements = document.querySelectorAll('.barcode-card')
|
||||
|
||||
for (let i = 0; i < cardElements.length; i++) {
|
||||
const cardElement = cardElements[i] as HTMLElement
|
||||
if (cardElement) {
|
||||
// 300 DPI 下的尺寸: 4cm = 472.44px, 3cm = 354.33px
|
||||
// 放大5倍: 2362px x 1772px
|
||||
// scale = (300 / 96) * 5 = 15.625
|
||||
const canvas = await html2canvas(cardElement, {
|
||||
width: 151, // 原始尺寸 4cm (96 DPI)
|
||||
height: 113, // 原始尺寸 3cm (96 DPI)
|
||||
scale: 16, // 设置为16倍,确保高分辨率 (约等于 300 DPI * 5倍)
|
||||
backgroundColor: '#ffffff',
|
||||
useCORS: true,
|
||||
logging: false,
|
||||
allowTaint: false,
|
||||
windowWidth: 151,
|
||||
windowHeight: 113
|
||||
})
|
||||
|
||||
// 生成的canvas尺寸约为 151*16 = 2416px x 113*16 = 1808px
|
||||
// 使用最高质量导出
|
||||
images.push(canvas.toDataURL('image/png', 1.0))
|
||||
}
|
||||
}
|
||||
|
||||
return images
|
||||
}
|
||||
|
||||
const handlePrint = async () => {
|
||||
if (equipmentList.value.length === 0) {
|
||||
alert('没有可打印的条码')
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
// 生成图片
|
||||
const images = await generateImages()
|
||||
|
||||
// 创建打印窗口
|
||||
const printWindow = window.open('', '_blank')
|
||||
if (!printWindow) {
|
||||
alert('无法打开打印窗口,请允许弹出窗口')
|
||||
return
|
||||
}
|
||||
|
||||
// 生成打印 HTML
|
||||
const printHTML = `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<title>打印条码</title>
|
||||
<style>
|
||||
@page {
|
||||
size: 4cm 3cm;
|
||||
margin: 0;
|
||||
}
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: white;
|
||||
width: 4cm;
|
||||
height: 3cm;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
overflow: hidden;
|
||||
}
|
||||
.barcode-image {
|
||||
width: 4cm;
|
||||
height: 3cm;
|
||||
display: block;
|
||||
page-break-after: always;
|
||||
page-break-inside: avoid;
|
||||
}
|
||||
.barcode-image:last-child {
|
||||
page-break-after: auto;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
${images.map(img => `<img src="${img}" class="barcode-image" />`).join('')}
|
||||
</body>
|
||||
</html>
|
||||
`
|
||||
|
||||
printWindow.document.write(printHTML)
|
||||
printWindow.document.close()
|
||||
|
||||
// 等待图片加载完成后打印
|
||||
printWindow.onload = () => {
|
||||
setTimeout(() => {
|
||||
printWindow.print()
|
||||
printWindow.close()
|
||||
}, 500)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('打印失败:', error)
|
||||
alert('打印失败,请重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = async () => {
|
||||
if (equipmentList.value.length === 0) {
|
||||
alert('没有可下载的条码')
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
// 生成图片
|
||||
const images = await generateImages()
|
||||
|
||||
// 下载每张图片,延迟下载以避免浏览器阻止多个下载
|
||||
for (let i = 0; i < images.length; i++) {
|
||||
if (i > 0) {
|
||||
// 延迟300ms,避免浏览器阻止多个下载
|
||||
await new Promise(resolve => setTimeout(resolve, 300))
|
||||
}
|
||||
|
||||
const equipment = equipmentList.value[i]
|
||||
const fileName = `${equipment.equipment_code || `barcode-${i + 1}`}.png`
|
||||
|
||||
// 创建下载链接
|
||||
const link = document.createElement('a')
|
||||
link.href = images[i]
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('下载失败:', error)
|
||||
alert('下载失败,请重试')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchEquipment()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.barcode-card {
|
||||
width: 4cm;
|
||||
height: 3cm;
|
||||
background-color: #ffffff; /* 纯白色背景 */
|
||||
border-radius: 0; /* 移除圆角,最大化空间 */
|
||||
padding: 0; /* 移除所有padding,让条码占据整个空间 */
|
||||
box-sizing: border-box;
|
||||
position: relative; /* 为绝对定位的数字提供定位上下文 */
|
||||
margin: 0 auto;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
|
||||
overflow: visible; /* 改为visible,确保文字不被裁剪 */
|
||||
isolation: isolate; /* 创建新的层叠上下文 */
|
||||
}
|
||||
|
||||
.barcode-canvas {
|
||||
width: 100%;
|
||||
height: 100%; /* 占据整个卡片高度 */
|
||||
background-color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 40px; /* 左右静默区:40像素(10个X尺寸),符合GB/T 12908-2002标准 */
|
||||
overflow: hidden; /* 防止条码溢出 */
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
z-index: 1; /* 确保条码在底层 */
|
||||
}
|
||||
|
||||
.barcode-text-overlay {
|
||||
position: absolute; /* 绝对定位,叠加在条码上方 */
|
||||
bottom: 0; /* 紧贴底部 */
|
||||
left: 0;
|
||||
right: 0;
|
||||
margin: 0;
|
||||
padding: 0.05cm 0.1cm; /* 增加左右padding,避免文字贴边 */
|
||||
font-size: 0.22cm; /* 稍微减小字体,确保能显示完整信息 */
|
||||
line-height: 1.3;
|
||||
color: #000;
|
||||
font-weight: 600;
|
||||
text-align: center;
|
||||
font-family: 'Arial', 'Microsoft YaHei', sans-serif; /* 使用更易读的字体 */
|
||||
background-color: rgba(255, 255, 255, 0.95); /* 更不透明的白色背景,确保文字清晰可见 */
|
||||
z-index: 9999; /* 最高层级,确保文字在所有元素之上 */
|
||||
pointer-events: none; /* 不阻挡条码扫描 */
|
||||
/* 强制向上移动,贴近条码底部显示 */
|
||||
transform: translateY(-0.3cm); /* 向上移动0.3cm,让文字更贴近条码 */
|
||||
white-space: nowrap; /* 不换行 */
|
||||
overflow: visible; /* 改为visible,确保文字不被裁剪 */
|
||||
text-overflow: ellipsis; /* 超出部分显示省略号 */
|
||||
}
|
||||
|
||||
.storage-location {
|
||||
color: #0066cc; /* 蓝色突出显示库位信息 */
|
||||
font-weight: 700; /* 加粗显示 */
|
||||
}
|
||||
|
||||
.barcode-canvas svg {
|
||||
max-width: 100%; /* 允许使用全部宽度,静默区已包含在SVG内部 */
|
||||
max-height: 100%;
|
||||
width: auto;
|
||||
height: auto;
|
||||
display: block; /* 确保SVG正确显示 */
|
||||
/* 确保条码清晰渲染,不被模糊 */
|
||||
shape-rendering: crispEdges;
|
||||
image-rendering: -webkit-optimize-contrast;
|
||||
image-rendering: crisp-edges;
|
||||
/* 移除SVG的上下空白,让条码紧贴容器边缘 */
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
/* 移除SVG内部可能的上下空白rect */
|
||||
.barcode-canvas svg rect[fill="#ffffff"] {
|
||||
display: none;
|
||||
}
|
||||
</style>
|
||||
|
||||
|
||||
41
frontend/src/components/HelloWorld.vue
Normal file
41
frontend/src/components/HelloWorld.vue
Normal file
@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
|
||||
defineProps<{ msg: string }>()
|
||||
|
||||
const count = ref(0)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<h1>{{ msg }}</h1>
|
||||
|
||||
<div class="card">
|
||||
<button type="button" @click="count++">count is {{ count }}</button>
|
||||
<p>
|
||||
Edit
|
||||
<code>components/HelloWorld.vue</code> to test HMR
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p>
|
||||
Check out
|
||||
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
|
||||
>create-vue</a
|
||||
>, the official Vue + Vite starter
|
||||
</p>
|
||||
<p>
|
||||
Learn more about IDE Support for Vue in the
|
||||
<a
|
||||
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
|
||||
target="_blank"
|
||||
>Vue Docs Scaling up Guide</a
|
||||
>.
|
||||
</p>
|
||||
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
</style>
|
||||
68
frontend/src/components/StatCard.vue
Normal file
68
frontend/src/components/StatCard.vue
Normal file
@ -0,0 +1,68 @@
|
||||
<template>
|
||||
<div class="card-apple hover:shadow-apple-lg transition-shadow">
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<span v-if="iconString" class="text-2xl">{{ iconString }}</span>
|
||||
<component
|
||||
v-else-if="iconComponent"
|
||||
:is="iconComponent"
|
||||
class="h-6 w-6 text-system-label-tertiary"
|
||||
/>
|
||||
<span
|
||||
v-if="trend"
|
||||
class="text-xs px-2 py-1 rounded-apple"
|
||||
:class="trend > 0 ? 'bg-apple-green text-white' : 'bg-apple-red text-white'"
|
||||
>
|
||||
{{ trend > 0 ? '+' : '' }}{{ trend }}%
|
||||
</span>
|
||||
</div>
|
||||
<h3 class="text-apple-title mb-1">{{ title }}</h3>
|
||||
<p class="stat-value" :class="getColorClass()">{{ value }}</p>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { Component } from 'vue'
|
||||
|
||||
interface Props {
|
||||
title: string
|
||||
value: string | number
|
||||
icon?: string | Component
|
||||
color?: string
|
||||
trend?: number | null
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
color: 'apple-blue',
|
||||
trend: null
|
||||
})
|
||||
|
||||
const iconString = computed(() =>
|
||||
typeof props.icon === 'string' ? props.icon : ''
|
||||
)
|
||||
|
||||
const iconComponent = computed<Component | null>(() =>
|
||||
props.icon && typeof props.icon !== 'string' ? props.icon : null
|
||||
)
|
||||
|
||||
const getColorClass = () => {
|
||||
const colorMap: Record<string, string> = {
|
||||
'apple-blue': 'text-apple-blue',
|
||||
'apple-green': 'text-apple-green',
|
||||
'apple-orange': 'text-apple-orange',
|
||||
'apple-yellow': 'text-apple-yellow',
|
||||
'apple-red': 'text-apple-red'
|
||||
}
|
||||
return colorMap[props.color] || 'text-system-label-primary'
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.stat-value {
|
||||
font-size: clamp(1.75rem, 1.5rem + 1vw, 2.375rem);
|
||||
line-height: 1.1;
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
</style>
|
||||
|
||||
94
frontend/src/layouts/MainLayout.vue
Normal file
94
frontend/src/layouts/MainLayout.vue
Normal file
@ -0,0 +1,94 @@
|
||||
<template>
|
||||
<div class="min-h-screen bg-system-background-secondary">
|
||||
<!-- Navigation Bar - Apple Style -->
|
||||
<nav class="nav-apple sticky top-0 z-50 px-6 py-4">
|
||||
<div class="max-w-7xl mx-auto flex items-center justify-between">
|
||||
<div class="flex items-center space-x-3">
|
||||
<img
|
||||
v-if="siteStore.logoUrl"
|
||||
:src="siteStore.logoUrl"
|
||||
alt="logo"
|
||||
class="h-10 w-10 rounded-apple object-cover"
|
||||
/>
|
||||
<h1 class="text-apple-title text-system-label-primary">
|
||||
{{ siteStore.siteName }}
|
||||
</h1>
|
||||
</div>
|
||||
<div class="flex items-center space-x-4">
|
||||
<button
|
||||
@click="handleLogout"
|
||||
class="btn-apple-secondary text-sm"
|
||||
>
|
||||
退出登录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<!-- Sidebar Navigation - Apple Style -->
|
||||
<div class="flex max-w-7xl mx-auto">
|
||||
<aside class="w-[200px] bg-system-background-primary border-r border-system-gray-5 min-h-screen p-5">
|
||||
<nav class="space-y-2">
|
||||
<router-link
|
||||
v-for="item in visibleNavItems"
|
||||
:key="item.path"
|
||||
:to="item.path"
|
||||
class="nav-link flex items-center space-x-3 px-3 py-3 rounded-apple transition-colors text-system-label-secondary hover:bg-system-gray-6"
|
||||
:class="{ 'nav-link--active': $route.path === item.path }"
|
||||
>
|
||||
<component :is="item.icon" class="w-5 h-5" />
|
||||
<span class="text-apple-body">{{ item.title }}</span>
|
||||
</router-link>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<!-- Main Content -->
|
||||
<main class="flex-1 p-6">
|
||||
<router-view />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useSiteStore } from '@/stores/site'
|
||||
import { HomeIcon, CubeIcon, ArrowRightIcon, ChartBarIcon, Cog6ToothIcon } from '@heroicons/vue/24/outline'
|
||||
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const siteStore = useSiteStore()
|
||||
|
||||
const navItems = [
|
||||
{ path: '/dashboard', title: '首页', icon: HomeIcon },
|
||||
{ path: '/equipment', title: '设备管理', icon: CubeIcon, requiresAdmin: true },
|
||||
{ path: '/borrow', title: '借用管理', icon: ArrowRightIcon },
|
||||
{ path: '/statistics', title: '统计分析', icon: ChartBarIcon },
|
||||
{ path: '/settings', title: '系统设置', icon: Cog6ToothIcon, requiresAdmin: true }
|
||||
]
|
||||
|
||||
const visibleNavItems = computed(() => {
|
||||
const isAdmin = authStore.user?.role === 'admin'
|
||||
return navItems.filter((item) => !item.requiresAdmin || isAdmin)
|
||||
})
|
||||
|
||||
const handleLogout = async () => {
|
||||
await authStore.logout()
|
||||
router.push('/login')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
siteStore.fetchSiteConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.nav-link--active {
|
||||
background-color: var(--theme-primary);
|
||||
color: #ffffff;
|
||||
box-shadow: 0 6px 18px var(--theme-primary-ring);
|
||||
}
|
||||
</style>
|
||||
|
||||
92
frontend/src/main.ts
Normal file
92
frontend/src/main.ts
Normal file
@ -0,0 +1,92 @@
|
||||
import { createApp } from 'vue'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import './style.css'
|
||||
import keycloak from './auth/keycloak'
|
||||
import { useAuthStore } from './stores/auth'
|
||||
import api from './api'
|
||||
import type { User } from './types'
|
||||
|
||||
const bootstrap = async () => {
|
||||
const app = createApp(App)
|
||||
const pinia = createPinia()
|
||||
app.use(pinia)
|
||||
setActivePinia(pinia)
|
||||
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const authMode = import.meta.env.VITE_AUTH_MODE || 'keycloak'
|
||||
|
||||
if (authMode === 'local') {
|
||||
localStorage.removeItem('token')
|
||||
authStore.$patch({
|
||||
token: null,
|
||||
user: null,
|
||||
isAuthenticated: false
|
||||
})
|
||||
try {
|
||||
const resp = await api.get('/auth/user')
|
||||
if (resp?.data?.data) {
|
||||
const user = resp.data.data
|
||||
const normalizedUser: User = {
|
||||
...user,
|
||||
id: String(user.id ?? user.username ?? ''),
|
||||
username: user.username || '',
|
||||
name: user.name || user.username || '',
|
||||
role: user.role || (user.roles?.includes('admin') ? 'admin' : 'user'),
|
||||
roles: user.roles || []
|
||||
}
|
||||
authStore.setUser(normalizedUser)
|
||||
authStore.setToken('session')
|
||||
}
|
||||
} catch {
|
||||
// ignore, user not logged in
|
||||
}
|
||||
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const authenticated = await keycloak.init({
|
||||
onLoad: 'login-required',
|
||||
checkLoginIframe: false,
|
||||
pkceMethod: 'S256'
|
||||
})
|
||||
|
||||
if (!authenticated) {
|
||||
await keycloak.login()
|
||||
return
|
||||
}
|
||||
|
||||
if (keycloak.token) {
|
||||
authStore.setToken(keycloak.token)
|
||||
}
|
||||
|
||||
const roles = (keycloak.tokenParsed?.realm_access?.roles as string[]) || []
|
||||
authStore.setUser({
|
||||
id: (keycloak.tokenParsed?.sub as string) || '',
|
||||
username: (keycloak.tokenParsed?.preferred_username as string) || '',
|
||||
name: (keycloak.tokenParsed?.name as string) || (keycloak.tokenParsed?.preferred_username as string) || '',
|
||||
role: roles.includes('admin') ? 'admin' : 'user',
|
||||
email: (keycloak.tokenParsed?.email as string) || ''
|
||||
})
|
||||
|
||||
// 定期刷新token
|
||||
setInterval(() => {
|
||||
keycloak.updateToken(60).catch(() => {
|
||||
keycloak.login()
|
||||
})
|
||||
}, 60000)
|
||||
|
||||
app.use(router)
|
||||
app.mount('#app')
|
||||
} catch (error) {
|
||||
console.error('Keycloak 初始化失败:', error)
|
||||
await keycloak.login()
|
||||
}
|
||||
}
|
||||
|
||||
bootstrap()
|
||||
109
frontend/src/router/index.ts
Normal file
109
frontend/src/router/index.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import type { RouteRecordRaw } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import keycloak from '@/auth/keycloak'
|
||||
|
||||
const routes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: '/login',
|
||||
name: 'Login',
|
||||
component: () => import('../views/Login.vue'),
|
||||
meta: { requiresAuth: false }
|
||||
},
|
||||
{
|
||||
path: '/',
|
||||
component: () => import('../layouts/MainLayout.vue'),
|
||||
redirect: '/dashboard',
|
||||
meta: { requiresAuth: true },
|
||||
children: [
|
||||
{
|
||||
path: 'dashboard',
|
||||
name: 'Dashboard',
|
||||
component: () => import('../views/dashboard/Dashboard.vue'),
|
||||
meta: { title: '首页' }
|
||||
},
|
||||
{
|
||||
path: 'equipment',
|
||||
name: 'Equipment',
|
||||
component: () => import('../views/equipment/EquipmentList.vue'),
|
||||
meta: { title: '设备管理', requiresAdmin: true }
|
||||
},
|
||||
{
|
||||
path: 'equipment/add',
|
||||
name: 'EquipmentAdd',
|
||||
component: () => import('../views/equipment/EquipmentForm.vue'),
|
||||
meta: { title: '新增设备', requiresAdmin: true }
|
||||
},
|
||||
{
|
||||
path: 'equipment/edit/:id',
|
||||
name: 'EquipmentEdit',
|
||||
component: () => import('../views/equipment/EquipmentForm.vue'),
|
||||
meta: { title: '编辑设备', requiresAdmin: true }
|
||||
},
|
||||
{
|
||||
path: 'borrow',
|
||||
name: 'Borrow',
|
||||
component: () => import('../views/borrow/BorrowList.vue'),
|
||||
meta: { title: '借用管理' }
|
||||
},
|
||||
{
|
||||
path: 'borrow/scan',
|
||||
name: 'BorrowScan',
|
||||
component: () => import('../views/borrow/BorrowScan.vue'),
|
||||
meta: { title: '扫码出库' }
|
||||
},
|
||||
{
|
||||
path: 'return/scan',
|
||||
name: 'ReturnScan',
|
||||
component: () => import('../views/borrow/ReturnScan.vue'),
|
||||
meta: { title: '扫码入库' }
|
||||
},
|
||||
{
|
||||
path: 'statistics',
|
||||
name: 'Statistics',
|
||||
component: () => import('../views/statistics/Statistics.vue'),
|
||||
meta: { title: '统计分析' }
|
||||
},
|
||||
{
|
||||
path: 'settings',
|
||||
name: 'Settings',
|
||||
component: () => import('../views/settings/Settings.vue'),
|
||||
meta: { title: '系统设置', requiresAdmin: true }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHistory(),
|
||||
routes
|
||||
})
|
||||
|
||||
router.beforeEach((to, _from, next) => {
|
||||
const authStore = useAuthStore()
|
||||
const authMode = import.meta.env.VITE_AUTH_MODE || 'keycloak'
|
||||
|
||||
if (to.path === '/login' && authStore.isAuthenticated) {
|
||||
next('/dashboard')
|
||||
return
|
||||
}
|
||||
|
||||
if (to.meta.requiresAuth && !authStore.isAuthenticated) {
|
||||
if (authMode === 'local') {
|
||||
next('/login')
|
||||
} else {
|
||||
keycloak.login()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (to.meta.requiresAdmin && authStore.user?.role !== 'admin') {
|
||||
next('/dashboard')
|
||||
return
|
||||
}
|
||||
|
||||
next()
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
5
frontend/src/shims-vue.d.ts
vendored
Normal file
5
frontend/src/shims-vue.d.ts
vendored
Normal file
@ -0,0 +1,5 @@
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
const component: DefineComponent<Record<string, unknown>, Record<string, unknown>, any>
|
||||
export default component
|
||||
}
|
||||
49
frontend/src/stores/auth.ts
Normal file
49
frontend/src/stores/auth.ts
Normal file
@ -0,0 +1,49 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { User } from '@/types'
|
||||
import keycloak from '@/auth/keycloak'
|
||||
import api from '@/api'
|
||||
|
||||
interface AuthState {
|
||||
user: User | null
|
||||
token: string | null
|
||||
isAuthenticated: boolean
|
||||
}
|
||||
|
||||
export const useAuthStore = defineStore('auth', {
|
||||
state: (): AuthState => ({
|
||||
user: null,
|
||||
token: localStorage.getItem('token'),
|
||||
isAuthenticated: !!localStorage.getItem('token')
|
||||
}),
|
||||
|
||||
actions: {
|
||||
setUser(user: User) {
|
||||
this.user = user
|
||||
this.isAuthenticated = true
|
||||
},
|
||||
|
||||
setToken(token: string) {
|
||||
this.token = token
|
||||
this.isAuthenticated = true
|
||||
localStorage.setItem('token', token)
|
||||
},
|
||||
|
||||
async logout() {
|
||||
this.user = null
|
||||
this.token = null
|
||||
this.isAuthenticated = false
|
||||
localStorage.removeItem('token')
|
||||
try {
|
||||
const authMode = import.meta.env.VITE_AUTH_MODE || 'keycloak'
|
||||
if (authMode === 'local') {
|
||||
await api.post('/auth/logout')
|
||||
} else if (keycloak.authenticated) {
|
||||
await keycloak.logout()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Keycloak 登出失败:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
42
frontend/src/stores/equipment.ts
Normal file
42
frontend/src/stores/equipment.ts
Normal file
@ -0,0 +1,42 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import type { Equipment } from '@/types'
|
||||
import { getEquipmentList } from '@/api/equipment'
|
||||
|
||||
interface EquipmentState {
|
||||
equipmentList: Equipment[]
|
||||
total: number
|
||||
loading: boolean
|
||||
}
|
||||
|
||||
export const useEquipmentStore = defineStore('equipment', {
|
||||
state: (): EquipmentState => ({
|
||||
equipmentList: [],
|
||||
total: 0,
|
||||
loading: false
|
||||
}),
|
||||
|
||||
actions: {
|
||||
async fetchEquipmentList(params?: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
equipmentType?: string
|
||||
status?: string
|
||||
keyword?: string
|
||||
storageLocationId?: number
|
||||
}) {
|
||||
this.loading = true
|
||||
try {
|
||||
const response = await getEquipmentList(params || {})
|
||||
if (response.data) {
|
||||
this.equipmentList = response.data.list
|
||||
this.total = response.data.total
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备列表失败:', error)
|
||||
} finally {
|
||||
this.loading = false
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
142
frontend/src/stores/site.ts
Normal file
142
frontend/src/stores/site.ts
Normal file
@ -0,0 +1,142 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { getSiteConfig } from '@/api/settings'
|
||||
import type { SiteConfigResponse } from '@/api/settings'
|
||||
|
||||
const DEFAULT_SITE_NAME = '摄影设备借还系统'
|
||||
const DEFAULT_THEME_COLOR = '#409EFF'
|
||||
const DEFAULT_LOGO_URL = 'https://s3.1080p.hk/shuzhou/2025/05/18/8ebadf0a7cc34eaea00e8619b8efb827.png'
|
||||
|
||||
const normalizeHex = (color: string) => {
|
||||
if (!color) return null
|
||||
const hex = color.trim()
|
||||
const shortHexMatch = /^#?[0-9A-Fa-f]{3}$/
|
||||
const longHexMatch = /^#?[0-9A-Fa-f]{6}$/
|
||||
if (!shortHexMatch.test(hex) && !longHexMatch.test(hex)) {
|
||||
return null
|
||||
}
|
||||
const value = hex.startsWith('#') ? hex.slice(1) : hex
|
||||
const expanded =
|
||||
value.length === 3
|
||||
? value
|
||||
.split('')
|
||||
.map((char) => char + char)
|
||||
.join('')
|
||||
: value
|
||||
return `#${expanded.toUpperCase()}`
|
||||
}
|
||||
|
||||
const hexChannel = (hex: string, index: number) => parseInt(hex.slice(index, index + 2), 16)
|
||||
|
||||
const mixChannel = (channel: number, amount: number, target: number) =>
|
||||
Math.round(channel + (target - channel) * amount)
|
||||
|
||||
const lightenHex = (hex: string, amount: number) => {
|
||||
const normalized = normalizeHex(hex)
|
||||
if (!normalized) return hex
|
||||
const r = hexChannel(normalized, 1)
|
||||
const g = hexChannel(normalized, 3)
|
||||
const b = hexChannel(normalized, 5)
|
||||
const nr = mixChannel(r, amount, 255)
|
||||
const ng = mixChannel(g, amount, 255)
|
||||
const nb = mixChannel(b, amount, 255)
|
||||
return `#${nr.toString(16).padStart(2, '0')}${ng.toString(16).padStart(2, '0')}${nb
|
||||
.toString(16)
|
||||
.padStart(2, '0')}`.toUpperCase()
|
||||
}
|
||||
|
||||
const darkenHex = (hex: string, amount: number) => {
|
||||
const normalized = normalizeHex(hex)
|
||||
if (!normalized) return hex
|
||||
const r = hexChannel(normalized, 1)
|
||||
const g = hexChannel(normalized, 3)
|
||||
const b = hexChannel(normalized, 5)
|
||||
const nr = mixChannel(r, amount, 0)
|
||||
const ng = mixChannel(g, amount, 0)
|
||||
const nb = mixChannel(b, amount, 0)
|
||||
return `#${nr.toString(16).padStart(2, '0')}${ng.toString(16).padStart(2, '0')}${nb
|
||||
.toString(16)
|
||||
.padStart(2, '0')}`.toUpperCase()
|
||||
}
|
||||
|
||||
const hexToRgba = (hex: string, alpha: number) => {
|
||||
const normalized = normalizeHex(hex)
|
||||
if (!normalized) return `rgba(0, 122, 255, ${alpha})`
|
||||
const r = hexChannel(normalized, 1)
|
||||
const g = hexChannel(normalized, 3)
|
||||
const b = hexChannel(normalized, 5)
|
||||
return `rgba(${r}, ${g}, ${b}, ${alpha})`
|
||||
}
|
||||
|
||||
const applyThemeColor = (color: string) => {
|
||||
if (typeof document === 'undefined') return
|
||||
const normalized = normalizeHex(color) || DEFAULT_THEME_COLOR
|
||||
const root = document.documentElement
|
||||
root.style.setProperty('--theme-primary', normalized)
|
||||
root.style.setProperty('--theme-primary-hover', lightenHex(normalized, 0.1))
|
||||
root.style.setProperty('--theme-primary-active', darkenHex(normalized, 0.15))
|
||||
root.style.setProperty('--theme-primary-ring', hexToRgba(normalized, 0.35))
|
||||
}
|
||||
|
||||
interface SiteState {
|
||||
siteName: string
|
||||
logoUrl: string
|
||||
faviconUrl: string
|
||||
themeColor: string
|
||||
loaded: boolean
|
||||
updatedAt: string | null
|
||||
updatedBy: SiteConfigResponse['updated_by']
|
||||
}
|
||||
|
||||
export const useSiteStore = defineStore('site', {
|
||||
state: (): SiteState => ({
|
||||
siteName: DEFAULT_SITE_NAME,
|
||||
logoUrl: DEFAULT_LOGO_URL,
|
||||
faviconUrl: '',
|
||||
themeColor: DEFAULT_THEME_COLOR,
|
||||
loaded: false,
|
||||
updatedAt: null,
|
||||
updatedBy: null
|
||||
}),
|
||||
actions: {
|
||||
setSiteConfig(config: SiteConfigResponse) {
|
||||
this.siteName = config.site_name || DEFAULT_SITE_NAME
|
||||
this.logoUrl = config.logo_url || DEFAULT_LOGO_URL
|
||||
this.faviconUrl = config.favicon_url || ''
|
||||
this.themeColor = config.theme_color || DEFAULT_THEME_COLOR
|
||||
this.updatedAt = config.updated_at
|
||||
this.updatedBy = config.updated_by
|
||||
this.loaded = true
|
||||
applyThemeColor(this.themeColor)
|
||||
if (typeof document !== 'undefined') {
|
||||
document.title = this.siteName
|
||||
if (this.faviconUrl) {
|
||||
this.updateFavicon(this.faviconUrl)
|
||||
}
|
||||
}
|
||||
},
|
||||
updateFavicon(iconUrl: string) {
|
||||
if (typeof document === 'undefined') return
|
||||
const link =
|
||||
(document.querySelector("link[rel*='icon']") as HTMLLinkElement | null) ||
|
||||
document.createElement('link')
|
||||
link.type = 'image/x-icon'
|
||||
link.rel = 'shortcut icon'
|
||||
link.href = iconUrl
|
||||
if (!link.parentNode) {
|
||||
document.getElementsByTagName('head')[0].appendChild(link)
|
||||
}
|
||||
},
|
||||
async fetchSiteConfig(force = false) {
|
||||
if (this.loaded && !force) return
|
||||
try {
|
||||
const response = await getSiteConfig()
|
||||
if (response.data) {
|
||||
this.setSiteConfig(response.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('[site] 获取站点配置失败', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
190
frontend/src/style.css
Normal file
190
frontend/src/style.css
Normal file
@ -0,0 +1,190 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Apple Design System Base Styles */
|
||||
@layer base {
|
||||
:root {
|
||||
--theme-primary: #007AFF;
|
||||
--theme-primary-hover: #2F8CFF;
|
||||
--theme-primary-active: #0063CC;
|
||||
--theme-primary-ring: rgba(0, 122, 255, 0.35);
|
||||
}
|
||||
|
||||
* {
|
||||
@apply antialiased;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-system-background-secondary text-system-label-primary font-sans;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', Helvetica, Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
@apply font-semibold text-system-label-primary;
|
||||
}
|
||||
|
||||
h1 {
|
||||
@apply text-3xl;
|
||||
}
|
||||
|
||||
h2 {
|
||||
@apply text-2xl;
|
||||
}
|
||||
|
||||
h3 {
|
||||
@apply text-xl;
|
||||
}
|
||||
}
|
||||
|
||||
/* Apple Design System Components */
|
||||
@layer components {
|
||||
/* Apple Button Styles */
|
||||
.btn-apple {
|
||||
@apply px-4 py-2 rounded-apple font-medium text-sm transition-all duration-200;
|
||||
@apply active:scale-95;
|
||||
}
|
||||
|
||||
.btn-apple-primary {
|
||||
@apply btn-apple text-white;
|
||||
background-color: var(--theme-primary);
|
||||
}
|
||||
.btn-apple-primary:hover {
|
||||
background-color: var(--theme-primary-hover);
|
||||
}
|
||||
.btn-apple-primary:active {
|
||||
background-color: var(--theme-primary-active);
|
||||
}
|
||||
.btn-apple-primary:disabled {
|
||||
@apply opacity-60 cursor-not-allowed;
|
||||
}
|
||||
|
||||
.btn-apple-secondary {
|
||||
@apply btn-apple bg-system-background-primary text-system-label-primary border border-system-gray-5;
|
||||
@apply hover:bg-system-gray-6;
|
||||
@apply active:bg-system-gray-5;
|
||||
}
|
||||
|
||||
.btn-apple-danger {
|
||||
@apply btn-apple bg-apple-red text-white;
|
||||
@apply hover:bg-opacity-90;
|
||||
@apply active:bg-opacity-80;
|
||||
}
|
||||
|
||||
/* Apple Card Styles */
|
||||
.card-apple {
|
||||
@apply bg-system-background-primary rounded-apple-lg shadow-apple p-6;
|
||||
@apply border border-system-gray-5;
|
||||
}
|
||||
|
||||
.card-apple-elevated {
|
||||
@apply card-apple shadow-apple-lg;
|
||||
}
|
||||
|
||||
/* Apple Input Styles */
|
||||
.input-apple {
|
||||
@apply w-full px-4 py-3 rounded-apple border border-system-gray-5 bg-system-background-primary;
|
||||
@apply text-system-label-primary placeholder-system-label-quaternary;
|
||||
@apply focus:outline-none;
|
||||
@apply transition-all duration-200;
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
|
||||
.input-apple:focus {
|
||||
border-color: transparent;
|
||||
box-shadow: 0 0 0 2px var(--theme-primary);
|
||||
}
|
||||
|
||||
/* Apple Glass Effect */
|
||||
.glass-apple {
|
||||
@apply bg-white bg-opacity-80 backdrop-blur-apple;
|
||||
@apply border border-white border-opacity-20;
|
||||
}
|
||||
|
||||
/* Apple Navigation Bar */
|
||||
.nav-apple {
|
||||
@apply bg-system-background-primary border-b border-system-gray-5;
|
||||
@apply backdrop-blur-apple bg-opacity-80;
|
||||
}
|
||||
|
||||
/* Apple Tab Bar */
|
||||
.tab-bar-apple {
|
||||
@apply bg-system-background-primary border-t border-system-gray-5;
|
||||
@apply backdrop-blur-apple bg-opacity-80;
|
||||
}
|
||||
}
|
||||
|
||||
/* Apple Design System Utilities */
|
||||
@layer utilities {
|
||||
.text-apple-large-title {
|
||||
@apply text-4xl font-bold;
|
||||
}
|
||||
|
||||
.text-apple-title {
|
||||
@apply text-2xl font-semibold;
|
||||
}
|
||||
|
||||
.text-apple-title-2 {
|
||||
@apply text-xl font-semibold;
|
||||
}
|
||||
|
||||
.text-apple-title-3 {
|
||||
@apply text-lg font-semibold;
|
||||
}
|
||||
|
||||
.text-apple-headline {
|
||||
@apply text-base font-semibold;
|
||||
}
|
||||
|
||||
.text-apple-body {
|
||||
@apply text-base font-normal;
|
||||
}
|
||||
|
||||
.text-apple-callout {
|
||||
@apply text-base font-medium;
|
||||
}
|
||||
|
||||
.text-apple-subhead {
|
||||
@apply text-sm font-normal;
|
||||
}
|
||||
|
||||
.text-apple-footnote {
|
||||
@apply text-xs font-normal;
|
||||
}
|
||||
|
||||
.text-apple-caption {
|
||||
@apply text-xs font-normal;
|
||||
}
|
||||
}
|
||||
|
||||
/* Custom Scrollbar - Apple Style */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
@apply bg-system-background-secondary;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-system-gray-4 rounded-full;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-system-gray-3;
|
||||
}
|
||||
|
||||
/* Focus Ring - Apple Style */
|
||||
*:focus-visible {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 2px var(--theme-primary);
|
||||
}
|
||||
|
||||
/* Selection - Apple Style */
|
||||
::selection {
|
||||
background-color: var(--theme-primary);
|
||||
color: #ffffff;
|
||||
}
|
||||
155
frontend/src/types/index.ts
Normal file
155
frontend/src/types/index.ts
Normal file
@ -0,0 +1,155 @@
|
||||
// 设备类型
|
||||
export type EquipmentType = '相机' | '镜头' | '三脚架' | '闪光灯' | '摄影配饰品'
|
||||
|
||||
// 设备状态
|
||||
export type EquipmentStatus = '可用' | '已借出' | '维护中' | '已损坏'
|
||||
|
||||
// 编码生成方式
|
||||
export type CodeGenerationMode = 'auto' | 'manual'
|
||||
|
||||
export interface StorageLocation {
|
||||
id: number
|
||||
name: string
|
||||
code?: string | null
|
||||
status: 'active' | 'inactive'
|
||||
description?: string | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
_count?: {
|
||||
equipments: number
|
||||
}
|
||||
}
|
||||
|
||||
// 设备接口
|
||||
export interface Equipment {
|
||||
id: number
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
equipment_model?: string
|
||||
equipment_type: EquipmentType
|
||||
code_generation_mode: CodeGenerationMode
|
||||
status: EquipmentStatus
|
||||
total_quantity: number
|
||||
remaining_quantity: number
|
||||
unit_price: number
|
||||
total_value: number
|
||||
borrowed_value: number
|
||||
available_value: number
|
||||
description?: string
|
||||
purchase_date?: string
|
||||
supplier?: string
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: StorageLocation | null
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// 借用记录接口
|
||||
export interface Person {
|
||||
id: number
|
||||
nickname: string
|
||||
real_name: string
|
||||
id_number?: string
|
||||
department?: string
|
||||
position?: string
|
||||
phone?: string
|
||||
email?: string
|
||||
status: 'active' | 'inactive'
|
||||
remarks?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface BorrowRecord {
|
||||
id: number
|
||||
equipment_id: number
|
||||
equipment_code: string
|
||||
equipment_name?: string
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: StorageLocation | null
|
||||
person_id: number
|
||||
person_name: string
|
||||
person_nickname: string
|
||||
person_identifier?: string
|
||||
person?: Person
|
||||
borrow_time: string
|
||||
expected_return_time?: string
|
||||
is_long_term?: boolean
|
||||
return_time?: string
|
||||
status: '已借出' | '已归还' | '逾期'
|
||||
return_condition?: '正常' | '损坏' | '丢失'
|
||||
notes?: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// 用户接口
|
||||
export interface User {
|
||||
id: number | string
|
||||
username: string
|
||||
name: string
|
||||
role: 'admin' | 'user'
|
||||
email?: string
|
||||
phone?: string
|
||||
roles?: string[]
|
||||
}
|
||||
|
||||
// API响应接口
|
||||
export interface ApiResponse<T = any> {
|
||||
code: number
|
||||
message: string
|
||||
data: T
|
||||
}
|
||||
|
||||
// 分页响应接口
|
||||
export interface PaginatedResponse<T> {
|
||||
list: T[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
}
|
||||
|
||||
// 统计数据接口
|
||||
export interface DashboardStats {
|
||||
total_equipment: number
|
||||
available_equipment: number
|
||||
borrowed_equipment: number
|
||||
maintenance_equipment: number
|
||||
usage_rate: number
|
||||
today_borrow: number
|
||||
today_return: number
|
||||
total_value: number
|
||||
borrowed_value: number
|
||||
available_value: number
|
||||
maintenance_value: number
|
||||
value_usage_rate: number
|
||||
today_borrow_value: number
|
||||
today_return_value: number
|
||||
inventory_by_type: Array<{
|
||||
equipment_type: string
|
||||
total_quantity: number
|
||||
available_quantity: number
|
||||
borrowed_quantity: number
|
||||
}>
|
||||
}
|
||||
|
||||
// 设备价值统计接口
|
||||
export interface ValueStatistics {
|
||||
total_value: number
|
||||
borrowed_value: number
|
||||
available_value: number
|
||||
maintenance_value: number
|
||||
value_by_type: Array<{
|
||||
equipment_type: EquipmentType
|
||||
total_value: number
|
||||
borrowed_value: number
|
||||
available_value: number
|
||||
}>
|
||||
top_equipment: Array<{
|
||||
equipment_name: string
|
||||
unit_price: number
|
||||
total_value: number
|
||||
borrowed_value: number
|
||||
available_value: number
|
||||
}>
|
||||
}
|
||||
86
frontend/src/utils/format.ts
Normal file
86
frontend/src/utils/format.ts
Normal file
@ -0,0 +1,86 @@
|
||||
// 格式化金额
|
||||
export const formatCurrency = (amount: number, options?: { fractionDigits?: number }): string => {
|
||||
const fractionDigits = options?.fractionDigits ?? 2
|
||||
return new Intl.NumberFormat('zh-CN', {
|
||||
style: 'currency',
|
||||
currency: 'CNY',
|
||||
minimumFractionDigits: fractionDigits,
|
||||
maximumFractionDigits: fractionDigits
|
||||
}).format(amount)
|
||||
}
|
||||
|
||||
export const formatCurrencyNoFraction = (amount: number): string => {
|
||||
return formatCurrency(amount, { fractionDigits: 0 })
|
||||
}
|
||||
|
||||
// 格式化数字(千分位)
|
||||
export const formatNumber = (num: number): string => {
|
||||
return new Intl.NumberFormat('zh-CN').format(num)
|
||||
}
|
||||
|
||||
// 格式化日期
|
||||
export const formatDate = (date: string | Date): string => {
|
||||
const d = typeof date === 'string' ? new Date(date) : date
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit'
|
||||
}).format(d)
|
||||
}
|
||||
|
||||
// 格式化日期时间
|
||||
export const formatDateTime = (date: string | Date): string => {
|
||||
const d = typeof date === 'string' ? new Date(date) : date
|
||||
return new Intl.DateTimeFormat('zh-CN', {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
}).format(d)
|
||||
}
|
||||
|
||||
// 格式化百分比
|
||||
export const formatPercent = (value: number): string => {
|
||||
return `${value.toFixed(1)}%`
|
||||
}
|
||||
|
||||
// 播放提示音
|
||||
export const playBeepSound = () => {
|
||||
// 使用Web Audio API生成提示音
|
||||
const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
|
||||
const oscillator = audioContext.createOscillator()
|
||||
const gainNode = audioContext.createGain()
|
||||
|
||||
oscillator.connect(gainNode)
|
||||
gainNode.connect(audioContext.destination)
|
||||
|
||||
oscillator.frequency.value = 800
|
||||
oscillator.type = 'sine'
|
||||
|
||||
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime)
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1)
|
||||
|
||||
oscillator.start(audioContext.currentTime)
|
||||
oscillator.stop(audioContext.currentTime + 0.1)
|
||||
}
|
||||
|
||||
// 播放错误提示音
|
||||
export const playErrorSound = () => {
|
||||
const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
|
||||
const oscillator = audioContext.createOscillator()
|
||||
const gainNode = audioContext.createGain()
|
||||
|
||||
oscillator.connect(gainNode)
|
||||
gainNode.connect(audioContext.destination)
|
||||
|
||||
oscillator.frequency.value = 400
|
||||
oscillator.type = 'sawtooth'
|
||||
|
||||
gainNode.gain.setValueAtTime(0.3, audioContext.currentTime)
|
||||
gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.2)
|
||||
|
||||
oscillator.start(audioContext.currentTime)
|
||||
oscillator.stop(audioContext.currentTime + 0.2)
|
||||
}
|
||||
|
||||
170
frontend/src/views/Login.vue
Normal file
170
frontend/src/views/Login.vue
Normal file
@ -0,0 +1,170 @@
|
||||
<template>
|
||||
<div class="flex min-h-screen items-center justify-center bg-system-background-secondary px-4">
|
||||
<div class="w-full max-w-md space-y-8 rounded-apple-xl bg-system-background-primary p-8 shadow-apple-xl">
|
||||
<div class="space-y-4 text-center">
|
||||
<div class="mx-auto flex h-16 w-16 items-center justify-center overflow-hidden rounded-apple bg-apple-blue/10 text-apple-title text-apple-blue">
|
||||
<img
|
||||
v-if="siteStore.logoUrl"
|
||||
:src="siteStore.logoUrl"
|
||||
:alt="siteStore.siteName"
|
||||
class="h-full w-full object-cover"
|
||||
/>
|
||||
<span v-else></span>
|
||||
</div>
|
||||
<h1 class="text-apple-title-2 text-system-label-primary">{{ siteStore.siteName }}</h1>
|
||||
<p class="text-apple-footnote text-system-label-tertiary">
|
||||
{{ isLocalAuth ? '请输入账号密码登录系统' : `使用 ${keycloakHostname} 完成身份认证` }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form v-if="isLocalAuth" class="space-y-5" @submit.prevent="handleLocalLogin">
|
||||
<div class="space-y-2 text-left">
|
||||
<label class="text-apple-footnote text-system-label-secondary">用户名</label>
|
||||
<input
|
||||
v-model.trim="username"
|
||||
class="input-apple"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
placeholder="请输入用户名"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2 text-left">
|
||||
<label class="text-apple-footnote text-system-label-secondary">密码</label>
|
||||
<input
|
||||
v-model="password"
|
||||
class="input-apple"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
placeholder="请输入密码"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="btn-apple-primary w-full py-3 text-base"
|
||||
:aria-busy="loading"
|
||||
:disabled="loading || !canSubmit"
|
||||
>
|
||||
{{ loading ? '正在登录…' : '登录' }}
|
||||
</button>
|
||||
<p v-if="errorText" class="text-center text-apple-footnote text-red-500">{{ errorText }}</p>
|
||||
</form>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-apple-primary w-full py-3 text-base"
|
||||
:aria-busy="loading"
|
||||
:disabled="loading"
|
||||
@click="handleLogin"
|
||||
>
|
||||
{{ loginButtonLabel }}
|
||||
</button>
|
||||
<p class="text-center text-apple-footnote text-system-label-tertiary">
|
||||
认证由 {{ keycloakHostname }} 提供。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-apple-footnote text-system-label-tertiary">© {{ currentYear }} {{ siteStore.siteName }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import keycloak from '@/auth/keycloak'
|
||||
import api from '@/api'
|
||||
import type { User } from '@/types'
|
||||
import { useSiteStore } from '@/stores/site'
|
||||
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const loading = ref(false)
|
||||
const username = ref('')
|
||||
const password = ref('')
|
||||
const errorText = ref('')
|
||||
const siteStore = useSiteStore()
|
||||
|
||||
const keycloakBaseUrl = import.meta.env.VITE_KEYCLOAK_URL ?? ''
|
||||
|
||||
const keycloakHostname = computed(() => {
|
||||
if (!keycloakBaseUrl) return '认证中心'
|
||||
try {
|
||||
return new URL(keycloakBaseUrl).host
|
||||
} catch {
|
||||
return keycloakBaseUrl
|
||||
}
|
||||
})
|
||||
|
||||
const authMode = (import.meta.env as any).VITE_AUTH_MODE || 'keycloak'
|
||||
const isLocalAuth = computed(() => authMode === 'local')
|
||||
|
||||
const currentYear = new Date().getFullYear()
|
||||
|
||||
const loginButtonLabel = computed(() => (loading.value ? '正在安全跳转…' : '使用企业账号登录'))
|
||||
|
||||
const handleLogin = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
await keycloak.login()
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const canSubmit = computed(() => username.value.length > 0 && password.value.length > 0)
|
||||
|
||||
const handleLocalLogin = async () => {
|
||||
if (!canSubmit.value) return
|
||||
loading.value = true
|
||||
errorText.value = ''
|
||||
try {
|
||||
const resp = await api.post('/auth/local/login', {
|
||||
username: username.value,
|
||||
password: password.value
|
||||
})
|
||||
const payload = resp?.data
|
||||
authStore.setToken(payload?.token || 'session')
|
||||
const rawUser = payload?.user as Partial<User> | undefined
|
||||
const normalizedUser: User = rawUser
|
||||
? {
|
||||
...rawUser,
|
||||
id: String(rawUser.id ?? rawUser.username ?? ''),
|
||||
username: rawUser.username || '',
|
||||
name: rawUser.name || rawUser.username || '',
|
||||
role: rawUser.role || (rawUser.roles?.includes('admin') ? 'admin' : 'user'),
|
||||
roles: rawUser.roles || []
|
||||
}
|
||||
: {
|
||||
id: '0',
|
||||
username: username.value,
|
||||
name: username.value,
|
||||
role: username.value === 'admin' ? 'admin' : 'user',
|
||||
roles: []
|
||||
}
|
||||
authStore.setUser(normalizedUser)
|
||||
window.alert('登录成功')
|
||||
await router.push('/dashboard')
|
||||
} catch (e: any) {
|
||||
errorText.value = e?.message || '登录失败,请重试'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => authStore.isAuthenticated,
|
||||
(isAuthenticated) => {
|
||||
if (isAuthenticated) {
|
||||
router.push('/dashboard')
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
siteStore.fetchSiteConfig()
|
||||
})
|
||||
</script>
|
||||
|
||||
107
frontend/src/views/borrow/BorrowList.vue
Normal file
107
frontend/src/views/borrow/BorrowList.vue
Normal file
@ -0,0 +1,107 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Actions -->
|
||||
<div class="flex justify-end space-x-4">
|
||||
<router-link to="/borrow/scan" class="btn-apple-primary">
|
||||
扫码出库
|
||||
</router-link>
|
||||
<router-link to="/return/scan" class="btn-apple-secondary">
|
||||
扫码入库
|
||||
</router-link>
|
||||
</div>
|
||||
|
||||
<!-- Borrow Records Table -->
|
||||
<div class="card-apple">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5">
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">设备编码</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">设备名称</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">使用者</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">借用时间</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">预计归还时间</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">归还时间</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="record in borrowRecords"
|
||||
:key="record.id"
|
||||
class="border-b border-system-gray-6 hover:bg-system-gray-6 transition-colors"
|
||||
>
|
||||
<td class="py-3 px-4 text-apple-body font-mono">{{ record.equipment_code }}</td>
|
||||
<td class="py-3 px-4 text-apple-body">{{ record.equipment_name }}</td>
|
||||
<td class="py-3 px-4 text-apple-body">
|
||||
{{ record.person_nickname }} · {{ record.person_name }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-subhead">{{ formatDateTime(record.borrow_time) }}</td>
|
||||
<td class="py-3 px-4 text-apple-subhead">
|
||||
{{
|
||||
record.is_long_term
|
||||
? '在职长期'
|
||||
: record.expected_return_time
|
||||
? formatDateTime(record.expected_return_time)
|
||||
: '-'
|
||||
}}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-subhead">
|
||||
{{ record.return_time ? formatDateTime(record.return_time) : '-' }}
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="px-3 py-1 rounded-apple text-apple-footnote font-medium"
|
||||
:class="getStatusClass(record.status)"
|
||||
>
|
||||
{{ record.status }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { getBorrowRecordList } from '@/api/borrow'
|
||||
import type { BorrowRecord } from '@/types'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
|
||||
const borrowRecords = ref<BorrowRecord[]>([])
|
||||
const loading = ref(false)
|
||||
|
||||
const fetchBorrowRecords = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await getBorrowRecordList({
|
||||
page: 1,
|
||||
pageSize: 100
|
||||
})
|
||||
if (response.data) {
|
||||
borrowRecords.value = response.data.list
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取借用记录失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const getStatusClass = (status: string) => {
|
||||
const classes: Record<string, string> = {
|
||||
'已借出': 'bg-apple-orange text-white',
|
||||
'已归还': 'bg-apple-green text-white',
|
||||
'逾期': 'bg-apple-red text-white'
|
||||
}
|
||||
return classes[status] || 'bg-system-gray-5 text-system-label-secondary'
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchBorrowRecords()
|
||||
})
|
||||
</script>
|
||||
|
||||
375
frontend/src/views/borrow/BorrowScan.vue
Normal file
375
frontend/src/views/borrow/BorrowScan.vue
Normal file
@ -0,0 +1,375 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Scan Input Area -->
|
||||
<div class="card-apple">
|
||||
<div class="mb-6">
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备编码</label>
|
||||
<input
|
||||
ref="scanInputRef"
|
||||
v-model="scanCode"
|
||||
type="text"
|
||||
class="input-apple text-lg"
|
||||
placeholder="请使用扫码枪扫描设备条码"
|
||||
@keyup.enter="handleScan"
|
||||
@focus="handleFocus"
|
||||
/>
|
||||
<p class="text-apple-footnote text-system-label-tertiary mt-2">
|
||||
提示:扫描条码后按回车键或等待自动识别
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Info -->
|
||||
<div v-if="equipmentInfo" class="mt-6 p-4 bg-system-gray-6 rounded-apple space-y-4">
|
||||
<h3 class="text-apple-title mb-4">设备信息</h3>
|
||||
<div class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备编码</p>
|
||||
<p class="text-apple-body font-mono">{{ equipmentInfo.equipment_code }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备名称</p>
|
||||
<p class="text-apple-body">{{ equipmentInfo.equipment_name }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备型号</p>
|
||||
<p class="text-apple-body">{{ equipmentInfo.equipment_model || '-' }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备状态</p>
|
||||
<p class="text-apple-body">{{ equipmentInfo.status }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">库位</p>
|
||||
<p class="text-apple-body">{{ equipmentInfo.storageLocation?.name || '-' }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">单价</p>
|
||||
<p class="text-apple-body">{{ formatCurrency(equipmentInfo.unit_price) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">可用数量</p>
|
||||
<p class="text-apple-body">{{ equipmentInfo.remaining_quantity }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col gap-2 md:flex-row md:items-center md:justify-between">
|
||||
<p class="text-apple-footnote text-system-label-secondary">
|
||||
请核对设备信息无误后再进行出库操作。
|
||||
</p>
|
||||
<div class="flex items-center gap-3">
|
||||
<button
|
||||
v-if="!equipmentConfirmed"
|
||||
class="btn-apple-secondary"
|
||||
@click="equipmentConfirmed = true"
|
||||
>
|
||||
确认设备信息
|
||||
</button>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex items-center rounded-full bg-apple-green/15 px-3 py-1 text-apple-footnote text-apple-green"
|
||||
>
|
||||
✅ 已确认
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Borrower Info Form -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">使用者信息</h2>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">使用者 *</label>
|
||||
<div class="space-y-2">
|
||||
<input
|
||||
v-model.trim="personKeyword"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="输入花名 / 姓名 / 证件号进行搜索"
|
||||
/>
|
||||
<select
|
||||
v-model.number="selectedPersonId"
|
||||
class="input-apple"
|
||||
>
|
||||
<option value="" disabled>请选择使用者</option>
|
||||
<option
|
||||
v-for="person in filteredPersons"
|
||||
:key="person.id"
|
||||
:value="person.id"
|
||||
>
|
||||
{{ person.nickname }} · {{ person.real_name }}{{ person.department ? `(${person.department})` : '' }}
|
||||
</option>
|
||||
</select>
|
||||
<p class="text-apple-footnote text-system-label-tertiary">
|
||||
未找到需要的人员?前往
|
||||
<router-link
|
||||
:to="{ path: '/settings', query: { tab: 'persons' } }"
|
||||
class="text-apple-blue underline"
|
||||
>
|
||||
系统设置 > 使用者信息
|
||||
</router-link>
|
||||
新增。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="selectedPerson">
|
||||
<div class="rounded-apple bg-system-gray-6 px-4 py-3 text-apple-footnote text-system-label-secondary">
|
||||
<p>花名:{{ selectedPerson.nickname }}</p>
|
||||
<p>姓名:{{ selectedPerson.real_name }}</p>
|
||||
<p v-if="selectedPerson.department">部门:{{ selectedPerson.department }}</p>
|
||||
<p v-if="selectedPerson.phone">电话:{{ selectedPerson.phone }}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex items-center justify-between mb-2">
|
||||
<label class="block text-apple-body text-system-label-primary">预计归还时间</label>
|
||||
<label class="flex items-center space-x-2 text-apple-footnote text-system-label-secondary">
|
||||
<input
|
||||
v-model="borrowForm.is_long_term"
|
||||
type="checkbox"
|
||||
class="h-4 w-4 rounded border-system-gray-4 text-apple-blue focus:ring-apple-blue"
|
||||
/>
|
||||
<span>在职长期</span>
|
||||
</label>
|
||||
</div>
|
||||
<input
|
||||
v-model="borrowForm.expected_return_time"
|
||||
type="datetime-local"
|
||||
class="input-apple"
|
||||
:disabled="borrowForm.is_long_term"
|
||||
/>
|
||||
<p class="mt-1 text-apple-footnote text-system-label-tertiary">
|
||||
选择“在职长期”后将不设置具体归还日期。
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">备注</label>
|
||||
<textarea
|
||||
v-model="borrowForm.notes"
|
||||
class="input-apple"
|
||||
rows="3"
|
||||
placeholder="请输入备注信息"
|
||||
></textarea>
|
||||
</div>
|
||||
<button
|
||||
@click="handleSubmit"
|
||||
:disabled="!canSubmit"
|
||||
class="btn-apple-primary w-full"
|
||||
>
|
||||
{{ loading ? '提交中...' : '确认出库' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="successInfo" class="card-apple border border-apple-green/40 bg-apple-green/5">
|
||||
<h2 class="text-apple-title text-apple-green mb-2">出库成功</h2>
|
||||
<p class="text-apple-body text-system-label-secondary">设备 {{ successInfo.equipment_name }} ({{ successInfo.equipment_code }})已成功出库。</p>
|
||||
<p class="text-apple-footnote text-system-label-tertiary mt-2">
|
||||
出库人:{{ successInfo.person_display }};时间:{{ successInfo.borrow_time }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { scanEquipment } from '@/api/equipment'
|
||||
import { scanBorrow } from '@/api/borrow'
|
||||
import { getPersonList } from '@/api/person'
|
||||
import type { Equipment, Person } from '@/types'
|
||||
import { formatCurrency, playBeepSound, playErrorSound } from '@/utils/format'
|
||||
|
||||
const scanCode = ref('')
|
||||
const scanInputRef = ref<HTMLInputElement>()
|
||||
const equipmentInfo = ref<Equipment | null>(null)
|
||||
const equipmentConfirmed = ref(false)
|
||||
const successInfo = ref<{
|
||||
equipment_name: string
|
||||
equipment_code: string
|
||||
person_display: string
|
||||
borrow_time: string
|
||||
} | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
const borrowForm = ref({
|
||||
expected_return_time: '',
|
||||
notes: '',
|
||||
is_long_term: false
|
||||
})
|
||||
|
||||
const personKeyword = ref('')
|
||||
const selectedPersonId = ref<number | null>(null)
|
||||
const persons = ref<Person[]>([])
|
||||
let searchTimer: number | null = null
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
const hasEquipment = Boolean(equipmentInfo.value)
|
||||
const personId = selectedPersonId.value
|
||||
const hasPerson = personId !== null && !Number.isNaN(personId)
|
||||
return hasEquipment && hasPerson && equipmentConfirmed.value && !loading.value
|
||||
})
|
||||
|
||||
const filteredPersons = computed(() => {
|
||||
if (!personKeyword.value) {
|
||||
return persons.value
|
||||
}
|
||||
const keyword = personKeyword.value.trim().toLowerCase()
|
||||
return persons.value.filter((person) => {
|
||||
return (
|
||||
person.nickname.toLowerCase().includes(keyword) ||
|
||||
person.real_name.toLowerCase().includes(keyword) ||
|
||||
(person.id_number && person.id_number.toLowerCase().includes(keyword)) ||
|
||||
(person.department && person.department.toLowerCase().includes(keyword))
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
const selectedPerson = computed(() => {
|
||||
if (!selectedPersonId.value) return null
|
||||
return persons.value.find((person) => person.id === selectedPersonId.value) || null
|
||||
})
|
||||
|
||||
const handleFocus = () => {
|
||||
scanCode.value = ''
|
||||
}
|
||||
|
||||
const handleScan = async () => {
|
||||
if (!scanCode.value) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await scanEquipment(scanCode.value)
|
||||
if (response.data) {
|
||||
equipmentInfo.value = response.data
|
||||
equipmentConfirmed.value = false
|
||||
successInfo.value = null
|
||||
playBeepSound()
|
||||
|
||||
// 清空扫码框,准备下次扫码
|
||||
scanCode.value = ''
|
||||
nextTick(() => {
|
||||
scanInputRef.value?.focus()
|
||||
})
|
||||
}
|
||||
} catch (error: any) {
|
||||
playErrorSound()
|
||||
alert(error.message || '扫码失败,请检查设备编码是否正确')
|
||||
scanCode.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!equipmentInfo.value || selectedPersonId.value === null || Number.isNaN(selectedPersonId.value)) {
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await scanBorrow({
|
||||
equipment_code: equipmentInfo.value.equipment_code,
|
||||
person_id: Number(selectedPersonId.value),
|
||||
expected_return_time: borrowForm.value.is_long_term
|
||||
? undefined
|
||||
: borrowForm.value.expected_return_time || undefined,
|
||||
notes: borrowForm.value.notes || undefined,
|
||||
is_long_term: borrowForm.value.is_long_term
|
||||
})
|
||||
if (response.data) {
|
||||
alert('出库成功!')
|
||||
const personDisplay = selectedPerson.value
|
||||
? `${selectedPerson.value.nickname}(${selectedPerson.value.real_name})`
|
||||
: `ID ${selectedPersonId.value}`
|
||||
successInfo.value = {
|
||||
equipment_name: equipmentInfo.value.equipment_name,
|
||||
equipment_code: equipmentInfo.value.equipment_code,
|
||||
person_display: personDisplay,
|
||||
borrow_time: response.data.borrow_time
|
||||
? new Date(response.data.borrow_time).toLocaleString()
|
||||
: new Date().toLocaleString()
|
||||
}
|
||||
if (typeof response.data.remaining_quantity === 'number') {
|
||||
equipmentInfo.value.remaining_quantity = response.data.remaining_quantity
|
||||
}
|
||||
if (response.data.equipment_status) {
|
||||
equipmentInfo.value.status = response.data.equipment_status
|
||||
} else if (equipmentInfo.value.remaining_quantity === 0) {
|
||||
equipmentInfo.value.status = '已借出'
|
||||
}
|
||||
equipmentConfirmed.value = false
|
||||
borrowForm.value.notes = ''
|
||||
if (!borrowForm.value.is_long_term) {
|
||||
borrowForm.value.expected_return_time = ''
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(error.message || '出库失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const fetchPersons = async (keyword = '') => {
|
||||
try {
|
||||
const response = await getPersonList({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
keyword: keyword || undefined,
|
||||
status: 'active'
|
||||
})
|
||||
if (response.data) {
|
||||
persons.value = response.data.list
|
||||
if (selectedPersonId.value) {
|
||||
const exists = persons.value.some((person) => person.id === selectedPersonId.value)
|
||||
if (!exists) {
|
||||
selectedPersonId.value = null
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取使用者列表失败', error)
|
||||
}
|
||||
}
|
||||
|
||||
watch(
|
||||
() => personKeyword.value,
|
||||
(value) => {
|
||||
if (searchTimer) {
|
||||
window.clearTimeout(searchTimer)
|
||||
}
|
||||
searchTimer = window.setTimeout(() => {
|
||||
fetchPersons(value)
|
||||
}, 300)
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => borrowForm.value.is_long_term,
|
||||
(value) => {
|
||||
if (value) {
|
||||
borrowForm.value.expected_return_time = ''
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => equipmentInfo.value?.equipment_code,
|
||||
() => {
|
||||
equipmentConfirmed.value = false
|
||||
}
|
||||
)
|
||||
|
||||
onMounted(() => {
|
||||
fetchPersons()
|
||||
nextTick(() => {
|
||||
scanInputRef.value?.focus()
|
||||
})
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (searchTimer) {
|
||||
window.clearTimeout(searchTimer)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
262
frontend/src/views/borrow/ReturnScan.vue
Normal file
262
frontend/src/views/borrow/ReturnScan.vue
Normal file
@ -0,0 +1,262 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Scan Input Area -->
|
||||
<div class="card-apple">
|
||||
<div class="mb-6">
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备编码</label>
|
||||
<input
|
||||
ref="scanInputRef"
|
||||
v-model="scanCode"
|
||||
type="text"
|
||||
class="input-apple text-lg"
|
||||
placeholder="请使用扫码枪扫描设备条码"
|
||||
@keyup.enter="handleScan"
|
||||
@focus="handleFocus"
|
||||
/>
|
||||
<p class="text-apple-footnote text-system-label-tertiary mt-2">
|
||||
提示:扫描条码后按回车键或等待自动识别
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Equipment and Borrow Record Info -->
|
||||
<div v-if="borrowRecordInfo" class="mt-6 p-4 bg-system-gray-6 rounded-apple">
|
||||
<h3 class="text-apple-title mb-4">设备信息</h3>
|
||||
<div class="grid grid-cols-2 gap-4 mb-6">
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备编码</p>
|
||||
<p class="text-apple-body font-mono">{{ borrowRecordInfo.equipment_code }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备名称</p>
|
||||
<p class="text-apple-body">{{ borrowRecordInfo.equipment_name }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">库位</p>
|
||||
<p class="text-apple-body">
|
||||
{{ borrowRecordInfo.storageLocation?.name || '-' }}
|
||||
<span v-if="borrowRecordInfo.storageLocation?.code">
|
||||
({{ borrowRecordInfo.storageLocation?.code }})
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">单价</p>
|
||||
<p class="text-apple-body">{{ formatCurrency(borrowRecordInfo.unit_price) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">设备价值</p>
|
||||
<p class="text-apple-body">{{ formatCurrency(borrowRecordInfo.equipment_value) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h3 class="text-apple-title mb-4">借用记录</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">选择归还使用者</label>
|
||||
<select v-model="selectedBorrowRecordId" class="input-apple">
|
||||
<option value="" disabled>请选择归还使用者</option>
|
||||
<option
|
||||
v-for="record in borrowRecordInfo.borrow_records"
|
||||
:key="record.id"
|
||||
:value="String(record.id)"
|
||||
>
|
||||
{{ record.person_nickname }} · {{ record.person_name }}
|
||||
(借用时间:{{ formatDateTime(record.borrow_time) }})
|
||||
</option>
|
||||
</select>
|
||||
<p
|
||||
v-if="borrowRecordInfo.borrow_records.length > 1"
|
||||
class="text-apple-footnote text-system-label-tertiary mt-2"
|
||||
>
|
||||
提示:该设备有多位使用者同时借出,请选择正确的归还人。
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="selectedBorrowRecord" class="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">使用者</p>
|
||||
<p class="text-apple-body">
|
||||
{{ selectedBorrowRecord.person_nickname }} · {{ selectedBorrowRecord.person_name }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="selectedBorrowRecord.person?.department">
|
||||
<p class="text-apple-footnote text-system-label-secondary">部门</p>
|
||||
<p class="text-apple-body">{{ selectedBorrowRecord.person?.department }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">借用时间</p>
|
||||
<p class="text-apple-body">{{ formatDateTime(selectedBorrowRecord.borrow_time) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">预计归还时间</p>
|
||||
<p class="text-apple-body">
|
||||
{{
|
||||
selectedBorrowRecord.is_long_term
|
||||
? '在职长期'
|
||||
: selectedBorrowRecord.expected_return_time
|
||||
? formatDateTime(selectedBorrowRecord.expected_return_time)
|
||||
: '未设置'
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary">状态</p>
|
||||
<p class="text-apple-body">{{ selectedBorrowRecord.status }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Return Info Form -->
|
||||
<div v-if="borrowRecordInfo" class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">归还信息</h2>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">归还状态</label>
|
||||
<select v-model="returnInfo.return_condition" class="input-apple">
|
||||
<option value="正常">正常</option>
|
||||
<option value="损坏">损坏</option>
|
||||
<option value="丢失">丢失</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">备注</label>
|
||||
<textarea
|
||||
v-model="returnInfo.notes"
|
||||
class="input-apple"
|
||||
rows="3"
|
||||
placeholder="请输入备注信息"
|
||||
></textarea>
|
||||
</div>
|
||||
<button
|
||||
@click="handleSubmit"
|
||||
:disabled="loading || !selectedBorrowRecord"
|
||||
class="btn-apple-primary w-full"
|
||||
>
|
||||
{{ loading ? '提交中...' : '确认入库' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, nextTick, computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { getBorrowRecordByCode } from '@/api/borrow'
|
||||
import { scanReturn } from '@/api/borrow'
|
||||
import { formatCurrency, formatDateTime, playBeepSound, playErrorSound } from '@/utils/format'
|
||||
import type { BorrowRecord, StorageLocation } from '@/types'
|
||||
|
||||
interface BorrowRecordInfo {
|
||||
equipment_code: string
|
||||
equipment_name: string
|
||||
unit_price: number
|
||||
equipment_value: number
|
||||
storage_location_id?: number | null
|
||||
storageLocation?: StorageLocation | null
|
||||
borrow_records: BorrowRecord[]
|
||||
can_return: boolean
|
||||
message: string
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const scanCode = ref('')
|
||||
const scanInputRef = ref<HTMLInputElement>()
|
||||
const borrowRecordInfo = ref<BorrowRecordInfo | null>(null)
|
||||
const loading = ref(false)
|
||||
|
||||
const returnInfo = ref({
|
||||
return_condition: '正常',
|
||||
notes: ''
|
||||
})
|
||||
|
||||
const selectedBorrowRecordId = ref<string>('')
|
||||
|
||||
const selectedBorrowRecord = computed(() => {
|
||||
if (
|
||||
!borrowRecordInfo.value ||
|
||||
!selectedBorrowRecordId.value ||
|
||||
Number.isNaN(Number(selectedBorrowRecordId.value))
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
borrowRecordInfo.value.borrow_records.find(
|
||||
(record) => record.id === Number(selectedBorrowRecordId.value)
|
||||
) || null
|
||||
)
|
||||
})
|
||||
|
||||
const handleFocus = () => {
|
||||
scanCode.value = ''
|
||||
}
|
||||
|
||||
const handleScan = async () => {
|
||||
if (!scanCode.value) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await getBorrowRecordByCode(scanCode.value)
|
||||
if (response.data) {
|
||||
borrowRecordInfo.value = response.data
|
||||
selectedBorrowRecordId.value = ''
|
||||
returnInfo.value = {
|
||||
return_condition: '正常',
|
||||
notes: ''
|
||||
}
|
||||
playBeepSound()
|
||||
|
||||
// 清空扫码框,准备下次扫码
|
||||
scanCode.value = ''
|
||||
nextTick(() => {
|
||||
scanInputRef.value?.focus()
|
||||
})
|
||||
}
|
||||
} catch (error: any) {
|
||||
playErrorSound()
|
||||
alert(error.message || '扫码失败,请检查设备编码是否正确')
|
||||
scanCode.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!borrowRecordInfo.value) {
|
||||
return
|
||||
}
|
||||
|
||||
const record = selectedBorrowRecord.value
|
||||
|
||||
if (!record) {
|
||||
alert('请选择归还使用者')
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
await scanReturn({
|
||||
equipment_code: borrowRecordInfo.value.equipment_code,
|
||||
return_condition: returnInfo.value.return_condition,
|
||||
notes: returnInfo.value.notes || undefined,
|
||||
person_id: record.person_id,
|
||||
borrow_record_id: record.id
|
||||
})
|
||||
|
||||
alert('入库成功!')
|
||||
router.push('/borrow')
|
||||
} catch (error: any) {
|
||||
alert(error.message || '入库失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(() => {
|
||||
scanInputRef.value?.focus()
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
282
frontend/src/views/dashboard/Dashboard.vue
Normal file
282
frontend/src/views/dashboard/Dashboard.vue
Normal file
@ -0,0 +1,282 @@
|
||||
<template>
|
||||
<div class="space-y-6 relative">
|
||||
<Transition name="fade">
|
||||
<div
|
||||
v-if="isLoading"
|
||||
class="absolute inset-0 z-10 flex items-center justify-center bg-system-background-primary/70 backdrop-blur-sm"
|
||||
>
|
||||
<div class="flex flex-col items-center space-y-3 text-system-label-secondary">
|
||||
<svg class="w-8 h-8 animate-spin text-apple-blue" viewBox="0 0 24 24" fill="none">
|
||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" />
|
||||
<path
|
||||
class="opacity-75"
|
||||
fill="currentColor"
|
||||
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-apple-footnote">数据加载中,请稍候…</span>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
<!-- Statistics Cards Grid - Apple Style -->
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
|
||||
<StatCard
|
||||
v-for="card in statCards"
|
||||
:key="card.title"
|
||||
:title="card.title"
|
||||
:value="card.value"
|
||||
:icon="card.icon"
|
||||
:color="card.color"
|
||||
:trend="card.trend"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Charts Section -->
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<!-- Equipment Status Distribution -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">设备状态分布</h2>
|
||||
<div ref="statusChartRef" class="h-64"></div>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Category Inventory Distribution -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">设备分类库存占比</h2>
|
||||
<div ref="categoryChartRef" class="h-64"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Borrow Records -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">最近借用记录</h2>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5">
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">设备名称</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">使用者</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">借用时间</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">预计归还时间</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary">状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="record in recentRecords"
|
||||
:key="record.id"
|
||||
class="border-b border-system-gray-6 hover:bg-system-gray-6 transition-colors"
|
||||
>
|
||||
<td class="py-3 px-4 text-apple-body">{{ record.equipment_name }}</td>
|
||||
<td class="py-3 px-4 text-apple-body">
|
||||
{{ record.person_nickname }} · {{ record.person_name }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-subhead">{{ formatDateTime(record.borrow_time) }}</td>
|
||||
<td class="py-3 px-4 text-apple-subhead">
|
||||
{{
|
||||
record.is_long_term
|
||||
? '在职长期'
|
||||
: record.expected_return_time
|
||||
? formatDateTime(record.expected_return_time)
|
||||
: '-'
|
||||
}}
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="px-3 py-1 rounded-apple text-apple-footnote font-medium"
|
||||
:class="getStatusClass(record.status)"
|
||||
>
|
||||
{{ record.status }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import * as echarts from 'echarts'
|
||||
import { getDashboardStats } from '@/api/statistics'
|
||||
import { getBorrowRecordList } from '@/api/borrow'
|
||||
import type { DashboardStats, BorrowRecord } from '@/types'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import StatCard from '@/components/StatCard.vue'
|
||||
import {
|
||||
CubeIcon,
|
||||
CheckCircleIcon,
|
||||
ArrowUpTrayIcon,
|
||||
WrenchScrewdriverIcon
|
||||
} from '@heroicons/vue/24/outline'
|
||||
|
||||
const stats = ref<DashboardStats | null>(null)
|
||||
const recentRecords = ref<BorrowRecord[]>([])
|
||||
const statusChartRef = ref<HTMLElement>()
|
||||
const categoryChartRef = ref<HTMLElement>()
|
||||
let statusChart: echarts.ECharts | null = null
|
||||
let categoryChart: echarts.ECharts | null = null
|
||||
const isLoading = ref(false)
|
||||
|
||||
const statCards = ref([
|
||||
{ title: '设备库存总量', value: '0', icon: CubeIcon, color: 'apple-blue', trend: null },
|
||||
{ title: '可用库存', value: '0', icon: CheckCircleIcon, color: 'apple-green', trend: null },
|
||||
{ title: '已借出库存', value: '0', icon: ArrowUpTrayIcon, color: 'apple-orange', trend: null },
|
||||
{ title: '维护中库存', value: '0', icon: WrenchScrewdriverIcon, color: 'apple-yellow', trend: null }
|
||||
])
|
||||
|
||||
const fetchDashboardData = async () => {
|
||||
isLoading.value = true
|
||||
try {
|
||||
const [statsResponse, recordsResponse] = await Promise.all([
|
||||
getDashboardStats(),
|
||||
getBorrowRecordList({ page: 1, pageSize: 10 })
|
||||
])
|
||||
|
||||
if (statsResponse.data) {
|
||||
stats.value = statsResponse.data
|
||||
updateStatCards(statsResponse.data)
|
||||
updateStatusChart()
|
||||
updateCategoryChart()
|
||||
}
|
||||
|
||||
if (recordsResponse.data) {
|
||||
recentRecords.value = recordsResponse.data.list
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取仪表板数据失败:', error)
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const updateStatCards = (data: DashboardStats) => {
|
||||
statCards.value[0].value = data.total_equipment.toString()
|
||||
statCards.value[1].value = data.available_equipment.toString()
|
||||
statCards.value[2].value = data.borrowed_equipment.toString()
|
||||
statCards.value[3].value = data.maintenance_equipment.toString()
|
||||
}
|
||||
|
||||
const initCharts = () => {
|
||||
if (statusChartRef.value && !statusChart) {
|
||||
statusChart = echarts.init(statusChartRef.value)
|
||||
}
|
||||
|
||||
if (categoryChartRef.value && !categoryChart) {
|
||||
categoryChart = echarts.init(categoryChartRef.value)
|
||||
}
|
||||
|
||||
updateStatusChart()
|
||||
updateCategoryChart()
|
||||
}
|
||||
|
||||
const updateStatusChart = () => {
|
||||
if (!statusChart) return
|
||||
statusChart.setOption({
|
||||
tooltip: {
|
||||
trigger: 'item'
|
||||
},
|
||||
series: [{
|
||||
type: 'pie',
|
||||
radius: '70%',
|
||||
data: [
|
||||
{ value: stats.value?.available_equipment || 0, name: '可用', itemStyle: { color: '#34C759' } },
|
||||
{ value: stats.value?.borrowed_equipment || 0, name: '已借出', itemStyle: { color: '#FF9500' } },
|
||||
{ value: stats.value?.maintenance_equipment || 0, name: '维护中', itemStyle: { color: '#FFCC00' } }
|
||||
],
|
||||
emphasis: {
|
||||
itemStyle: {
|
||||
shadowBlur: 10,
|
||||
shadowOffsetX: 0,
|
||||
shadowColor: 'rgba(0, 0, 0, 0.5)'
|
||||
}
|
||||
},
|
||||
label: {
|
||||
formatter: '{b}: {d}%'
|
||||
}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
const updateCategoryChart = () => {
|
||||
if (!categoryChart) return
|
||||
const categories = stats.value?.inventory_by_type || []
|
||||
categoryChart.setOption({
|
||||
tooltip: {
|
||||
trigger: 'item'
|
||||
},
|
||||
series: [{
|
||||
type: 'pie',
|
||||
radius: ['45%', '70%'],
|
||||
avoidLabelOverlap: false,
|
||||
data: categories.length
|
||||
? categories.map((item) => ({
|
||||
value: item.total_quantity,
|
||||
name: item.equipment_type,
|
||||
itemStyle: {
|
||||
color: categoryColorPalette[item.equipment_type] || undefined
|
||||
}
|
||||
}))
|
||||
: [{ value: 1, name: '暂无数据', itemStyle: { color: '#d1d1d6' } }],
|
||||
emphasis: {
|
||||
itemStyle: {
|
||||
shadowBlur: 10,
|
||||
shadowOffsetX: 0,
|
||||
shadowColor: 'rgba(0, 0, 0, 0.5)'
|
||||
}
|
||||
},
|
||||
label: {
|
||||
formatter: '{b}: {d}%'
|
||||
}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
const categoryColorPalette: Record<string, string> = {
|
||||
相机: '#0071e3',
|
||||
镜头: '#34c759',
|
||||
三脚架: '#ff9500',
|
||||
闪光灯: '#af52de',
|
||||
摄影配饰品: '#ff2d55'
|
||||
}
|
||||
|
||||
const getStatusClass = (status: string) => {
|
||||
const classes: Record<string, string> = {
|
||||
'已借出': 'bg-apple-orange text-white',
|
||||
'已归还': 'bg-apple-green text-white',
|
||||
'逾期': 'bg-apple-red text-white'
|
||||
}
|
||||
return classes[status] || 'bg-system-gray-5 text-system-label-secondary'
|
||||
}
|
||||
|
||||
const resizeHandler = () => {
|
||||
statusChart?.resize()
|
||||
categoryChart?.resize()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchDashboardData()
|
||||
initCharts()
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
statusChart?.dispose()
|
||||
categoryChart?.dispose()
|
||||
window.removeEventListener('resize', resizeHandler)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.fade-enter-active,
|
||||
.fade-leave-active {
|
||||
transition: opacity 0.2s ease;
|
||||
}
|
||||
.fade-enter-from,
|
||||
.fade-leave-to {
|
||||
opacity: 0;
|
||||
}
|
||||
</style>
|
||||
|
||||
392
frontend/src/views/equipment/EquipmentForm.vue
Normal file
392
frontend/src/views/equipment/EquipmentForm.vue
Normal file
@ -0,0 +1,392 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Equipment Form -->
|
||||
<div class="card-apple">
|
||||
<form @submit.prevent="handleSubmit" class="space-y-6">
|
||||
<!-- Code Generation Mode -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">编码生成方式</label>
|
||||
<div class="flex items-center space-x-4">
|
||||
<label class="flex items-center">
|
||||
<input
|
||||
v-model="form.code_generation_mode"
|
||||
type="radio"
|
||||
value="auto"
|
||||
class="mr-2"
|
||||
/>
|
||||
<span class="text-apple-body">自动生成</span>
|
||||
</label>
|
||||
<label class="flex items-center">
|
||||
<input
|
||||
v-model="form.code_generation_mode"
|
||||
type="radio"
|
||||
value="manual"
|
||||
class="mr-2"
|
||||
/>
|
||||
<span class="text-apple-body">自定义录入</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Code -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备编码 *</label>
|
||||
<input
|
||||
v-if="form.code_generation_mode === 'manual'"
|
||||
v-model="form.equipment_code"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="请输入设备编码"
|
||||
required
|
||||
/>
|
||||
<input
|
||||
v-else
|
||||
v-model="form.equipment_code"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="系统自动生成"
|
||||
readonly
|
||||
/>
|
||||
<button
|
||||
v-if="form.code_generation_mode === 'auto'"
|
||||
type="button"
|
||||
@click="handleGenerateCode"
|
||||
class="btn-apple-secondary mt-2"
|
||||
>
|
||||
重新生成
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Name -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备名称 *</label>
|
||||
<input
|
||||
v-model="form.equipment_name"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="请输入设备名称"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Model -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备型号</label>
|
||||
<input
|
||||
v-model="form.equipment_model"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="请输入设备型号"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Type -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备类型 *</label>
|
||||
<select v-model="form.equipment_type" class="input-apple" required>
|
||||
<option value="">请选择设备类型</option>
|
||||
<option value="相机">相机</option>
|
||||
<option value="镜头">镜头</option>
|
||||
<option value="三脚架">三脚架</option>
|
||||
<option value="闪光灯">闪光灯</option>
|
||||
<option value="摄影配饰品">摄影配饰品</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Storage Location -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库位 *</label>
|
||||
<select v-model="form.storage_location_id" class="input-apple" required>
|
||||
<option value="">请选择库位</option>
|
||||
<option
|
||||
v-for="location in storageLocations"
|
||||
:key="location.id"
|
||||
:value="location.id"
|
||||
>
|
||||
{{ location.name }}<span v-if="location.code">({{ location.code }})</span>
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<!-- Unit Price -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">单价(元) *</label>
|
||||
<input
|
||||
v-model.number="form.unit_price"
|
||||
type="number"
|
||||
step="0.01"
|
||||
min="0"
|
||||
class="input-apple"
|
||||
placeholder="请输入单价"
|
||||
required
|
||||
@input="handlePriceChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Total Quantity -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库存总数量 *</label>
|
||||
<input
|
||||
v-model.number="form.total_quantity"
|
||||
type="number"
|
||||
min="1"
|
||||
class="input-apple"
|
||||
placeholder="请输入库存总数量"
|
||||
required
|
||||
@input="handlePriceChange"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Calculated Values -->
|
||||
<div class="grid grid-cols-3 gap-4 p-4 bg-system-gray-6 rounded-apple">
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary mb-1">总价值</p>
|
||||
<p class="text-apple-body font-semibold">{{ formatCurrency(calculatedTotalValue) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary mb-1">已借出价值</p>
|
||||
<p class="text-apple-body font-semibold">{{ formatCurrency(calculatedBorrowedValue) }}</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-apple-footnote text-system-label-secondary mb-1">可用价值</p>
|
||||
<p class="text-apple-body font-semibold">{{ formatCurrency(calculatedAvailableValue) }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Purchase Date -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">采购日期</label>
|
||||
<input
|
||||
v-model="form.purchase_date"
|
||||
type="date"
|
||||
class="input-apple"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Supplier -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">供应商</label>
|
||||
<input
|
||||
v-model="form.supplier"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="请输入供应商"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">设备描述</label>
|
||||
<textarea
|
||||
v-model="form.description"
|
||||
class="input-apple"
|
||||
rows="3"
|
||||
placeholder="请输入设备描述"
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<!-- Actions -->
|
||||
<div class="flex items-center space-x-4 pt-4 border-t border-system-gray-5">
|
||||
<button type="submit" class="btn-apple-primary" :disabled="loading">
|
||||
{{ loading ? '保存中...' : '保存' }}
|
||||
</button>
|
||||
<button type="button" @click="handleCancel" class="btn-apple-secondary">
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, watch } from 'vue'
|
||||
import { useRouter, useRoute } from 'vue-router'
|
||||
import { createEquipment, updateEquipment, getEquipmentDetail, generateEquipmentCode } from '@/api/equipment'
|
||||
import { getStorageLocationOptions } from '@/api/storageLocation'
|
||||
import type { Equipment, StorageLocation } from '@/types'
|
||||
import { formatCurrency } from '@/utils/format'
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
|
||||
const isEdit = computed(() => !!route.params.id)
|
||||
const loading = ref(false)
|
||||
|
||||
const storageLocations = ref<StorageLocation[]>([])
|
||||
const editingLocation = ref<StorageLocation | null>(null)
|
||||
|
||||
const form = ref<Partial<Equipment>>({
|
||||
equipment_code: '',
|
||||
equipment_name: '',
|
||||
equipment_model: '',
|
||||
equipment_type: '相机',
|
||||
code_generation_mode: 'auto',
|
||||
unit_price: 0,
|
||||
total_quantity: 1,
|
||||
remaining_quantity: 1,
|
||||
purchase_date: '',
|
||||
supplier: '',
|
||||
description: '',
|
||||
storage_location_id: undefined
|
||||
})
|
||||
|
||||
const ensureSelectedLocationInOptions = () => {
|
||||
const selectedId = form.value.storage_location_id
|
||||
if (!selectedId) return
|
||||
const exists = storageLocations.value.some((location) => location.id === selectedId)
|
||||
if (!exists && editingLocation.value) {
|
||||
storageLocations.value = [...storageLocations.value, editingLocation.value]
|
||||
}
|
||||
}
|
||||
|
||||
const loadStorageLocations = async () => {
|
||||
try {
|
||||
const response = await getStorageLocationOptions()
|
||||
if (response.data) {
|
||||
storageLocations.value = response.data
|
||||
ensureSelectedLocationInOptions()
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取库位列表失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const setFormFromEquipment = (equipment: Equipment) => {
|
||||
form.value = {
|
||||
equipment_code: equipment.equipment_code,
|
||||
equipment_name: equipment.equipment_name,
|
||||
equipment_model: equipment.equipment_model,
|
||||
equipment_type: equipment.equipment_type,
|
||||
code_generation_mode: equipment.code_generation_mode,
|
||||
unit_price: Number(equipment.unit_price),
|
||||
total_quantity: Number(equipment.total_quantity),
|
||||
remaining_quantity: Number(equipment.remaining_quantity),
|
||||
purchase_date: equipment.purchase_date || '',
|
||||
supplier: equipment.supplier,
|
||||
description: equipment.description,
|
||||
status: equipment.status,
|
||||
storage_location_id: equipment.storage_location_id ?? undefined
|
||||
}
|
||||
editingLocation.value = equipment.storageLocation ?? null
|
||||
ensureSelectedLocationInOptions()
|
||||
}
|
||||
|
||||
const calculatedTotalValue = computed(() => {
|
||||
return (form.value.unit_price || 0) * (form.value.total_quantity || 0)
|
||||
})
|
||||
|
||||
const calculatedBorrowedValue = computed(() => {
|
||||
const borrowed = (form.value.total_quantity || 0) - (form.value.remaining_quantity || 0)
|
||||
return (form.value.unit_price || 0) * borrowed
|
||||
})
|
||||
|
||||
const calculatedAvailableValue = computed(() => {
|
||||
return (form.value.unit_price || 0) * (form.value.remaining_quantity || 0)
|
||||
})
|
||||
|
||||
const handleGenerateCode = async () => {
|
||||
if (!form.value.equipment_type) {
|
||||
alert('请先选择设备类型')
|
||||
return
|
||||
}
|
||||
|
||||
if (!form.value.storage_location_id) {
|
||||
alert('请先选择库位')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await generateEquipmentCode(
|
||||
form.value.equipment_type,
|
||||
'auto',
|
||||
Number(form.value.storage_location_id)
|
||||
)
|
||||
if (response.data) {
|
||||
form.value.equipment_code = response.data.equipment_code
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('生成设备编码失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePriceChange = () => {
|
||||
// 自动计算剩余数量
|
||||
if (form.value.total_quantity && !form.value.remaining_quantity) {
|
||||
form.value.remaining_quantity = form.value.total_quantity
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const locationId = Number(form.value.storage_location_id)
|
||||
if (!locationId) {
|
||||
alert('请选择库位')
|
||||
loading.value = false
|
||||
return
|
||||
}
|
||||
|
||||
if (isEdit.value) {
|
||||
const payload = { ...form.value, storage_location_id: locationId }
|
||||
await updateEquipment(Number(route.params.id), payload)
|
||||
} else {
|
||||
const payload = { ...form.value, storage_location_id: locationId }
|
||||
await createEquipment(payload)
|
||||
}
|
||||
router.push('/equipment')
|
||||
} catch (error: any) {
|
||||
alert(error.message || '保存失败')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleCancel = () => {
|
||||
router.push('/equipment')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadStorageLocations()
|
||||
|
||||
if (isEdit.value) {
|
||||
try {
|
||||
const response = await getEquipmentDetail(Number(route.params.id))
|
||||
if (response.data) {
|
||||
setFormFromEquipment(response.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备详情失败:', error)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
watch(
|
||||
storageLocations,
|
||||
(locations) => {
|
||||
if (!isEdit.value && !form.value.storage_location_id && locations.length > 0) {
|
||||
form.value.storage_location_id = locations[0].id
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
// 当库位和设备类型都设置后,自动生成编码
|
||||
watch(
|
||||
[() => form.value.storage_location_id, () => form.value.equipment_type, () => form.value.code_generation_mode],
|
||||
async ([locationId, equipmentType, codeMode]) => {
|
||||
if (!isEdit.value && codeMode === 'auto' && locationId && equipmentType) {
|
||||
try {
|
||||
const response = await generateEquipmentCode(equipmentType, 'auto', Number(locationId))
|
||||
if (response.data) {
|
||||
form.value.equipment_code = response.data.equipment_code
|
||||
}
|
||||
} catch (error) {
|
||||
// 静默失败,用户可以选择手动生成
|
||||
console.error('自动生成设备编码失败:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
303
frontend/src/views/equipment/EquipmentList.vue
Normal file
303
frontend/src/views/equipment/EquipmentList.vue
Normal file
@ -0,0 +1,303 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Actions -->
|
||||
<div class="flex justify-end">
|
||||
<button @click="handleAdd" class="btn-apple-primary">
|
||||
+ 新增设备
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Filters -->
|
||||
<div class="card-apple">
|
||||
<div class="grid grid-cols-1 md:grid-cols-5 gap-4">
|
||||
<input
|
||||
v-model="filters.keyword"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="搜索设备名称或编码"
|
||||
@input="handleSearch"
|
||||
/>
|
||||
<select v-model="filters.equipmentType" class="input-apple" @change="handleSearch">
|
||||
<option value="">全部类型</option>
|
||||
<option value="相机">相机</option>
|
||||
<option value="镜头">镜头</option>
|
||||
<option value="三脚架">三脚架</option>
|
||||
<option value="闪光灯">闪光灯</option>
|
||||
<option value="摄影配饰品">摄影配饰品</option>
|
||||
</select>
|
||||
<select v-model="filters.status" class="input-apple" @change="handleSearch">
|
||||
<option value="">全部状态</option>
|
||||
<option value="可用">可用</option>
|
||||
<option value="已借出">已借出</option>
|
||||
<option value="维护中">维护中</option>
|
||||
<option value="已损坏">已损坏</option>
|
||||
</select>
|
||||
<select v-model="filters.storageLocationId" class="input-apple" @change="handleSearch">
|
||||
<option value="">全部库位</option>
|
||||
<option
|
||||
v-for="location in storageLocations"
|
||||
:key="location.id"
|
||||
:value="String(location.id)"
|
||||
>
|
||||
{{ location.name }}<span v-if="location.code">({{ location.code }})</span>
|
||||
</option>
|
||||
</select>
|
||||
<button @click="handleReset" class="btn-apple-secondary">重置</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Equipment Table -->
|
||||
<div class="card-apple">
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5">
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">序号</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">设备编码</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">设备名称</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">设备型号</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">设备类型</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">库位</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">库位编码</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">单价</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">状态</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">库存</th>
|
||||
<th class="text-left py-3 px-4 text-apple-subhead text-system-label-secondary whitespace-nowrap">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="equipment in equipmentList"
|
||||
:key="equipment.id"
|
||||
class="border-b border-system-gray-6 hover:bg-system-gray-6 transition-colors"
|
||||
>
|
||||
<td class="py-3 px-4 text-apple-body whitespace-nowrap">{{ equipment.id }}</td>
|
||||
<td class="py-3 px-4 text-apple-body font-mono whitespace-nowrap">{{ equipment.equipment_code }}</td>
|
||||
<td class="py-3 px-4 text-apple-body whitespace-nowrap">{{ equipment.equipment_name }}</td>
|
||||
<td class="py-3 px-4 text-apple-subhead whitespace-nowrap">{{ equipment.equipment_model || '-' }}</td>
|
||||
<td class="py-3 px-4 text-apple-subhead whitespace-nowrap">{{ equipment.equipment_type }}</td>
|
||||
<td class="py-3 px-4 text-apple-subhead whitespace-nowrap">
|
||||
<template v-if="equipment.storageLocation">
|
||||
{{ equipment.storageLocation.name }}<span v-if="equipment.storageLocation.code">({{ equipment.storageLocation.code }})</span>
|
||||
</template>
|
||||
<template v-else>-</template>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-subhead whitespace-nowrap">
|
||||
{{ equipment.storageLocation?.code || '-' }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-body whitespace-nowrap">{{ formatCurrencyNoFraction(Number(equipment.unit_price || 0)) }}</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<span
|
||||
class="px-3 py-1 rounded-apple text-apple-footnote font-medium whitespace-nowrap"
|
||||
:class="getStatusClass(equipment.status)"
|
||||
>
|
||||
{{ equipment.status }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-body whitespace-nowrap">
|
||||
{{ equipment.remaining_quantity }} / {{ equipment.total_quantity }}
|
||||
</td>
|
||||
<td class="py-3 px-4 whitespace-nowrap">
|
||||
<div class="flex items-center space-x-3 whitespace-nowrap">
|
||||
<button
|
||||
@click="handleEdit(equipment.id)"
|
||||
class="text-apple-blue hover:underline text-apple-footnote"
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
@click="handleDelete(equipment.id)"
|
||||
class="text-apple-red hover:underline text-apple-footnote"
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
<button
|
||||
@click="handlePrintBarcode(equipment.id)"
|
||||
class="text-apple-green hover:underline text-apple-footnote"
|
||||
>
|
||||
打印条码
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Pagination -->
|
||||
<div class="flex items-center justify-between mt-4 pt-4 border-t border-system-gray-5">
|
||||
<p class="text-apple-subhead text-system-label-secondary">
|
||||
共 {{ total }} 条记录
|
||||
</p>
|
||||
<div class="flex items-center space-x-2">
|
||||
<button
|
||||
@click="handlePrevPage"
|
||||
:disabled="currentPage === 1"
|
||||
class="btn-apple-secondary"
|
||||
>
|
||||
上一页
|
||||
</button>
|
||||
<span class="text-apple-body">{{ currentPage }} / {{ totalPages }}</span>
|
||||
<button
|
||||
@click="handleNextPage"
|
||||
:disabled="currentPage === totalPages"
|
||||
class="btn-apple-secondary"
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Barcode Print Modal -->
|
||||
<div v-if="showBarcodePrint && selectedEquipmentId" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
|
||||
<div class="bg-system-background-primary rounded-apple-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-apple-title">打印条码</h2>
|
||||
<button @click="showBarcodePrint = false" class="text-system-label-secondary hover:text-system-label-primary">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<BarcodePrint :equipment-ids="[selectedEquipmentId]" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { getEquipmentList, deleteEquipment } from '@/api/equipment'
|
||||
import { getStorageLocationOptions } from '@/api/storageLocation'
|
||||
import type { Equipment, StorageLocation } from '@/types'
|
||||
import { formatCurrencyNoFraction } from '@/utils/format'
|
||||
import BarcodePrint from '@/components/BarcodePrint.vue'
|
||||
|
||||
const router = useRouter()
|
||||
|
||||
const equipmentList = ref<Equipment[]>([])
|
||||
const total = ref(0)
|
||||
const currentPage = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const loading = ref(false)
|
||||
const storageLocations = ref<StorageLocation[]>([])
|
||||
|
||||
const filters = ref({
|
||||
keyword: '',
|
||||
equipmentType: '',
|
||||
status: '',
|
||||
storageLocationId: ''
|
||||
})
|
||||
|
||||
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
|
||||
|
||||
const fetchEquipmentList = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await getEquipmentList({
|
||||
page: currentPage.value,
|
||||
pageSize: pageSize.value,
|
||||
equipmentType: filters.value.equipmentType || undefined,
|
||||
status: filters.value.status || undefined,
|
||||
keyword: filters.value.keyword || undefined,
|
||||
storageLocationId: filters.value.storageLocationId
|
||||
? Number(filters.value.storageLocationId)
|
||||
: undefined
|
||||
})
|
||||
if (response.data) {
|
||||
equipmentList.value = response.data.list
|
||||
total.value = response.data.total
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取设备列表失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearch = () => {
|
||||
currentPage.value = 1
|
||||
fetchEquipmentList()
|
||||
}
|
||||
|
||||
const handleReset = () => {
|
||||
filters.value = {
|
||||
keyword: '',
|
||||
equipmentType: '',
|
||||
status: '',
|
||||
storageLocationId: ''
|
||||
}
|
||||
handleSearch()
|
||||
}
|
||||
|
||||
const handleAdd = () => {
|
||||
router.push('/equipment/add')
|
||||
}
|
||||
|
||||
const handleEdit = (id: number) => {
|
||||
router.push(`/equipment/edit/${id}`)
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (confirm('确定要删除这个设备吗?')) {
|
||||
try {
|
||||
const response = await deleteEquipment(id)
|
||||
alert(response.message || '删除成功')
|
||||
fetchEquipmentList()
|
||||
} catch (error: any) {
|
||||
const message = error?.message || '删除设备失败'
|
||||
alert(message)
|
||||
console.error('删除设备失败:', error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handlePrevPage = () => {
|
||||
if (currentPage.value > 1) {
|
||||
currentPage.value--
|
||||
fetchEquipmentList()
|
||||
}
|
||||
}
|
||||
|
||||
const handleNextPage = () => {
|
||||
if (currentPage.value < totalPages.value) {
|
||||
currentPage.value++
|
||||
fetchEquipmentList()
|
||||
}
|
||||
}
|
||||
|
||||
const showBarcodePrint = ref(false)
|
||||
const selectedEquipmentId = ref<number | null>(null)
|
||||
|
||||
const handlePrintBarcode = async (id: number) => {
|
||||
selectedEquipmentId.value = id
|
||||
showBarcodePrint.value = true
|
||||
}
|
||||
|
||||
const getStatusClass = (status: string) => {
|
||||
const classes: Record<string, string> = {
|
||||
'可用': 'bg-apple-green text-white',
|
||||
'已借出': 'bg-apple-orange text-white',
|
||||
'维护中': 'bg-apple-yellow text-white',
|
||||
'已损坏': 'bg-apple-red text-white'
|
||||
}
|
||||
return classes[status] || 'bg-system-gray-5 text-system-label-secondary'
|
||||
}
|
||||
|
||||
const fetchStorageLocations = async () => {
|
||||
try {
|
||||
const response = await getStorageLocationOptions()
|
||||
if (response.data) {
|
||||
storageLocations.value = response.data
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取库位列表失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchStorageLocations()
|
||||
fetchEquipmentList()
|
||||
})
|
||||
</script>
|
||||
|
||||
73
frontend/src/views/settings/Settings.vue
Normal file
73
frontend/src/views/settings/Settings.vue
Normal file
@ -0,0 +1,73 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<div class="flex flex-wrap items-center gap-3">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
:key="tab.key"
|
||||
class="rounded-apple px-4 py-2 text-apple-body transition-colors bg-system-gray-6 text-system-label-secondary hover:bg-system-gray-5 tab-button"
|
||||
:class="activeTab === tab.key ? 'tab-button--active' : ''"
|
||||
@click="switchTab(tab.key)"
|
||||
>
|
||||
{{ tab.label }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<SiteSettings v-if="activeTab === 'site'" />
|
||||
<UserManagement v-else-if="activeTab === 'users'" />
|
||||
<PersonManagement v-else-if="activeTab === 'persons'" />
|
||||
<StorageLocationManagement v-else />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import SiteSettings from './components/SiteSettings.vue'
|
||||
import UserManagement from './components/UserManagement.vue'
|
||||
import PersonManagement from './components/PersonManagement.vue'
|
||||
import StorageLocationManagement from './components/StorageLocationManagement.vue'
|
||||
|
||||
type TabKey = 'site' | 'users' | 'persons' | 'locations'
|
||||
|
||||
const tabs: Array<{ key: TabKey; label: string }> = [
|
||||
{ key: 'site', label: '站点信息' },
|
||||
{ key: 'users', label: '用户管理' },
|
||||
{ key: 'persons', label: '使用者信息' },
|
||||
{ key: 'locations', label: '库位管理' }
|
||||
]
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const initialTab = (route.query.tab as TabKey) || 'site'
|
||||
const activeTab = ref<TabKey>(tabs.some((t) => t.key === initialTab) ? initialTab : 'site')
|
||||
|
||||
const switchTab = (tab: TabKey) => {
|
||||
activeTab.value = tab
|
||||
}
|
||||
|
||||
watch(
|
||||
() => activeTab.value,
|
||||
(tab) => {
|
||||
router.replace({ query: { ...route.query, tab } })
|
||||
}
|
||||
)
|
||||
|
||||
watch(
|
||||
() => route.query.tab,
|
||||
(tab) => {
|
||||
if (!tab) return
|
||||
if (tabs.some((t) => t.key === tab)) {
|
||||
activeTab.value = tab as TabKey
|
||||
}
|
||||
}
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.tab-button--active {
|
||||
background-color: var(--theme-primary) !important;
|
||||
color: #ffffff !important;
|
||||
box-shadow: 0 6px 18px var(--theme-primary-ring);
|
||||
}
|
||||
</style>
|
||||
367
frontend/src/views/settings/components/PersonManagement.vue
Normal file
367
frontend/src/views/settings/components/PersonManagement.vue
Normal file
@ -0,0 +1,367 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<section class="card-apple">
|
||||
<div class="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
|
||||
<div class="flex-1">
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">搜索使用者</label>
|
||||
<input
|
||||
v-model.trim="keyword"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="输入花名 / 姓名 / 证件编号"
|
||||
@keyup.enter="fetchPersons"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex space-x-3">
|
||||
<select v-model="statusFilter" class="input-apple">
|
||||
<option value="">全部状态</option>
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">禁用</option>
|
||||
</select>
|
||||
<button class="btn-apple-secondary" :disabled="listLoading" @click="fetchPersons">
|
||||
查询
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">新增使用者</h2>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">花名 *</label>
|
||||
<input v-model.trim="newPerson.nickname" class="input-apple" type="text" placeholder="花名 / 昵称" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">真实姓名 *</label>
|
||||
<input v-model.trim="newPerson.real_name" class="input-apple" type="text" placeholder="真实姓名" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">证件编号</label>
|
||||
<input
|
||||
v-model.trim="newPerson.id_number"
|
||||
class="input-apple"
|
||||
type="text"
|
||||
placeholder="身份证 / 工号(可选)"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">部门</label>
|
||||
<input v-model.trim="newPerson.department" class="input-apple" type="text" placeholder="部门(可选)" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">职位</label>
|
||||
<input v-model.trim="newPerson.position" class="input-apple" type="text" placeholder="职位(可选)" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">手机号</label>
|
||||
<input v-model.trim="newPerson.phone" class="input-apple" type="tel" placeholder="手机号(可选)" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">邮箱</label>
|
||||
<input v-model.trim="newPerson.email" class="input-apple" type="email" placeholder="邮箱(可选)" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">状态</label>
|
||||
<select v-model="newPerson.status" class="input-apple">
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">备注</label>
|
||||
<textarea
|
||||
v-model.trim="newPerson.remarks"
|
||||
class="input-apple"
|
||||
rows="3"
|
||||
placeholder="备注信息(可选)"
|
||||
></textarea>
|
||||
</div>
|
||||
<button class="btn-apple-primary mt-4" :disabled="createLoading || !canCreate" @click="handleCreatePerson">
|
||||
{{ createLoading ? '提交中...' : '新增使用者' }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-apple-title">使用者列表</h2>
|
||||
<button class="btn-apple-secondary" :disabled="listLoading" @click="fetchPersons">刷新</button>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5 text-left text-apple-footnote text-system-label-tertiary">
|
||||
<th class="py-3 px-4">花名</th>
|
||||
<th class="py-3 px-4">真实姓名</th>
|
||||
<th class="py-3 px-4">证件编号</th>
|
||||
<th class="py-3 px-4">部门 / 职位</th>
|
||||
<th class="py-3 px-4">联系方式</th>
|
||||
<th class="py-3 px-4">状态</th>
|
||||
<th class="py-3 px-4 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="person in persons"
|
||||
:key="person.id"
|
||||
class="border-b border-system-gray-6 text-apple-body text-system-label-primary"
|
||||
>
|
||||
<td class="py-3 px-4">{{ person.nickname }}</td>
|
||||
<td class="py-3 px-4">{{ person.real_name }}</td>
|
||||
<td class="py-3 px-4 font-mono text-apple-footnote text-system-label-secondary">
|
||||
{{ person.id_number || '-' }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-footnote text-system-label-secondary">
|
||||
<p>{{ person.department || '-' }}</p>
|
||||
<p v-if="person.position">{{ person.position }}</p>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-footnote text-system-label-secondary">
|
||||
<p v-if="person.phone">📞 {{ person.phone }}</p>
|
||||
<p v-if="person.email">📧 {{ person.email }}</p>
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="rounded-apple px-3 py-1 text-apple-footnote"
|
||||
:class="person.status === 'active' ? 'bg-apple-green/10 text-apple-green' : 'bg-system-gray-6 text-system-label-tertiary'"
|
||||
>
|
||||
{{ person.status === 'active' ? '启用' : '禁用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right space-x-2">
|
||||
<button class="text-apple-blue hover:underline" @click="openEdit(person)">编辑</button>
|
||||
<button class="text-apple-red hover:underline" @click="toggleStatus(person)">
|
||||
{{ person.status === 'active' ? '禁用' : '启用' }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-if="!listLoading && persons.length === 0" class="mt-6 text-center text-system-label-tertiary">
|
||||
暂无使用者数据。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="editingPerson"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm px-4"
|
||||
>
|
||||
<div class="w-full max-w-2xl rounded-apple bg-system-background-primary p-6 shadow-apple-xl">
|
||||
<h3 class="text-apple-title mb-4">编辑使用者</h3>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">花名</label>
|
||||
<input v-model.trim="editDraft.nickname" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">真实姓名</label>
|
||||
<input v-model.trim="editDraft.real_name" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">证件编号</label>
|
||||
<input v-model.trim="editDraft.id_number" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">部门</label>
|
||||
<input v-model.trim="editDraft.department" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">职位</label>
|
||||
<input v-model.trim="editDraft.position" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">手机号</label>
|
||||
<input v-model.trim="editDraft.phone" class="input-apple" type="tel" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">邮箱</label>
|
||||
<input v-model.trim="editDraft.email" class="input-apple" type="email" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">状态</label>
|
||||
<select v-model="editDraft.status" class="input-apple">
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2 mt-4">备注</label>
|
||||
<textarea v-model.trim="editDraft.remarks" class="input-apple" rows="3"></textarea>
|
||||
</div>
|
||||
<div class="mt-6 flex justify-end space-x-3">
|
||||
<button class="btn-apple-secondary" @click="closeEdit">取消</button>
|
||||
<button class="btn-apple-primary" :disabled="updateLoading" @click="submitEdit">
|
||||
{{ updateLoading ? '保存中...' : '保存修改' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import type { Person } from '@/types'
|
||||
import {
|
||||
createPerson,
|
||||
getPersonList,
|
||||
updatePerson,
|
||||
updatePersonStatus
|
||||
} from '@/api/person'
|
||||
|
||||
const persons = ref<Person[]>([])
|
||||
const listLoading = ref(false)
|
||||
const createLoading = ref(false)
|
||||
const updateLoading = ref(false)
|
||||
const keyword = ref('')
|
||||
const statusFilter = ref('')
|
||||
|
||||
const newPerson = reactive({
|
||||
nickname: '',
|
||||
real_name: '',
|
||||
id_number: '',
|
||||
department: '',
|
||||
position: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
status: 'active',
|
||||
remarks: ''
|
||||
})
|
||||
|
||||
const editingPerson = ref<Person | null>(null)
|
||||
const editDraft = reactive({
|
||||
id: 0,
|
||||
nickname: '',
|
||||
real_name: '',
|
||||
id_number: '',
|
||||
department: '',
|
||||
position: '',
|
||||
phone: '',
|
||||
email: '',
|
||||
status: 'active' as 'active' | 'inactive',
|
||||
remarks: ''
|
||||
})
|
||||
|
||||
const canCreate = computed(() => {
|
||||
return newPerson.nickname.trim() && newPerson.real_name.trim()
|
||||
})
|
||||
|
||||
const fetchPersons = async () => {
|
||||
listLoading.value = true
|
||||
try {
|
||||
const response = await getPersonList({
|
||||
page: 1,
|
||||
pageSize: 100,
|
||||
keyword: keyword.value || undefined,
|
||||
status: statusFilter.value || undefined
|
||||
})
|
||||
if (response.data) {
|
||||
persons.value = response.data.list
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取使用者列表失败', error)
|
||||
} finally {
|
||||
listLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const resetNewForm = () => {
|
||||
newPerson.nickname = ''
|
||||
newPerson.real_name = ''
|
||||
newPerson.id_number = ''
|
||||
newPerson.department = ''
|
||||
newPerson.position = ''
|
||||
newPerson.phone = ''
|
||||
newPerson.email = ''
|
||||
newPerson.status = 'active'
|
||||
newPerson.remarks = ''
|
||||
}
|
||||
|
||||
const handleCreatePerson = async () => {
|
||||
if (!canCreate.value) return
|
||||
try {
|
||||
createLoading.value = true
|
||||
await createPerson({
|
||||
nickname: newPerson.nickname,
|
||||
real_name: newPerson.real_name,
|
||||
id_number: newPerson.id_number || undefined,
|
||||
department: newPerson.department || undefined,
|
||||
position: newPerson.position || undefined,
|
||||
phone: newPerson.phone || undefined,
|
||||
email: newPerson.email || undefined,
|
||||
status: newPerson.status,
|
||||
remarks: newPerson.remarks || undefined
|
||||
})
|
||||
alert('使用者创建成功')
|
||||
resetNewForm()
|
||||
fetchPersons()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '创建使用者失败')
|
||||
} finally {
|
||||
createLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openEdit = (person: Person) => {
|
||||
editingPerson.value = person
|
||||
editDraft.id = person.id
|
||||
editDraft.nickname = person.nickname
|
||||
editDraft.real_name = person.real_name
|
||||
editDraft.id_number = person.id_number || ''
|
||||
editDraft.department = person.department || ''
|
||||
editDraft.position = person.position || ''
|
||||
editDraft.phone = person.phone || ''
|
||||
editDraft.email = person.email || ''
|
||||
editDraft.status = person.status
|
||||
editDraft.remarks = person.remarks || ''
|
||||
}
|
||||
|
||||
const closeEdit = () => {
|
||||
editingPerson.value = null
|
||||
}
|
||||
|
||||
const submitEdit = async () => {
|
||||
if (!editingPerson.value) return
|
||||
try {
|
||||
updateLoading.value = true
|
||||
await updatePerson(editingPerson.value.id, {
|
||||
nickname: editDraft.nickname,
|
||||
real_name: editDraft.real_name,
|
||||
id_number: editDraft.id_number || undefined,
|
||||
department: editDraft.department || undefined,
|
||||
position: editDraft.position || undefined,
|
||||
phone: editDraft.phone || undefined,
|
||||
email: editDraft.email || undefined,
|
||||
status: editDraft.status,
|
||||
remarks: editDraft.remarks || undefined
|
||||
})
|
||||
alert('使用者信息已更新')
|
||||
closeEdit()
|
||||
fetchPersons()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '更新失败')
|
||||
} finally {
|
||||
updateLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleStatus = async (person: Person) => {
|
||||
const targetStatus = person.status === 'active' ? 'inactive' : 'active'
|
||||
if (!confirm(`确定要${targetStatus === 'active' ? '启用' : '禁用'}该使用者吗?`)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await updatePersonStatus(person.id, targetStatus)
|
||||
fetchPersons()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '更新状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchPersons()
|
||||
})
|
||||
</script>
|
||||
|
||||
135
frontend/src/views/settings/components/SiteSettings.vue
Normal file
135
frontend/src/views/settings/components/SiteSettings.vue
Normal file
@ -0,0 +1,135 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<section class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">站点基础信息</h2>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">网站名称 *</label>
|
||||
<input
|
||||
v-model.trim="form.siteName"
|
||||
type="text"
|
||||
class="input-apple"
|
||||
placeholder="请输入网站名称"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">主题主色</label>
|
||||
<input
|
||||
v-model="form.themeColor"
|
||||
type="color"
|
||||
class="h-10 w-20 rounded-apple border border-system-gray-5 bg-transparent"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="rounded-apple border border-dashed border-system-gray-5 bg-system-gray-6/40 p-4">
|
||||
<p class="text-apple-footnote text-system-label-tertiary">
|
||||
网站 Logo 与浏览器图标已固定为系统默认标识,不支持自定义上传。
|
||||
</p>
|
||||
<div class="mt-4 flex items-center space-x-3">
|
||||
<div class="flex h-16 w-16 items-center justify-center overflow-hidden rounded-apple bg-white shadow-apple">
|
||||
<img :src="logoUrl" alt="默认 Logo" class="h-full w-full object-cover" />
|
||||
</div>
|
||||
<div class="text-apple-footnote text-system-label-secondary">
|
||||
<p>默认地址:</p>
|
||||
<p class="truncate">{{ logoUrl }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pt-4">
|
||||
<button
|
||||
class="btn-apple-primary"
|
||||
:disabled="saving || !form.siteName"
|
||||
@click="handleSubmit"
|
||||
>
|
||||
{{ saving ? '保存中...' : '保存配置' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<h3 class="text-apple-title mb-4">实时预览</h3>
|
||||
<div class="grid gap-6 md:grid-cols-2">
|
||||
<div class="rounded-apple border border-system-gray-5 bg-system-background-primary p-6">
|
||||
<p class="text-apple-footnote text-system-label-tertiary mb-2">导航栏预览</p>
|
||||
<div class="flex items-center space-x-3">
|
||||
<div class="flex h-10 w-10 items-center justify-center overflow-hidden rounded-apple bg-system-gray-6">
|
||||
<img :src="logoUrl" alt="logo" class="h-full w-full object-cover" />
|
||||
</div>
|
||||
<span class="text-apple-title text-system-label-primary">{{ form.siteName }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-apple border border-system-gray-5 bg-system-background-primary p-6">
|
||||
<p class="text-apple-footnote text-system-label-tertiary mb-2">登录页预览</p>
|
||||
<div class="rounded-apple border border-system-gray-5 bg-white/80 p-6 shadow-apple backdrop-blur-sm">
|
||||
<div class="mx-auto flex h-12 w-12 items-center justify-center rounded-apple bg-apple-blue/10">
|
||||
<img :src="logoUrl" alt="logo" class="h-full w-full rounded-apple object-cover" />
|
||||
</div>
|
||||
<p class="mt-4 text-center text-apple-title">{{ form.siteName }}</p>
|
||||
<p class="mt-2 text-center text-apple-footnote text-system-label-tertiary">
|
||||
使用者体验将同步更新。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useSiteStore } from '@/stores/site'
|
||||
import { updateSiteConfig } from '@/api/settings'
|
||||
|
||||
const siteStore = useSiteStore()
|
||||
const saving = ref(false)
|
||||
|
||||
const form = ref({
|
||||
siteName: siteStore.siteName,
|
||||
themeColor: siteStore.themeColor
|
||||
})
|
||||
|
||||
const logoUrl = computed(() => siteStore.logoUrl)
|
||||
|
||||
const syncFromStore = () => {
|
||||
form.value.siteName = siteStore.siteName
|
||||
form.value.themeColor = siteStore.themeColor
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await siteStore.fetchSiteConfig()
|
||||
syncFromStore()
|
||||
})
|
||||
|
||||
watch(
|
||||
() => [siteStore.siteName, siteStore.themeColor],
|
||||
() => syncFromStore()
|
||||
)
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!form.value.siteName) {
|
||||
alert('网站名称不能为空')
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
saving.value = true
|
||||
const response = await updateSiteConfig({
|
||||
site_name: form.value.siteName,
|
||||
theme_color: form.value.themeColor
|
||||
})
|
||||
if (response.data) {
|
||||
siteStore.setSiteConfig(response.data)
|
||||
alert('站点配置已更新')
|
||||
}
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '保存配置失败')
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@ -0,0 +1,307 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<section class="card-apple">
|
||||
<div class="grid gap-4 md:grid-cols-3 md:items-end">
|
||||
<div class="md:col-span-2">
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">搜索库位</label>
|
||||
<input
|
||||
v-model.trim="filters.keyword"
|
||||
class="input-apple"
|
||||
type="text"
|
||||
placeholder="输入库位名称 / 编码 / 备注关键字"
|
||||
@keyup.enter="fetchLocations"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<select v-model="filters.status" class="input-apple">
|
||||
<option value="">全部状态</option>
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">停用</option>
|
||||
</select>
|
||||
<button class="btn-apple-secondary" :disabled="loading" @click="fetchLocations">查询</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">新增库位</h2>
|
||||
<div class="grid gap-4 md:grid-cols-3">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库位名称 *</label>
|
||||
<input
|
||||
v-model.trim="createForm.name"
|
||||
class="input-apple"
|
||||
type="text"
|
||||
placeholder="例如:A区-01柜"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库位编码</label>
|
||||
<input
|
||||
v-model.trim="createForm.code"
|
||||
class="input-apple"
|
||||
type="text"
|
||||
placeholder="可选,如:A-01"
|
||||
/>
|
||||
</div>
|
||||
<div class="md:col-span-3">
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">描述</label>
|
||||
<textarea
|
||||
v-model.trim="createForm.description"
|
||||
class="input-apple"
|
||||
rows="2"
|
||||
placeholder="可填写放置区域、注意事项等"
|
||||
></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="btn-apple-primary mt-4"
|
||||
:disabled="createLoading || !canCreate"
|
||||
@click="handleCreate"
|
||||
>
|
||||
{{ createLoading ? '提交中...' : '新增库位' }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-apple-title">库位列表</h2>
|
||||
<button class="btn-apple-secondary" :disabled="loading" @click="fetchLocations">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5 text-left text-apple-footnote text-system-label-tertiary">
|
||||
<th class="py-3 px-4">名称</th>
|
||||
<th class="py-3 px-4">编码</th>
|
||||
<th class="py-3 px-4">状态</th>
|
||||
<th class="py-3 px-4">当前设备数量</th>
|
||||
<th class="py-3 px-4">备注</th>
|
||||
<th class="py-3 px-4 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="location in locations"
|
||||
:key="location.id"
|
||||
class="border-b border-system-gray-6 text-system-label-primary text-apple-body"
|
||||
>
|
||||
<td class="py-3 px-4">
|
||||
<div class="font-medium">{{ location.name }}</div>
|
||||
<div class="text-apple-footnote text-system-label-tertiary">
|
||||
更新于 {{ formatDateTime(location.updated_at) }}
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-3 px-4 font-mono text-apple-footnote text-system-label-secondary">
|
||||
{{ location.code || '-' }}
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="rounded-apple px-3 py-1 text-apple-footnote"
|
||||
:class="location.status === 'active' ? 'bg-apple-green/15 text-apple-green' : 'bg-system-gray-6 text-system-label-tertiary'"
|
||||
>
|
||||
{{ location.status === 'active' ? '启用' : '停用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-body">
|
||||
{{ location._count?.equipments ?? 0 }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-footnote text-system-label-secondary max-w-xs">
|
||||
<p class="line-clamp-2">
|
||||
{{ location.description || '—' }}
|
||||
</p>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right space-x-3">
|
||||
<button class="text-apple-blue hover:underline" @click="openEdit(location)">
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
class="text-apple-red hover:underline"
|
||||
@click="toggleStatus(location)"
|
||||
>
|
||||
{{ location.status === 'active' ? '停用' : '启用' }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-if="!loading && locations.length === 0" class="mt-6 text-center text-system-label-tertiary">
|
||||
暂无库位数据。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="editingLocation"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm px-4"
|
||||
>
|
||||
<div class="w-full max-w-xl rounded-apple bg-system-background-primary p-6 shadow-apple-xl">
|
||||
<h3 class="text-apple-title mb-4">编辑库位</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库位名称 *</label>
|
||||
<input v-model.trim="editDraft.name" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">库位编码</label>
|
||||
<input v-model.trim="editDraft.code" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">状态</label>
|
||||
<select v-model="editDraft.status" class="input-apple">
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">停用</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">描述</label>
|
||||
<textarea v-model.trim="editDraft.description" class="input-apple" rows="3"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button class="btn-apple-secondary" @click="closeEdit">取消</button>
|
||||
<button class="btn-apple-primary" :disabled="updateLoading" @click="submitEdit">
|
||||
{{ updateLoading ? '保存中...' : '保存修改' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { reactive, ref, onMounted, computed } from 'vue'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
import {
|
||||
getStorageLocationList,
|
||||
createStorageLocation,
|
||||
updateStorageLocation,
|
||||
updateStorageLocationStatus
|
||||
} from '@/api/storageLocation'
|
||||
import type { StorageLocation } from '@/types'
|
||||
|
||||
const loading = ref(false)
|
||||
const createLoading = ref(false)
|
||||
const updateLoading = ref(false)
|
||||
|
||||
const filters = reactive({
|
||||
keyword: '',
|
||||
status: ''
|
||||
})
|
||||
|
||||
const pagination = reactive({
|
||||
page: 1,
|
||||
pageSize: 10
|
||||
})
|
||||
|
||||
const locations = ref<StorageLocation[]>([])
|
||||
|
||||
const createForm = reactive({
|
||||
name: '',
|
||||
code: '',
|
||||
description: ''
|
||||
})
|
||||
|
||||
const editingLocation = ref<StorageLocation | null>(null)
|
||||
const editDraft = reactive({
|
||||
id: 0,
|
||||
name: '',
|
||||
code: '',
|
||||
description: '',
|
||||
status: 'active' as 'active' | 'inactive'
|
||||
})
|
||||
|
||||
const canCreate = computed(() => createForm.name.trim().length > 0)
|
||||
|
||||
const resetCreateForm = () => {
|
||||
createForm.name = ''
|
||||
createForm.code = ''
|
||||
createForm.description = ''
|
||||
}
|
||||
|
||||
const fetchLocations = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await getStorageLocationList({
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
keyword: filters.keyword || undefined,
|
||||
status: filters.status || undefined
|
||||
})
|
||||
if (response.data) {
|
||||
locations.value = response.data.list
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取库位数据失败:', error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreate = async () => {
|
||||
if (!canCreate.value) return
|
||||
createLoading.value = true
|
||||
try {
|
||||
await createStorageLocation({
|
||||
name: createForm.name,
|
||||
code: createForm.code || undefined,
|
||||
description: createForm.description || undefined
|
||||
})
|
||||
resetCreateForm()
|
||||
await fetchLocations()
|
||||
} catch (error: any) {
|
||||
alert(error.message || '新增库位失败')
|
||||
} finally {
|
||||
createLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openEdit = (location: StorageLocation) => {
|
||||
editingLocation.value = location
|
||||
editDraft.id = location.id
|
||||
editDraft.name = location.name
|
||||
editDraft.code = location.code || ''
|
||||
editDraft.description = location.description || ''
|
||||
editDraft.status = location.status
|
||||
}
|
||||
|
||||
const closeEdit = () => {
|
||||
editingLocation.value = null
|
||||
}
|
||||
|
||||
const submitEdit = async () => {
|
||||
if (!editingLocation.value) return
|
||||
updateLoading.value = true
|
||||
try {
|
||||
await updateStorageLocation(editDraft.id, {
|
||||
name: editDraft.name,
|
||||
code: editDraft.code || undefined,
|
||||
description: editDraft.description || undefined,
|
||||
status: editDraft.status
|
||||
})
|
||||
editingLocation.value = null
|
||||
await fetchLocations()
|
||||
} catch (error: any) {
|
||||
alert(error.message || '更新库位失败')
|
||||
} finally {
|
||||
updateLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleStatus = async (location: StorageLocation) => {
|
||||
try {
|
||||
const targetStatus = location.status === 'active' ? 'inactive' : 'active'
|
||||
await updateStorageLocationStatus(location.id, targetStatus)
|
||||
await fetchLocations()
|
||||
} catch (error: any) {
|
||||
alert(error.message || '更新状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchLocations()
|
||||
})
|
||||
</script>
|
||||
|
||||
313
frontend/src/views/settings/components/UserManagement.vue
Normal file
313
frontend/src/views/settings/components/UserManagement.vue
Normal file
@ -0,0 +1,313 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<section class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">新增用户</h2>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">用户名 *</label>
|
||||
<input v-model.trim="newUser.username" class="input-apple" type="text" placeholder="登录用户名" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">姓名 *</label>
|
||||
<input v-model.trim="newUser.name" class="input-apple" type="text" placeholder="显示姓名" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">密码 *</label>
|
||||
<input v-model="newUser.password" class="input-apple" type="password" placeholder="初始密码" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">角色 *</label>
|
||||
<select v-model="newUser.role" class="input-apple">
|
||||
<option value="user">普通用户</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">邮箱</label>
|
||||
<input v-model.trim="newUser.email" class="input-apple" type="email" placeholder="邮箱(可选)" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">手机号</label>
|
||||
<input v-model.trim="newUser.phone" class="input-apple" type="tel" placeholder="手机号(可选)" />
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
class="btn-apple-primary mt-4"
|
||||
:disabled="createLoading || !canCreate"
|
||||
@click="handleCreateUser"
|
||||
>
|
||||
{{ createLoading ? '创建中...' : '创建用户' }}
|
||||
</button>
|
||||
</section>
|
||||
|
||||
<section class="card-apple">
|
||||
<div class="flex items-center justify-between mb-4">
|
||||
<h2 class="text-apple-title">用户列表</h2>
|
||||
<button class="btn-apple-secondary" :disabled="listLoading" @click="fetchUsers">
|
||||
刷新
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full">
|
||||
<thead>
|
||||
<tr class="border-b border-system-gray-5 text-left text-apple-footnote text-system-label-tertiary">
|
||||
<th class="py-3 px-4">用户名</th>
|
||||
<th class="py-3 px-4">姓名</th>
|
||||
<th class="py-3 px-4">角色</th>
|
||||
<th class="py-3 px-4">状态</th>
|
||||
<th class="py-3 px-4">联系方式</th>
|
||||
<th class="py-3 px-4">最近登录</th>
|
||||
<th class="py-3 px-4 text-right">操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="user in users"
|
||||
:key="user.id"
|
||||
class="border-b border-system-gray-6 text-apple-body text-system-label-primary"
|
||||
>
|
||||
<td class="py-3 px-4 font-mono">{{ user.username }}</td>
|
||||
<td class="py-3 px-4">{{ user.name }}</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="rounded-apple px-3 py-1 text-apple-footnote"
|
||||
:class="user.role === 'admin' ? 'bg-apple-orange/10 text-apple-orange' : 'bg-system-gray-6 text-system-label-secondary'"
|
||||
>
|
||||
{{ user.role === 'admin' ? '管理员' : '普通用户' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<span
|
||||
class="rounded-apple px-3 py-1 text-apple-footnote"
|
||||
:class="user.status === 'active' ? 'bg-apple-green/10 text-apple-green' : 'bg-system-gray-6 text-system-label-tertiary'"
|
||||
>
|
||||
{{ user.status === 'active' ? '启用' : '禁用' }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="py-3 px-4">
|
||||
<div class="text-apple-footnote text-system-label-secondary space-y-1">
|
||||
<p v-if="user.email">📧 {{ user.email }}</p>
|
||||
<p v-if="user.phone">📞 {{ user.phone }}</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="py-3 px-4 text-apple-footnote text-system-label-secondary">
|
||||
{{ user.last_login_at ? formatDateTime(user.last_login_at) : '-' }}
|
||||
</td>
|
||||
<td class="py-3 px-4 text-right space-x-2">
|
||||
<button class="text-apple-blue hover:underline" @click="openEdit(user)">编辑</button>
|
||||
<button class="text-apple-orange hover:underline" @click="handleResetPassword(user)">
|
||||
重置密码
|
||||
</button>
|
||||
<button class="text-apple-red hover:underline" @click="toggleStatus(user)">
|
||||
{{ user.status === 'active' ? '禁用' : '启用' }}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p v-if="!listLoading && users.length === 0" class="mt-6 text-center text-system-label-tertiary">
|
||||
暂无用户数据。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="editingUser"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/30 backdrop-blur-sm px-4"
|
||||
>
|
||||
<div class="w-full max-w-xl rounded-apple bg-system-background-primary p-6 shadow-apple-xl">
|
||||
<h3 class="text-apple-title mb-4">编辑用户</h3>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">姓名</label>
|
||||
<input v-model.trim="editingUserDraft.name" class="input-apple" type="text" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">角色</label>
|
||||
<select v-model="editingUserDraft.role" class="input-apple">
|
||||
<option value="user">普通用户</option>
|
||||
<option value="admin">管理员</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="grid gap-4 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">邮箱</label>
|
||||
<input v-model.trim="editingUserDraft.email" class="input-apple" type="email" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">手机号</label>
|
||||
<input v-model.trim="editingUserDraft.phone" class="input-apple" type="tel" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-apple-body text-system-label-primary mb-2">状态</label>
|
||||
<select v-model="editingUserDraft.status" class="input-apple">
|
||||
<option value="active">启用</option>
|
||||
<option value="inactive">禁用</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-6 flex justify-end space-x-3">
|
||||
<button class="btn-apple-secondary" @click="closeEdit">取消</button>
|
||||
<button class="btn-apple-primary" :disabled="updateLoading" @click="submitEdit">
|
||||
{{ updateLoading ? '保存中...' : '保存修改' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import type { User } from '@/types'
|
||||
import {
|
||||
createUser,
|
||||
getUserList,
|
||||
resetUserPassword,
|
||||
updateUser,
|
||||
updateUserStatus
|
||||
} from '@/api/users'
|
||||
import { formatDateTime } from '@/utils/format'
|
||||
|
||||
const users = ref<(User & { status: 'active' | 'inactive'; last_login_at?: string | null })[]>([])
|
||||
const listLoading = ref(false)
|
||||
const createLoading = ref(false)
|
||||
const updateLoading = ref(false)
|
||||
|
||||
const newUser = reactive({
|
||||
username: '',
|
||||
name: '',
|
||||
password: '',
|
||||
role: 'user',
|
||||
email: '',
|
||||
phone: ''
|
||||
})
|
||||
|
||||
const editingUser = ref<User | null>(null)
|
||||
const editingUserDraft = reactive({
|
||||
id: '',
|
||||
name: '',
|
||||
role: 'user',
|
||||
email: '',
|
||||
phone: '',
|
||||
status: 'active'
|
||||
})
|
||||
|
||||
const canCreate = computed(() => {
|
||||
return newUser.username.trim() && newUser.name.trim() && newUser.password.length >= 6
|
||||
})
|
||||
|
||||
const fetchUsers = async () => {
|
||||
listLoading.value = true
|
||||
try {
|
||||
const response = await getUserList({ page: 1, pageSize: 100 })
|
||||
if (response.data) {
|
||||
users.value = response.data.list as any
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取用户列表失败', error)
|
||||
} finally {
|
||||
listLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const resetNewForm = () => {
|
||||
newUser.username = ''
|
||||
newUser.name = ''
|
||||
newUser.password = ''
|
||||
newUser.role = 'user'
|
||||
newUser.email = ''
|
||||
newUser.phone = ''
|
||||
}
|
||||
|
||||
const handleCreateUser = async () => {
|
||||
if (!canCreate.value) return
|
||||
try {
|
||||
createLoading.value = true
|
||||
await createUser({
|
||||
username: newUser.username,
|
||||
name: newUser.name,
|
||||
password: newUser.password,
|
||||
role: newUser.role,
|
||||
email: newUser.email || undefined,
|
||||
phone: newUser.phone || undefined
|
||||
})
|
||||
alert('用户创建成功')
|
||||
resetNewForm()
|
||||
fetchUsers()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '创建用户失败')
|
||||
} finally {
|
||||
createLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openEdit = (user: User & { status: 'active' | 'inactive' }) => {
|
||||
editingUser.value = user
|
||||
editingUserDraft.id = String(user.id)
|
||||
editingUserDraft.name = user.name
|
||||
editingUserDraft.role = user.role
|
||||
editingUserDraft.email = user.email || ''
|
||||
editingUserDraft.phone = user.phone || ''
|
||||
editingUserDraft.status = user.status
|
||||
}
|
||||
|
||||
const closeEdit = () => {
|
||||
editingUser.value = null
|
||||
}
|
||||
|
||||
const submitEdit = async () => {
|
||||
if (!editingUser.value) return
|
||||
try {
|
||||
updateLoading.value = true
|
||||
await updateUser(editingUser.value.id, {
|
||||
name: editingUserDraft.name,
|
||||
role: editingUserDraft.role,
|
||||
email: editingUserDraft.email || undefined,
|
||||
phone: editingUserDraft.phone || undefined,
|
||||
status: editingUserDraft.status
|
||||
})
|
||||
alert('用户信息已更新')
|
||||
closeEdit()
|
||||
fetchUsers()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '更新用户失败')
|
||||
} finally {
|
||||
updateLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const toggleStatus = async (user: any) => {
|
||||
const targetStatus = user.status === 'active' ? 'inactive' : 'active'
|
||||
if (!confirm(`确定要${targetStatus === 'active' ? '启用' : '禁用'}该用户吗?`)) return
|
||||
try {
|
||||
await updateUserStatus(user.id, targetStatus)
|
||||
fetchUsers()
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '更新状态失败')
|
||||
}
|
||||
}
|
||||
|
||||
const handleResetPassword = async (user: any) => {
|
||||
const newPassword = prompt('请输入新的密码(至少6位)')
|
||||
if (!newPassword) return
|
||||
if (newPassword.length < 6) {
|
||||
alert('密码长度需至少6位')
|
||||
return
|
||||
}
|
||||
try {
|
||||
await resetUserPassword(user.id, newPassword)
|
||||
alert('密码已重置')
|
||||
} catch (error: any) {
|
||||
alert(error?.message || '重置密码失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchUsers()
|
||||
})
|
||||
</script>
|
||||
|
||||
126
frontend/src/views/statistics/Statistics.vue
Normal file
126
frontend/src/views/statistics/Statistics.vue
Normal file
@ -0,0 +1,126 @@
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<!-- Value Statistics -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">设备价值统计</h2>
|
||||
<div ref="valueChartRef" class="h-96"></div>
|
||||
</div>
|
||||
|
||||
<!-- Value by Type -->
|
||||
<div class="card-apple">
|
||||
<h2 class="text-apple-title mb-4">设备类型价值分布</h2>
|
||||
<div ref="typeChartRef" class="h-96"></div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted } from 'vue'
|
||||
import * as echarts from 'echarts'
|
||||
import { getValueStatistics } from '@/api/statistics'
|
||||
|
||||
const valueChartRef = ref<HTMLElement>()
|
||||
const typeChartRef = ref<HTMLElement>()
|
||||
let valueChart: echarts.ECharts | null = null
|
||||
let typeChart: echarts.ECharts | null = null
|
||||
|
||||
const fetchStatistics = async () => {
|
||||
try {
|
||||
const response = await getValueStatistics()
|
||||
if (response.data) {
|
||||
initCharts(response.data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取统计数据失败:', error)
|
||||
}
|
||||
}
|
||||
|
||||
const initCharts = (data: any) => {
|
||||
if (valueChartRef.value) {
|
||||
valueChart = echarts.init(valueChartRef.value)
|
||||
valueChart.setOption({
|
||||
tooltip: {
|
||||
trigger: 'item'
|
||||
},
|
||||
legend: {
|
||||
orient: 'vertical',
|
||||
left: 'left'
|
||||
},
|
||||
series: [{
|
||||
type: 'pie',
|
||||
radius: '50%',
|
||||
data: [
|
||||
{ value: data.available_value, name: '可用价值', itemStyle: { color: '#34C759' } },
|
||||
{ value: data.borrowed_value, name: '已借出价值', itemStyle: { color: '#FF9500' } },
|
||||
{ value: data.maintenance_value, name: '维护中价值', itemStyle: { color: '#FFCC00' } }
|
||||
],
|
||||
emphasis: {
|
||||
itemStyle: {
|
||||
shadowBlur: 10,
|
||||
shadowOffsetX: 0,
|
||||
shadowColor: 'rgba(0, 0, 0, 0.5)'
|
||||
}
|
||||
}
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
if (typeChartRef.value && data.value_by_type) {
|
||||
typeChart = echarts.init(typeChartRef.value)
|
||||
typeChart.setOption({
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: {
|
||||
type: 'shadow'
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
data: ['总价值', '已借出价值', '可用价值']
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: data.value_by_type.map((item: any) => item.equipment_type)
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value'
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: '总价值',
|
||||
type: 'bar',
|
||||
data: data.value_by_type.map((item: any) => item.total_value),
|
||||
itemStyle: { color: '#007AFF' }
|
||||
},
|
||||
{
|
||||
name: '已借出价值',
|
||||
type: 'bar',
|
||||
data: data.value_by_type.map((item: any) => item.borrowed_value),
|
||||
itemStyle: { color: '#FF9500' }
|
||||
},
|
||||
{
|
||||
name: '可用价值',
|
||||
type: 'bar',
|
||||
data: data.value_by_type.map((item: any) => item.available_value),
|
||||
itemStyle: { color: '#34C759' }
|
||||
}
|
||||
]
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchStatistics()
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
valueChart?.resize()
|
||||
typeChart?.resize()
|
||||
})
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
valueChart?.dispose()
|
||||
typeChart?.dispose()
|
||||
window.removeEventListener('resize', () => {})
|
||||
})
|
||||
</script>
|
||||
|
||||
11
frontend/src/vite-env.d.ts
vendored
Normal file
11
frontend/src/vite-env.d.ts
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
interface ImportMetaEnv {
|
||||
readonly VITE_API_BASE_URL: string
|
||||
// 更多环境变量...
|
||||
}
|
||||
|
||||
interface ImportMeta {
|
||||
readonly env: ImportMetaEnv
|
||||
}
|
||||
|
||||
76
frontend/tailwind.config.js
Normal file
76
frontend/tailwind.config.js
Normal file
@ -0,0 +1,76 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default {
|
||||
content: [
|
||||
"./index.html",
|
||||
"./src/**/*.{vue,js,ts,jsx,tsx}",
|
||||
],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
// Apple Design System Colors
|
||||
apple: {
|
||||
blue: '#007AFF',
|
||||
green: '#34C759',
|
||||
indigo: '#5856D6',
|
||||
orange: '#FF9500',
|
||||
pink: '#FF2D55',
|
||||
purple: '#AF52DE',
|
||||
red: '#FF3B30',
|
||||
teal: '#5AC8FA',
|
||||
yellow: '#FFCC00',
|
||||
},
|
||||
// System Colors
|
||||
system: {
|
||||
gray: {
|
||||
1: '#8E8E93',
|
||||
2: '#AEAEB2',
|
||||
3: '#C7C7CC',
|
||||
4: '#D1D1D6',
|
||||
5: '#E5E5EA',
|
||||
6: '#F2F2F7',
|
||||
},
|
||||
background: {
|
||||
primary: '#FFFFFF',
|
||||
secondary: '#F2F2F7',
|
||||
tertiary: '#FFFFFF',
|
||||
},
|
||||
label: {
|
||||
primary: '#000000',
|
||||
secondary: '#3C3C43',
|
||||
tertiary: '#3C3C4399',
|
||||
quaternary: '#3C3C434D',
|
||||
},
|
||||
},
|
||||
},
|
||||
fontFamily: {
|
||||
sans: [
|
||||
'-apple-system',
|
||||
'BlinkMacSystemFont',
|
||||
'"SF Pro Display"',
|
||||
'"SF Pro Text"',
|
||||
'"Helvetica Neue"',
|
||||
'Helvetica',
|
||||
'Arial',
|
||||
'sans-serif',
|
||||
],
|
||||
},
|
||||
borderRadius: {
|
||||
'apple': '10px',
|
||||
'apple-lg': '14px',
|
||||
'apple-xl': '20px',
|
||||
},
|
||||
boxShadow: {
|
||||
'apple': '0 2px 8px rgba(0, 0, 0, 0.1)',
|
||||
'apple-lg': '0 4px 16px rgba(0, 0, 0, 0.15)',
|
||||
'apple-xl': '0 8px 32px rgba(0, 0, 0, 0.2)',
|
||||
},
|
||||
backdropBlur: {
|
||||
'apple': '20px',
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
require('@tailwindcss/forms'),
|
||||
],
|
||||
}
|
||||
|
||||
16
frontend/tsconfig.app.json
Normal file
16
frontend/tsconfig.app.json
Normal file
@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "@vue/tsconfig/tsconfig.dom.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"types": ["vite/client"],
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
|
||||
}
|
||||
31
frontend/tsconfig.json
Normal file
31
frontend/tsconfig.json
Normal file
@ -0,0 +1,31 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "ESNext",
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "preserve",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
|
||||
/* Path Aliases */
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
29
frontend/tsconfig.node.json
Normal file
29
frontend/tsconfig.node.json
Normal file
@ -0,0 +1,29 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "ES2023",
|
||||
"lib": ["ES2023"],
|
||||
"module": "ESNext",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"composite": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
},
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedSideEffectImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
1
frontend/tsconfig.tsbuildinfo
Normal file
1
frontend/tsconfig.tsbuildinfo
Normal file
@ -0,0 +1 @@
|
||||
{"root":["./src/app.vue","./src/main.ts","./src/shims-vue.d.ts","./src/vite-env.d.ts","./src/api/agents.ts","./src/api/barcode.ts","./src/api/borrow.ts","./src/api/equipment.ts","./src/api/index.ts","./src/api/person.ts","./src/api/settings.ts","./src/api/statistics.ts","./src/api/storagelocation.ts","./src/api/users.ts","./src/auth/keycloak.ts","./src/components/barcodeprint.vue","./src/components/helloworld.vue","./src/components/statcard.vue","./src/layouts/mainlayout.vue","./src/router/index.ts","./src/stores/auth.ts","./src/stores/equipment.ts","./src/stores/site.ts","./src/types/index.ts","./src/utils/format.ts","./src/views/login.vue","./src/views/borrow/borrowlist.vue","./src/views/borrow/borrowscan.vue","./src/views/borrow/returnscan.vue","./src/views/dashboard/dashboard.vue","./src/views/equipment/equipmentform.vue","./src/views/equipment/equipmentlist.vue","./src/views/settings/settings.vue","./src/views/settings/components/aiagentworkspace.vue","./src/views/settings/components/personmanagement.vue","./src/views/settings/components/sitesettings.vue","./src/views/settings/components/storagelocationmanagement.vue","./src/views/settings/components/usermanagement.vue","./src/views/statistics/statistics.vue"],"version":"5.9.3"}
|
||||
2
frontend/vite.config.d.ts
vendored
Normal file
2
frontend/vite.config.d.ts
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
declare const _default: import("vite").UserConfig;
|
||||
export default _default;
|
||||
29
frontend/vite.config.js
Normal file
29
frontend/vite.config.js
Normal file
@ -0,0 +1,29 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
import { resolve } from 'path';
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src')
|
||||
}
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
host: '192.168.150.22',
|
||||
port: 5173,
|
||||
clientPort: 5173,
|
||||
protocol: 'ws'
|
||||
},
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
30
frontend/vite.config.ts
Normal file
30
frontend/vite.config.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
import { resolve } from 'path'
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': resolve(__dirname, 'src')
|
||||
}
|
||||
},
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
strictPort: true,
|
||||
hmr: {
|
||||
host: '192.168.150.22',
|
||||
port: 5173,
|
||||
clientPort: 5173,
|
||||
protocol: 'ws'
|
||||
},
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://localhost:3000',
|
||||
changeOrigin: true
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
229
椤圭洰寮€鍙戞€荤粨.md
Normal file
229
椤圭洰寮€鍙戞€荤粨.md
Normal file
@ -0,0 +1,229 @@
|
||||
# 摄影设备借还系统 - 项目开发总结
|
||||
|
||||
## 项目完成情况
|
||||
|
||||
### ✅ 已完成功能
|
||||
|
||||
#### 1. 前端项目(Vue.js 3 + Apple Design System)
|
||||
|
||||
**项目结构**
|
||||
- ✅ Vue.js 3 + TypeScript + Vite 项目初始化
|
||||
- ✅ Tailwind CSS + Apple Design System 配置
|
||||
- ✅ Pinia 状态管理配置
|
||||
- ✅ Vue Router 路由配置
|
||||
- ✅ Axios HTTP客户端配置
|
||||
- ✅ ECharts 图表库集成
|
||||
- ✅ JsBarcode 条码生成库集成
|
||||
|
||||
**页面组件**
|
||||
- ✅ 登录页面(Apple风格)
|
||||
- ✅ 主布局(导航栏 + 侧边栏)
|
||||
- ✅ 首页仪表板(统计卡片 + 图表)
|
||||
- ✅ 设备管理页面(列表 + 表单)
|
||||
- ✅ 设备新增/编辑表单
|
||||
- ✅ 借用管理页面
|
||||
- ✅ 扫码出库页面
|
||||
- ✅ 扫码入库页面
|
||||
- ✅ 统计分析页面
|
||||
- ✅ 系统设置页面
|
||||
|
||||
**功能实现**
|
||||
- ✅ 设备列表查看、搜索、筛选
|
||||
- ✅ 设备新增、编辑、删除
|
||||
- ✅ 设备编码自动生成和自定义录入
|
||||
- ✅ 设备价格信息管理
|
||||
- ✅ 扫码出库功能(红外扫码枪支持)
|
||||
- ✅ 扫码入库功能(红外扫码枪支持)
|
||||
- ✅ 批量扫码功能
|
||||
- ✅ 条码生成和打印
|
||||
- ✅ 数据可视化图表
|
||||
|
||||
**Apple UI设计规范**
|
||||
- ✅ 系统字体(SF Pro Display/Text)
|
||||
- ✅ Apple色彩系统(蓝色、绿色、橙色等)
|
||||
- ✅ 圆角设计(10px、14px、20px)
|
||||
- ✅ 阴影效果(Apple风格)
|
||||
- ✅ 毛玻璃效果(backdrop-blur)
|
||||
- ✅ 响应式设计
|
||||
- ✅ 流畅的动画和过渡效果
|
||||
|
||||
#### 2. 后端项目(Node.js + Express + TypeScript)
|
||||
|
||||
**项目结构**
|
||||
- ✅ Express + TypeScript 项目初始化
|
||||
- ✅ Prisma ORM 配置
|
||||
- ✅ MySQL 数据库模型定义
|
||||
- ✅ 路由和控制器架构
|
||||
- ✅ 统一响应格式
|
||||
- ✅ 错误处理中间件
|
||||
|
||||
**API接口实现**
|
||||
- ✅ 设备管理接口(CRUD)
|
||||
- ✅ 设备编码生成和验证接口
|
||||
- ✅ 扫码查询设备接口
|
||||
- ✅ 借用管理接口
|
||||
- ✅ 扫码出库/入库接口
|
||||
- ✅ 批量扫码接口
|
||||
- ✅ 统计分析接口
|
||||
- ✅ 价值统计接口
|
||||
- ✅ 条码相关接口
|
||||
- ✅ Keycloak 用户认证接口集成
|
||||
|
||||
**业务逻辑**
|
||||
- ✅ 设备编码自动生成规则
|
||||
- ✅ 设备价值自动计算
|
||||
- ✅ 库存管理逻辑
|
||||
- ✅ 借用归还状态更新
|
||||
- ✅ 数据统计和聚合
|
||||
- ✅ 基于 Keycloak 的访问控制与角色判定
|
||||
|
||||
#### 3. 数据库设计
|
||||
|
||||
- ✅ 设备表(equipment)
|
||||
- ✅ 借用记录表(borrow_record)
|
||||
- ✅ 用户表(user)
|
||||
- ✅ 操作日志表(operation_log)
|
||||
- ✅ Prisma Schema 完整定义
|
||||
- ✅ 索引优化
|
||||
|
||||
## 项目特色
|
||||
|
||||
### 1. Apple Design System UI
|
||||
|
||||
前端严格遵循Apple官方UI设计规范:
|
||||
|
||||
- **字体系统**:使用系统字体(-apple-system, SF Pro)
|
||||
- **色彩系统**:Apple标准色彩(蓝色#007AFF、绿色#34C759等)
|
||||
- **组件样式**:圆角、阴影、毛玻璃效果
|
||||
- **交互体验**:流畅的动画、按压反馈效果
|
||||
- **响应式设计**:适配不同屏幕尺寸
|
||||
|
||||
### 2. 扫码功能
|
||||
|
||||
- **红外扫码枪支持**:通过键盘事件监听实现
|
||||
- **自动聚焦**:页面加载后自动聚焦到扫码输入框
|
||||
- **提示音反馈**:扫码成功/失败提示音
|
||||
- **批量扫码**:支持连续扫码多个设备
|
||||
- **实时验证**:扫码后立即验证设备状态
|
||||
|
||||
### 3. 设备编码管理
|
||||
|
||||
- **自动生成**:系统根据规则自动生成唯一编码
|
||||
- **自定义录入**:管理员可手动输入编码
|
||||
- **格式验证**:实时验证编码格式和唯一性
|
||||
- **编码规则**:`EQ-{类型代码}-{日期}-{序号}`
|
||||
|
||||
### 4. 价格信息管理
|
||||
|
||||
- **单价管理**:支持设备单价录入
|
||||
- **价值计算**:自动计算总价值、已借出价值、可用价值
|
||||
- **价值统计**:首页显示设备价值统计卡片
|
||||
- **价值分析**:按设备类型统计价值分布
|
||||
|
||||
### 5. 用户认证与权限管理
|
||||
- Keycloak 集成本地身份认证系统
|
||||
- 支持 OAuth 2.0 / OpenID Connect 登录
|
||||
- 前端自动刷新 Token、同步角色信息
|
||||
- 后端使用 `keycloak-connect` 保护所有受限接口
|
||||
|
||||
## 技术亮点
|
||||
|
||||
1. **类型安全**:全面使用TypeScript,确保类型安全
|
||||
2. **现代化架构**:前后端分离,RESTful API设计
|
||||
3. **ORM使用**:Prisma提供类型安全的数据库操作
|
||||
4. **组件化开发**:Vue 3 Composition API,代码复用性高
|
||||
5. **状态管理**:Pinia轻量级状态管理
|
||||
6. **UI设计规范**:严格遵循Apple Design System
|
||||
|
||||
## 待完善功能
|
||||
|
||||
1. **操作日志**:记录所有操作日志
|
||||
2. **数据导入导出**:支持Excel导入导出
|
||||
3. **消息通知**:借用归还提醒功能
|
||||
4. **缓存和性能优化**
|
||||
|
||||
## 快速启动
|
||||
|
||||
### Keycloak 启动
|
||||
```bash
|
||||
docker run -d \
|
||||
--name keycloak \
|
||||
-p 8080:8080 \
|
||||
-e KEYCLOAK_ADMIN=admin \
|
||||
-e KEYCLOAK_ADMIN_PASSWORD=admin \
|
||||
quay.io/keycloak/keycloak:23.0.7 start-dev
|
||||
```
|
||||
|
||||
1. 创建 Realm `equipment-management`
|
||||
2. 创建客户端 `equipment-client` 并配置重定向 URI
|
||||
3. 创建用户并赋予角色(如 `admin`、`user`)
|
||||
|
||||
### 后端启动
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
npm install --registry=https://registry.npmmirror.com
|
||||
# 配置 .env 文件中的 DATABASE_URL
|
||||
npx prisma generate
|
||||
npx prisma migrate dev
|
||||
npm run dev
|
||||
```
|
||||
|
||||
### 前端启动
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm install --registry=https://registry.npmmirror.com
|
||||
npm run dev
|
||||
```
|
||||
|
||||
## 项目文件说明
|
||||
|
||||
### 前端关键文件
|
||||
|
||||
- `frontend/src/style.css` - Apple Design System样式定义
|
||||
- `frontend/src/router/index.ts` - 路由配置
|
||||
- `frontend/src/api/` - API接口定义
|
||||
- `frontend/src/views/` - 页面组件
|
||||
- `frontend/src/components/` - 通用组件
|
||||
- `frontend/tailwind.config.js` - Tailwind配置(Apple色彩系统)
|
||||
|
||||
### 后端关键文件
|
||||
|
||||
- `backend/src/index.ts` - 服务器入口
|
||||
- `backend/src/routes/` - 路由定义
|
||||
- `backend/src/controllers/` - 业务逻辑控制器
|
||||
- `backend/prisma/schema.prisma` - 数据库模型定义
|
||||
- `backend/src/utils/` - 工具函数
|
||||
|
||||
## 开发建议
|
||||
|
||||
1. **数据库迁移**:使用 `npx prisma migrate dev` 进行数据库迁移
|
||||
2. **类型生成**:修改Prisma schema后运行 `npx prisma generate`
|
||||
3. **代码规范**:遵循ESLint和Prettier配置
|
||||
4. **API测试**:使用Postman测试API接口
|
||||
5. **UI调试**:使用浏览器开发者工具调试样式
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **数据库配置**:确保MySQL服务运行,数据库已创建
|
||||
2. **Keycloak配置**:确认 Realm / Client / 用户已创建,环境变量配置正确
|
||||
3. **环境变量**:前后端 `.env` 文件需同步 Keycloak 信息
|
||||
4. **端口冲突**:确保3000(后端)、5173(前端)、8080(Keycloak)端口可用
|
||||
5. **扫码枪配置**:确保扫码枪设置为键盘输入模式
|
||||
6. **CORS配置**:开发环境已配置CORS,生产环境需要调整
|
||||
|
||||
## 后续开发建议
|
||||
|
||||
1. 完善Keycloak认证集成
|
||||
2. 添加单元测试和集成测试
|
||||
3. 优化数据库查询性能
|
||||
4. 添加缓存机制
|
||||
5. 实现数据导入导出功能
|
||||
6. 添加消息推送功能
|
||||
7. 优化移动端适配
|
||||
|
||||
---
|
||||
|
||||
**项目已基本完成核心功能开发,可以开始测试和部署!**
|
||||
|
||||
302
椤圭洰鍚姩鎸囧崡.md
Normal file
302
椤圭洰鍚姩鎸囧崡.md
Normal file
@ -0,0 +1,302 @@
|
||||
# 摄影设备借还系统 - 项目启动指南
|
||||
|
||||
## 项目概述
|
||||
|
||||
本项目是一个摄影设备借还管理系统,采用前后端分离架构,前端严格遵循Apple官方UI设计规范。
|
||||
|
||||
## 技术栈
|
||||
|
||||
### 前端
|
||||
- Vue.js 3 + TypeScript
|
||||
- Vite (构建工具)
|
||||
- Tailwind CSS (Apple Design System)
|
||||
- Pinia (状态管理)
|
||||
- Vue Router 4 (路由)
|
||||
- Axios (HTTP客户端)
|
||||
- ECharts (图表库)
|
||||
- JsBarcode (条码生成)
|
||||
|
||||
### 后端
|
||||
- Node.js + Express + TypeScript
|
||||
- Prisma ORM
|
||||
- MySQL 8.0
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Node.js 18+
|
||||
- MySQL 8.0+
|
||||
- npm 或 yarn
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 1. Keycloak 身份认证配置
|
||||
|
||||
项目使用 Keycloak 作为开源本地身份认证系统,提供 SSO、角色管理等能力。首次启动前请完成以下步骤:
|
||||
|
||||
1. 启动 Keycloak(示例使用 Docker):
|
||||
```bash
|
||||
docker run -d \
|
||||
--name keycloak \
|
||||
-p 8080:8080 \
|
||||
-e KEYCLOAK_ADMIN=admin \
|
||||
-e KEYCLOAK_ADMIN_PASSWORD=admin \
|
||||
quay.io/keycloak/keycloak:23.0.7 start-dev
|
||||
```
|
||||
2. 在 Keycloak 控制台中创建 Realm `equipment-management`
|
||||
3. 创建前端客户端 `equipment-client`
|
||||
- 类型:Public Client(或机密客户端并配置 `KEYCLOAK_CLIENT_SECRET`)
|
||||
- 有效重定向 URI:`http://localhost:5173/*`
|
||||
4. 创建用户并分配角色(例如 `admin`、`user`)
|
||||
|
||||
> 提示:建议为开发环境导入一份测试 Realm 配置,或参考文档快速创建必要资源。
|
||||
|
||||
### 2. 环境变量准备
|
||||
|
||||
- `backend/.env`
|
||||
```
|
||||
DATABASE_URL="mysql://root:password@localhost:3306/equipment_management?charset=utf8mb4"
|
||||
SESSION_SECRET=equipment-management-secret
|
||||
KEYCLOAK_URL=http://localhost:8080
|
||||
KEYCLOAK_REALM=equipment-management
|
||||
KEYCLOAK_CLIENT_ID=equipment-client
|
||||
# 若为机密客户端,请同时配置 KEYCLOAK_CLIENT_SECRET
|
||||
```
|
||||
|
||||
- `frontend/.env`
|
||||
```
|
||||
VITE_API_BASE_URL=http://localhost:3000/api
|
||||
VITE_KEYCLOAK_URL=http://localhost:8080
|
||||
VITE_KEYCLOAK_REALM=equipment-management
|
||||
VITE_KEYCLOAK_CLIENT_ID=equipment-client
|
||||
```
|
||||
|
||||
### 3. 数据库准备
|
||||
|
||||
创建MySQL数据库:
|
||||
|
||||
```sql
|
||||
CREATE DATABASE equipment_management CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
```
|
||||
|
||||
### 4. 后端配置
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
|
||||
# 安装依赖(使用国内镜像)
|
||||
npm install --registry=https://registry.npmmirror.com
|
||||
|
||||
# Prisma 初始化
|
||||
npx prisma generate
|
||||
npx prisma migrate dev --name init
|
||||
|
||||
# 启动开发服务器
|
||||
npm run dev
|
||||
```
|
||||
|
||||
后端服务运行在: http://localhost:3000
|
||||
|
||||
### 5. 前端配置
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
|
||||
# 安装依赖(使用国内镜像)
|
||||
npm install --registry=https://registry.npmmirror.com
|
||||
|
||||
# 启动开发服务器
|
||||
npm run dev
|
||||
```
|
||||
|
||||
前端服务运行在: http://localhost:5173
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
shebeiguanli/
|
||||
├── frontend/ # 前端项目
|
||||
│ ├── src/
|
||||
│ │ ├── api/ # API接口定义
|
||||
│ │ ├── components/ # 组件
|
||||
│ │ ├── layouts/ # 布局组件
|
||||
│ │ ├── router/ # 路由配置
|
||||
│ │ ├── stores/ # Pinia状态管理
|
||||
│ │ ├── types/ # TypeScript类型定义
|
||||
│ │ ├── utils/ # 工具函数
|
||||
│ │ └── views/ # 页面组件
|
||||
│ ├── tailwind.config.js # Tailwind配置(Apple Design System)
|
||||
│ └── vite.config.ts # Vite配置
|
||||
│
|
||||
├── backend/ # 后端项目
|
||||
│ ├── src/
|
||||
│ │ ├── controllers/ # 控制器
|
||||
│ │ ├── routes/ # 路由
|
||||
│ │ ├── utils/ # 工具函数
|
||||
│ │ └── index.ts # 入口文件
|
||||
│ ├── prisma/
|
||||
│ │ └── schema.prisma # 数据库模型定义
|
||||
│ └── .env # 环境变量配置
|
||||
│
|
||||
└── 开发文档.md # 详细开发文档
|
||||
```
|
||||
|
||||
## 主要功能
|
||||
|
||||
### ✅ 已实现功能
|
||||
|
||||
1. **设备管理**
|
||||
- 设备列表查看
|
||||
- 设备新增/编辑/删除
|
||||
- 设备编码自动生成和自定义录入
|
||||
- 设备价格信息管理
|
||||
- 设备搜索和筛选
|
||||
|
||||
2. **借用归还管理**
|
||||
- 设备借用
|
||||
- 设备归还
|
||||
- 红外扫码枪扫码出库
|
||||
- 红外扫码枪扫码入库
|
||||
- 批量扫码功能
|
||||
- 借用记录查询
|
||||
|
||||
3. **统计分析**
|
||||
- 首页仪表板(设备状态统计)
|
||||
- 设备价值统计
|
||||
- 设备使用率分析
|
||||
- 数据可视化图表
|
||||
|
||||
4. **条码打印**
|
||||
- 条码生成(前端JsBarcode)
|
||||
- 条码预览
|
||||
- 条码打印
|
||||
|
||||
5. **用户认证与权限管理**
|
||||
- Keycloak 集成本地身份认证系统
|
||||
- 支持 OAuth 2.0 / OpenID Connect 登录
|
||||
- 前端使用 `keycloak-js` 自动登录、刷新 Token
|
||||
- 后端使用 `keycloak-connect` 验证访问令牌、保护 API 路由
|
||||
|
||||
6. **Apple Design System UI**
|
||||
- 严格遵循Apple官方UI设计规范
|
||||
- 系统字体(SF Pro)
|
||||
- Apple色彩系统
|
||||
- 圆角、阴影、毛玻璃效果
|
||||
- 流畅的动画和过渡
|
||||
|
||||
### ⏳ 待实现功能
|
||||
|
||||
1. **操作日志与审计**
|
||||
2. **设备批量导入/导出**
|
||||
3. **数据备份和恢复**
|
||||
4. **消息通知与提醒**
|
||||
|
||||
## API接口
|
||||
|
||||
### 设备管理
|
||||
- `GET /api/equipment/list` - 获取设备列表
|
||||
- `GET /api/equipment/:id` - 获取设备详情
|
||||
- `POST /api/equipment` - 新增设备
|
||||
- `PUT /api/equipment/:id` - 更新设备
|
||||
- `DELETE /api/equipment/:id` - 删除设备
|
||||
- `POST /api/equipment/generate-code` - 生成设备编码
|
||||
- `POST /api/equipment/verify-code` - 验证设备编码
|
||||
- `GET /api/equipment/scan/:equipment_code` - 扫码查询设备
|
||||
|
||||
### 借用归还
|
||||
- `POST /api/borrow` - 借用设备
|
||||
- `POST /api/borrow/scan` - 扫码出库
|
||||
- `POST /api/borrow/scan-batch` - 批量扫码出库
|
||||
- `GET /api/borrow/scan/:equipment_code` - 查询借用记录
|
||||
- `GET /api/borrow/records` - 获取借用记录列表
|
||||
- `POST /api/return` - 归还设备
|
||||
- `POST /api/return/scan` - 扫码入库
|
||||
- `POST /api/return/scan-batch` - 批量扫码入库
|
||||
|
||||
### 统计分析
|
||||
- `GET /api/statistics/dashboard` - 获取首页统计数据
|
||||
- `GET /api/statistics/value` - 获取设备价值统计
|
||||
|
||||
### 条码打印
|
||||
- `GET /api/barcode/:equipment_code` - 获取设备信息(用于生成条码)
|
||||
- `POST /api/barcode/batch` - 批量获取设备信息
|
||||
|
||||
## 开发注意事项
|
||||
|
||||
### 前端开发
|
||||
|
||||
1. **Apple UI设计规范**
|
||||
- 使用Tailwind CSS的Apple Design System类
|
||||
- 遵循Apple的色彩、字体、间距规范
|
||||
- 使用系统字体(-apple-system)
|
||||
|
||||
2. **扫码功能**
|
||||
- 红外扫码枪模拟键盘输入
|
||||
- 监听input框的keyup事件
|
||||
- 检测回车键触发扫码完成
|
||||
- 自动聚焦到扫码输入框
|
||||
|
||||
3. **条码生成**
|
||||
- 使用JsBarcode在前端生成条码
|
||||
- 支持Code128格式
|
||||
- 支持打印功能
|
||||
|
||||
### 后端开发
|
||||
|
||||
1. **数据库操作**
|
||||
- 使用Prisma ORM
|
||||
- 所有数据库操作通过Prisma Client
|
||||
- 价值字段由应用层计算
|
||||
|
||||
2. **API响应格式**
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "操作成功",
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
3. **错误处理**
|
||||
- 统一使用errorResponse返回错误
|
||||
- HTTP状态码和业务错误码分离
|
||||
|
||||
## 常见问题
|
||||
|
||||
### 1. 数据库连接失败
|
||||
- 检查MySQL服务是否启动
|
||||
- 检查.env文件中的DATABASE_URL配置
|
||||
- 确认数据库用户权限
|
||||
|
||||
### 2. Prisma迁移失败
|
||||
- 检查数据库连接
|
||||
- 确认数据库已创建
|
||||
- 查看Prisma错误日志
|
||||
|
||||
### 3. 前端API请求失败
|
||||
- 检查后端服务是否启动
|
||||
- 检查.env文件中的VITE_API_BASE_URL配置
|
||||
- 检查 Keycloak 是否运行且配置正确
|
||||
- 查看浏览器控制台错误信息
|
||||
|
||||
### 4. 扫码功能不工作
|
||||
- 确认红外扫码枪已连接
|
||||
- 检查扫码输入框是否获得焦点
|
||||
- 确认扫码枪设置为键盘输入模式
|
||||
|
||||
### 5. 无法登录系统
|
||||
- 确认 Keycloak 服务已启动
|
||||
- 检查 Realm、Client 与用户配置是否正确
|
||||
- 查看浏览器网络请求与后端日志
|
||||
|
||||
## 下一步开发计划
|
||||
|
||||
1. 集成Keycloak认证系统
|
||||
2. 完善用户权限管理
|
||||
3. 添加操作日志功能
|
||||
4. 实现数据导入/导出
|
||||
5. 优化性能和用户体验
|
||||
|
||||
## 技术支持
|
||||
|
||||
如有问题,请参考开发文档或联系开发团队。
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user