forked from ITStudio_OUC/itstudio_manager
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1bacf534b9 | |||
| 77cf75a2be | |||
| dd660d416a | |||
| 5d3a727b73 | |||
| 4f640b134a | |||
| 36d1b94fd8 | |||
| a1bcde0a37 | |||
| bb3df45b9f | |||
| 92ffc47169 | |||
| 774c7f8cc2 | |||
| 3c280c5353 | |||
| 0af6fd35ab | |||
| 53855df24a | |||
| 0536ffd632 | |||
| b4c78c1f01 | |||
| 8262b3469f | |||
| 905f1d897d | |||
| 2912d83b5e | |||
| 091684357d | |||
| d6e8390ed6 | |||
| 2a678d9093 | |||
| 7afef64ed8 | |||
| aacf474b5c | |||
| 887ce3a697 | |||
| 2ead497ec2 | |||
| f13aef29b3 | |||
| b56f7bd9bf | |||
| 39a7d89dad | |||
| 065b9f77e4 | |||
| 830d3254e4 | |||
| 6ba540aab3 | |||
| 8195b82396 | |||
| 43139784b2 | |||
| 18224b9a97 | |||
| d8b60339a5 | |||
| 71fd8ded88 | |||
| d58ffe0985 | |||
| e76623a8ed | |||
| 1e9d86283b | |||
| 6328f97153 | |||
| 994b2ff5b3 | |||
| 999ce5a68a | |||
| 2f76422054 | |||
| dd317e091b | |||
| 9e9dc051d1 | |||
| fe85d1fe77 | |||
| c11a1dccf4 | |||
| c1f0c2441a | |||
| 43d171b6bc | |||
| 066fbf8a22 | |||
| 9d2a5f5217 | |||
| 4a0813b284 |
Generated
+10
@@ -0,0 +1,10 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# 已忽略包含查询文件的默认文件夹
|
||||
/queries/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
Generated
+18
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="CompilerConfiguration">
|
||||
<bytecodeTargetLevel>
|
||||
<module name="itmanager" target="25" />
|
||||
</bytecodeTargetLevel>
|
||||
</component>
|
||||
<component name="JavacSettings">
|
||||
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
|
||||
<module name="club.itstudio.itmanager" options="-parameters" />
|
||||
<module name="club.itstudio.itmanager.main" options="-parameters" />
|
||||
<module name="club.itstudio.itmanager.test" options="-parameters" />
|
||||
<module name="itmanager" options="-parameters" />
|
||||
<module name="itmanager.main" options="-parameters" />
|
||||
<module name="itmanager.test" options="-parameters" />
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+17
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="root@localhost" uuid="c13cb29f-8398-41b6-a24b-5cf0642c9759">
|
||||
<driver-ref>mariadb</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.mariadb.jdbc.Driver</jdbc-driver>
|
||||
<jdbc-url>jdbc:mariadb://localhost:3306</jdbc-url>
|
||||
<jdbc-additional-properties>
|
||||
<property name="com.intellij.clouds.kubernetes.db.host.port" />
|
||||
<property name="com.intellij.clouds.kubernetes.db.enabled" value="false" />
|
||||
<property name="com.intellij.clouds.kubernetes.db.container.port" />
|
||||
</jdbc-additional-properties>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourcePerFileMappings">
|
||||
<file url="file://$PROJECT_DIR$/schema.sql" value="c13cb29f-8398-41b6-a24b-5cf0642c9759" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<component name="ProjectDictionaryState">
|
||||
<dictionary name="project">
|
||||
<words>
|
||||
<w>itmanager</w>
|
||||
<w>itstudio</w>
|
||||
</words>
|
||||
</dictionary>
|
||||
</component>
|
||||
Generated
+17
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="GradleMigrationSettings" migrationVersion="1" />
|
||||
<component name="GradleSettings">
|
||||
<option name="linkedExternalProjectsSettings">
|
||||
<GradleProjectSettings>
|
||||
<option name="externalProjectPath" value="$PROJECT_DIR$/src/backend" />
|
||||
<option name="gradleJvm" value="ms-25" />
|
||||
<option name="modules">
|
||||
<set>
|
||||
<option value="$PROJECT_DIR$/src/backend" />
|
||||
</set>
|
||||
</option>
|
||||
</GradleProjectSettings>
|
||||
</option>
|
||||
</component>
|
||||
</project>
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="DuplicatedCode" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<Languages>
|
||||
<language minSize="49" name="Kotlin" />
|
||||
</Languages>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyShadowingBuiltinsInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredNames">
|
||||
<list>
|
||||
<option value="id" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="ShellCheck" enabled="true" level="ERROR" enabled_by_default="true">
|
||||
<shellcheck_settings value="SC2317" />
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
Generated
+13
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/src/backend/.kotlin" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/src/backend/build" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.idea/dataSources" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
Generated
+13
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Kotlin2JsCompilerArguments">
|
||||
<option name="moduleKind" value="plain" />
|
||||
</component>
|
||||
<component name="Kotlin2JvmCompilerArguments">
|
||||
<option name="jvmTarget" value="21" />
|
||||
</component>
|
||||
<component name="KotlinJpsPluginSettings">
|
||||
<option name="externalSystemId" value="Gradle" />
|
||||
<option name="version" value="2.4.20-RC" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+10
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ExternalStorageConfigurationManager" enabled="true" />
|
||||
<component name="FrameworkDetectionExcludesConfiguration">
|
||||
<file type="web" url="file://$PROJECT_DIR$/src/backend" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" languageLevel="JDK_25" project-jdk-name="ms-25" project-jdk-type="JavaSDK">
|
||||
<output url="file://$PROJECT_DIR$/out" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/itstudio_manager.iml" filepath="$PROJECT_DIR$/.idea/itstudio_manager.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="SqlDialectMappings">
|
||||
<file url="file://$PROJECT_DIR$/schema.sql" dialect="MariaDB" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,690 @@
|
||||
# API 文档
|
||||
|
||||
Base URL:`http://localhost:8080/api`
|
||||
|
||||
## 通用约定
|
||||
|
||||
所有接口均返回统一 JSON 结构:
|
||||
|
||||
```typescript
|
||||
class Response<T> {
|
||||
"code": number;
|
||||
"message": string;
|
||||
"data": T | null;
|
||||
}
|
||||
```
|
||||
|
||||
- `code === 200` 表示成功;**`code !== 200` 时 `data` 恒为 `null`**
|
||||
- 除特别标注(公开)外,接口需在请求头携带 `Authorization: Bearer <token>`
|
||||
- 下文路径均省略 `/api` 前缀,`data` 仅给出 `T` 的声明
|
||||
- 部分 `/test` 接口的返回值不遵循上述格式
|
||||
- 前端类示例使用 **TypeScript** 类定义
|
||||
|
||||
## 接口总览
|
||||
|
||||
| 分组 | 路径前缀 | 说明 |
|
||||
|--------------|--------------------|-------------------------------------------|
|
||||
| 测试 | `/test` | 连通性测试 |
|
||||
| 认证 | `/v1/auth` | 登录 / 注册 / 验证码 / Token 管理 |
|
||||
| 物品管理 | `/v1/items` | 物品 / 类别 / 图片 CRUD、借还、上下架查询 |
|
||||
| 使用记录 | `/v1/usages` | 使用记录 CRUD、图片、当前/按用户查询 |
|
||||
| 财务管理 | `/v1/finance` | 财务记录 / 分类 CRUD、凭证图片上传 |
|
||||
| 财务凭证图片 | `/v1/proof-images` | 财务凭证图片 CRUD |
|
||||
| 邮件通知 | `/v1/email` | 通知设置、收件邮箱启用状态 |
|
||||
|
||||
---
|
||||
|
||||
## 分组:测试 `/test`
|
||||
|
||||
### GET /hello
|
||||
|
||||
需要认证。
|
||||
|
||||
**响应**
|
||||
|
||||
```typescript
|
||||
"Hello Kotlin WebFlux!"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 分组:认证 `/v1/auth`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|---------------------------|------|--------------------------|
|
||||
| POST | `/login` | 公开 | 登录,获取 Token |
|
||||
| GET | `/logout` | 需要 | 注销,Token 加入黑名单 |
|
||||
| GET | `/ask-code` | 公开 | 发送邮箱验证码 |
|
||||
| POST | `/register` | 公开 | 邮箱注册 |
|
||||
| POST | `/reset` | 公开 | 重置密码 |
|
||||
| GET | `/relogin` | 需要 | 用旧 Token 换取新 Token |
|
||||
|
||||
### POST /login
|
||||
|
||||
以 `application/x-www-form-urlencoded` 表单提交。
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|--------|----------|
|
||||
| username | string | 用户名 |
|
||||
| password | string | 密码 |
|
||||
|
||||
**响应 data**
|
||||
|
||||
```typescript
|
||||
class data {
|
||||
"username": string;
|
||||
"role": string;
|
||||
"token": string;
|
||||
"expire": Date;
|
||||
}
|
||||
```
|
||||
|
||||
### GET /logout
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /ask-code
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|-------|-----------------------------|------------------------------------|
|
||||
| email | string | 接收验证码的邮箱 |
|
||||
| type | `register` \| `reset` | 验证码用途(注册 / 重置密码) |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /register
|
||||
|
||||
**请求体字段**:`email`、`code`、`username`、`password`
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /reset
|
||||
|
||||
**请求体字段**:`email`、`code`、`password`
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /relogin
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**
|
||||
|
||||
```typescript
|
||||
class data {
|
||||
"token": string;
|
||||
"expire": Date;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 分组:物品管理 `/v1/items`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|---------------------------------|------|----------------------------------------|
|
||||
| GET | `/items` | 需要 | 分页查询物品 |
|
||||
| POST | `/items` | 需要 | 创建物品 |
|
||||
| PUT | `/items` | 需要 | 更新物品 |
|
||||
| DELETE | `/items` | 需要 | 删除物品(同时清理其图片) |
|
||||
| POST | `/items/{id}/upload_images` | 需要 | 上传物品图片(multipart) |
|
||||
| POST | `/items/{id}/set_primary_image` | 需要 | 设置物品主图 |
|
||||
| POST | `/items/{id}/borrow` | 需要 | 借用物品(扣减可用库存) |
|
||||
| POST | `/items/{id}/return_item` | 需要 | 归还物品(恢复可用库存) |
|
||||
| GET | `/items/available` | 需要 | 获取可用物品列表 |
|
||||
| GET | `/items/in_use` | 需要 | 获取使用中物品列表 |
|
||||
| GET | `/items/categories` | 需要 | 查询物品类别列表 |
|
||||
| POST | `/items/categories` | 需要 | 创建物品类别 |
|
||||
| PUT | `/items/categories` | 需要 | 更新物品类别 |
|
||||
| DELETE | `/items/categories` | 需要 | 删除物品类别 |
|
||||
| GET | `/items/images` | 需要 | 查询物品图片列表 |
|
||||
| POST | `/items/images` | 需要 | 创建物品图片 |
|
||||
| PUT | `/items/images` | 需要 | 更新物品图片 |
|
||||
| DELETE | `/items/images` | 需要 | 删除物品图片(同时删除物理文件) |
|
||||
|
||||
### 实体定义
|
||||
|
||||
```typescript
|
||||
class Item {
|
||||
"id": number | null;
|
||||
"code": string; // 物品编号 / 资产编号
|
||||
"name": string;
|
||||
"categoryId": number | null;
|
||||
"model": string | null;
|
||||
"brand": string | null;
|
||||
"location": string | null;
|
||||
"totalQuantity": number;
|
||||
"availableQuantity": number;
|
||||
"unit": string; // 默认 "件"
|
||||
"price": number | null;
|
||||
"purchaseDate": string | null;
|
||||
"supplier": string | null;
|
||||
"status": string; // normal / disabled / lost / repair
|
||||
"description": string | null;
|
||||
"imagePath": string | null;
|
||||
"createdBy": number | null;
|
||||
"createdAt": string | null;
|
||||
"updatedAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
class Category {
|
||||
"id": number | null;
|
||||
"name": string;
|
||||
"parentId": number | null;
|
||||
"description": string | null;
|
||||
"createdAt": string | null;
|
||||
"updatedAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
class Attachment {
|
||||
"id": number | null;
|
||||
"relatedTable": string | null; // 关联表名,如 "items"
|
||||
"relatedId": number | null; // 关联记录 ID
|
||||
"fileName": string | null;
|
||||
"filePath": string | null;
|
||||
"fileSize": number | null;
|
||||
"contentType": string | null;
|
||||
"uploadedBy": number | null;
|
||||
"uploadedAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
```typescript
|
||||
class Page<T> {
|
||||
"records": T[];
|
||||
"total": number;
|
||||
"size": number;
|
||||
"current": number;
|
||||
"pages": number;
|
||||
}
|
||||
```
|
||||
|
||||
### GET /items
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|---------|-----------------------------------|
|
||||
| pageNum | number | 页码,默认 `1` |
|
||||
| pageSize | number | 每页条数,默认 `10` |
|
||||
| keyword | string? | 按名称 / 编号模糊搜索 |
|
||||
| status | string? | 按状态过滤,如 `normal` |
|
||||
|
||||
**响应 data**:`Page<Item>`
|
||||
|
||||
### POST /items
|
||||
|
||||
**请求体**:`Item`(`id` / `createdAt` / `updatedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /items
|
||||
|
||||
**请求体**:`Item`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /items
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|---------|
|
||||
| id | number | 物品 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /items/{id}/upload_images
|
||||
|
||||
**请求**:`multipart/form-data`,字段名 `files`,可传多个图片文件
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /items/{id}/set_primary_image
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|---------|--------|------------------------------------------|
|
||||
| imageId | number | 附件 ID,须属于该物品 |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /items/{id}/borrow
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|--------|--------------------|
|
||||
| quantity | number | 借用数量,默认 `1` |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /items/{id}/return_item
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|--------|--------------------|
|
||||
| quantity | number | 归还数量,默认 `1` |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /items/available
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Item[]`
|
||||
|
||||
### GET /items/in_use
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Item[]`
|
||||
|
||||
### GET /items/categories
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Category[]`
|
||||
|
||||
### POST /items/categories
|
||||
|
||||
**请求体**:`Category`(`id` / `createdAt` / `updatedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /items/categories
|
||||
|
||||
**请求体**:`Category`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /items/categories
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|----------|
|
||||
| id | number | 类别 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /items/images
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Attachment[]`(`relatedTable` 为 `"items"` 的图片)
|
||||
|
||||
### POST /items/images
|
||||
|
||||
**请求体**:`Attachment`(`id` / `uploadedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /items/images
|
||||
|
||||
**请求体**:`Attachment`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /items/images
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|----------|
|
||||
| id | number | 图片 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
---
|
||||
|
||||
## 分组:使用记录 `/v1/usages`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|------------------------------|------|--------------------------------------|
|
||||
| GET | `/usages` | 需要 | 分页查询使用记录 |
|
||||
| POST | `/usages` | 需要 | 创建使用记录 |
|
||||
| PUT | `/usages` | 需要 | 更新使用记录 |
|
||||
| DELETE | `/usages` | 需要 | 删除使用记录 |
|
||||
| POST | `/usages/{id}/upload_images` | 需要 | 上传使用记录图片(multipart) |
|
||||
| GET | `/usages/current` | 需要 | 获取当前使用中的记录 |
|
||||
| GET | `/usages/by_user` | 需要 | 根据用户姓名获取使用记录 |
|
||||
| GET | `/usages/images` | 需要 | 查询使用记录图片列表 |
|
||||
| POST | `/usages/images` | 需要 | 创建使用记录图片 |
|
||||
| PUT | `/usages/images` | 需要 | 更新使用记录图片 |
|
||||
| DELETE | `/usages/images` | 需要 | 删除使用记录图片(同时删除物理文件) |
|
||||
|
||||
### 实体定义
|
||||
|
||||
```typescript
|
||||
class BorrowRecord {
|
||||
"id": number | null;
|
||||
"itemId": number;
|
||||
"borrower": string;
|
||||
"quantity": number;
|
||||
"borrowDate": string | null;
|
||||
"dueDate": string | null;
|
||||
"returnDate": string | null;
|
||||
"status": string; // BORROWED / RETURNED / OVERDUE / CANCELED
|
||||
"approver": string | null;
|
||||
"note": string | null;
|
||||
"createdAt": string | null;
|
||||
"updatedAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
### GET /usages
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|---------|---------------------|
|
||||
| pageNum | number | 页码,默认 `1` |
|
||||
| pageSize | number | 每页条数,默认 `10` |
|
||||
| keyword | string? | 按借入人模糊搜索 |
|
||||
| status | string? | 按状态过滤 |
|
||||
|
||||
**响应 data**:`Page<BorrowRecord>`
|
||||
|
||||
### POST /usages
|
||||
|
||||
**请求体**:`BorrowRecord`(`id` / `createdAt` / `updatedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /usages
|
||||
|
||||
**请求体**:`BorrowRecord`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /usages
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|---------|
|
||||
| id | number | 记录 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /usages/{id}/upload_images
|
||||
|
||||
**请求**:`multipart/form-data`,字段名 `files`,可传多个图片文件
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /usages/current
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`BorrowRecord[]`(当前 `BORROWED` 与 `OVERDUE` 记录)
|
||||
|
||||
### GET /usages/by_user
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|---------|------------|
|
||||
| name | string? | 借入人姓名 |
|
||||
|
||||
**响应 data**:`BorrowRecord[]`
|
||||
|
||||
### GET /usages/images
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Attachment[]`(`relatedTable` 为 `"borrow_records"` 的图片)
|
||||
|
||||
### POST /usages/images
|
||||
|
||||
**请求体**:`Attachment`(`id` / `uploadedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /usages/images
|
||||
|
||||
**请求体**:`Attachment`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /usages/images
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|----------|
|
||||
| id | number | 图片 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
---
|
||||
|
||||
## 分组:财务管理 `/v1/finance`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|-------------------------------|------|---------------------------------------|
|
||||
| GET | `/finance` | 需要 | 分页查询财务记录 |
|
||||
| POST | `/finance` | 需要 | 创建财务记录 |
|
||||
| PUT | `/finance` | 需要 | 更新财务记录 |
|
||||
| DELETE | `/finance` | 需要 | 删除财务记录 |
|
||||
| POST | `/finance/{id}/upload_images` | 需要 | 上传财务凭证图片(multipart) |
|
||||
| DELETE | `/finance/{id}` | 需要 | 删除财务记录(发送邮件通知) |
|
||||
| GET | `/finance/categories` | 需要 | 查询财务分类列表 |
|
||||
| POST | `/finance/categories` | 需要 | 创建财务分类 |
|
||||
| PUT | `/finance/categories` | 需要 | 更新财务分类 |
|
||||
| DELETE | `/finance/categories` | 需要 | 删除财务分类 |
|
||||
|
||||
### 实体定义
|
||||
|
||||
```typescript
|
||||
class FinanceRecord {
|
||||
"id": number | null;
|
||||
"recordNo": string | null;
|
||||
"type": string; // PURCHASE / REFUND / REPAIR / DEPRECIATION / OTHER
|
||||
"relatedItemId": number | null;
|
||||
"amount": number; // BigDecimal
|
||||
"currency": string; // 默认 "CNY"
|
||||
"vendor": string | null;
|
||||
"occurredAt": string | null;
|
||||
"recordedBy": number | null;
|
||||
"note": string | null;
|
||||
"createdAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
### GET /finance
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|----------|---------|--------------------------------|
|
||||
| pageNum | number | 页码,默认 `1` |
|
||||
| pageSize | number | 每页条数,默认 `10` |
|
||||
| keyword | string? | 按单号 / 供应商 / 备注模糊搜索 |
|
||||
| type | string? | 按类型过滤 |
|
||||
| start | string? | 发生时间起点 |
|
||||
| end | string? | 发生时间终点 |
|
||||
| vendor | string? | 按供应商过滤 |
|
||||
| itemId | number? | 按关联物品 ID 过滤 |
|
||||
|
||||
**响应 data**:`Page<FinanceRecord>`
|
||||
|
||||
### POST /finance
|
||||
|
||||
**请求体**:`FinanceRecord`(`id` / `createdAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /finance
|
||||
|
||||
**请求体**:`FinanceRecord`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /finance
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|---------|
|
||||
| id | number | 记录 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /finance/{id}/upload_images
|
||||
|
||||
**请求**:`multipart/form-data`,字段名 `files`,可传多个图片文件
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /finance/{id}
|
||||
|
||||
删除财务记录,并向 `recordedBy` 对应账号的邮箱发送删除通知。
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### GET /finance/categories
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Category[]`
|
||||
|
||||
### POST /finance/categories
|
||||
|
||||
**请求体**:`Category`(`id` / `createdAt` / `updatedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /finance/categories
|
||||
|
||||
**请求体**:`Category`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /finance/categories
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|----------|
|
||||
| id | number | 分类 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
---
|
||||
|
||||
## 分组:财务凭证图片 `/v1/proof-images`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|------------------------|------|-----------------------------------|
|
||||
| GET | `/proof-images` | 需要 | 查询财务凭证图片列表 |
|
||||
| POST | `/proof-images` | 需要 | 创建财务凭证图片 |
|
||||
| PUT | `/proof-images` | 需要 | 更新财务凭证图片 |
|
||||
| DELETE | `/proof-images` | 需要 | 删除财务凭证图片 |
|
||||
| DELETE | `/proof-images/{id}` | 需要 | 删除凭证图片(同时删除物理文件) |
|
||||
|
||||
凭证图片为 `relatedTable` 为 `"finance_records"` 的 `Attachment`,与 `/items/images` 共用 `Attachment` 实体。
|
||||
|
||||
### GET /proof-images
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`Attachment[]`
|
||||
|
||||
### POST /proof-images
|
||||
|
||||
**请求体**:`Attachment`(`id` / `uploadedAt` 由服务端填充)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### PUT /proof-images
|
||||
|
||||
**请求体**:`Attachment`(须包含 `id`)
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /proof-images
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|--------|----------|
|
||||
| id | number | 图片 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### DELETE /proof-images/{id}
|
||||
|
||||
删除图片并清理物理文件。
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
---
|
||||
|
||||
## 分组:邮件通知 `/v1/email`
|
||||
|
||||
| 方法 | 路径 | 认证 | 说明 |
|
||||
|--------|--------------------------|------|-------------------------|
|
||||
| GET | `/notification-settings` | 需要 | 获取通知设置和邮箱列表 |
|
||||
| POST | `/notification-settings` | 需要 | 创建 / 更新通知设置 |
|
||||
| POST | `/toggle-email-status` | 需要 | 切换邮箱启用 / 禁用状态 |
|
||||
|
||||
### 实体定义
|
||||
|
||||
```typescript
|
||||
class EmailNotice {
|
||||
"id": number | null;
|
||||
"name": string | null;
|
||||
"targetEmails": string | null;
|
||||
"subject": string | null;
|
||||
"body": string | null;
|
||||
"enabled": boolean; // 默认 true
|
||||
"scheduleCron": string | null;
|
||||
"lastSentAt": string | null;
|
||||
"createdAt": string | null;
|
||||
"updatedAt": string | null;
|
||||
}
|
||||
```
|
||||
|
||||
### GET /notification-settings
|
||||
|
||||
**请求参数**:无
|
||||
|
||||
**响应 data**:`EmailNotice[]`
|
||||
|
||||
### POST /notification-settings
|
||||
|
||||
**请求体**:`EmailNotice`。`id` 为 `null` 时创建新记录,否则更新已有记录。
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
### POST /toggle-email-status
|
||||
|
||||
**请求参数**
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|---------|----------|
|
||||
| id | number? | 通知 ID |
|
||||
|
||||
**响应 data**:`null`
|
||||
|
||||
---
|
||||
|
||||
## 其他
|
||||
|
||||
### WebSocket
|
||||
|
||||
`ws://localhost:8080/ws` — 目前不支持
|
||||
@@ -1,2 +1,76 @@
|
||||
# itstudio_manager
|
||||
|
||||
## 目前完成的 API 列表
|
||||
|
||||
[完整信息](./API.md)
|
||||
|
||||
- /api
|
||||
- /test
|
||||
- /hello
|
||||
- /v1
|
||||
- /auth
|
||||
- /login
|
||||
- /logout
|
||||
- /relogin
|
||||
- /ask-code
|
||||
- /register
|
||||
- /reset
|
||||
- /email
|
||||
- /notification-settings
|
||||
- /toggle-email-status
|
||||
- /finance
|
||||
- /
|
||||
- /{id}/upload_images
|
||||
- /{id}
|
||||
- /categories
|
||||
- /items
|
||||
- /
|
||||
- /{id}/upload_images
|
||||
- /{id}/set_primary_image
|
||||
- /{id}/borrow
|
||||
- /{id}/return_item
|
||||
- /available
|
||||
- /in_use
|
||||
- /categories
|
||||
- /images
|
||||
- /proof-images
|
||||
- /
|
||||
- /{id}
|
||||
- /usages
|
||||
- /
|
||||
- /{id}/upload_images
|
||||
- /current
|
||||
- /by_user
|
||||
- /images
|
||||
|
||||
#### 认证方式
|
||||
|
||||
所有 API 均使用 **JWT 认证**(除了需要特殊处理的端点)
|
||||
|
||||
```
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
## 数据库结构
|
||||
|
||||
[schema.sql](./schema.sql)
|
||||
|
||||
- users/account (系统用户/认证信息)
|
||||
- categories (物品类别)
|
||||
- parent_id -> categories.id (自关联父级)
|
||||
- items (物品基本信息)
|
||||
- category_id -> categories.id
|
||||
- created_by -> account.id
|
||||
- item_transactions (物品出入库流水)
|
||||
- item_id -> items.id (ON DELETE CASCADE)
|
||||
- operator_id -> account.id
|
||||
- borrow_records (借用/归还记录)
|
||||
- item_id -> items.id (ON DELETE CASCADE)
|
||||
- borrower (借入人,字符串)
|
||||
- approver (借出/审批人,字符串)
|
||||
- finance_records (财务相关记录)
|
||||
- related_item_id -> items.id
|
||||
- recorded_by -> account.id
|
||||
- email_notices (邮件通知规则/历史)
|
||||
- attachments (文件附件存储索引表)
|
||||
- uploaded_by -> account.id
|
||||
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
-- 用户表(若项目使用 Django auth,可忽略或与 auth_user 对应)
|
||||
DROP TABLE IF EXISTS account;
|
||||
CREATE TABLE account
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
username VARCHAR(150) NOT NULL UNIQUE,
|
||||
password VARCHAR(128) NOT NULL,
|
||||
email VARCHAR(254),
|
||||
full_name VARCHAR(200),
|
||||
is_active TINYINT(1) NOT NULL DEFAULT 1,
|
||||
is_staff TINYINT(1) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COLLATE = utf8mb4_unicode_ci COMMENT ='系统用户/认证信息';
|
||||
|
||||
-- 物品类别
|
||||
DROP TABLE IF EXISTS categories;
|
||||
CREATE TABLE categories
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(150) NOT NULL,
|
||||
parent_id BIGINT UNSIGNED,
|
||||
description TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_categories_parent FOREIGN KEY (parent_id) REFERENCES categories (id) ON DELETE SET NULL
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='物品类别';
|
||||
|
||||
-- 物品(物品主表)
|
||||
DROP TABLE IF EXISTS items;
|
||||
CREATE TABLE items
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
code VARCHAR(100) NOT NULL UNIQUE, -- 物品编号/资产编号
|
||||
name VARCHAR(200) NOT NULL,
|
||||
category_id BIGINT UNSIGNED,
|
||||
model VARCHAR(150),
|
||||
brand VARCHAR(150),
|
||||
location VARCHAR(200),
|
||||
total_quantity INT NOT NULL DEFAULT 0,
|
||||
available_quantity INT NOT NULL DEFAULT 0,
|
||||
unit VARCHAR(30) DEFAULT '件',
|
||||
price DECIMAL(12, 2) DEFAULT NULL,
|
||||
purchase_date DATE DEFAULT NULL,
|
||||
supplier VARCHAR(200) DEFAULT NULL,
|
||||
status VARCHAR(50) DEFAULT 'normal', -- 如 normal/disabled/lost/repair
|
||||
description TEXT,
|
||||
image_path VARCHAR(500),
|
||||
created_by BIGINT UNSIGNED, -- 关联 account.id
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_items_category FOREIGN KEY (category_id) REFERENCES categories (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_items_creator FOREIGN KEY (created_by) REFERENCES account (id) ON DELETE SET NULL,
|
||||
INDEX (name),
|
||||
INDEX (code)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='物品基本信息';
|
||||
|
||||
-- 物品库存/流水(每次入库/出库/调整都记录)
|
||||
DROP TABLE IF EXISTS item_transactions;
|
||||
CREATE TABLE item_transactions
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
item_id BIGINT UNSIGNED NOT NULL,
|
||||
trans_type ENUM ('IN','OUT','ADJUST','TRANSFER') NOT NULL,
|
||||
quantity INT NOT NULL,
|
||||
from_location VARCHAR(200),
|
||||
to_location VARCHAR(200),
|
||||
related_id BIGINT UNSIGNED, -- 可关联采购单/借用记录/调拨单 id
|
||||
operator_id BIGINT UNSIGNED, -- 关联 account.id(操作者)
|
||||
note TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_trans_item FOREIGN KEY (item_id) REFERENCES items (id) ON DELETE CASCADE,
|
||||
CONSTRAINT fk_trans_operator FOREIGN KEY (operator_id) REFERENCES account (id) ON DELETE SET NULL,
|
||||
INDEX (item_id),
|
||||
INDEX (trans_type)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='物品出入库与调整流水';
|
||||
|
||||
-- 借用记录(借/还)
|
||||
DROP TABLE IF EXISTS borrow_records;
|
||||
CREATE TABLE borrow_records
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
item_id BIGINT UNSIGNED NOT NULL,
|
||||
borrower VARCHAR(100) NOT NULL, -- 借入人(姓名,字符串)
|
||||
quantity INT NOT NULL DEFAULT 1,
|
||||
borrow_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
due_date DATETIME DEFAULT NULL,
|
||||
return_date DATETIME DEFAULT NULL,
|
||||
status ENUM ('BORROWED','RETURNED','OVERDUE','CANCELED') NOT NULL DEFAULT 'BORROWED',
|
||||
approver VARCHAR(100) DEFAULT NULL, -- 借出/审批人(姓名,字符串)
|
||||
note TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_borrow_item FOREIGN KEY (item_id) REFERENCES items (id) ON DELETE CASCADE,
|
||||
INDEX (borrower),
|
||||
INDEX (status)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='借用/归还记录';
|
||||
|
||||
-- 财务记录(采购/报销等)
|
||||
DROP TABLE IF EXISTS finance_records;
|
||||
CREATE TABLE finance_records
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
record_no VARCHAR(100) UNIQUE,
|
||||
type ENUM ('PURCHASE','REFUND','REPAIR','DEPRECIATION','OTHER') NOT NULL,
|
||||
related_item_id BIGINT UNSIGNED,
|
||||
amount DECIMAL(14, 2) NOT NULL DEFAULT 0.00,
|
||||
currency VARCHAR(10) DEFAULT 'CNY',
|
||||
vendor VARCHAR(200),
|
||||
occurred_at DATETIME,
|
||||
recorded_by BIGINT UNSIGNED, -- 关联 account.id(记录人)
|
||||
note TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_finance_item FOREIGN KEY (related_item_id) REFERENCES items (id) ON DELETE SET NULL,
|
||||
CONSTRAINT fk_finance_user FOREIGN KEY (recorded_by) REFERENCES account (id) ON DELETE SET NULL,
|
||||
INDEX (record_no)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='财务相关记录';
|
||||
|
||||
-- 邮件通知规则/历史
|
||||
DROP TABLE IF EXISTS email_notices;
|
||||
CREATE TABLE email_notices
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
name VARCHAR(200),
|
||||
target_emails TEXT, -- 以逗号分隔或 JSON 数组
|
||||
subject VARCHAR(300),
|
||||
body TEXT,
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
schedule_cron VARCHAR(100), -- 若使用定时任务
|
||||
last_sent_at DATETIME,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='邮件通知规则/历史';
|
||||
|
||||
-- 附件表(文件存储路径)
|
||||
DROP TABLE IF EXISTS attachments;
|
||||
CREATE TABLE attachments
|
||||
(
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
related_table VARCHAR(100), -- 指示关联表,如 'items'
|
||||
related_id BIGINT UNSIGNED, -- 关联记录 ID
|
||||
file_name VARCHAR(300),
|
||||
file_path VARCHAR(1000),
|
||||
file_size BIGINT UNSIGNED,
|
||||
content_type VARCHAR(200),
|
||||
uploaded_by BIGINT UNSIGNED, -- 关联 account.id(上传者)
|
||||
uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_attachments_user FOREIGN KEY (uploaded_by) REFERENCES account (id) ON DELETE SET NULL,
|
||||
INDEX (related_table, related_id)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4 COMMENT ='文件附件存储索引表';
|
||||
@@ -0,0 +1,3 @@
|
||||
/gradlew text eol=lf
|
||||
*.bat text eol=crlf
|
||||
*.jar binary
|
||||
@@ -0,0 +1,43 @@
|
||||
HELP.md
|
||||
.gradle
|
||||
build/
|
||||
!../../gradle-wrapper.jar
|
||||
!**/src/main/**/build/
|
||||
!**/src/test/**/build/
|
||||
|
||||
src/main/resources/
|
||||
!src/main/resources/application.yaml
|
||||
|
||||
### STS ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Kotlin ###
|
||||
.kotlin
|
||||
@@ -0,0 +1,57 @@
|
||||
plugins {
|
||||
kotlin("jvm") version "2.3.21"
|
||||
kotlin("plugin.spring") version "2.3.21"
|
||||
id("org.jetbrains.kotlin.plugin.serialization") version "2.4.20-RC"
|
||||
id("org.springframework.boot") version "4.1.0"
|
||||
id("io.spring.dependency-management") version "1.1.7"
|
||||
}
|
||||
|
||||
group = "club.itstudio"
|
||||
version = "1.0.0"
|
||||
description = "itmanager"
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(25)
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("com.auth0:java-jwt:4.4.0")
|
||||
implementation("com.baomidou:mybatis-plus-spring-boot4-starter:3.5.15")
|
||||
implementation("com.baomidou:mybatis-plus-jsqlparser:3.5.15")
|
||||
implementation("org.springframework.boot:spring-boot-starter-amqp")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-redis-reactive")
|
||||
implementation("org.springframework.boot:spring-boot-starter-json")
|
||||
implementation("org.springframework.boot:spring-boot-starter-mail")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-validation")
|
||||
implementation("org.springframework.boot:spring-boot-starter-webflux")
|
||||
implementation("org.springframework:spring-messaging")
|
||||
implementation("org.jetbrains.kotlin:kotlin-reflect")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.0")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1")
|
||||
implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
|
||||
implementation("tools.jackson.module:jackson-module-kotlin")
|
||||
runtimeOnly("org.mariadb.jdbc:mariadb-java-client")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-security-test")
|
||||
testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")
|
||||
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
compilerOptions {
|
||||
freeCompilerArgs.addAll("-Xjsr305=strict", "-Xannotation-default-target=param-property")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.withType<Test> {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
kotlin.jvm.target.validation=warning
|
||||
kotlin.jvm.target=25
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
#Mon Aug 17 12:30:11 UTC 2026
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://mirrors.cloud.tencent.com/gradle/gradle-9.7.0-bin.zip
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 the original authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# gradlew start up script for POSIX generated by Gradle.
|
||||
#
|
||||
# Important for running:
|
||||
#
|
||||
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||
# noncompliant, but you have some other compliant shell such as ksh or
|
||||
# bash, then to run this script, type that shell name before the whole
|
||||
# command line, like:
|
||||
#
|
||||
# ksh gradlew
|
||||
#
|
||||
# Busybox and similar reduced shells will NOT work, because this script
|
||||
# requires all of these POSIX shell features:
|
||||
# * functions;
|
||||
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||
# * compound commands having a testable exit status, especially «case»;
|
||||
# * various built-in commands including «command», «set», and «ulimit».
|
||||
#
|
||||
# Important for patching:
|
||||
#
|
||||
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||
#
|
||||
# The "traditional" practice of packing multiple parameters into a
|
||||
# space-separated string is a well documented source of bugs and security
|
||||
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||
# options in "$@", and eventually passing that to Java.
|
||||
#
|
||||
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||
# see the in-line comments for details.
|
||||
#
|
||||
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||
# Darwin, MinGW, and NonStop.
|
||||
#
|
||||
# (3) This script is generated from the Groovy template
|
||||
# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||
# within the Gradle project.
|
||||
#
|
||||
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||
#
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
|
||||
# Resolve links: $0 may be a link
|
||||
app_path=$0
|
||||
|
||||
# Need this for daisy-chained symlinks.
|
||||
while
|
||||
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||
[ -h "$app_path" ]
|
||||
do
|
||||
ls=$( ls -ld "$app_path" )
|
||||
link=${ls#*' -> '}
|
||||
case $link in #(
|
||||
/*) app_path=$link ;; #(
|
||||
*) app_path=$APP_HOME$link ;;
|
||||
esac
|
||||
done
|
||||
|
||||
# This is normally unused
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
} >&2
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
} >&2
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "$( uname )" in #(
|
||||
CYGWIN* ) cygwin=true ;; #(
|
||||
Darwin* ) darwin=true ;; #(
|
||||
MSYS* | MINGW* ) msys=true ;; #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||
else
|
||||
JAVACMD=$JAVA_HOME/bin/java
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD=java
|
||||
if ! command -v java >/dev/null 2>&1
|
||||
then
|
||||
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||
case $MAX_FD in #(
|
||||
max*)
|
||||
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
MAX_FD=$( ulimit -H -n ) ||
|
||||
warn "Could not query maximum file descriptor limit"
|
||||
esac
|
||||
case $MAX_FD in #(
|
||||
'' | soft) :;; #(
|
||||
*)
|
||||
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||
# shellcheck disable=SC2039,SC3045
|
||||
ulimit -n "$MAX_FD" ||
|
||||
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||
esac
|
||||
fi
|
||||
|
||||
# Collect all arguments for the java command, stacking in reverse order:
|
||||
# * args from the command line
|
||||
# * the main class name
|
||||
# * -classpath
|
||||
# * -D...appname settings
|
||||
# * --module-path (only if needed)
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if "$cygwin" || "$msys" ; then
|
||||
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||
|
||||
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
for arg do
|
||||
if
|
||||
case $arg in #(
|
||||
-*) false ;; # don't mess with options #(
|
||||
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||
[ -e "$t" ] ;; #(
|
||||
*) false ;;
|
||||
esac
|
||||
then
|
||||
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||
fi
|
||||
# Roll the args list around exactly as many times as the number of
|
||||
# args, so each arg winds up back in the position where it started, but
|
||||
# possibly modified.
|
||||
#
|
||||
# NB: a `for` loop captures its iteration list before it begins, so
|
||||
# changing the positional parameters here affects neither the number of
|
||||
# iterations, nor the values presented in `arg`.
|
||||
shift # remove old arg
|
||||
set -- "$@" "$arg" # push replacement arg
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
if ! command -v xargs >/dev/null 2>&1
|
||||
then
|
||||
die "xargs is not available"
|
||||
fi
|
||||
|
||||
# Use "xargs" to parse quoted args.
|
||||
#
|
||||
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||
#
|
||||
# In Bash we could simply go:
|
||||
#
|
||||
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||
# set -- "${ARGS[@]}" "$@"
|
||||
#
|
||||
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||
# character that might be a shell metacharacter, then use eval to reverse
|
||||
# that process (while maintaining the separation between arguments), and wrap
|
||||
# the whole thing up as a single "set" statement.
|
||||
#
|
||||
# This will of course break if any of these variables contains a newline or
|
||||
# an unmatched quote.
|
||||
#
|
||||
|
||||
eval "set -- $(
|
||||
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||
xargs -n1 |
|
||||
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||
tr '\n' ' '
|
||||
)" '"$@"'
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+82
@@ -0,0 +1,82 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
@rem SPDX-License-Identifier: Apache-2.0
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%"=="" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem gradlew startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||
setlocal EnableExtensions
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%"=="" set DIRNAME=.
|
||||
@rem This is normally unused
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if %ERRORLEVEL% equ 0 goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo. 1>&2
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||
echo. 1>&2
|
||||
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||
echo location of your Java installation. 1>&2
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute gradlew
|
||||
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||
@rem which allows us to clear the local environment before executing the java command
|
||||
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel
|
||||
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
@@ -0,0 +1 @@
|
||||
rootProject.name = "itmanager"
|
||||
@@ -0,0 +1,11 @@
|
||||
package club.itstudio.itmanager
|
||||
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication
|
||||
import org.springframework.boot.runApplication
|
||||
|
||||
@SpringBootApplication
|
||||
class ItmanagerApplication
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
runApplication<ItmanagerApplication>(*args)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package club.itstudio.itmanager.config
|
||||
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
|
||||
@Configuration
|
||||
class BeanConfig {
|
||||
|
||||
@Bean
|
||||
fun passwordEncoder(): PasswordEncoder {
|
||||
return BCryptPasswordEncoder()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package club.itstudio.itmanager.config
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
@Configuration
|
||||
class MybatisConfig {
|
||||
|
||||
@Bean
|
||||
fun mybatisPlusInterceptor(): MybatisPlusInterceptor {
|
||||
val interceptor = MybatisPlusInterceptor()
|
||||
interceptor.addInnerInterceptor(PaginationInnerInterceptor(DbType.MARIADB))
|
||||
return interceptor
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package club.itstudio.itmanager.config
|
||||
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.serializer
|
||||
import org.springframework.amqp.core.Message
|
||||
import org.springframework.amqp.core.MessageProperties
|
||||
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate
|
||||
import org.springframework.amqp.support.converter.AbstractMessageConverter
|
||||
import org.springframework.amqp.support.converter.MessageConverter
|
||||
import org.springframework.beans.factory.annotation.Qualifier
|
||||
import org.springframework.boot.amqp.autoconfigure.SimpleRabbitListenerContainerFactoryConfigurer
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
@Configuration
|
||||
class RabbitConfig {
|
||||
|
||||
@Bean
|
||||
fun messageConverter(@Qualifier("kotlinxSerializationJson") json: Json): MessageConverter =
|
||||
object : AbstractMessageConverter() {
|
||||
override fun createMessage(obj: Any, messageProperties: MessageProperties): Message {
|
||||
val serializer = json.serializersModule.serializer(obj::class.java)
|
||||
val jsonString = json.encodeToString(serializer, obj)
|
||||
|
||||
val bytes = jsonString.toByteArray(Charsets.UTF_8)
|
||||
messageProperties.contentType = MessageProperties.CONTENT_TYPE_JSON
|
||||
messageProperties.contentLength = bytes.size.toLong()
|
||||
return Message(bytes, messageProperties)
|
||||
}
|
||||
|
||||
override fun fromMessage(message: Message): Any {
|
||||
val content = String(message.body, Charsets.UTF_8)
|
||||
return content
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun rabbitTemplate(
|
||||
connectionFactory: ConnectionFactory,
|
||||
messageConverter: MessageConverter
|
||||
): RabbitTemplate {
|
||||
val rabbitTemplate = RabbitTemplate(connectionFactory)
|
||||
rabbitTemplate.messageConverter = messageConverter
|
||||
return rabbitTemplate
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun rabbitListenerContainerFactory(
|
||||
configurer: SimpleRabbitListenerContainerFactoryConfigurer,
|
||||
connectionFactory: ConnectionFactory,
|
||||
messageConverter: MessageConverter
|
||||
): SimpleRabbitListenerContainerFactory {
|
||||
val factory = SimpleRabbitListenerContainerFactory()
|
||||
configurer.configure(factory, connectionFactory)
|
||||
factory.setMessageConverter(messageConverter)
|
||||
return factory
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package club.itstudio.itmanager.config
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.vo.response.AuthorizeVO
|
||||
import club.itstudio.itmanager.filter.JwtAuthorizeFilter
|
||||
import club.itstudio.itmanager.service.AccountService
|
||||
import club.itstudio.itmanager.utils.DateUtils
|
||||
import club.itstudio.itmanager.utils.JwtUtils
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.encodeToJsonElement
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.security.authentication.ReactiveAuthenticationManager
|
||||
import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity
|
||||
import org.springframework.security.config.web.server.SecurityWebFiltersOrder
|
||||
import org.springframework.security.config.web.server.ServerHttpSecurity
|
||||
import org.springframework.security.core.userdetails.User
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.security.web.server.SecurityWebFilterChain
|
||||
import org.springframework.security.web.server.authentication.AuthenticationWebFilter
|
||||
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter
|
||||
import org.springframework.security.web.server.context.NoOpServerSecurityContextRepository
|
||||
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers
|
||||
import org.springframework.web.server.ServerWebExchange
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Configuration
|
||||
@EnableWebFluxSecurity
|
||||
class SecurityConfig(
|
||||
private val jwtUtils: JwtUtils,
|
||||
private val service: AccountService,
|
||||
private val jwtAuthorizeFilter: JwtAuthorizeFilter,
|
||||
private val passwordEncoder: PasswordEncoder
|
||||
) {
|
||||
|
||||
@Bean
|
||||
fun reactiveAuthenticationManager(): ReactiveAuthenticationManager {
|
||||
val manager = UserDetailsRepositoryReactiveAuthenticationManager(service)
|
||||
manager.setPasswordEncoder(passwordEncoder)
|
||||
return manager
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
|
||||
return http
|
||||
.authorizeExchange {
|
||||
it
|
||||
.pathMatchers(
|
||||
"/api/v1/auth/relogin"
|
||||
).authenticated()
|
||||
.pathMatchers(
|
||||
"/api/v1/auth/**",
|
||||
"/ws/**",
|
||||
"/error"
|
||||
).permitAll()
|
||||
.anyExchange()
|
||||
.authenticated()
|
||||
}
|
||||
.addFilterAt(loginAuthenticationFilter(), SecurityWebFiltersOrder.AUTHENTICATION)
|
||||
.addFilterAt(jwtAuthorizeFilter, SecurityWebFiltersOrder.AUTHENTICATION)
|
||||
.exceptionHandling {
|
||||
it.authenticationEntryPoint { exchange, ex ->
|
||||
writeJsonResponse(
|
||||
exchange,
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
ApiResponse.unauthenticated(ex.message)
|
||||
)
|
||||
}
|
||||
.accessDeniedHandler { exchange, ex ->
|
||||
writeJsonResponse(
|
||||
exchange,
|
||||
HttpStatus.FORBIDDEN,
|
||||
ApiResponse.forbidden(ex.message)
|
||||
)
|
||||
}
|
||||
}
|
||||
.csrf { it.disable() }
|
||||
.securityContextRepository(NoOpServerSecurityContextRepository.getInstance())
|
||||
.build()
|
||||
}
|
||||
|
||||
@Bean
|
||||
fun loginAuthenticationFilter(): AuthenticationWebFilter {
|
||||
val filter = AuthenticationWebFilter(reactiveAuthenticationManager())
|
||||
filter.setRequiresAuthenticationMatcher(
|
||||
ServerWebExchangeMatchers.pathMatchers("/api/v1/auth/login")
|
||||
)
|
||||
filter.setServerAuthenticationConverter(loginAuthenticationConverter())
|
||||
filter.setAuthenticationSuccessHandler { webFilterExchange, authentication ->
|
||||
val user = authentication.principal as User
|
||||
service.findAccountByNameOrEmail(user.username)
|
||||
.flatMap { account ->
|
||||
val vo = account.toAnotherObject(
|
||||
AuthorizeVO::class,
|
||||
mapOf(
|
||||
"token" to jwtUtils.createJwt(user, account.id!!, account.username),
|
||||
"expire" to DateUtils.dateToLocalDateTime(jwtUtils.expiresTime())
|
||||
)
|
||||
)
|
||||
writeJsonResponse(
|
||||
webFilterExchange.exchange,
|
||||
HttpStatus.OK,
|
||||
ApiResponse.success(vo)
|
||||
)
|
||||
}
|
||||
}
|
||||
filter.setAuthenticationFailureHandler { webFilterExchange, exception ->
|
||||
writeJsonResponse(
|
||||
webFilterExchange.exchange,
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
ApiResponse.unauthenticated(exception.message)
|
||||
)
|
||||
}
|
||||
return filter
|
||||
}
|
||||
|
||||
private fun loginAuthenticationConverter(): ServerAuthenticationConverter {
|
||||
return ServerAuthenticationConverter { exchange ->
|
||||
exchange.formData.flatMap { formData ->
|
||||
val username = formData.getFirst("username")
|
||||
val password = formData.getFirst("password")
|
||||
if (username != null && password != null) {
|
||||
Mono.just(
|
||||
UsernamePasswordAuthenticationToken(
|
||||
username,
|
||||
password
|
||||
)
|
||||
)
|
||||
} else {
|
||||
Mono.empty()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <reified T> writeJsonResponse(
|
||||
exchange: ServerWebExchange,
|
||||
status: HttpStatus,
|
||||
body: ApiResponse<T>
|
||||
): Mono<Void> {
|
||||
val response = exchange.response
|
||||
response.statusCode = status
|
||||
response.headers.contentType = MediaType.APPLICATION_JSON
|
||||
|
||||
val jsonString = Json.encodeToJsonElement(body).toString()
|
||||
val buffer = response.bufferFactory().wrap(jsonString.toByteArray())
|
||||
return response.writeWith(Mono.just(buffer))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package club.itstudio.itmanager.config
|
||||
|
||||
import club.itstudio.itmanager.utils.BigDecimalSerializer
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.modules.SerializersModule
|
||||
import kotlinx.serialization.modules.contextual
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
@Configuration
|
||||
class SerializationConfig {
|
||||
|
||||
@Bean
|
||||
fun kotlinxSerializationJson(): Json = Json {
|
||||
serializersModule = SerializersModule {
|
||||
contextual(BigDecimalSerializer)
|
||||
}
|
||||
ignoreUnknownKeys = true
|
||||
isLenient = true
|
||||
encodeDefaults = false
|
||||
prettyPrint = true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package club.itstudio.itmanager.controller
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/test")
|
||||
class TestController {
|
||||
|
||||
@GetMapping("/hello")
|
||||
fun test(): Mono<String> = Mono.just("Hello Kotlin WebFlux!")
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.enums.EmailType
|
||||
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
||||
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
||||
import club.itstudio.itmanager.service.v1.AuthorizationService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import jakarta.validation.Valid
|
||||
import jakarta.validation.constraints.Email
|
||||
import jakarta.validation.constraints.NotBlank
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import org.springframework.web.server.ServerWebExchange
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/auth")
|
||||
class AuthorizeController(
|
||||
private val service: AuthorizationService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@GetMapping("/ask-code")
|
||||
fun askVerifyCode(
|
||||
@RequestParam @NotBlank @Email email: String,
|
||||
@RequestParam type: EmailType,
|
||||
exchange: ServerWebExchange
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to ask code")
|
||||
val ip = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
||||
return service.askEmailVerifyCode(type, email, ip)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
fun emailRegister(@RequestBody @Valid vo: EmailRegisterVO): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to register")
|
||||
return service.registerEmailAccount(vo)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PostMapping("/reset")
|
||||
fun emailResetPassword(@RequestBody @Valid vo: PasswordResetVO): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to reset password")
|
||||
return service.resetEmailAccountPassword(vo)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@GetMapping("/logout")
|
||||
fun logout(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to logout")
|
||||
val authorization = exchange.request.headers.getFirst("Authorization")
|
||||
return Mono.fromCallable { service.invalidateJwt(authorization) }
|
||||
.map { success ->
|
||||
if (success) ApiResponse.success()
|
||||
else ApiResponse.logoutFailed()
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/relogin")
|
||||
fun relogin(exchange: ServerWebExchange): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to relogin")
|
||||
val authorization = exchange.request.headers.getFirst("Authorization")
|
||||
return service
|
||||
.jwtTokenRelogin(authorization)
|
||||
?.map { ApiResponse.success(it) }
|
||||
?: Mono.just(ApiResponse.failure(401, null, "Please login with password."))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.dto.EmailNotice
|
||||
import club.itstudio.itmanager.service.v1.EmailApiService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import jakarta.validation.Valid
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/email")
|
||||
class EmailController(
|
||||
private val service: EmailApiService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
// notification-settings/ GET/POST 获取/更新通知设置和邮箱列表
|
||||
@GetMapping("/notification-settings", "/notification-settings/")
|
||||
fun getNotificationSettings(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list notification settings")
|
||||
return service.getNotificationSettings()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("/notification-settings", "/notification-settings/")
|
||||
fun updateNotificationSettings(@RequestBody @Valid notice: EmailNotice): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update notification settings")
|
||||
return service.updateNotificationSettings(notice)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// toggle-email-status/ POST 切换邮箱启用/禁用状态
|
||||
@PostMapping("/toggle-email-status", "/toggle-email-status/")
|
||||
fun toggleEmailStatus(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to toggle email status")
|
||||
return service.toggleEmailStatus(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import club.itstudio.itmanager.entity.dto.FinanceRecord
|
||||
import club.itstudio.itmanager.service.v1.FinanceApiService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import jakarta.validation.Valid
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/finance")
|
||||
class FinanceController(
|
||||
private val service: FinanceApiService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
// finance/ GET/POST/PUT/DELETE 财务记录 CRUD 操作
|
||||
@GetMapping("", "/")
|
||||
fun getFinanceRecords(
|
||||
@RequestParam(defaultValue = "1") pageNum: Long,
|
||||
@RequestParam(defaultValue = "10") pageSize: Long,
|
||||
@RequestParam(required = false) keyword: String?,
|
||||
@RequestParam(required = false) type: String?,
|
||||
@RequestParam(required = false) start: String?,
|
||||
@RequestParam(required = false) end: String?,
|
||||
@RequestParam(required = false) vendor: String?,
|
||||
@RequestParam(required = false) itemId: Long?
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list finance records")
|
||||
val page = Page<FinanceRecord>(pageNum, pageSize)
|
||||
return service.getFinanceRecords(page, keyword, type, start, end, vendor, itemId)
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("", "/")
|
||||
fun createFinanceRecord(@RequestBody @Valid record: FinanceRecord): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create finance record")
|
||||
return service.createFinanceRecord(record)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("", "/")
|
||||
fun updateFinanceRecord(@RequestBody @Valid record: FinanceRecord): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update finance record")
|
||||
return service.updateFinanceRecord(record)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("", "/")
|
||||
fun deleteFinanceRecord(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete finance record")
|
||||
return service.deleteFinanceRecord(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// finance/{id}/upload_images/ POST 上传财务凭证图片
|
||||
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
|
||||
fun uploadImages(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestPart("files") files: Flux<FilePart>
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to upload images for finance record {}", id)
|
||||
return service.uploadImages(id, files)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// finance/{id}/ DELETE 删除财务记录(发送邮件通知)
|
||||
@DeleteMapping("/{id}", "/{id}/")
|
||||
fun deleteById(@PathVariable("id") id: Long): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete finance record {} with email notification", id)
|
||||
return service.deleteById(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// finance/categories/ GET/POST/PUT/DELETE 财务分类 CRUD 操作
|
||||
@GetMapping("/categories", "/categories/")
|
||||
fun getFinanceCategories(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list finance categories")
|
||||
return service.getFinanceCategories()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("/categories", "/categories/")
|
||||
fun createFinanceCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create finance category")
|
||||
return service.createFinanceCategory(category)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("/categories", "/categories/")
|
||||
fun updateFinanceCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update finance category")
|
||||
return service.updateFinanceCategory(category)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("/categories", "/categories/")
|
||||
fun deleteFinanceCategory(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete finance category")
|
||||
return service.deleteFinanceCategory(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import club.itstudio.itmanager.entity.dto.Item
|
||||
import club.itstudio.itmanager.service.v1.ItemsApiService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import jakarta.validation.Valid
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/items")
|
||||
class ItemsController(
|
||||
private val service: ItemsApiService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
// items/ GET/POST/PUT/DELETE 物品 CRUD 操作
|
||||
@GetMapping("", "/")
|
||||
fun getItems(
|
||||
@RequestParam(defaultValue = "1") pageNum: Long,
|
||||
@RequestParam(defaultValue = "10") pageSize: Long,
|
||||
@RequestParam(required = false) keyword: String?,
|
||||
@RequestParam(required = false) status: String?
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list items")
|
||||
val page = Page<Item>(pageNum, pageSize)
|
||||
return service.getItems(page, keyword, status)
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("", "/")
|
||||
fun createItem(@RequestBody @Valid item: Item): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create item")
|
||||
return service.createItem(item)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("", "/")
|
||||
fun updateItem(@RequestBody @Valid item: Item): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update item")
|
||||
return service.updateItem(item)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("", "/")
|
||||
fun deleteItem(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete item")
|
||||
return service.deleteItem(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/{id}/upload_images/ POST 上传物品图片
|
||||
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
|
||||
fun uploadImages(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestPart("files") files: Flux<FilePart>
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to upload images for item {}", id)
|
||||
return service.uploadImages(id, files)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/{id}/set_primary_image/ POST 设置主图片
|
||||
@PostMapping("/{id}/set_primary_image", "/{id}/set_primary_image/")
|
||||
fun setPrimaryImage(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestParam imageId: Long
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to set primary image for item {}", id)
|
||||
return service.setPrimaryImage(id, imageId)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/{id}/borrow/ POST 借用物品
|
||||
@PostMapping("/{id}/borrow", "/{id}/borrow/")
|
||||
fun borrowItem(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestParam(defaultValue = "1") quantity: Int
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to borrow item {}", id)
|
||||
return service.borrowItem(id, quantity)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/{id}/return_item/ POST 归还物品
|
||||
@PostMapping("/{id}/return_item", "/{id}/return_item/")
|
||||
fun returnItem(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestParam(defaultValue = "1") quantity: Int
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to return item {}", id)
|
||||
return service.returnItem(id, quantity)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/available/ GET 获取可用物品列表
|
||||
@GetMapping("/available", "/available/")
|
||||
fun getAvailableItems(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list available items")
|
||||
return service.getAvailableItems()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
// items/in_use/ GET 获取使用中的物品列表
|
||||
@GetMapping("/in_use", "/in_use/")
|
||||
fun getInUseItems(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list in-use items")
|
||||
return service.getInUseItems()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
// items/categories/ GET/POST/PUT/DELETE 物品类别 CRUD 操作
|
||||
@GetMapping("/categories", "/categories/")
|
||||
fun getItemCategories(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list item categories")
|
||||
return service.getItemCategories()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("/categories", "/categories/")
|
||||
fun createItemCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create item category")
|
||||
return service.createItemCategory(category)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("/categories", "/categories/")
|
||||
fun updateItemCategory(@RequestBody @Valid category: Category): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update item category")
|
||||
return service.updateItemCategory(category)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("/categories", "/categories/")
|
||||
fun deleteItemCategory(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete item category")
|
||||
return service.deleteItemCategory(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// items/images/ GET/POST/PUT/DELETE 物品图片 CRUD 操作
|
||||
@GetMapping("/images", "/images/")
|
||||
fun getItemImages(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list item images")
|
||||
return service.getItemImages()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("/images", "/images/")
|
||||
fun createItemImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create item image")
|
||||
return service.createItemImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("/images", "/images/")
|
||||
fun updateItemImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update item image")
|
||||
return service.updateItemImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("/images", "/images/")
|
||||
fun deleteItemImage(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete item image")
|
||||
return service.deleteItemImage(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.service.v1.ProofImagesApiService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import jakarta.validation.Valid
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/proof-images")
|
||||
class ProofImagesController(
|
||||
private val service: ProofImagesApiService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
// proof-images/ GET/POST/PUT/DELETE 财务凭证图片 CRUD 操作
|
||||
@GetMapping("", "/")
|
||||
fun getProofImages(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list proof images")
|
||||
return service.getProofImages()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("", "/")
|
||||
fun createProofImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create proof image")
|
||||
return service.createProofImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("", "/")
|
||||
fun updateProofImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update proof image")
|
||||
return service.updateProofImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("", "/")
|
||||
fun deleteProofImage(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete proof image")
|
||||
return service.deleteProofImage(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// proof-images/{id}/ DELETE 删除凭证图片(自动删除物理文件)
|
||||
@DeleteMapping("/{id}", "/{id}/")
|
||||
fun deleteById(@PathVariable("id") id: Long): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete proof image {}", id)
|
||||
return service.deleteProofImage(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package club.itstudio.itmanager.controller.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.entity.dto.BorrowRecord
|
||||
import club.itstudio.itmanager.service.v1.UsagesApiService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import jakarta.validation.Valid
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.validation.annotation.Validated
|
||||
import org.springframework.web.bind.annotation.*
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Validated
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/usages")
|
||||
class UsagesController(
|
||||
private val service: UsagesApiService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
// usages/ GET/POST/PUT/DELETE 物品使用记录 CRUD 操作
|
||||
@GetMapping("", "/")
|
||||
fun getUsages(
|
||||
@RequestParam(defaultValue = "1") pageNum: Long,
|
||||
@RequestParam(defaultValue = "10") pageSize: Long,
|
||||
@RequestParam(required = false) keyword: String?,
|
||||
@RequestParam(required = false) status: String?
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list usages")
|
||||
val page = Page<BorrowRecord>(pageNum, pageSize)
|
||||
return service.getUsages(page, keyword, status)
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("", "/")
|
||||
fun createUsage(@RequestBody @Valid record: BorrowRecord): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create usage")
|
||||
return service.createUsage(record)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("", "/")
|
||||
fun updateUsage(@RequestBody @Valid record: BorrowRecord): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update usage")
|
||||
return service.updateUsage(record)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("", "/")
|
||||
fun deleteUsage(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete usage")
|
||||
return service.deleteUsage(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// usages/{id}/upload_images/ POST 上传使用记录图片
|
||||
@PostMapping("/{id}/upload_images", "/{id}/upload_images/")
|
||||
fun uploadImages(
|
||||
@PathVariable("id") id: Long,
|
||||
@RequestPart("files") files: Flux<FilePart>
|
||||
): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to upload images for usage {}", id)
|
||||
return service.uploadImages(id, files)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
// usages/current/ GET 获取当前使用中的记录
|
||||
@GetMapping("/current", "/current/")
|
||||
fun getCurrentUsages(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list current usages")
|
||||
return service.getCurrentUsages()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
// usages/by_user/ GET 根据用户姓名获取使用记录
|
||||
@GetMapping("/by_user", "/by_user/")
|
||||
fun getUsagesByUser(@RequestParam(required = false) name: String?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list usages by user")
|
||||
return service.getUsagesByUser(name)
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
// usages/images/ GET/POST/PUT/DELETE 使用记录图片 CRUD 操作
|
||||
@GetMapping("/images", "/images/")
|
||||
fun getUsageImages(): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to list usage images")
|
||||
return service.getUsageImages()
|
||||
.map { ApiResponse.success(it) }
|
||||
}
|
||||
|
||||
@PostMapping("/images", "/images/")
|
||||
fun createUsageImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to create usage image")
|
||||
return service.createUsageImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@PutMapping("/images", "/images/")
|
||||
fun updateUsageImage(@RequestBody @Valid attachment: Attachment): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to update usage image")
|
||||
return service.updateUsageImage(attachment)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
|
||||
@DeleteMapping("/images", "/images/")
|
||||
fun deleteUsageImage(@RequestParam(required = false) id: Long?): Mono<ApiResponse<Any?>> {
|
||||
logger.info("Trying to delete usage image")
|
||||
return service.deleteUsageImage(id)
|
||||
.map(Const::messageHandler)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package club.itstudio.itmanager.entity
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
|
||||
@Serializable
|
||||
data class ApiResponse<T>(
|
||||
val code: Int,
|
||||
val data: T,
|
||||
val message: String
|
||||
) {
|
||||
companion object {
|
||||
fun <T> success(data: T, message: String = "Success"): ApiResponse<T> {
|
||||
return ApiResponse(200, data, message)
|
||||
}
|
||||
|
||||
// 针对无 data 返回的情况,统一使用 Any?
|
||||
fun success(message: String = "Success"): ApiResponse<Any?> {
|
||||
return ApiResponse(200, null, message)
|
||||
}
|
||||
|
||||
fun <T> failure(code: Int = 401, data: T, message: String?): ApiResponse<T> {
|
||||
return ApiResponse(code, data, message ?: "Failure")
|
||||
}
|
||||
|
||||
fun unauthenticated(message: String?) =
|
||||
failure(401, null, message)
|
||||
|
||||
fun forbidden(message: String?) =
|
||||
failure(403, null, message)
|
||||
|
||||
fun logoutFailed(message: String = ""): ApiResponse<Any?> {
|
||||
val formatMessage = if (message.isBlank()) "" else ": $message"
|
||||
return failure(400, null, "Logout Failed$formatMessage")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T> ApiResponse<T>.toJsonString(): String {
|
||||
return Json.encodeToString(this)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package club.itstudio.itmanager.entity
|
||||
|
||||
import kotlin.reflect.KClass
|
||||
import kotlin.reflect.KMutableProperty1
|
||||
import kotlin.reflect.KProperty1
|
||||
import kotlin.reflect.full.createInstance
|
||||
import kotlin.reflect.full.declaredMemberProperties
|
||||
import kotlin.reflect.full.memberProperties
|
||||
import kotlin.reflect.jvm.isAccessible
|
||||
import kotlin.reflect.jvm.javaField
|
||||
|
||||
interface DataCopy {
|
||||
fun <T : Any> toAnotherObject(
|
||||
toClass: KClass<T>,
|
||||
otherProperties: Map<String, Any?> = emptyMap()
|
||||
): T {
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val sourceProps = this::class.memberProperties
|
||||
.associate { it.name to (it as KProperty1<Any, *>).get(this) }
|
||||
return try {
|
||||
val vo = toClass.createInstance()
|
||||
for (prop in toClass.declaredMemberProperties) {
|
||||
val value = when {
|
||||
sourceProps.containsKey(prop.name) -> sourceProps[prop.name]
|
||||
otherProperties.containsKey(prop.name) -> otherProperties[prop.name]
|
||||
else -> continue
|
||||
}
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val mutableProp = prop as? KMutableProperty1<Any, Any?>
|
||||
if (mutableProp != null) {
|
||||
mutableProp.isAccessible = true
|
||||
mutableProp.set(vo, value)
|
||||
} else {
|
||||
val field = prop.javaField ?: continue
|
||||
field.isAccessible = true
|
||||
field.set(vo, value)
|
||||
}
|
||||
}
|
||||
vo
|
||||
} catch (e: ReflectiveOperationException) {
|
||||
throw RuntimeException(
|
||||
"Failed to instantiate ${toClass.simpleName}. Does it have a no-arg constructor?", e
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("account")
|
||||
data class Account(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val username: String = "",
|
||||
val password: String = "",
|
||||
val email: String? = null,
|
||||
val fullName: String? = null,
|
||||
val isActive: Boolean = true,
|
||||
val isStaff: Boolean = false,
|
||||
val createdAt: LocalDateTime? = null,
|
||||
val updatedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,23 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("attachments")
|
||||
data class Attachment(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val relatedTable: String? = null,
|
||||
val relatedId: Long? = null,
|
||||
val fileName: String? = null,
|
||||
val filePath: String? = null,
|
||||
val fileSize: Long? = null,
|
||||
val contentType: String? = null,
|
||||
val uploadedBy: Long? = null,
|
||||
val uploadedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,26 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("borrow_records")
|
||||
data class BorrowRecord(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val itemId: Long = 0,
|
||||
val borrower: String = "",
|
||||
val quantity: Int = 1,
|
||||
val borrowDate: LocalDateTime? = null,
|
||||
val dueDate: LocalDateTime? = null,
|
||||
val returnDate: LocalDateTime? = null,
|
||||
val status: String = "BORROWED", // BORROWED / RETURNED / OVERDUE / CANCELED
|
||||
val approver: String? = null,
|
||||
val note: String? = null,
|
||||
val createdAt: LocalDateTime? = null,
|
||||
val updatedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,20 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("categories")
|
||||
data class Category(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val name: String = "",
|
||||
val parentId: Long? = null,
|
||||
val description: String? = null,
|
||||
val createdAt: LocalDateTime? = null,
|
||||
val updatedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,24 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("email_notices")
|
||||
data class EmailNotice(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val name: String? = null,
|
||||
val targetEmails: String? = null,
|
||||
val subject: String? = null,
|
||||
val body: String? = null,
|
||||
val enabled: Boolean = true,
|
||||
val scheduleCron: String? = null,
|
||||
val lastSentAt: LocalDateTime? = null,
|
||||
val createdAt: LocalDateTime? = null,
|
||||
val updatedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import club.itstudio.itmanager.entity.enums.EmailType
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class EmailVerificationMsg(
|
||||
val email: String,
|
||||
val type: EmailType,
|
||||
val code: String
|
||||
)
|
||||
@@ -0,0 +1,28 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import club.itstudio.itmanager.entity.enums.FinanceRecordType
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Contextual
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.math.BigDecimal
|
||||
|
||||
@Serializable
|
||||
@TableName("finance_records")
|
||||
data class FinanceRecord(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val recordNo: String? = null,
|
||||
val type: FinanceRecordType = FinanceRecordType.OTHER,
|
||||
val relatedItemId: Long? = null,
|
||||
val amount: @Contextual BigDecimal = BigDecimal.ZERO,
|
||||
val currency: String = "CNY",
|
||||
val vendor: String? = null,
|
||||
val occurredAt: LocalDateTime? = null,
|
||||
val recordedBy: Long? = null,
|
||||
val note: String? = null,
|
||||
val createdAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,36 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import kotlinx.datetime.LocalDate
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Contextual
|
||||
import kotlinx.serialization.Serializable
|
||||
import java.math.BigDecimal
|
||||
|
||||
@Serializable
|
||||
@TableName("items")
|
||||
data class Item(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val code: String = "",
|
||||
val name: String = "",
|
||||
val categoryId: Long? = null,
|
||||
val model: String? = null,
|
||||
val brand: String? = null,
|
||||
val location: String? = null,
|
||||
val totalQuantity: Int = 0,
|
||||
val availableQuantity: Int = 0,
|
||||
val unit: String = "件",
|
||||
val price: @Contextual BigDecimal? = null,
|
||||
val purchaseDate: LocalDate? = null,
|
||||
val supplier: String? = null,
|
||||
val status: String = "normal",
|
||||
val description: String? = null,
|
||||
val imagePath: String? = null,
|
||||
val createdBy: Long? = null,
|
||||
val createdAt: LocalDateTime? = null,
|
||||
val updatedAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,25 @@
|
||||
package club.itstudio.itmanager.entity.dto
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType
|
||||
import com.baomidou.mybatisplus.annotation.TableId
|
||||
import com.baomidou.mybatisplus.annotation.TableName
|
||||
import club.itstudio.itmanager.entity.DataCopy
|
||||
import club.itstudio.itmanager.entity.enums.TransactionType
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@TableName("item_transactions")
|
||||
data class ItemTransaction(
|
||||
@TableId(type = IdType.AUTO)
|
||||
val id: Long? = null,
|
||||
val itemId: Long = 0,
|
||||
val transType: TransactionType = TransactionType.IN,
|
||||
val quantity: Int = 0,
|
||||
val fromLocation: String? = null,
|
||||
val toLocation: String? = null,
|
||||
val relatedId: Long? = null,
|
||||
val operatorId: Long? = null,
|
||||
val note: String? = null,
|
||||
val createdAt: LocalDateTime? = null
|
||||
) : DataCopy
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.itstudio.itmanager.entity.enums
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class AccountRole {
|
||||
@SerialName("user")
|
||||
USER,
|
||||
@SerialName("admin")
|
||||
ADMIN;
|
||||
|
||||
companion object {
|
||||
fun fromIsStaff(isStaff: Boolean): AccountRole = if (isStaff) ADMIN else USER
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.itstudio.itmanager.entity.enums
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class EmailType {
|
||||
@SerialName("register")
|
||||
REGISTER,
|
||||
|
||||
@SerialName("reset")
|
||||
RESET,
|
||||
|
||||
@SerialName("finance-delete")
|
||||
FINANCE_DELETE,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package club.itstudio.itmanager.entity.enums
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class FinanceRecordType {
|
||||
@SerialName("PURCHASE")
|
||||
PURCHASE,
|
||||
|
||||
@SerialName("REFUND")
|
||||
REFUND,
|
||||
|
||||
@SerialName("REPAIR")
|
||||
REPAIR,
|
||||
|
||||
@SerialName("DEPRECIATION")
|
||||
DEPRECIATION,
|
||||
|
||||
@SerialName("OTHER")
|
||||
OTHER,
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package club.itstudio.itmanager.entity.enums
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
enum class TransactionType {
|
||||
@SerialName("IN")
|
||||
IN,
|
||||
|
||||
@SerialName("OUT")
|
||||
OUT,
|
||||
|
||||
@SerialName("ADJUST")
|
||||
ADJUST,
|
||||
|
||||
@SerialName("TRANSFER")
|
||||
TRANSFER,
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package club.itstudio.itmanager.entity.vo.request
|
||||
|
||||
import jakarta.validation.constraints.Email
|
||||
import jakarta.validation.constraints.Pattern
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.hibernate.validator.constraints.Length
|
||||
|
||||
@Serializable
|
||||
data class EmailRegisterVO(
|
||||
@param:Email
|
||||
val email: String = "",
|
||||
@param:Length(min = 6, max = 6)
|
||||
val code: String? = null,
|
||||
@param:Pattern(regexp = "^[a-zA-Z0-9\\u4e00-\\u9fa5]+$")
|
||||
@param:Length(min = 4, max = 16)
|
||||
val username: String = "",
|
||||
@param:Length(min = 6, max = 20)
|
||||
val password: String = "",
|
||||
)
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package club.itstudio.itmanager.entity.vo.request
|
||||
|
||||
import jakarta.validation.constraints.Email
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.hibernate.validator.constraints.Length
|
||||
|
||||
@Serializable
|
||||
data class PasswordResetVO(
|
||||
@param:Email
|
||||
val email: String = "",
|
||||
@param:Length(min = 6, max = 6)
|
||||
val code: String? = null,
|
||||
@param:Length(min = 6, max = 20)
|
||||
val password: String = "",
|
||||
)
|
||||
@@ -0,0 +1,13 @@
|
||||
package club.itstudio.itmanager.entity.vo.response
|
||||
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class AuthorizeVO(
|
||||
val username: String = "",
|
||||
val role: String = "",
|
||||
val token: String = "",
|
||||
val expire: LocalDateTime = getCurrentDateTime(),
|
||||
)
|
||||
@@ -0,0 +1,11 @@
|
||||
package club.itstudio.itmanager.entity.vo.response
|
||||
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class ReloginVO(
|
||||
val token: String = "",
|
||||
val expire: LocalDateTime = getCurrentDateTime(),
|
||||
)
|
||||
@@ -0,0 +1,23 @@
|
||||
package club.itstudio.itmanager.exception
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import jakarta.validation.ValidationException
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice
|
||||
|
||||
@RestControllerAdvice
|
||||
class ValidationController {
|
||||
|
||||
private val log = LoggerFactory.getLogger(ValidationController::class.java)
|
||||
|
||||
@ExceptionHandler(ValidationException::class)
|
||||
fun validationException(e: Exception): ApiResponse<out String?> {
|
||||
log.warn("Resolve [${e.javaClass.name}: ${e.message}]")
|
||||
return ApiResponse.failure(
|
||||
400,
|
||||
null,
|
||||
"parameter validation error"
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package club.itstudio.itmanager.filter
|
||||
|
||||
import org.springframework.context.annotation.Bean
|
||||
import org.springframework.context.annotation.Configuration
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.http.HttpMethod
|
||||
import org.springframework.web.cors.CorsConfiguration
|
||||
import org.springframework.web.cors.reactive.CorsWebFilter
|
||||
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource
|
||||
|
||||
@Configuration
|
||||
class CorsFilter {
|
||||
|
||||
@Bean
|
||||
fun corsWebFilter(): CorsWebFilter {
|
||||
val config = CorsConfiguration().apply {
|
||||
allowedOriginPatterns = listOf("*")
|
||||
allowedMethods = listOf(
|
||||
HttpMethod.GET.name(),
|
||||
HttpMethod.POST.name(),
|
||||
HttpMethod.PUT.name(),
|
||||
HttpMethod.DELETE.name(),
|
||||
HttpMethod.OPTIONS.name()
|
||||
)
|
||||
allowedHeaders = listOf(
|
||||
HttpHeaders.AUTHORIZATION,
|
||||
HttpHeaders.CONTENT_TYPE
|
||||
)
|
||||
allowCredentials = true
|
||||
}
|
||||
|
||||
val source = UrlBasedCorsConfigurationSource().apply {
|
||||
registerCorsConfiguration("/**", config)
|
||||
}
|
||||
|
||||
return CorsWebFilter(source)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package club.itstudio.itmanager.filter
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import club.itstudio.itmanager.entity.toJsonString
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.core.annotation.Order
|
||||
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
|
||||
import org.springframework.http.HttpStatus
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.stereotype.Component
|
||||
import org.springframework.web.server.ServerWebExchange
|
||||
import org.springframework.web.server.WebFilter
|
||||
import org.springframework.web.server.WebFilterChain
|
||||
import reactor.core.publisher.Mono
|
||||
import java.time.Duration
|
||||
|
||||
@Component
|
||||
@Order(Const.FLOW_LIMIT_ORDER)
|
||||
class FlowLimitFilter(
|
||||
private val template: ReactiveStringRedisTemplate,
|
||||
|
||||
@param:Value($$"${app.flow-limit.count}")
|
||||
private val limitCount: Int,
|
||||
@param:Value($$"${app.flow-limit.limit-time}")
|
||||
private val limitTime: Int,
|
||||
@param:Value($$"${app.flow-limit.ban-time}")
|
||||
private val expireTime: Int,
|
||||
) : WebFilter {
|
||||
|
||||
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
|
||||
val address = exchange.request.remoteAddress?.address?.hostAddress ?: "unknown"
|
||||
|
||||
return tryCount(address).flatMap { allowed ->
|
||||
if (allowed) {
|
||||
chain.filter(exchange)
|
||||
} else {
|
||||
writeBlockMessage(exchange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun writeBlockMessage(exchange: ServerWebExchange): Mono<Void> {
|
||||
val response = exchange.response
|
||||
response.statusCode = HttpStatus.FORBIDDEN
|
||||
response.headers.contentType = MediaType.APPLICATION_JSON
|
||||
val buffer = response.bufferFactory()
|
||||
.wrap(ApiResponse.forbidden("Too many requests").toJsonString().toByteArray())
|
||||
return response.writeWith(Mono.just(buffer))
|
||||
}
|
||||
|
||||
private fun tryCount(ip: String): Mono<Boolean> {
|
||||
val blockKey = Const.FLOW_LIMIT_BLOCK + ip
|
||||
val counterKey = Const.FLOW_LIMIT_COUNTER + ip
|
||||
|
||||
return template.hasKey(blockKey).flatMap { isBlocked ->
|
||||
if (isBlocked) {
|
||||
Mono.just(false)
|
||||
} else {
|
||||
template.opsForValue().increment(counterKey).flatMap { count ->
|
||||
if (count == 1L) {
|
||||
template.expire(
|
||||
counterKey,
|
||||
Duration.ofSeconds(limitTime.toLong())
|
||||
).thenReturn(true)
|
||||
} else if (count > limitCount) {
|
||||
template.opsForValue()
|
||||
.set(
|
||||
blockKey,
|
||||
"1",
|
||||
Duration.ofSeconds(expireTime.toLong())
|
||||
)
|
||||
.thenReturn(false)
|
||||
} else {
|
||||
Mono.just(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package club.itstudio.itmanager.filter
|
||||
|
||||
import club.itstudio.itmanager.utils.JwtUtils
|
||||
import org.springframework.http.HttpHeaders
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
|
||||
import org.springframework.security.core.context.ReactiveSecurityContextHolder
|
||||
import org.springframework.stereotype.Component
|
||||
import org.springframework.web.server.ServerWebExchange
|
||||
import org.springframework.web.server.WebFilter
|
||||
import org.springframework.web.server.WebFilterChain
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
@Component
|
||||
class JwtAuthorizeFilter(
|
||||
private val utils: JwtUtils
|
||||
) : WebFilter {
|
||||
|
||||
override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> {
|
||||
val authorization = exchange.request.headers.getFirst(HttpHeaders.AUTHORIZATION)
|
||||
val jwt = utils.resolveJwt(authorization)
|
||||
|
||||
return if (jwt != null) {
|
||||
val user = utils.toUser(jwt)
|
||||
val authentication = UsernamePasswordAuthenticationToken(
|
||||
user,
|
||||
null,
|
||||
user.authorities
|
||||
)
|
||||
exchange.attributes["id"] = utils.toId(jwt)
|
||||
|
||||
chain.filter(exchange)
|
||||
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(authentication))
|
||||
} else {
|
||||
chain.filter(exchange)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package club.itstudio.itmanager.listener
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
||||
import club.itstudio.itmanager.entity.enums.EmailType
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitHandler
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.mail.SimpleMailMessage
|
||||
import org.springframework.mail.javamail.JavaMailSender
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
@Component
|
||||
@RabbitListener(queues = ["mail"])
|
||||
class MailQueueListener(
|
||||
@param:Value($$"${spring.mail.username}")
|
||||
private val username: String,
|
||||
|
||||
private val json: Json,
|
||||
private val sender: JavaMailSender
|
||||
) {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
@RabbitHandler
|
||||
fun senderMailMessage(content: String) {
|
||||
val data = json.decodeFromString<EmailVerificationMsg>(content)
|
||||
val (email, type, code) = data
|
||||
|
||||
val message = when (type) {
|
||||
EmailType.REGISTER -> createMailMessage(
|
||||
"Welcome to Our Service",
|
||||
"Thank you for registering! Your verification code is: $code"
|
||||
+ "\nThis code is valid for 3 minutes.",
|
||||
email
|
||||
)
|
||||
|
||||
EmailType.RESET -> createMailMessage(
|
||||
"Password Reset Request",
|
||||
"You requested a password reset. Your verification code is: $code"
|
||||
+ "\nThis code is valid for 3 minutes.",
|
||||
email
|
||||
)
|
||||
|
||||
EmailType.FINANCE_DELETE -> createMailMessage(
|
||||
"Finance Record Deleted",
|
||||
"A finance record has been deleted. Record No: $code",
|
||||
email
|
||||
)
|
||||
}
|
||||
sender.send(message)
|
||||
logger.info("Email sent to $email.")
|
||||
}
|
||||
|
||||
fun createMailMessage(title: String, content: String, to: String): SimpleMailMessage {
|
||||
val message = SimpleMailMessage()
|
||||
message.subject = title
|
||||
message.text = content
|
||||
message.from = username
|
||||
message.setTo(to)
|
||||
return message
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.Account
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface AccountMapper : BaseMapper<Account>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface AttachmentMapper : BaseMapper<Attachment>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.BorrowRecord
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface BorrowRecordMapper : BaseMapper<BorrowRecord>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface CategoryMapper : BaseMapper<Category>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.EmailNotice
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface EmailNoticeMapper : BaseMapper<EmailNotice>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.FinanceRecord
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface FinanceRecordMapper : BaseMapper<FinanceRecord>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.Item
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface ItemMapper : BaseMapper<Item>
|
||||
@@ -0,0 +1,8 @@
|
||||
package club.itstudio.itmanager.mapper
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper
|
||||
import club.itstudio.itmanager.entity.dto.ItemTransaction
|
||||
import org.apache.ibatis.annotations.Mapper
|
||||
|
||||
@Mapper
|
||||
interface ItemTransactionMapper : BaseMapper<ItemTransaction>
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package club.itstudio.itmanager.mapper.typehandler
|
||||
|
||||
import kotlinx.datetime.LocalDateTime
|
||||
import kotlinx.datetime.toJavaLocalDateTime
|
||||
import kotlinx.datetime.toKotlinLocalDateTime
|
||||
import org.apache.ibatis.type.BaseTypeHandler
|
||||
import org.apache.ibatis.type.JdbcType
|
||||
import org.apache.ibatis.type.MappedJdbcTypes
|
||||
import org.apache.ibatis.type.MappedTypes
|
||||
import java.sql.CallableStatement
|
||||
import java.sql.PreparedStatement
|
||||
import java.sql.ResultSet
|
||||
|
||||
@MappedTypes(LocalDateTime::class)
|
||||
@MappedJdbcTypes(JdbcType.TIMESTAMP)
|
||||
class TimeTypeHandler : BaseTypeHandler<LocalDateTime>() {
|
||||
override fun setNonNullParameter(
|
||||
ps: PreparedStatement,
|
||||
i: Int,
|
||||
parameter: LocalDateTime,
|
||||
jdbcType: JdbcType?
|
||||
) {
|
||||
ps.setObject(i, parameter.toJavaLocalDateTime())
|
||||
}
|
||||
|
||||
override fun getNullableResult(
|
||||
rs: ResultSet,
|
||||
columnName: String
|
||||
): LocalDateTime? =
|
||||
rs.getTimestamp(columnName)
|
||||
?.toLocalDateTime()
|
||||
?.toKotlinLocalDateTime()
|
||||
|
||||
override fun getNullableResult(
|
||||
rs: ResultSet,
|
||||
columnIndex: Int
|
||||
): LocalDateTime? =
|
||||
rs.getTimestamp(columnIndex)
|
||||
?.toLocalDateTime()
|
||||
?.toKotlinLocalDateTime()
|
||||
|
||||
override fun getNullableResult(
|
||||
cs: CallableStatement,
|
||||
columnIndex: Int
|
||||
): LocalDateTime? =
|
||||
cs.getTimestamp(columnIndex)
|
||||
?.toLocalDateTime()
|
||||
?.toKotlinLocalDateTime()
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Account
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import org.springframework.security.core.userdetails.ReactiveUserDetailsService
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface AccountService : IService<Account>, ReactiveUserDetailsService {
|
||||
fun findAccountById(id: Long): Mono<Account>
|
||||
fun findAccountByNameOrEmail(text: String): Mono<Account>
|
||||
fun findAccountByName(username: String): Mono<Account>
|
||||
fun findAccountByEmail(email: String): Mono<Account>
|
||||
fun existAccountByName(username: String): Mono<Boolean>
|
||||
fun existAccountByEmail(email: String): Mono<Boolean>
|
||||
fun resetPasswordByEmail(email: String, encodedPassword: String): Mono<Void>
|
||||
fun createAccount(account: Account): Mono<Boolean>
|
||||
|
||||
// fun batchInsert(accounts: List<Account>): Mono<Boolean>
|
||||
// fun replaceAll(accounts: List<Account>): Mono<Boolean>
|
||||
// fun exportAll(): Mono<List<Account>>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface AttachmentService : IService<Attachment> {
|
||||
fun getAttachmentById(id: Long): Mono<Attachment>
|
||||
fun listByRelated(relatedTable: String, relatedId: Long): Mono<List<Attachment>>
|
||||
fun listByUploader(uploadedBy: Long): Mono<List<Attachment>>
|
||||
fun createAttachment(attachment: Attachment): Mono<Boolean>
|
||||
fun updateAttachment(attachment: Attachment): Mono<Boolean>
|
||||
fun deleteAttachment(id: Long): Mono<Boolean>
|
||||
fun deleteByRelated(relatedTable: String, relatedId: Long): Mono<Boolean>
|
||||
fun exportAllAttachments(): Mono<List<Attachment>>
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.BorrowRecord
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface BorrowRecordService : IService<BorrowRecord> {
|
||||
fun getBorrowRecordById(id: Long): Mono<BorrowRecord>
|
||||
fun pageUsages(page: Page<BorrowRecord>, keyword: String?, status: String?): Mono<Page<BorrowRecord>>
|
||||
fun listByItem(itemId: Long): Mono<List<BorrowRecord>>
|
||||
fun listByBorrower(borrower: String): Mono<List<BorrowRecord>>
|
||||
fun listByStatus(status: String): Mono<List<BorrowRecord>>
|
||||
fun listOverdueRecords(): Mono<List<BorrowRecord>>
|
||||
fun createBorrowRecord(record: BorrowRecord): Mono<Boolean>
|
||||
fun updateBorrowRecord(record: BorrowRecord): Mono<Boolean>
|
||||
fun deleteBorrowRecord(id: Long): Mono<Boolean>
|
||||
fun exportAllBorrowRecords(): Mono<List<BorrowRecord>>
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface CategoryService : IService<Category> {
|
||||
fun getCategoryById(id: Long): Mono<Category>
|
||||
fun listAllCategories(): Mono<List<Category>>
|
||||
fun listByParentId(parentId: Long): Mono<List<Category>>
|
||||
fun createCategory(category: Category): Mono<Boolean>
|
||||
fun updateCategory(category: Category): Mono<Boolean>
|
||||
fun deleteCategory(id: Long): Mono<Boolean>
|
||||
fun exportAllCategories(): Mono<List<Category>>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.EmailNotice
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface EmailNoticeService : IService<EmailNotice> {
|
||||
fun getEmailNoticeById(id: Long): Mono<EmailNotice>
|
||||
fun listAllNotices(): Mono<List<EmailNotice>>
|
||||
fun listEnabledNotices(): Mono<List<EmailNotice>>
|
||||
fun createEmailNotice(notice: EmailNotice): Mono<Boolean>
|
||||
fun updateEmailNotice(notice: EmailNotice): Mono<Boolean>
|
||||
fun deleteEmailNotice(id: Long): Mono<Boolean>
|
||||
fun toggleEnabled(id: Long): Mono<Boolean>
|
||||
fun exportAllEmailNotices(): Mono<List<EmailNotice>>
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.Paths
|
||||
import java.util.*
|
||||
|
||||
@Service
|
||||
class FileStorageService(
|
||||
@Value($$"${app.file.data-path}")
|
||||
private val dataPath: String
|
||||
) {
|
||||
data class StoredFile(
|
||||
val path: Path,
|
||||
val size: Long
|
||||
)
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun saveImage(file: FilePart, subDir: String, entityId: Long): Mono<StoredFile> {
|
||||
val directory = Paths.get(dataPath, Const.FILE_DIR_IMAGE, subDir, entityId.toString())
|
||||
val savedName = generateSafeFileName(file.filename())
|
||||
val target = directory.resolve(savedName)
|
||||
return Mono.fromCallable<Void> { Files.createDirectories(directory); null }
|
||||
.then(file.transferTo(target))
|
||||
.then(Mono.fromCallable { StoredFile(target, Files.size(target)) })
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
}
|
||||
|
||||
fun deleteFile(path: String?): Mono<Void> {
|
||||
if (path.isNullOrBlank()) return Mono.empty()
|
||||
return Mono.fromRunnable<Void> {
|
||||
try {
|
||||
Files.deleteIfExists(Paths.get(path))
|
||||
} catch (e: IOException) {
|
||||
logger.warn("Failed to delete file: {}", path, e)
|
||||
}
|
||||
}.subscribeOn(Schedulers.boundedElastic())
|
||||
}
|
||||
|
||||
fun generateSafeFileName(original: String?): String {
|
||||
val extension = original
|
||||
?.substringAfterLast('.')
|
||||
?.lowercase()
|
||||
?.takeIf {
|
||||
it.isNotBlank() &&
|
||||
it.length <= 10 &&
|
||||
it.all { ch -> ch.isLetterOrDigit() }
|
||||
}
|
||||
return if (extension != null) "${UUID.randomUUID()}.$extension" else UUID.randomUUID().toString()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.FinanceRecord
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface FinanceRecordService : IService<FinanceRecord> {
|
||||
fun getFinanceRecordById(id: Long): Mono<FinanceRecord>
|
||||
fun pageFinanceRecords(
|
||||
page: Page<FinanceRecord>,
|
||||
keyword: String?,
|
||||
type: String?,
|
||||
start: String?,
|
||||
end: String?,
|
||||
vendor: String?,
|
||||
itemId: Long?
|
||||
): Mono<Page<FinanceRecord>>
|
||||
fun listByType(type: String): Mono<List<FinanceRecord>>
|
||||
fun listByDateRange(start: String, end: String): Mono<List<FinanceRecord>>
|
||||
fun listByVendor(vendor: String): Mono<List<FinanceRecord>>
|
||||
fun listByRelatedItem(itemId: Long): Mono<List<FinanceRecord>>
|
||||
fun createFinanceRecord(record: FinanceRecord): Mono<Boolean>
|
||||
fun updateFinanceRecord(record: FinanceRecord): Mono<Boolean>
|
||||
fun deleteFinanceRecord(id: Long): Mono<Boolean>
|
||||
fun exportAllFinanceRecords(): Mono<List<FinanceRecord>>
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.Item
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface ItemService : IService<Item> {
|
||||
fun pageItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>>
|
||||
fun getItemById(id: Long): Mono<Item>
|
||||
fun listAvailableItems(): Mono<List<Item>>
|
||||
fun listInUseItems(): Mono<List<Item>>
|
||||
fun listItemsByCategory(categoryId: Long): Mono<List<Item>>
|
||||
fun createItem(item: Item): Mono<Boolean>
|
||||
fun updateItem(item: Item): Mono<Boolean>
|
||||
fun removeItemById(id: Long): Mono<Boolean>
|
||||
fun setPrimaryImage(id: Long, imagePath: String): Mono<Boolean>
|
||||
fun borrowItem(id: Long, quantity: Int): Mono<Boolean>
|
||||
fun returnItem(id: Long, quantity: Int): Mono<Boolean>
|
||||
fun batchInsertItems(items: List<Item>): Mono<Boolean>
|
||||
fun replaceAllItems(items: List<Item>): Mono<Boolean>
|
||||
fun exportAllItems(): Mono<List<Item>>
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.itstudio.itmanager.service
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService
|
||||
import club.itstudio.itmanager.entity.dto.ItemTransaction
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
interface ItemTransactionService : IService<ItemTransaction> {
|
||||
fun getTransactionById(id: Long): Mono<ItemTransaction>
|
||||
fun listByItem(itemId: Long): Mono<List<ItemTransaction>>
|
||||
fun listByType(transType: String): Mono<List<ItemTransaction>>
|
||||
fun listByOperator(operatorId: Long): Mono<List<ItemTransaction>>
|
||||
fun createTransaction(transaction: ItemTransaction): Mono<Boolean>
|
||||
fun updateTransaction(transaction: ItemTransaction): Mono<Boolean>
|
||||
fun deleteTransaction(id: Long): Mono<Boolean>
|
||||
fun exportAllTransactions(): Mono<List<ItemTransaction>>
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Account
|
||||
import club.itstudio.itmanager.entity.enums.AccountRole
|
||||
import club.itstudio.itmanager.mapper.AccountMapper
|
||||
import club.itstudio.itmanager.service.AccountService
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.security.core.userdetails.User
|
||||
import org.springframework.security.core.userdetails.UserDetails
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
import javax.security.auth.login.AccountNotFoundException
|
||||
import kotlin.jvm.java
|
||||
|
||||
@Service
|
||||
class AccountServiceImpl : ServiceImpl<AccountMapper, Account>(), AccountService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
override fun findByUsername(
|
||||
username: String
|
||||
): Mono<UserDetails> {
|
||||
|
||||
return findAccountByName(username)
|
||||
.map {
|
||||
User.withUsername(it.username)
|
||||
.password(it.password)
|
||||
.roles(AccountRole.fromIsStaff(it.isStaff).name)
|
||||
.build()
|
||||
}
|
||||
.onErrorMap(
|
||||
AccountNotFoundException::class.java
|
||||
) {
|
||||
UsernameNotFoundException(
|
||||
"User not found"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun findAccountByName(username: String): Mono<Account> =
|
||||
findAccount("username") {
|
||||
ktQuery()
|
||||
.eq(Account::username, username)
|
||||
.one()
|
||||
}
|
||||
|
||||
override fun findAccountById(id: Long): Mono<Account> =
|
||||
blockingCall {
|
||||
logger.info("Searching account by id")
|
||||
ktQuery()
|
||||
.eq(Account::id, id)
|
||||
.one()
|
||||
}
|
||||
|
||||
override fun findAccountByEmail(email: String): Mono<Account> =
|
||||
findAccount("email") {
|
||||
ktQuery()
|
||||
.eq(Account::email, email)
|
||||
.one()
|
||||
}
|
||||
|
||||
private fun <T : Any> blockingCall(
|
||||
block: () -> T?
|
||||
): Mono<T> =
|
||||
Mono.fromCallable(block)
|
||||
.subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
private fun findAccount(
|
||||
fieldName: String,
|
||||
query: () -> Account?
|
||||
): Mono<Account> {
|
||||
return blockingCall {
|
||||
logger.info(
|
||||
"Searching account by {}",
|
||||
fieldName
|
||||
)
|
||||
query()
|
||||
}.switchIfEmpty(
|
||||
Mono.error(
|
||||
AccountNotFoundException()
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
override fun findAccountByNameOrEmail(
|
||||
text: String
|
||||
): Mono<Account> {
|
||||
return blockingCall {
|
||||
logger.info(
|
||||
"Searching account by identifier"
|
||||
)
|
||||
ktQuery()
|
||||
.and {
|
||||
it.eq(Account::email, text)
|
||||
.or()
|
||||
.eq(Account::username, text)
|
||||
}
|
||||
.one()
|
||||
}.switchIfEmpty(
|
||||
Mono.error(AccountNotFoundException())
|
||||
)
|
||||
}
|
||||
|
||||
override fun existAccountByName(
|
||||
username: String
|
||||
): Mono<Boolean> {
|
||||
return blockingCall {
|
||||
ktQuery()
|
||||
.eq(Account::username, username)
|
||||
.exists()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
override fun existAccountByEmail(
|
||||
email: String
|
||||
): Mono<Boolean> {
|
||||
return blockingCall {
|
||||
ktQuery()
|
||||
.eq(Account::email, email)
|
||||
.exists()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
override fun resetPasswordByEmail(
|
||||
email: String,
|
||||
encodedPassword: String
|
||||
): Mono<Void> {
|
||||
return blockingCall {
|
||||
ktUpdate()
|
||||
.eq(Account::email, email)
|
||||
.set(
|
||||
Account::password,
|
||||
encodedPassword
|
||||
)
|
||||
.update()
|
||||
}
|
||||
.flatMap { updated ->
|
||||
if (updated) {
|
||||
Mono.empty()
|
||||
} else {
|
||||
Mono.error(
|
||||
AccountNotFoundException()
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun createAccount(account: Account): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating account")
|
||||
save(account)
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.mapper.AttachmentMapper
|
||||
import club.itstudio.itmanager.service.AttachmentService
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class AttachmentServiceImpl : ServiceImpl<AttachmentMapper, Attachment>(), AttachmentService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getAttachmentById(id: Long): Mono<Attachment> =
|
||||
blockingCall {
|
||||
logger.info("Searching attachment by id")
|
||||
ktQuery()
|
||||
.eq(Attachment::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("Attachment not found")))
|
||||
|
||||
override fun listByRelated(relatedTable: String, relatedId: Long): Mono<List<Attachment>> =
|
||||
blockingCall {
|
||||
logger.info("Searching attachments by related table and id")
|
||||
ktQuery()
|
||||
.eq(Attachment::relatedTable, relatedTable)
|
||||
.eq(Attachment::relatedId, relatedId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByUploader(uploadedBy: Long): Mono<List<Attachment>> =
|
||||
blockingCall {
|
||||
logger.info("Searching attachments by uploader")
|
||||
ktQuery()
|
||||
.eq(Attachment::uploadedBy, uploadedBy)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createAttachment(attachment: Attachment): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating attachment")
|
||||
save(attachment)
|
||||
}
|
||||
|
||||
override fun updateAttachment(attachment: Attachment): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating attachment")
|
||||
updateById(attachment)
|
||||
}
|
||||
|
||||
override fun deleteAttachment(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting attachment by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun deleteByRelated(relatedTable: String, relatedId: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting attachments by related table and id")
|
||||
remove(
|
||||
ktQuery()
|
||||
.eq(Attachment::relatedTable, relatedTable)
|
||||
.eq(Attachment::relatedId, relatedId)
|
||||
)
|
||||
}
|
||||
|
||||
override fun exportAllAttachments(): Mono<List<Attachment>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all attachments")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.BorrowRecord
|
||||
import club.itstudio.itmanager.mapper.BorrowRecordMapper
|
||||
import club.itstudio.itmanager.service.BorrowRecordService
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
|
||||
import com.baomidou.mybatisplus.core.metadata.OrderItem
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class BorrowRecordServiceImpl : ServiceImpl<BorrowRecordMapper, BorrowRecord>(), BorrowRecordService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getBorrowRecordById(id: Long): Mono<BorrowRecord> =
|
||||
blockingCall {
|
||||
logger.info("Searching borrow record by id")
|
||||
ktQuery()
|
||||
.eq(BorrowRecord::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("BorrowRecord not found")))
|
||||
|
||||
override fun pageUsages(
|
||||
page: Page<BorrowRecord>,
|
||||
keyword: String?,
|
||||
status: String?
|
||||
): Mono<Page<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Paging borrow records")
|
||||
if (keyword.isNullOrBlank() && status.isNullOrBlank()) {
|
||||
page.addOrder(OrderItem.desc("created_at"))
|
||||
page(page)
|
||||
} else {
|
||||
val wrapper = QueryWrapper<BorrowRecord>()
|
||||
if (!keyword.isNullOrBlank()) {
|
||||
wrapper.like("borrower", keyword)
|
||||
}
|
||||
if (!status.isNullOrBlank()) {
|
||||
wrapper.eq("status", status)
|
||||
}
|
||||
wrapper.orderByDesc("created_at")
|
||||
page(page, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun listByItem(itemId: Long): Mono<List<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching borrow records by item id")
|
||||
ktQuery()
|
||||
.eq(BorrowRecord::itemId, itemId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByBorrower(borrower: String): Mono<List<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching borrow records by borrower")
|
||||
ktQuery()
|
||||
.eq(BorrowRecord::borrower, borrower)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByStatus(status: String): Mono<List<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching borrow records by status")
|
||||
ktQuery()
|
||||
.eq(BorrowRecord::status, status)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listOverdueRecords(): Mono<List<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching overdue borrow records")
|
||||
ktQuery()
|
||||
.eq(BorrowRecord::status, "OVERDUE")
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createBorrowRecord(record: BorrowRecord): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating borrow record")
|
||||
save(record)
|
||||
}
|
||||
|
||||
override fun updateBorrowRecord(record: BorrowRecord): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating borrow record")
|
||||
updateById(record)
|
||||
}
|
||||
|
||||
override fun deleteBorrowRecord(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting borrow record by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun exportAllBorrowRecords(): Mono<List<BorrowRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all borrow records")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import club.itstudio.itmanager.mapper.CategoryMapper
|
||||
import club.itstudio.itmanager.service.CategoryService
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class CategoryServiceImpl : ServiceImpl<CategoryMapper, Category>(), CategoryService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getCategoryById(id: Long): Mono<Category> =
|
||||
blockingCall {
|
||||
logger.info("Searching category by id")
|
||||
ktQuery()
|
||||
.eq(Category::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("Category not found")))
|
||||
|
||||
override fun listAllCategories(): Mono<List<Category>> =
|
||||
blockingCall {
|
||||
logger.info("Listing all categories")
|
||||
list()
|
||||
}
|
||||
|
||||
override fun listByParentId(parentId: Long): Mono<List<Category>> =
|
||||
blockingCall {
|
||||
logger.info("Searching categories by parent id")
|
||||
ktQuery()
|
||||
.eq(Category::parentId, parentId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createCategory(category: Category): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating category")
|
||||
save(category)
|
||||
}
|
||||
|
||||
override fun updateCategory(category: Category): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating category")
|
||||
updateById(category)
|
||||
}
|
||||
|
||||
override fun deleteCategory(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting category by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun exportAllCategories(): Mono<List<Category>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all categories")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.EmailNotice
|
||||
import club.itstudio.itmanager.mapper.EmailNoticeMapper
|
||||
import club.itstudio.itmanager.service.EmailNoticeService
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class EmailNoticeServiceImpl : ServiceImpl<EmailNoticeMapper, EmailNotice>(), EmailNoticeService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getEmailNoticeById(id: Long): Mono<EmailNotice> =
|
||||
blockingCall {
|
||||
logger.info("Searching email notice by id")
|
||||
ktQuery()
|
||||
.eq(EmailNotice::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("EmailNotice not found")))
|
||||
|
||||
override fun listAllNotices(): Mono<List<EmailNotice>> =
|
||||
blockingCall {
|
||||
logger.info("Listing all email notices")
|
||||
list()
|
||||
}
|
||||
|
||||
override fun listEnabledNotices(): Mono<List<EmailNotice>> =
|
||||
blockingCall {
|
||||
logger.info("Listing enabled email notices")
|
||||
ktQuery()
|
||||
.eq(EmailNotice::enabled, true)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createEmailNotice(notice: EmailNotice): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating email notice")
|
||||
save(notice)
|
||||
}
|
||||
|
||||
override fun updateEmailNotice(notice: EmailNotice): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating email notice")
|
||||
updateById(notice)
|
||||
}
|
||||
|
||||
override fun deleteEmailNotice(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting email notice by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun toggleEnabled(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
val notice = ktQuery().eq(EmailNotice::id, id).one()
|
||||
notice != null
|
||||
&& updateById(notice.copy(enabled = !notice.enabled))
|
||||
}
|
||||
|
||||
override fun exportAllEmailNotices(): Mono<List<EmailNotice>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all email notices")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.FinanceRecord
|
||||
import club.itstudio.itmanager.mapper.FinanceRecordMapper
|
||||
import club.itstudio.itmanager.service.FinanceRecordService
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class FinanceRecordServiceImpl : ServiceImpl<FinanceRecordMapper, FinanceRecord>(), FinanceRecordService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getFinanceRecordById(id: Long): Mono<FinanceRecord> =
|
||||
blockingCall {
|
||||
logger.info("Searching finance record by id")
|
||||
ktQuery()
|
||||
.eq(FinanceRecord::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("FinanceRecord not found")))
|
||||
|
||||
override fun pageFinanceRecords(
|
||||
page: Page<FinanceRecord>,
|
||||
keyword: String?,
|
||||
type: String?,
|
||||
start: String?,
|
||||
end: String?,
|
||||
vendor: String?,
|
||||
itemId: Long?
|
||||
): Mono<Page<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Paging finance records")
|
||||
if (keyword.isNullOrBlank() && type.isNullOrBlank() && start.isNullOrBlank() &&
|
||||
end.isNullOrBlank() && vendor.isNullOrBlank() && itemId == null
|
||||
) {
|
||||
page(page)
|
||||
} else {
|
||||
val wrapper = QueryWrapper<FinanceRecord>()
|
||||
if (!keyword.isNullOrBlank()) {
|
||||
wrapper.and {
|
||||
it.like("record_no", keyword)
|
||||
.or().like("vendor", keyword)
|
||||
.or().like("note", keyword)
|
||||
}
|
||||
}
|
||||
if (!type.isNullOrBlank()) {
|
||||
wrapper.eq("type", type)
|
||||
}
|
||||
if (!start.isNullOrBlank() && !end.isNullOrBlank()) {
|
||||
wrapper.apply("occurred_at BETWEEN {0} AND {1}", start, end)
|
||||
} else if (!start.isNullOrBlank()) {
|
||||
wrapper.ge("occurred_at", start)
|
||||
} else if (!end.isNullOrBlank()) {
|
||||
wrapper.le("occurred_at", end)
|
||||
}
|
||||
if (!vendor.isNullOrBlank()) {
|
||||
wrapper.eq("vendor", vendor)
|
||||
}
|
||||
if (itemId != null) {
|
||||
wrapper.eq("related_item_id", itemId)
|
||||
}
|
||||
page(page, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun listByType(type: String): Mono<List<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching finance records by type")
|
||||
ktQuery()
|
||||
.eq(FinanceRecord::type, type)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByDateRange(start: String, end: String): Mono<List<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching finance records by date range")
|
||||
ktQuery()
|
||||
.apply("occurred_at BETWEEN {0} AND {1}", start, end)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByVendor(vendor: String): Mono<List<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching finance records by vendor")
|
||||
ktQuery()
|
||||
.eq(FinanceRecord::vendor, vendor)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByRelatedItem(itemId: Long): Mono<List<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Searching finance records by related item id")
|
||||
ktQuery()
|
||||
.eq(FinanceRecord::relatedItemId, itemId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createFinanceRecord(record: FinanceRecord): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating finance record")
|
||||
save(record)
|
||||
}
|
||||
|
||||
override fun updateFinanceRecord(record: FinanceRecord): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating finance record")
|
||||
updateById(record)
|
||||
}
|
||||
|
||||
override fun deleteFinanceRecord(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting finance record by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun exportAllFinanceRecords(): Mono<List<FinanceRecord>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all finance records")
|
||||
list()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Item
|
||||
import club.itstudio.itmanager.mapper.ItemMapper
|
||||
import club.itstudio.itmanager.service.ItemService
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import org.springframework.transaction.annotation.Transactional
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class ItemServiceImpl : ServiceImpl<ItemMapper, Item>(), ItemService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun pageItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>> =
|
||||
blockingCall {
|
||||
logger.info("Paging items with keyword and status")
|
||||
if (keyword.isNullOrBlank() && status.isNullOrBlank()) {
|
||||
page(page)
|
||||
} else {
|
||||
val wrapper = QueryWrapper<Item>()
|
||||
if (!keyword.isNullOrBlank()) {
|
||||
wrapper.and {
|
||||
it.like("name", keyword)
|
||||
.or().like("code", keyword)
|
||||
}
|
||||
}
|
||||
if (!status.isNullOrBlank()) {
|
||||
wrapper.eq("status", status)
|
||||
}
|
||||
page(page, wrapper)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getItemById(id: Long): Mono<Item> =
|
||||
blockingCall {
|
||||
logger.info("Searching item by id")
|
||||
ktQuery()
|
||||
.eq(Item::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("Item not found")))
|
||||
|
||||
override fun listAvailableItems(): Mono<List<Item>> =
|
||||
blockingCall {
|
||||
logger.info("Listing available items")
|
||||
ktQuery()
|
||||
.gt(Item::availableQuantity, 0)
|
||||
.eq(Item::status, "normal")
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listInUseItems(): Mono<List<Item>> =
|
||||
blockingCall {
|
||||
logger.info("Listing in-use items")
|
||||
ktQuery()
|
||||
.apply("total_quantity - available_quantity > 0")
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listItemsByCategory(categoryId: Long): Mono<List<Item>> =
|
||||
blockingCall {
|
||||
logger.info("Listing items by category")
|
||||
ktQuery()
|
||||
.eq(Item::categoryId, categoryId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createItem(item: Item): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating item")
|
||||
save(item)
|
||||
}
|
||||
|
||||
override fun updateItem(item: Item): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating item")
|
||||
updateById(item)
|
||||
}
|
||||
|
||||
override fun removeItemById(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Removing item by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun setPrimaryImage(id: Long, imagePath: String): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Setting primary image for item")
|
||||
ktUpdate()
|
||||
.eq(Item::id, id)
|
||||
.set(Item::imagePath, imagePath)
|
||||
.update()
|
||||
}
|
||||
|
||||
override fun borrowItem(id: Long, quantity: Int): Mono<Boolean> =
|
||||
blockingCall {
|
||||
val item = ktQuery().eq(Item::id, id).one()
|
||||
item != null
|
||||
&& item.availableQuantity >= quantity
|
||||
&& ktUpdate()
|
||||
.eq(Item::id, id)
|
||||
.set(Item::availableQuantity, item.availableQuantity - quantity)
|
||||
.update()
|
||||
}
|
||||
|
||||
override fun returnItem(id: Long, quantity: Int): Mono<Boolean> =
|
||||
blockingCall {
|
||||
val item = ktQuery().eq(Item::id, id).one()
|
||||
item != null
|
||||
&& item.totalQuantity >= item.availableQuantity + quantity
|
||||
&& ktUpdate()
|
||||
.eq(Item::id, id)
|
||||
.set(Item::availableQuantity, item.availableQuantity + quantity)
|
||||
.update()
|
||||
}
|
||||
|
||||
@Transactional
|
||||
override fun batchInsertItems(items: List<Item>): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Batch inserting items")
|
||||
saveBatch(items)
|
||||
}
|
||||
|
||||
@Transactional
|
||||
override fun replaceAllItems(items: List<Item>): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Replacing all items")
|
||||
remove(ktQuery())
|
||||
saveBatch(items)
|
||||
}
|
||||
|
||||
override fun exportAllItems(): Mono<List<Item>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all items")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package club.itstudio.itmanager.service.impl
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.ItemTransaction
|
||||
import club.itstudio.itmanager.mapper.ItemTransactionMapper
|
||||
import club.itstudio.itmanager.service.ItemTransactionService
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
|
||||
@Service
|
||||
class ItemTransactionServiceImpl : ServiceImpl<ItemTransactionMapper, ItemTransaction>(), ItemTransactionService {
|
||||
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
private fun <T : Any> blockingCall(block: () -> T?): Mono<T> =
|
||||
Mono.fromCallable(block).subscribeOn(Schedulers.boundedElastic())
|
||||
|
||||
override fun getTransactionById(id: Long): Mono<ItemTransaction> =
|
||||
blockingCall {
|
||||
logger.info("Searching transaction by id")
|
||||
ktQuery()
|
||||
.eq(ItemTransaction::id, id)
|
||||
.one()
|
||||
}.switchIfEmpty(Mono.error(NoSuchElementException("ItemTransaction not found")))
|
||||
|
||||
override fun listByItem(itemId: Long): Mono<List<ItemTransaction>> =
|
||||
blockingCall {
|
||||
logger.info("Searching transactions by item id")
|
||||
ktQuery()
|
||||
.eq(ItemTransaction::itemId, itemId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByType(transType: String): Mono<List<ItemTransaction>> =
|
||||
blockingCall {
|
||||
logger.info("Searching transactions by type")
|
||||
ktQuery()
|
||||
.eq(ItemTransaction::transType, transType)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun listByOperator(operatorId: Long): Mono<List<ItemTransaction>> =
|
||||
blockingCall {
|
||||
logger.info("Searching transactions by operator id")
|
||||
ktQuery()
|
||||
.eq(ItemTransaction::operatorId, operatorId)
|
||||
.list()
|
||||
}
|
||||
|
||||
override fun createTransaction(transaction: ItemTransaction): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Creating transaction")
|
||||
save(transaction)
|
||||
}
|
||||
|
||||
override fun updateTransaction(transaction: ItemTransaction): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Updating transaction")
|
||||
updateById(transaction)
|
||||
}
|
||||
|
||||
override fun deleteTransaction(id: Long): Mono<Boolean> =
|
||||
blockingCall {
|
||||
logger.info("Deleting transaction by id")
|
||||
removeById(id)
|
||||
}
|
||||
|
||||
override fun exportAllTransactions(): Mono<List<ItemTransaction>> =
|
||||
blockingCall {
|
||||
logger.info("Exporting all transactions")
|
||||
list()
|
||||
}
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Account
|
||||
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
||||
import club.itstudio.itmanager.entity.enums.EmailType
|
||||
import club.itstudio.itmanager.entity.vo.request.EmailRegisterVO
|
||||
import club.itstudio.itmanager.entity.vo.request.PasswordResetVO
|
||||
import club.itstudio.itmanager.entity.vo.response.ReloginVO
|
||||
import club.itstudio.itmanager.service.AccountService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import club.itstudio.itmanager.utils.FlowUtils
|
||||
import club.itstudio.itmanager.utils.JwtUtils
|
||||
import org.springframework.amqp.core.AmqpTemplate
|
||||
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
|
||||
import org.springframework.security.crypto.password.PasswordEncoder
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
import java.time.Duration
|
||||
|
||||
@Service
|
||||
class AuthorizationService(
|
||||
private val accountService: AccountService,
|
||||
private val utils: FlowUtils,
|
||||
private val jwtUtils: JwtUtils,
|
||||
private val amqpTemplate: AmqpTemplate,
|
||||
private val stringRedisTemplate: ReactiveStringRedisTemplate,
|
||||
private val encoder: PasswordEncoder
|
||||
) {
|
||||
fun askEmailVerifyCode(type: EmailType, email: String, ip: String): Mono<String> {
|
||||
return verifyLimit(ip).flatMap { allowed ->
|
||||
if (allowed) {
|
||||
val code = (100000..999999).random().toString()
|
||||
val data = EmailVerificationMsg(email, type, code)
|
||||
|
||||
Mono.fromRunnable<Void> {
|
||||
amqpTemplate.convertAndSend("mail", data)
|
||||
}.then(
|
||||
stringRedisTemplate.opsForValue()
|
||||
.set(
|
||||
Const.VERIFY_EMAIL_DATA + email,
|
||||
code,
|
||||
Duration.ofMinutes(3)
|
||||
)
|
||||
).thenReturn("").subscribeOn(Schedulers.boundedElastic())
|
||||
} else {
|
||||
Mono.just("Request limit exceeded. Please try again later.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun registerEmailAccount(vo: EmailRegisterVO): Mono<String> {
|
||||
val (email, code, username, password) = vo
|
||||
|
||||
return verifyCode(email, code)
|
||||
.flatMap { result ->
|
||||
if (result.isNotBlank()) {
|
||||
return@flatMap Mono.just(result)
|
||||
}
|
||||
accountService.existAccountByEmail(email)
|
||||
.flatMap { emailExists ->
|
||||
if (emailExists) {
|
||||
return@flatMap Mono.just("account with the same email already exists.")
|
||||
}
|
||||
accountService.existAccountByName(username)
|
||||
.flatMap { usernameExists ->
|
||||
if (usernameExists) {
|
||||
return@flatMap Mono.just("username already exists.")
|
||||
}
|
||||
val account = Account(
|
||||
id = null,
|
||||
username = username,
|
||||
password = encoder.encode(password)!!,
|
||||
email = email,
|
||||
isStaff = false,
|
||||
createdAt = getCurrentDateTime()
|
||||
)
|
||||
accountService.createAccount(account)
|
||||
.flatMap { success ->
|
||||
if (success) {
|
||||
stringRedisTemplate.delete(Const.VERIFY_EMAIL_DATA + email)
|
||||
.thenReturn("")
|
||||
} else {
|
||||
Const.INTERNAL_ERROR_MONO
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun resetEmailAccountPassword(vo: PasswordResetVO): Mono<String> {
|
||||
val (email, code, password) = vo
|
||||
|
||||
val encodedPassword =
|
||||
encoder.encode(password)
|
||||
?: return Const.INTERNAL_ERROR_MONO
|
||||
|
||||
return verifyCode(email, code)
|
||||
.then(
|
||||
accountService.resetPasswordByEmail(
|
||||
email,
|
||||
encodedPassword
|
||||
)
|
||||
)
|
||||
.then(
|
||||
stringRedisTemplate.delete(
|
||||
Const.VERIFY_EMAIL_DATA + email
|
||||
)
|
||||
)
|
||||
.thenReturn("Password reset successfully")
|
||||
}
|
||||
|
||||
fun jwtTokenRelogin(headerToken: String?): Mono<ReloginVO>? {
|
||||
val user = jwtUtils.resolveJwt(headerToken?.substring("Bearer ".length))
|
||||
?.let { jwtUtils.toUser(it) }
|
||||
?: return null
|
||||
val accountMono = accountService.findAccountByName(user.username)
|
||||
val voMono = accountMono.map {
|
||||
ReloginVO(
|
||||
jwtUtils.createJwt(user, it.id!!, it.username),
|
||||
DateUtils.dateToLocalDateTime(jwtUtils.expiresTime())
|
||||
)
|
||||
}
|
||||
return voMono
|
||||
}
|
||||
|
||||
fun invalidateJwt(headerToken: String?): Boolean {
|
||||
return jwtUtils.invalidateJwt(headerToken)
|
||||
}
|
||||
|
||||
private fun verifyLimit(ip: String): Mono<Boolean> {
|
||||
val key = Const.VERIFY_EMAIL_LIMIT + ip
|
||||
return utils.limitOnceCheck(key, 60)
|
||||
}
|
||||
|
||||
private fun verifyCode(email: String, receivedCode: String?): Mono<String> {
|
||||
return stringRedisTemplate.opsForValue()
|
||||
.get(Const.VERIFY_EMAIL_DATA + email)
|
||||
.flatMap { code ->
|
||||
if (receivedCode == null || code != receivedCode)
|
||||
Mono.just("verify code is wrong.")
|
||||
else Mono.just("")
|
||||
}
|
||||
.switchIfEmpty(Mono.just("verify code has not been sent"))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.EmailNotice
|
||||
import club.itstudio.itmanager.service.EmailNoticeService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import java.util.NoSuchElementException
|
||||
|
||||
@Service
|
||||
class EmailApiService(
|
||||
private val emailNoticeService: EmailNoticeService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun getNotificationSettings(): Mono<List<EmailNotice>> {
|
||||
logger.info("Listing notification settings and email list")
|
||||
return emailNoticeService.listAllNotices()
|
||||
}
|
||||
|
||||
fun updateNotificationSettings(notice: EmailNotice): Mono<String> {
|
||||
logger.info("Updating notification settings")
|
||||
if (notice.id == null) {
|
||||
return emailNoticeService.createEmailNotice(
|
||||
notice.copy(
|
||||
id = null,
|
||||
createdAt = getCurrentDateTime(),
|
||||
updatedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("notification settings create failed.")
|
||||
}
|
||||
}
|
||||
return emailNoticeService.updateEmailNotice(
|
||||
notice.copy(updatedAt = getCurrentDateTime())
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("notification settings update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun toggleEmailStatus(id: Long?): Mono<String> {
|
||||
logger.info("Toggling email status for id {}", id)
|
||||
if (id == null) return Mono.just("email notice id is required.")
|
||||
return emailNoticeService.toggleEnabled(id)
|
||||
.flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("email notice not found or toggle failed.")
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("email notice not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import club.itstudio.itmanager.entity.dto.EmailVerificationMsg
|
||||
import club.itstudio.itmanager.entity.dto.FinanceRecord
|
||||
import club.itstudio.itmanager.entity.enums.EmailType
|
||||
import club.itstudio.itmanager.service.AccountService
|
||||
import club.itstudio.itmanager.service.AttachmentService
|
||||
import club.itstudio.itmanager.service.CategoryService
|
||||
import club.itstudio.itmanager.service.FinanceRecordService
|
||||
import club.itstudio.itmanager.service.FileStorageService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.amqp.core.AmqpTemplate
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
import java.util.NoSuchElementException
|
||||
|
||||
@Service
|
||||
class FinanceApiService(
|
||||
private val financeRecordService: FinanceRecordService,
|
||||
private val categoryService: CategoryService,
|
||||
private val attachmentService: AttachmentService,
|
||||
private val accountService: AccountService,
|
||||
private val amqpTemplate: AmqpTemplate,
|
||||
private val fileStorageService: FileStorageService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun getFinanceRecords(
|
||||
page: Page<FinanceRecord>,
|
||||
keyword: String?,
|
||||
type: String?,
|
||||
start: String?,
|
||||
end: String?,
|
||||
vendor: String?,
|
||||
itemId: Long?
|
||||
): Mono<Page<FinanceRecord>> {
|
||||
logger.info("Listing finance records")
|
||||
return financeRecordService.pageFinanceRecords(page, keyword, type, start, end, vendor, itemId)
|
||||
}
|
||||
|
||||
fun createFinanceRecord(record: FinanceRecord): Mono<String> {
|
||||
logger.info("Creating finance record")
|
||||
val rightNow = getCurrentDateTime()
|
||||
return financeRecordService.createFinanceRecord(
|
||||
record.copy(
|
||||
id = null,
|
||||
createdAt = rightNow
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("finance record create failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun updateFinanceRecord(record: FinanceRecord): Mono<String> {
|
||||
logger.info("Updating finance record")
|
||||
if (record.id == null) return Mono.just("finance record id is required.")
|
||||
return financeRecordService.updateFinanceRecord(record).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("finance record update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteFinanceRecord(id: Long?): Mono<String> {
|
||||
logger.info("Deleting finance record with id {}", id)
|
||||
if (id == null) return Mono.just("finance record id is required.")
|
||||
return financeRecordService.deleteFinanceRecord(id).flatMap { success ->
|
||||
if (success) cleanupFinanceAttachments(id).thenReturn("")
|
||||
else Mono.just("finance record delete failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun uploadImages(id: Long, files: Flux<FilePart>): Mono<String> {
|
||||
logger.info("Uploading images for finance record {}", id)
|
||||
return financeRecordService.getFinanceRecordById(id)
|
||||
.flatMap { _ ->
|
||||
files.flatMap { file -> saveFinanceImage(id, file) }
|
||||
.collectList()
|
||||
.flatMap { attachments ->
|
||||
if (attachments.isEmpty()) {
|
||||
Mono.just("no image files provided.")
|
||||
} else {
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { attachmentService.createAttachment(it) }
|
||||
.collectList()
|
||||
.flatMap { results ->
|
||||
if (results.any { !it }) {
|
||||
Mono.just("finance image upload failed.")
|
||||
} else {
|
||||
Mono.just("")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("finance record not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun deleteById(id: Long?): Mono<String> {
|
||||
logger.info("Deleting finance record {} and notifying by email", id)
|
||||
if (id == null) return Mono.just("finance record id is required.")
|
||||
return financeRecordService.getFinanceRecordById(id)
|
||||
.flatMap { record ->
|
||||
financeRecordService.deleteFinanceRecord(id)
|
||||
.flatMap { success ->
|
||||
if (success) {
|
||||
cleanupFinanceAttachments(id)
|
||||
.then(sendFinanceDeleteNotification(record))
|
||||
.thenReturn("")
|
||||
} else {
|
||||
Mono.just("finance record delete failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("finance record not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun getFinanceCategories(): Mono<List<Category>> {
|
||||
logger.info("Listing finance categories")
|
||||
return categoryService.listAllCategories()
|
||||
}
|
||||
|
||||
fun createFinanceCategory(category: Category): Mono<String> {
|
||||
logger.info("Creating finance category")
|
||||
return categoryService.createCategory(
|
||||
category.copy(
|
||||
id = null,
|
||||
createdAt = getCurrentDateTime(),
|
||||
updatedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category create failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun updateFinanceCategory(category: Category): Mono<String> {
|
||||
logger.info("Updating finance category")
|
||||
if (category.id == null) return Mono.just("category id is required.")
|
||||
return categoryService.updateCategory(
|
||||
category.copy(updatedAt = getCurrentDateTime())
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteFinanceCategory(id: Long?): Mono<String> {
|
||||
logger.info("Deleting finance category with id {}", id)
|
||||
if (id == null) return Mono.just("category id is required.")
|
||||
return categoryService.deleteCategory(id).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category delete failed.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveFinanceImage(financeRecordId: Long, file: FilePart): Mono<Attachment> {
|
||||
return fileStorageService.saveImage(file, "finance", financeRecordId)
|
||||
.map { stored ->
|
||||
Attachment(
|
||||
relatedTable = "finance_records",
|
||||
relatedId = financeRecordId,
|
||||
fileName = stored.path.fileName.toString(),
|
||||
filePath = stored.path.toString(),
|
||||
fileSize = stored.size,
|
||||
contentType = file.headers().contentType?.toString(),
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanupFinanceAttachments(financeRecordId: Long): Mono<Boolean> {
|
||||
return attachmentService.listByRelated("finance_records", financeRecordId)
|
||||
.flatMap { attachments ->
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { fileStorageService.deleteFile(it.filePath) }
|
||||
.then(attachmentService.deleteByRelated("finance_records", financeRecordId))
|
||||
}
|
||||
.onErrorResume { error ->
|
||||
logger.warn("Failed to clean up attachments for finance record {}: {}", financeRecordId, error.message)
|
||||
Mono.just(false)
|
||||
}
|
||||
}
|
||||
|
||||
private fun sendFinanceDeleteNotification(record: FinanceRecord): Mono<Void> {
|
||||
val recordedBy = record.recordedBy ?: return Mono.empty()
|
||||
return accountService.findAccountById(recordedBy)
|
||||
.flatMap { account ->
|
||||
val email = account.email
|
||||
if (email.isNullOrBlank()) {
|
||||
logger.warn("Skipping finance delete notification for record {}: no email for account {}", record.id, recordedBy)
|
||||
Mono.empty()
|
||||
} else {
|
||||
Mono.fromRunnable<Void> {
|
||||
amqpTemplate.convertAndSend(
|
||||
"mail",
|
||||
EmailVerificationMsg(
|
||||
email = email,
|
||||
type = EmailType.FINANCE_DELETE,
|
||||
code = record.recordNo ?: record.id?.toString() ?: ""
|
||||
)
|
||||
)
|
||||
}.subscribeOn(Schedulers.boundedElastic())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.entity.dto.Category
|
||||
import club.itstudio.itmanager.entity.dto.Item
|
||||
import club.itstudio.itmanager.entity.dto.ItemTransaction
|
||||
import club.itstudio.itmanager.entity.enums.TransactionType
|
||||
import club.itstudio.itmanager.service.AttachmentService
|
||||
import club.itstudio.itmanager.service.CategoryService
|
||||
import club.itstudio.itmanager.service.FileStorageService
|
||||
import club.itstudio.itmanager.service.ItemService
|
||||
import club.itstudio.itmanager.service.ItemTransactionService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
import java.util.NoSuchElementException
|
||||
|
||||
@Service
|
||||
class ItemsApiService(
|
||||
private val itemService: ItemService,
|
||||
private val categoryService: CategoryService,
|
||||
private val attachmentService: AttachmentService,
|
||||
private val transactionService: ItemTransactionService,
|
||||
private val fileStorageService: FileStorageService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun getItems(page: Page<Item>, keyword: String?, status: String?): Mono<Page<Item>> {
|
||||
logger.info("Listing items with keyword and status")
|
||||
return itemService.pageItems(page, keyword, status)
|
||||
}
|
||||
|
||||
fun createItem(item: Item): Mono<String> {
|
||||
logger.info("Creating item")
|
||||
val rightNow = getCurrentDateTime()
|
||||
return itemService.createItem(
|
||||
item.copy(
|
||||
id = null,
|
||||
createdAt = rightNow,
|
||||
updatedAt = rightNow
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("item create failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun updateItem(item: Item): Mono<String> {
|
||||
logger.info("Updating item")
|
||||
if (item.id == null) return Mono.just("item id is required.")
|
||||
return itemService.updateItem(
|
||||
item.copy(updatedAt = getCurrentDateTime())
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("item update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteItem(id: Long?): Mono<String> {
|
||||
logger.info("Deleting item with id {}", id)
|
||||
if (id == null) return Mono.just("item id is required.")
|
||||
return itemService.removeItemById(id).flatMap { success ->
|
||||
if (success) {
|
||||
cleanupItemAttachments(id)
|
||||
} else {
|
||||
Mono.just("item delete failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun uploadImages(id: Long, files: Flux<FilePart>): Mono<String> {
|
||||
logger.info("Uploading images for item {}", id)
|
||||
return itemService.getItemById(id)
|
||||
.flatMap { item ->
|
||||
files.flatMap { file -> saveItemImage(id, file) }
|
||||
.collectList()
|
||||
.flatMap { attachments ->
|
||||
if (attachments.isEmpty()) {
|
||||
Mono.just("no image files provided.")
|
||||
} else {
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { attachmentService.createAttachment(it) }
|
||||
.collectList()
|
||||
.flatMap { results ->
|
||||
if (results.any { !it }) {
|
||||
Mono.just("item image upload failed.")
|
||||
} else {
|
||||
setPrimaryImageIfBlank(item, attachments.first(), id)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun setPrimaryImage(id: Long, imageId: Long): Mono<String> {
|
||||
logger.info("Setting primary image for item {}", id)
|
||||
return itemService.getItemById(id)
|
||||
.flatMap { _ ->
|
||||
attachmentService.getAttachmentById(imageId)
|
||||
.flatMap { attachment ->
|
||||
if (attachment.relatedTable == "items" && attachment.relatedId == id) {
|
||||
val path = attachment.filePath
|
||||
if (path.isNullOrBlank()) {
|
||||
Mono.just("image file path is empty.")
|
||||
} else {
|
||||
itemService.setPrimaryImage(id, path).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("set primary image failed.")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Mono.just("image does not belong to this item.")
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { _ -> Mono.just("image not found.") }
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { _ -> Mono.just("item not found.") }
|
||||
.onErrorResume { _ -> Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun borrowItem(id: Long, quantity: Int): Mono<String> {
|
||||
logger.info("Borrowing item {} with quantity {}", id, quantity)
|
||||
if (quantity <= 0) return Mono.just("quantity must be positive.")
|
||||
return itemService.getItemById(id)
|
||||
.flatMap { item ->
|
||||
itemService.borrowItem(id, quantity)
|
||||
.flatMap { success ->
|
||||
if (success) {
|
||||
transactionService.createTransaction(
|
||||
ItemTransaction(
|
||||
itemId = id,
|
||||
transType = TransactionType.OUT,
|
||||
quantity = quantity,
|
||||
fromLocation = item.location,
|
||||
createdAt = getCurrentDateTime()
|
||||
)
|
||||
).onErrorResume { error ->
|
||||
logger.warn("Failed to record OUT transaction for item {}: {}", id, error.message)
|
||||
Mono.just(false)
|
||||
}.thenReturn("")
|
||||
} else {
|
||||
Mono.just("item available quantity is not enough.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun returnItem(id: Long, quantity: Int): Mono<String> {
|
||||
logger.info("Returning item {} with quantity {}", id, quantity)
|
||||
if (quantity <= 0) return Mono.just("quantity must be positive.")
|
||||
return itemService.getItemById(id)
|
||||
.flatMap { item ->
|
||||
itemService.returnItem(id, quantity)
|
||||
.flatMap { success ->
|
||||
if (success) {
|
||||
transactionService.createTransaction(
|
||||
ItemTransaction(
|
||||
itemId = id,
|
||||
transType = TransactionType.IN,
|
||||
quantity = quantity,
|
||||
toLocation = item.location,
|
||||
createdAt = getCurrentDateTime()
|
||||
)
|
||||
).onErrorResume { error ->
|
||||
logger.warn("Failed to record IN transaction for item {}: {}", id, error.message)
|
||||
Mono.just(false)
|
||||
}.thenReturn("")
|
||||
} else {
|
||||
Mono.just("item cannot be returned with the given quantity.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun getAvailableItems(): Mono<List<Item>> {
|
||||
logger.info("Listing available items")
|
||||
return itemService.listAvailableItems()
|
||||
}
|
||||
|
||||
fun getInUseItems(): Mono<List<Item>> {
|
||||
logger.info("Listing in-use items")
|
||||
return itemService.listInUseItems()
|
||||
}
|
||||
|
||||
fun getItemCategories(): Mono<List<Category>> {
|
||||
logger.info("Listing item categories")
|
||||
return categoryService.listAllCategories()
|
||||
}
|
||||
|
||||
fun createItemCategory(category: Category): Mono<String> {
|
||||
logger.info("Creating item category")
|
||||
return categoryService.createCategory(
|
||||
category.copy(
|
||||
id = null,
|
||||
createdAt = getCurrentDateTime(),
|
||||
updatedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category create failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun updateItemCategory(category: Category): Mono<String> {
|
||||
logger.info("Updating item category")
|
||||
if (category.id == null) return Mono.just("category id is required.")
|
||||
return categoryService.updateCategory(
|
||||
category.copy(updatedAt = getCurrentDateTime())
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteItemCategory(id: Long?): Mono<String> {
|
||||
logger.info("Deleting item category with id {}", id)
|
||||
if (id == null) return Mono.just("category id is required.")
|
||||
return categoryService.deleteCategory(id).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("category delete failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun getItemImages(): Mono<List<Attachment>> {
|
||||
logger.info("Listing item images")
|
||||
return attachmentService.exportAllAttachments()
|
||||
.map { list -> list.filter { it.relatedTable == "items" } }
|
||||
}
|
||||
|
||||
fun createItemImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Creating item image")
|
||||
return attachmentService.createAttachment(
|
||||
attachment.copy(
|
||||
id = null,
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("item image create failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun updateItemImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Updating item image")
|
||||
if (attachment.id == null) return Mono.just("item image id is required.")
|
||||
return attachmentService.updateAttachment(attachment)
|
||||
.flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("item image update failed.")
|
||||
}
|
||||
}
|
||||
|
||||
fun deleteItemImage(id: Long?): Mono<String> {
|
||||
logger.info("Deleting item image with id {}", id)
|
||||
if (id == null) return Mono.just("item image id is required.")
|
||||
return attachmentService.getAttachmentById(id)
|
||||
.flatMap { attachment ->
|
||||
attachmentService.deleteAttachment(id).flatMap { success ->
|
||||
if (success) {
|
||||
fileStorageService.deleteFile(attachment.filePath).thenReturn("")
|
||||
} else {
|
||||
Mono.just("item image delete failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("item image not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
private fun setPrimaryImageIfBlank(item: Item, attachment: Attachment, id: Long): Mono<String> {
|
||||
if (!item.imagePath.isNullOrBlank()) return Mono.just("")
|
||||
val path = attachment.filePath ?: return Mono.just("")
|
||||
return itemService.setPrimaryImage(id, path).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("set primary image failed.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun saveItemImage(itemId: Long, file: FilePart): Mono<Attachment> {
|
||||
return fileStorageService.saveImage(file, "items", itemId)
|
||||
.map { stored ->
|
||||
Attachment(
|
||||
relatedTable = "items",
|
||||
relatedId = itemId,
|
||||
fileName = stored.path.fileName.toString(),
|
||||
filePath = stored.path.toString(),
|
||||
fileSize = stored.size,
|
||||
contentType = file.headers().contentType?.toString(),
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanupItemAttachments(itemId: Long): Mono<String> {
|
||||
return attachmentService.listByRelated("items", itemId)
|
||||
.flatMap { attachments ->
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { fileStorageService.deleteFile(it.filePath) }
|
||||
.then(attachmentService.deleteByRelated("items", itemId))
|
||||
.thenReturn("")
|
||||
}
|
||||
.onErrorResume { error ->
|
||||
logger.warn("Failed to clean up attachments for item {}: {}", itemId, error.message)
|
||||
Mono.just("")
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.service.AttachmentService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Mono
|
||||
import reactor.core.scheduler.Schedulers
|
||||
import java.io.IOException
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Paths
|
||||
import java.util.NoSuchElementException
|
||||
|
||||
@Service
|
||||
class ProofImagesApiService(
|
||||
private val attachmentService: AttachmentService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun getProofImages(): Mono<List<Attachment>> {
|
||||
logger.info("Listing proof images")
|
||||
return attachmentService.exportAllAttachments()
|
||||
.map { list -> list.filter { it.relatedTable == RELATED_TABLE } }
|
||||
}
|
||||
|
||||
fun createProofImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Creating proof image")
|
||||
return attachmentService.createAttachment(
|
||||
attachment.copy(
|
||||
id = null,
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("proof image create failed.")
|
||||
}.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun updateProofImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Updating proof image")
|
||||
if (attachment.id == null) return Mono.just("proof image id is required.")
|
||||
return attachmentService.updateAttachment(attachment)
|
||||
.flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("proof image update failed.")
|
||||
}
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun deleteProofImage(id: Long?): Mono<String> {
|
||||
logger.info("Deleting proof image with id {}", id)
|
||||
if (id == null) return Mono.just("proof image id is required.")
|
||||
return attachmentService.getAttachmentById(id)
|
||||
.flatMap { attachment ->
|
||||
attachmentService.deleteAttachment(id).flatMap { success ->
|
||||
if (success) {
|
||||
deletePhysicalFile(attachment.filePath).thenReturn("")
|
||||
} else {
|
||||
Mono.just("proof image delete failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("proof image not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
private fun deletePhysicalFile(path: String?): Mono<Void> {
|
||||
if (path.isNullOrBlank()) return Mono.empty()
|
||||
return Mono.fromRunnable<Void> {
|
||||
try {
|
||||
Files.deleteIfExists(Paths.get(path))
|
||||
} catch (e: IOException) {
|
||||
logger.warn("Failed to delete file: {}", path, e)
|
||||
}
|
||||
}.subscribeOn(Schedulers.boundedElastic())
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val RELATED_TABLE = "finance_records"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package club.itstudio.itmanager.service.v1
|
||||
|
||||
import club.itstudio.itmanager.entity.dto.Attachment
|
||||
import club.itstudio.itmanager.entity.dto.BorrowRecord
|
||||
import club.itstudio.itmanager.service.AttachmentService
|
||||
import club.itstudio.itmanager.service.BorrowRecordService
|
||||
import club.itstudio.itmanager.service.FileStorageService
|
||||
import club.itstudio.itmanager.utils.Const
|
||||
import club.itstudio.itmanager.utils.DateUtils.getCurrentDateTime
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.http.codec.multipart.FilePart
|
||||
import org.springframework.stereotype.Service
|
||||
import reactor.core.publisher.Flux
|
||||
import reactor.core.publisher.Mono
|
||||
import java.util.NoSuchElementException
|
||||
|
||||
@Service
|
||||
class UsagesApiService(
|
||||
private val borrowRecordService: BorrowRecordService,
|
||||
private val attachmentService: AttachmentService,
|
||||
private val fileStorageService: FileStorageService
|
||||
) {
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun getUsages(page: Page<BorrowRecord>, keyword: String?, status: String?): Mono<Page<BorrowRecord>> {
|
||||
logger.info("Paging usages with keyword and status")
|
||||
return borrowRecordService.pageUsages(page, keyword, status)
|
||||
}
|
||||
|
||||
fun createUsage(record: BorrowRecord): Mono<String> {
|
||||
logger.info("Creating usage")
|
||||
val rightNow = getCurrentDateTime()
|
||||
return borrowRecordService.createBorrowRecord(
|
||||
record.copy(
|
||||
id = null,
|
||||
createdAt = rightNow,
|
||||
updatedAt = rightNow
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("usage create failed.")
|
||||
}.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun updateUsage(record: BorrowRecord): Mono<String> {
|
||||
logger.info("Updating usage")
|
||||
if (record.id == null) return Mono.just("usage id is required.")
|
||||
return borrowRecordService.updateBorrowRecord(
|
||||
record.copy(updatedAt = getCurrentDateTime())
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("usage update failed.")
|
||||
}.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun deleteUsage(id: Long?): Mono<String> {
|
||||
logger.info("Deleting usage with id {}", id)
|
||||
if (id == null) return Mono.just("usage id is required.")
|
||||
return borrowRecordService.deleteBorrowRecord(id).flatMap { success ->
|
||||
if (success) {
|
||||
cleanupUsageAttachments(id)
|
||||
} else {
|
||||
Mono.just("usage delete failed.")
|
||||
}
|
||||
}.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun uploadImages(id: Long, files: Flux<FilePart>): Mono<String> {
|
||||
logger.info("Uploading images for usage {}", id)
|
||||
return borrowRecordService.getBorrowRecordById(id)
|
||||
.flatMap { _ ->
|
||||
files.flatMap { file -> saveUsageImage(id, file) }
|
||||
.collectList()
|
||||
.flatMap { attachments ->
|
||||
if (attachments.isEmpty()) {
|
||||
Mono.just("no image files provided.")
|
||||
} else {
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { attachmentService.createAttachment(it) }
|
||||
.collectList()
|
||||
.flatMap { results ->
|
||||
if (results.any { !it }) {
|
||||
Mono.just("usage image upload failed.")
|
||||
} else {
|
||||
Mono.just("")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("usage not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun getCurrentUsages(): Mono<List<BorrowRecord>> {
|
||||
logger.info("Listing current usages")
|
||||
return borrowRecordService.listByStatus(STATUS_BORROWED)
|
||||
.zipWith(borrowRecordService.listOverdueRecords()) { borrowed, overdue -> borrowed + overdue }
|
||||
}
|
||||
|
||||
fun getUsagesByUser(name: String?): Mono<List<BorrowRecord>> {
|
||||
logger.info("Listing usages by user {}", name)
|
||||
if (name.isNullOrBlank()) return Mono.just(emptyList())
|
||||
return borrowRecordService.listByBorrower(name)
|
||||
}
|
||||
|
||||
fun getUsageImages(): Mono<List<Attachment>> {
|
||||
logger.info("Listing usage images")
|
||||
return attachmentService.exportAllAttachments()
|
||||
.map { list -> list.filter { it.relatedTable == RELATED_TABLE } }
|
||||
}
|
||||
|
||||
fun createUsageImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Creating usage image")
|
||||
return attachmentService.createAttachment(
|
||||
attachment.copy(
|
||||
id = null,
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
).flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("usage image create failed.")
|
||||
}.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun updateUsageImage(attachment: Attachment): Mono<String> {
|
||||
logger.info("Updating usage image")
|
||||
if (attachment.id == null) return Mono.just("usage image id is required.")
|
||||
return attachmentService.updateAttachment(attachment)
|
||||
.flatMap { success ->
|
||||
if (success) Mono.just("")
|
||||
else Mono.just("usage image update failed.")
|
||||
}
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
fun deleteUsageImage(id: Long?): Mono<String> {
|
||||
logger.info("Deleting usage image with id {}", id)
|
||||
if (id == null) return Mono.just("usage image id is required.")
|
||||
return attachmentService.getAttachmentById(id)
|
||||
.flatMap { attachment ->
|
||||
attachmentService.deleteAttachment(id).flatMap { success ->
|
||||
if (success) {
|
||||
fileStorageService.deleteFile(attachment.filePath).thenReturn("")
|
||||
} else {
|
||||
Mono.just("usage image delete failed.")
|
||||
}
|
||||
}
|
||||
}
|
||||
.onErrorResume(NoSuchElementException::class.java) { Mono.just("usage image not found.") }
|
||||
.onErrorResume { Mono.just(Const.INTERNAL_ERROR_STR) }
|
||||
}
|
||||
|
||||
private fun saveUsageImage(usageId: Long, file: FilePart): Mono<Attachment> {
|
||||
return fileStorageService.saveImage(file, "borrow_records", usageId)
|
||||
.map { stored ->
|
||||
Attachment(
|
||||
relatedTable = RELATED_TABLE,
|
||||
relatedId = usageId,
|
||||
fileName = stored.path.fileName.toString(),
|
||||
filePath = stored.path.toString(),
|
||||
fileSize = stored.size,
|
||||
contentType = file.headers().contentType?.toString(),
|
||||
uploadedAt = getCurrentDateTime()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun cleanupUsageAttachments(usageId: Long): Mono<String> {
|
||||
return attachmentService.listByRelated(RELATED_TABLE, usageId)
|
||||
.flatMap { attachments ->
|
||||
Flux.fromIterable(attachments)
|
||||
.flatMap { fileStorageService.deleteFile(it.filePath) }
|
||||
.then(attachmentService.deleteByRelated(RELATED_TABLE, usageId))
|
||||
.thenReturn("")
|
||||
}
|
||||
.onErrorResume { error ->
|
||||
logger.warn("Failed to clean up attachments for usage {}: {}", usageId, error.message)
|
||||
Mono.just("")
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val RELATED_TABLE = "borrow_records"
|
||||
private const val STATUS_BORROWED = "BORROWED"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package club.itstudio.itmanager.utils
|
||||
|
||||
import kotlinx.serialization.KSerializer
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.descriptors.PrimitiveKind
|
||||
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
|
||||
import kotlinx.serialization.descriptors.SerialDescriptor
|
||||
import kotlinx.serialization.encoding.Decoder
|
||||
import kotlinx.serialization.encoding.Encoder
|
||||
import kotlinx.serialization.json.JsonDecoder
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import java.math.BigDecimal
|
||||
|
||||
object BigDecimalSerializer : KSerializer<BigDecimal> {
|
||||
override val descriptor: SerialDescriptor =
|
||||
PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING)
|
||||
|
||||
override fun serialize(encoder: Encoder, value: BigDecimal) {
|
||||
encoder.encodeString(value.toPlainString())
|
||||
}
|
||||
|
||||
override fun deserialize(decoder: Decoder): BigDecimal {
|
||||
val element = (decoder as JsonDecoder).decodeJsonElement()
|
||||
if (element !is JsonPrimitive) {
|
||||
throw SerializationException("Expected JSON primitive, got $element")
|
||||
}
|
||||
return element.content.toBigDecimal()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package club.itstudio.itmanager.utils
|
||||
|
||||
import club.itstudio.itmanager.entity.ApiResponse
|
||||
import reactor.core.publisher.Mono
|
||||
|
||||
object Const {
|
||||
const val FLOW_LIMIT_ORDER = -101
|
||||
|
||||
const val JWT_BLACK_LIST = "jwt:blacklist:"
|
||||
const val VERIFY_EMAIL_LIMIT = "verify:email:limit:"
|
||||
const val VERIFY_EMAIL_DATA = "verify:email:data:"
|
||||
|
||||
const val FLOW_LIMIT_COUNTER = "flow:counter:"
|
||||
const val FLOW_LIMIT_BLOCK = "flow:block:"
|
||||
|
||||
const val FILE_DIR_IMAGE = "image"
|
||||
|
||||
const val INTERNAL_ERROR_STR = "something went wrong. Please contact the administrator."
|
||||
val INTERNAL_ERROR_MONO = Mono.just(INTERNAL_ERROR_STR)
|
||||
|
||||
// for Controllers
|
||||
fun messageHandler(wrongMessage: String): ApiResponse<Any?> {
|
||||
return if (wrongMessage.isBlank()) {
|
||||
ApiResponse.success()
|
||||
} else {
|
||||
ApiResponse.failure(400, null, wrongMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package club.itstudio.itmanager.utils
|
||||
|
||||
import kotlinx.datetime.*
|
||||
import kotlinx.datetime.TimeZone
|
||||
import java.util.*
|
||||
|
||||
object DateUtils {
|
||||
fun getCurrentDateTime() =
|
||||
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
|
||||
|
||||
fun dateToLocalDateTime(date: Date): LocalDateTime {
|
||||
return date
|
||||
.toInstant()
|
||||
.toKotlinInstant()
|
||||
.toLocalDateTime(TimeZone.currentSystemDefault())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package club.itstudio.itmanager.utils
|
||||
|
||||
import jakarta.annotation.Resource
|
||||
import org.springframework.data.redis.core.ReactiveStringRedisTemplate
|
||||
import org.springframework.stereotype.Component
|
||||
import reactor.core.publisher.Mono
|
||||
import java.time.Duration
|
||||
|
||||
@Component
|
||||
class FlowUtils(
|
||||
@Resource
|
||||
val template: ReactiveStringRedisTemplate
|
||||
) {
|
||||
|
||||
fun limitOnceCheck(key: String, blockTime: Int): Mono<Boolean> {
|
||||
return template.hasKey(key).flatMap { exists ->
|
||||
if (exists) {
|
||||
Mono.just(false)
|
||||
} else {
|
||||
template.opsForValue()
|
||||
.set(key, "", Duration.ofSeconds(blockTime.toLong()))
|
||||
.thenReturn(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package club.itstudio.itmanager.utils
|
||||
|
||||
import com.auth0.jwt.JWT
|
||||
import com.auth0.jwt.JWTVerifier
|
||||
import com.auth0.jwt.algorithms.Algorithm
|
||||
import com.auth0.jwt.interfaces.DecodedJWT
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Value
|
||||
import org.springframework.data.redis.core.StringRedisTemplate
|
||||
import org.springframework.security.core.userdetails.User
|
||||
import org.springframework.security.core.userdetails.UserDetails
|
||||
import org.springframework.stereotype.Component
|
||||
import java.time.Duration
|
||||
import java.util.*
|
||||
|
||||
@Component
|
||||
class JwtUtils(
|
||||
@param:Value($$"${spring.security.jwt.key}")
|
||||
private val key: String,
|
||||
@param:Value($$"${spring.security.jwt.expire-hours}")
|
||||
private val expireHours: Int,
|
||||
|
||||
private val template: StringRedisTemplate
|
||||
) {
|
||||
private val algorithm: Algorithm = Algorithm.HMAC256(key)
|
||||
private val jwtVerifier: JWTVerifier = JWT.require(algorithm).build()
|
||||
private val logger = LoggerFactory.getLogger(this::class.java)
|
||||
|
||||
fun invalidateJwt(headerToken: String?): Boolean {
|
||||
val token = this.convertToToken(headerToken) ?: return false
|
||||
try {
|
||||
val jwt = jwtVerifier.verify(token)
|
||||
val id = jwt.id
|
||||
return deleteToken(id, jwt.expiresAt)
|
||||
} catch (e: Exception) {
|
||||
logger.error("Error occurred while invalidating JWT", e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private fun deleteToken(uuid: String, time: Date): Boolean {
|
||||
val now = Date()
|
||||
val expire = (time.time - now.time).coerceAtLeast(0)
|
||||
template.opsForValue().set(
|
||||
Const.JWT_BLACK_LIST + uuid,
|
||||
"deleted",
|
||||
Duration.ofMillis(expire)
|
||||
)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun isInvalidToken(uuid: String): Boolean =
|
||||
template.hasKey(Const.JWT_BLACK_LIST + uuid) ?: false
|
||||
|
||||
fun resolveJwt(headerToken: String?): DecodedJWT? {
|
||||
val token = convertToToken(headerToken) ?: return null
|
||||
try {
|
||||
val decodedJWT = jwtVerifier.verify(token)
|
||||
if (this.isInvalidToken(decodedJWT.id)) return null
|
||||
val expiresAt = decodedJWT.expiresAt
|
||||
|
||||
return if (Date().after(expiresAt)) null
|
||||
else decodedJWT
|
||||
|
||||
} catch (e: Exception) {
|
||||
logger.error("Error occurred while resolving JWT", e)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
fun createJwt(
|
||||
details: UserDetails,
|
||||
id: Long,
|
||||
username: String
|
||||
): String {
|
||||
return JWT.create()
|
||||
.withJWTId(UUID.randomUUID().toString())
|
||||
.withClaim("id", id)
|
||||
.withClaim("username", username)
|
||||
.withClaim(
|
||||
"authorities",
|
||||
details.authorities.map { it.authority }.toList()
|
||||
)
|
||||
.withExpiresAt(expiresTime())
|
||||
.withIssuedAt(Date())
|
||||
.sign(algorithm)
|
||||
}
|
||||
|
||||
fun toUser(jwt: DecodedJWT): UserDetails {
|
||||
val claims = jwt.claims
|
||||
return User
|
||||
.withUsername(claims["username"]!!.asString())
|
||||
.password("********")
|
||||
.authorities(*(claims["authorities"]!!.asArray(String::class.java)))
|
||||
.build()
|
||||
}
|
||||
|
||||
fun toId(jwt: DecodedJWT) = jwt.claims["id"]?.asLong() ?: -1L
|
||||
|
||||
fun expiresTime(): Date {
|
||||
val cal = Calendar.getInstance()
|
||||
cal.add(Calendar.HOUR, expireHours)
|
||||
return cal.time
|
||||
}
|
||||
|
||||
fun convertToToken(headerToken: String?): String? {
|
||||
val token = headerToken?.replace("Bearer ", "")?.trim()
|
||||
return token?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
spring:
|
||||
profiles:
|
||||
active: private
|
||||
|
||||
webflux:
|
||||
base-path: /
|
||||
|
||||
mail:
|
||||
#host: smtp.example.com
|
||||
#username: 123456@example.com
|
||||
#password: password
|
||||
#port: 123456
|
||||
protocol: smtp
|
||||
properties:
|
||||
mail.smtp.auth: true
|
||||
mail.smtp.ssl.enable: true
|
||||
mail.smtp.timeout: 5000
|
||||
|
||||
rabbitmq:
|
||||
host: localhost
|
||||
port: 5672
|
||||
virtual-host: /
|
||||
#username: admin
|
||||
#password: 123456
|
||||
|
||||
application:
|
||||
name: itmanager
|
||||
|
||||
security:
|
||||
jwt:
|
||||
#key: 6846513216
|
||||
expire-hours: 168
|
||||
|
||||
datasource:
|
||||
url: jdbc:mariadb://localhost:3306/itstudio_manager
|
||||
driver-class-name: org.mariadb.jdbc.Driver
|
||||
#username: root
|
||||
#password: 123456
|
||||
|
||||
mybatis-plus:
|
||||
type-handlers-package: club.itstudio.itmanager.mapper.typehandler
|
||||
|
||||
app:
|
||||
flow-limit:
|
||||
count: 1000
|
||||
limit-time: 3
|
||||
ban-time: 60
|
||||
file:
|
||||
data-path: ./data
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user