This commit is contained in:
2023-03-04 16:29:55 +08:00
commit 397ba75479
1007 changed files with 109050 additions and 0 deletions

34
.gitignore vendored Normal file
View File

@@ -0,0 +1,34 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
.mvn/

12
bin/clean.bat Normal file
View File

@@ -0,0 +1,12 @@
@echo off
echo.
echo [信息] 清理工程target生成路径。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean
pause

12
bin/package.bat Normal file
View File

@@ -0,0 +1,12 @@
@echo off
echo.
echo [信息] 打包Web工程生成war/jar包文件。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean package -Dmaven.test.skip=true
pause

14
bin/run.bat Normal file
View File

@@ -0,0 +1,14 @@
@echo off
echo.
echo [信息] 使用Jar命令运行Web工程。
echo.
cd %~dp0
cd ../ruoyi-admin/target
set JAVA_OPTS=-Xms256m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m
java -jar %JAVA_OPTS% ruoyi-admin.jar
cd bin
pause

View File

@@ -0,0 +1,11 @@
充电桩
1. 充电桩桩类型全部都是运营桩
2. 充电桩必须绑定计费模板才能使用
3. 充电桩桩对白名单用户免费
4. 创建订单时,判断是否为白名单用户
站点白名单

134
doc/接口文档.md Normal file
View File

@@ -0,0 +1,134 @@
# 根据充电桩id查询详情接口
>根据充电桩id查询相关信息包括运营商信息、充电站信息、充电枪信息、协议信息、sim卡信息等。
入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ------ | ------ | -------- | -------- |
| pileId | String | Y | 充电桩id |
反参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | ---------------------------- |
| sn | String | Y | sn号 |
| stationName | String | Y | 站点名称 station |
| merchantName | String | Y | 运营商名称 merchant |
| pileType | String | Y | 设备类型(1-汽车桩2-电单车) model |
| gunNum | int | Y | 枪数量 model |
| interfaceStandard | String | Y | 接口标准 model |
| ratedPower | int | Y | 额定功率(单位W) model |
| outputCurrent | int | Y | 输出电流(单位A) model |
| ICCID | String | Y | sim卡信息 |
| registrationTime | String | Y | 注册时间 licence |
| expireTime | String | Y | 到期时间 licence |
![image-20220924155754954](C:\Users\李苗苗\AppData\Roaming\Typora\typora-user-images\image-20220924155754954.png)
## 站点管理列表
#### 反参
PileStationVO
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------- | -------- | :----------: |
| id | String | | 站点id |
| stationName | string | | 站点名称 |
| areaCode | S | | 省市辖区编码 |
| area | S | | 地区 |
| address | S | | 地址 |
| PileNum | Integer | | 充电设备数量 |
| merchantId | S | | 运营商ID |
| merchantName | S | | 运营商名称 |
| merchantAdminName | S | | 运营商管理员 |
| stationStatus | Integer | | 站点状态 |
| stationType | s | | 站点类型 |
| createTime | s | | 创建时间 |
| stationTel | s | | 站点电话 |
| matchCars | s | | 适用车型描述 |
| stationLng | s | | 经度 |
| stationLat | s | | 纬度 |
| construction | s | | 建设场所 |
| businessHours | s | | 营业时间描述 |
| organizationCode | s | | 组织结构代码 |
| publicFlag | s | | 是否对外开放 |
| openFlag | s | | 是否营业中 |
## BatchCreatePileDTO
| 字段名 | 类型 | | 备注 |
| ---------------- | ---- | ---- | ---------------------------- |
| merchantId | s | | 运营商id |
| stationId | s | | 充电站id |
| modelId | s | | 型号id |
| softwareProtocol | s | | 软件协议1-云快充2-永联) |
| productionDate | Date | | 生成日期 |
| connectorNum | int | | 接口数量 |
| num | int | | 生成台数 |
| remark | s | | 备注 |
### 计费模板时段详情
```
CreateBillingTemplateDTO
```
| 字段名 | 类型 | | 备注 |
| ----------------- | -------------------------------------- | ---- | ---------------------------------------- |
| name | s | | 模板名称 |
| type | s | | 时段类型 |
| electricityPriceA | BigDecimal | | 尖时段电费 |
| servicePriceA | BigDecimal | | 尖时段服务费 |
| electricityPriceB | BigDecimal | | 峰时段电费 |
| servicePriceB | | | 峰时段服务费 |
| electricityPriceC | | | 平时段电费 |
| servicePriceC | | | 平时段服务费 |
| electricityPriceD | | | 谷时段电费 |
| servicePriceD | | | 谷时段服务费 |
| remark | s | | 备注 |
| 时段清单 | private List<BillingTimeDTO> timeList; | | |
| type | String | | 时段类型1-尖时2-峰时3-平时4-谷时 |
| timeDesc | s | | 时段 例如0000-0500 |
### 快速建站DTO FastCreateStationDTO
| 字段名 | | | 备注 |
| ----------- | ---- | ---- | ------------ |
| merchantId | S | | 所属运营商id |
| stationName | S | | 名称 |
| address | S | | 地址 |
| areaCode | S | | 区域 |
### 站点导入计费模板dto ImportBillingTemplateDTO
| 字段名 | 类型 | | 备注 |
| ----------------- | ---- | ---- | ---------- |
| stationId | | | 站点id |
| billingTemplateId | | | 计费模板id |
### 查询充电枪返回前台参数
PileConnectorInfoVO
| 字段名 | 类型 | | 备注 |
| ------------------ | ---- | ---- | --------------------------- |
| connectorId | S | | 充电枪口id |
| connectorCode | S | | 枪口编号由充电桩SN+01生成 |
| connectorQrCodeUrl | S | | 充电二维码 |
| status | int | | 状态 |
| type | S | | 类型 |
| instantPower | B | | 即时功率 |
| electricity | big | | 电量 |
| SOC | S | | SOC |
| plantformOrderNum | S | | 平台订单 |
| equipmentOrderNum | S | | 设备订单号 |
| chargingTime | S | | 充电时长 |
| voltage | B | | 电压 |
| current | B | | 电流 |
| temperature | B | | 温度 |
| userInfo | S | | 用户信息 |
| orderId | S | | 订单id |
| carNo | S | | 车牌号 |

621
doc/接口文档New.md Normal file
View File

@@ -0,0 +1,621 @@
# 小程序接口
## 接口返回格式
| 字段名 | 类型 | 是否必传 | 备注 |
| ------- | ------ | -------- | ---------- |
| resCode | String | Y | 返回码 |
| msg | String | Y | 返回信息 |
| obj | Object | Y | 返回的数据 |
以下接口反参指的是obj中的数据接口返回都有resCodemsgobj这三个字段。
### 示例
~~~json
# 入参
{
"pageSize": "10",
"pageNum": "1",
"stationLng": "55.96",
"stationLat": "155.77"
}
# 反参
{
"resCode": "00100000",
"msg": "操作成功",
"obj": {
"pageNum": 1,
"pageSize": 10,
"list": [
{
"stationId": "2",
"stationName": "测试仓库",
"stationAddress": "华新镇华隆路1777号6幢D座",
"distance": "10745.74",
"electricityPrice": null,
"servicePrice": null,
"fastTotal": 0,
"fastFree": 0,
"slowTotal": 3,
"slowFree": 0
},
{
"stationId": "1",
"stationName": "测试",
"stationAddress": "黄埔江南路278号举视新能源",
"distance": "10762.94",
"electricityPrice": null,
"servicePrice": null,
"fastTotal": 0,
"fastFree": 0,
"slowTotal": 0,
"slowFree": 0
}
],
"total": 2,
"pages": 1
}
}
# 错误反参
{
"resCode": "00100010",
"msg": "查询充电站信息列表异常",
"obj": null
}
~~~
## 1001 登录注册接口
## 1002 查询会员信息
> 接口地址http://localhost:8080/uniapp/member/getMemberInfo
>
> 请求方式GET
### 入参
null在Header中需传Authorization
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| -------- | ------ | -------- | ------------ |
| MemberVO | Object | Y | 用户信息对象 |
### MemberVO
| 字段名 | 类型 | 是否必传 | 备注 |
| ------------------ | ------ | -------- | --------------------------- |
| memberId | String | Y | 会员Id |
| status | String | Y | 状态(1-正常;0-停用) |
| nickName | String | Y | 用户昵称 |
| mobileNumber | String | Y | 手机号码 |
| principalPrice | Number | Y | 本金金额 |
| giftPrice | Number | Y | 赠送金额 |
| totalAccountAmount | Number | Y | 总金额(本金金额 + 赠送金额) |
## 1003 修改会员信息
## 2001 根据经纬度查询充电站列表(分页排序)
> 接口地址http://localhost:8080/uniapp/pile/queryStationInfos
>
> 请求类型POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------- | ------ | -------- | ---------------- |
| stationLng | String | N | 经度 |
| stationLat | String | N | 纬度 |
| pageNum | Number | Y | 页码 |
| pageSize | Number | Y | 每页数量 |
| stationName | String | y | 站点名称(搜索) |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| -------- | ---------------- | -------- | ---------- |
| pageNum | Number | Y | 页码 |
| pageSize | Number | Y | 每页数量 |
| list | Array<StationVO> | Y | 充电站列表 |
| total | Number | Y | 总数 |
| pages | Number | Y | 总页数 |
StationVO
| 字段名 | 类型 | 是否必传 | 备注 |
| ---------------- | ------------- | -------- | --------------------- |
| stationId | String | Y | 站点id |
| stationName | String | Y | 站点名称 |
| stationAddress | String | Y | 站点地址 |
| stationImgList | Array<String> | N | 站点图片 |
| distance | String | N | 距离 单位千米 |
| electricityPrice | String | Y | 电费 每度单价 |
| servicePrice | String | Y | 服务费 每度单价 |
| totalPrice | String | Y | 总金额(电费+服务费) |
| fastTotal | Number | Y | 快充枪口总数 |
| fastFree | Number | Y | 快充枪口空闲数 |
| slowTotal | Number | Y | 慢充枪口总数 |
| slowFree | Number | Y | 慢充枪口空闲数 |
| stationLng | String | Y | 经度 |
| stationLat | String | Y | 纬度 |
## 3001 查询充电桩详情
## 3002 查询充电桩枪口详情
> 接口地址http://localhost:8080/uniapp/pile/selectConnectorListByParams
>
> 请求类型POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------------- | -------- | --------------------------- |
| pageNum | Number | Y | 页码 |
| pageSize | Number | Y | 每页数量 |
| merchantId | String | N | 运营商id ==接口暂未支持== |
| stationIdList | Array<Long> | N | 站点id列表 |
| pileIds | Array<Long> | N | 充电桩id列表 |
| connectorIdList | Array<Long> | N | 枪口id列表 |
| connectorCodeList | Array<String> | N | 枪口号列表 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| -------- | -------------------------- | -------- | ------------ |
| pageNum | Number | Y | 页码 |
| pageSize | Number | Y | 每页数量 |
| list | Array<PileConnectorInfoVO> | Y | 充电枪口对象 |
| total | Number | Y | 总数 |
| pages | Number | Y | 总页数 |
### PileConnectorInfoVO
| 字段名 | 类型 | 是否必传 | 备注 |
| ------------------ | ---------- | :------: | ------------------------------------------------------------ |
| connectorId | String | Y | 充电枪口id |
| connectorCode | String | Y | 枪口编号 |
| connectorQrCodeUrl | String | Y | 枪口二维码 |
| status | Number | Y | 状态 0离网 (默认)1空闲2占用未充电3占用充电中4占用预约锁定 255故障 |
| stationId | String | Y | 站点id |
| merchantId | String | Y | 运营商id |
| merchantName | String | Y | 运营商名称 |
| pileSn | String | Y | 充电桩编号 |
| type | String | Y | 类型 1-直流接口 汽车桩+快充 2-交流接口 汽车桩+慢充 3-插座接口 电单车桩 |
| instantPower | BigDecimal | Y | 即时功率 |
| electricity | BigDecimal | Y | 电量 |
| equipmentOrderNum | String | Y | 设备订单号 |
| platformOrderNum | String | Y | 平台订单 |
| chargingTime | String | Y | 充电时长 |
| voltage | BigDecimal | Y | 电压 |
| current | BigDecimal | Y | 电流 |
| gunLineTemperature | String | Y | 枪线温度 |
| userInfo | String | Y | 用户信息 |
| orderId | String | Y | 订单id |
| carNo | String | Y | 车牌号 |
| soc | String | Y | SOC |
| chargingAmount | BigDecimal | Y | 充电金额 |
| chargingDegree | BigDecimal | Y | 充电度数 |
| businessType | | y | 经营类型1-运营桩2-个人桩) |
### 示例:
```json
#
{
"pageNum": 1,
"pageSize":10,
"connectorIdList":[1]
}
#
{
"resCode": "00100000",
"msg": "操作成功",
"obj": {
"pageNum": 1,
"pageSize": 10,
"list": [
{
"connectorId": "1",
"connectorCode": "8800000000000101",
"connectorQrCodeUrl": "http://localhost/pileConnectorInfo&code=8800000000000101",
"status": 0,
"stationId": "2",
"merchantId": "5",
"merchantName": "举视(上海)新能源科技有限公司",
"pileSn": "88000000000001",
"type": "2",
"instantPower": 0.00,
"electricity": null,
"equipmentOrderNum": null,
"platformOrderNum": null,
"chargingTime": null,
"voltage": 0.0,
"current": 0.0,
"gunLineTemperature": "0",
"userInfo": null,
"orderId": null,
"carNo": null,
"chargingAmount": 0.00,
"chargingDegree": 0.00,
"soc": "0"
}
],
"total": 1,
"pages": 1
}
}
```
## 4001 启动充电
> 接口地址http://localhost:8080/uniapp/order/generateOrder
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | --------------------------- |
| pileSn | String | Y | 桩编码 |
| connectorCode | String | Y | 枪口号 |
| pileConnectorCode | String | Y | 桩枪口编号(桩编码+枪口号) |
| memToken | String | Y | 用户token写在Header中 |
备注pileSn + connectorCode 或 pileConnectorCode 选其一,接口都支持
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | ------ |
| orderCode | String | Y | 订单号 |
## 4002 结束充电
> 接口地址http://localhost:8080/uniapp/order/settleOrder
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | --------------------------- |
| orderCode | String | Y | 订单号 |
| pileSn | String | Y | 桩编码 |
| connectorCode | String | Y | 枪口号 |
| pileConnectorCode | String | Y | 桩枪口编号(桩编码+枪口号) |
### 反参
null若成功msg中会有“==操作成功==”提示
## 5001 查询订单列表
> 请求地址http://localhost:8080/uniapp/order/getOrderList
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | --------------------------- |
| memberId | String | Y | 会员id |
| pageSize | Number | Y | |
| pageNum | Number | Y | |
| orderStatus | String | Y | 订单状态 1-全部 2-未完成 3-已完成 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | --------------------------- |
| orderCode | String | Y | 订单号 |
| pileSn | String | Y | 桩编码 |
| connectorCode | String | Y | 枪口号 |
| stationName | String | Y | 站点名称 |
| pileConnectorCode | String | Y | 桩枪口编号(桩编码+枪口号) |
| chargingDegree | BigDecimal | Y | 充电度数|
| orderAmount | BigDecimal | Y | 订单金额 |
| orderStatus | String | Y | 订单状态(0-待支付1-充电中2-待结算3-待补缴4-异常5-可疑6-订单完成) |
| startTime | String | Y | 订单开始时间 |
| endTime | String | Y | 订单结束时间 |
| payAmount | BigDecimal | Y | 用户支付金额 |
| payStatus | String | Y | 支付状态(0-待支付1-支付完成) |
| reason | String | Y | 订单异常原因 |
## 60001 查询余额明细
> 请求地址: http://localhost:8080/uniapp/member/getMemberBalanceChanges
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------- | ------ | -------- | ------------------------ |
| memberToken | String | Y | 会员令牌 |
| type | String | Y | 交易类型 1-进账2-出账 |
| pageSize | | | |
| pageNum | | | |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| ------------------ | ------ | -------- | -------------------------- |
| memberId | String | Y | 会员Id |
| principalBalance | Number | Y | 当前账户本金余额 |
| giftBalance | Number | Y | 当前账户赠送余额 |
| totalAccountAmount | Number | Y | 账户总余额 |
| type | String | Y | 交易类型 1-进账2-出账 |
| subType | String | Y | 子类型 |
| amount | String | Y | 出账/入账金额 |
| transactionTime | String | Y | 交易时间 |
| category | String | Y | 余额类型1-本金2-赠送) |
## 7001 生成订单
> 请求地址http://localhost:8080/uniapp/order/generateOrder
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | ---------- |
| pileConnectorCode | String | Y | 桩枪口编码 |
| chargeAmount | Number | Y | 充电金额 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | ------ |
| orderCode | String | Y | 订单号 |
## 7002 支付订单
> 请求地址http://localhost:8080/uniapp/pay/payOrder
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | -------- |
| orderCode | String | Y | 订单号 |
| payMode | String | Y | 支付方式 |
| payAmount | String | Y | 支付金额 |
### 反参
null提示”==操作成功==“
## 7003 订单停止充电
> 请求地址http://localhost:8080/uniapp/order/stopCharging
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | ------ |
| orderCode | String | Y | 订单号 |
### 反参
null提示”==操作成功==“
# 首页大数据展示
## 8001 概况
> 请求地址http://localhost:8080/index/getGeneralSituation
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | ------ |
| stationId | String | N | 站点id |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------------------- | ------ | -------- | ---------- |
| totalChargingDegree | String | Y | 总充电电量 |
| totalChargingAmount | String | Y | 总充电费用 |
| totalChargingQuantity | String | Y | 总充电笔数 |
| totalPileQuantity | String | Y | 总设备数量 |
| totalMemberAmount | String | Y | 总客户余额 |
## 8002 订单
> 请求地址http://localhost:8080/index/getOrderInfo
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| --------- | ------ | -------- | ------ |
| stationId | String | N | 站点id |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| -------------------------- | ------ | -------- | -------------- |
| date | String | Y | 日期 |
| totalElectricity | String | Y | 总用电量 |
| totalOrderAmount | String | Y | 总订单金额 |
| totalSharpUsedElectricity | String | Y | 尖时段总用电量 |
| totalPeakUsedElectricity | String | Y | 峰时段总用电量 |
| totalFlatUsedElectricity | String | Y | 平时段总用电量 |
| totalValleyUsedElectricity | String | Y | 谷时段总用电量 |
# 个人桩相关
## 9001 用户绑定个人桩
> 请求地址: http://localhost:8080/uniapp/personalPile/pileMemberBinding
>
> 请求方式: POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ---------------- | ------ | -------- | -------------- |
| pileSn | String | Y | 桩编码 |
| phoneNumber | String | Y | 用户手机号码 |
| verificationCode | String | Y | 用户手机验证码 |
### 反参
## 9002 桩管理员下发给其他用户
> 请求地址http://localhost:8080/uniapp/personalPile/adminIssuePile
>
> 请求方式: POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------- | ------ | -------- | -------------------- |
| PileSn | String | Y | 桩编码 |
| phoneNumber | String | Y | 另一个用户的手机号码 |
## 9003 获取个人桩列表
> 请求地址: http://localhost:8080/uniapp/personalPile/getPersonalPileList
>
> 请求方式: GET
### 反参
### List<PersonalPileInfoVO>
| 字段名 | 类型 | 是否必传 | 备注 |
| ------------ | ------ | -------- | ---------------------------- |
| pileSn | String | Y | 桩编码 |
| connectorNum | String | Y | 枪口数量==(2023.02.23新增)== |
| memberId | String | Y | 会员id |
| type | String | Y | 身份类型 |
| modelName | String | Y | 型号 |
| ratedPower | String | Y | 额定功率 |
| ratedCurrent | String | Y | 额定电流 |
| ratedVoltage | String | Y | 额定电压 |
| speedType | String | Y | 充电类型 |
## 9004 获取枪口实时数据
> 请求地址http://localhost:8080/uniapp/personalPile/getConnectorRealTimeInfo
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | -------- |
| pileConnectorCode | String | Y | 桩枪口号 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| -------------- | ------ | -------- | -------- |
| instantCurrent | Number | Y | 实时电流 |
| instantVoltage | Number | Y | 实时电压 |
| instantPower | Number | Y | 实时功率 |
## 9005 累积充电量数据
> 请求地址http://localhost:8080/uniapp/personalPile/getAccumulativeInfo
>
> 请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | -------- |
| pileConnectorCode | String | Y | 桩枪口号 |
| startTime | String | Y | 开始日期 |
| endTime | String | Y | 结束日期 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| ---------------------- | ------ | -------- | ------------ |
| memberId | String | Y | 会员id |
| startTime | String | Y | 开始日期 |
| endTime | String | Y | 结束日期 |
| sumChargingElectricity | String | Y | 累计充电量 |
| sumChargingTime | String | Y | 累计充电时长 |
## 9006 充电记录
请求地址http://localhost:8080/uniapp/personalPile/getChargingRecord
请求方式POST
### 入参
| 字段名 | 类型 | 是否必传 | 备注 |
| ----------------- | ------ | -------- | -------- |
| pileConnectorCode | String | Y | 桩枪口号 |
| pageNum | Number | Y | 页码 |
| pageSize | Number | Y | 每页数量 |
### 反参
| 字段名 | 类型 | 是否必传 | 备注 |
| ------------------- | ------ | -------- | -------- |
| startChargingTime | String | Y | 启动时间 |
| endChargingTime | String | Y | 结束时间 |
| chargingElectricity | String | Y | 用电量 |
| chargingTime | String | Y | 充电时长 |

5
doc/测试问题.md Normal file
View File

@@ -0,0 +1,5 @@
# 测试问题
1、充电桩型号表 pile_model_info ==speed_type== 和==charger_pile_type==字段,在前台新增桩型号时未设置值
2、用户正常开始充电后桩由于意外情况清除订单记录此时后台该订单一直为充电中状态用户的开始扣款金额无法退回

127
jsowell-admin/pom.xml Normal file
View File

@@ -0,0 +1,127 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-charger-web</artifactId>
<version>1.0.0</version>
</parent>
<packaging>jar</packaging>
<artifactId>jsowell-admin</artifactId>
<description>
web服务入口
</description>
<dependencies>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional> <!-- 表示依赖不会传递 -->
</dependency>
<!-- swagger3-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
</dependency>
<!-- 防止进入swagger页面报类型转换错误排除3.0.0中的引用手动增加1.6.2版本 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.2</version>
</dependency>
<!-- Mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 核心模块-->
<dependency>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-framework</artifactId>
</dependency>
<!-- 定时任务-->
<dependency>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-quartz</artifactId>
</dependency>
<!-- 代码生成-->
<dependency>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-generator</artifactId>
</dependency>
<dependency>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-pile</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-netty</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.1.1.RELEASE</version>
<configuration>
<fork>true</fork> <!-- 如果没有该配置devtools不会生效 -->
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
<warName>${project.artifactId}</warName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<testExcludes>
<testExclude>/src/test/**</testExclude>
</testExcludes>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>

View File

@@ -0,0 +1,21 @@
package com.jsowell;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
/**
* 启动程序
*
* @author jsowell
*/
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class JsowellApplication {
public static void main(String[] args) {
// System.setProperty("spring.devtools.restart.enabled", "false");
SpringApplication.run(JsowellApplication.class, args);
}
}

View File

@@ -0,0 +1,16 @@
package com.jsowell;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* web容器中进行部署
*
* @author jsowell
*/
public class JsowellServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(JsowellApplication.class);
}
}

View File

@@ -0,0 +1,70 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.pile.vo.uniapp.PileConnectorVO;
import com.jsowell.service.PileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@Anonymous
@RestController
@RequestMapping("/app-xcx-h5")
public class JumpController extends BaseController {
@Autowired
private PileService pileService;
/**
* 查询充电桩详情
* http://localhost:8080/app-xcx-h5/pile/pileDetail/{pileSn}
*/
@GetMapping("/pile/pileDetail/{pileSn}")
public RestApiResponse<?> getPileDetail(HttpServletRequest request, @PathVariable("pileSn") String pileSn) {
logger.info("app-xcx-h5查询充电桩详情 param:{}", pileSn);
RestApiResponse<?> response = null;
try {
PileConnectorVO vo = pileService.getPileDetailByPileSn(pileSn);
response = new RestApiResponse<>(vo);
} catch (BusinessException e) {
logger.warn("app-xcx-h5查询充电桩详情 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("app-xcx-h5查询充电桩详情 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PILE_DETAIL_ERROR);
}
logger.info("app-xcx-h5查询充电桩详情 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 查询充电枪口详情
* http://localhost:8080/app-xcx-h5/pile/connectorDetail/{pileConnectorCode}
*/
@GetMapping("/pile/connectorDetail/{pileConnectorCode}")
public RestApiResponse<?> getConnectorDetail(HttpServletRequest request, @PathVariable("pileConnectorCode") String pileConnectorCode) {
logger.info("app-xcx-h5查询充电枪口详情 param:{}", pileConnectorCode);
RestApiResponse<?> response = null;
try {
PileConnectorVO vo = pileService.getConnectorDetail(pileConnectorCode);
response = new RestApiResponse<>(vo);
} catch (BusinessException e) {
logger.warn("app-xcx-h5查询充电枪口详情 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("app-xcx-h5查询充电枪口详情 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PILE_DETAIL_ERROR);
}
logger.info("app-xcx-h5查询充电枪口详情 result:{}", JSONObject.toJSONString(response));
return response;
}
}

View File

@@ -0,0 +1,199 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.exception.ServiceException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.SMSUtil;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.MemberRegisterDTO;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.dto.WechatLoginDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 小程序接口
*/
// 不登录直接访问
@Anonymous
@RestController
@RequestMapping("/uniapp/member")
public class MemberController extends BaseController {
@Autowired
private MemberService memberService;
/**
* 下发短信接口 business
* http://localhost:8080/uniapp/member/sendSMS
*/
@PostMapping("/sendSMS")
public RestApiResponse<?> sendSMS(HttpServletRequest request, @RequestBody MemberRegisterAndLoginDTO dto) {
logger.info("下发短信接口 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
if (StringUtils.isBlank(dto.getMobileNumber())) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
String sendSMSResult = SMSUtil.sendSMS(request, dto.getMobileNumber());
response = new RestApiResponse<>(sendSMSResult);
} catch (Exception e) {
logger.error("下发短信接口 发生异常 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_SEND_SMS_ERROR);
}
logger.info("下发短信接口 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 会员登录注册
* 登录成功返回memberToken
* http://localhost:8080/uniapp/member/memberRegisterAndLogin
*/
@PostMapping("/memberRegisterAndLogin")
public RestApiResponse<?> memberRegisterAndLogin(HttpServletRequest request, @RequestBody MemberRegisterAndLoginDTO dto) {
logger.info("会员登录注册接口 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
// 执行登录(查这个手机号在后台有没有数据,如果没有就静默注册)
String memberToken = memberService.memberRegisterAndLogin(dto);
// 返回前端成功
Map<String, String> map = Maps.newHashMap();
map.put("memberToken", memberToken);
response = new RestApiResponse<>(map);
} catch (ServiceException e) {
logger.warn("会员登录注册接口 warn", e);
response = new RestApiResponse<>(e.getMessage());
} catch (Exception e) {
logger.error("会员登录注册接口 发生异常 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_MEMBER_REGISTER_AND_LOGIN_ERROR);
}
return response;
}
/**
* 微信一键登录
* http://localhost:8080/uniapp/member/wechatLogin
*/
@PostMapping("/wechatLogin")
public RestApiResponse<?> wechatLogin(@RequestBody WechatLoginDTO dto) {
RestApiResponse<?> response = null;
try {
String memberToken = memberService.wechatLogin(dto);
response = new RestApiResponse<>(ImmutableMap.of("memberToken", memberToken));
} catch (Exception e) {
logger.error("微信登录异常", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_WECHAT_LOGIN_ERROR);
}
return response;
}
/**
* 接收并处理前端用户信息
*
* http://localhost:8080/uniapp/member/saveUserInfo
*/
@PostMapping("/saveUserInfo")
public RestApiResponse<?> saveUserInfo(@RequestBody MemberRegisterDTO dto) {
logger.info("接受前端用户信息并处理 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
memberService.handleUserInfo(dto);
response = new RestApiResponse<>();
} catch (Exception e) {
logger.error("处理用户信息异常", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_HANDLE_USER_INFO_ERROR);
}
logger.info("接受前端用户信息并处理 result:{}", response);
return response;
}
/**
* 查询用户账户信息
*
* http://localhost:8080/uniapp/member/getMemberInfo
* @return 用户账户信息
*/
@GetMapping("/getMemberInfo")
public RestApiResponse<?> getMemberInfo(HttpServletRequest request) {
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
logger.info("查询账户总余额 param memberId:{}", memberId);
MemberVO memberVO = memberService.getMemberInfoByMemberId(memberId);
response = new RestApiResponse<>(memberVO);
}catch (BusinessException e) {
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception e) {
logger.error("查询用户账户总余额异常", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_MEMBER_ACCOUNT_AMOUNT_ERROR);
}
logger.info("查询用户账户信息 result:{}", response);
return response;
}
/**
* 获取openId
* http://localhost:8080/uniapp/member/getOpenId
*/
@PostMapping("/getOpenId")
public RestApiResponse<?> getOpenId(HttpServletRequest request, @RequestBody WeixinPayDTO dto) {
logger.info("获取openId param:{}", dto.toString());
RestApiResponse<?> response;
try {
getMemberIdByAuthorization(request);
String openId = memberService.getOpenIdByCode(dto.getCode());
response = new RestApiResponse<>(ImmutableMap.of("openId", openId));
} catch (Exception e) {
logger.error("获取openId error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
}
logger.info("获取openId result:{}", response);
return response;
}
/**
* 获取用户账户余额变动信息
* http://localhost:8080/uniapp/member/getMemberBalanceChanges
* @param request
* @param dto
* @return
*/
@PostMapping("/getMemberBalanceChanges")
public RestApiResponse<?> getMemberBalanceChanges(HttpServletRequest request, @RequestBody UniAppQueryMemberBalanceDTO dto) {
logger.info("查询用户账户余额变动信息 params:{}", dto.toString() );
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
PageResponse pageResponse = memberService.getMemberBalanceChanges(dto);
response = new RestApiResponse<>(pageResponse);
} catch (Exception e) {
logger.error("查询用户账户余额变动信息 error:", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_BALANCE_CHANGES_ERROR);
}
logger.info("查询用户账户余额变动信息 result:{}", response);
return response;
}
}

View File

@@ -0,0 +1,244 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.dto.GenerateOrderDTO;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.dto.SettleOrderDTO;
import com.jsowell.pile.dto.StopChargingDTO;
import com.jsowell.pile.dto.UniAppQueryOrderDTO;
import com.jsowell.pile.vo.uniapp.UniAppOrderVO;
import com.jsowell.service.OrderService;
import com.jsowell.service.PileRemoteService;
import com.jsowell.wxpay.dto.WechatSendMsgDTO;
import com.jsowell.wxpay.service.WxAppletRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 订单相关接口
* 提供给小程序
*/
@Anonymous
@RestController
@RequestMapping("/uniapp/order")
public class OrderController extends BaseController {
@Autowired
private OrderService orderService;
@Autowired
private PileRemoteService pileRemoteService;
@Autowired
private WxAppletRemoteService wxAppletRemoteService;
/**
* 生成订单
* http://localhost:8080/uniapp/order/generateOrder
*/
@PostMapping("/generateOrder")
public RestApiResponse<?> generateOrder(HttpServletRequest request, @RequestBody GenerateOrderDTO dto) {
logger.info("生成订单 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response;
try {
if ((StringUtils.isBlank(dto.getPileSn()) || StringUtils.isBlank(dto.getConnectorCode())) && StringUtils.isBlank(dto.getPileConnectorCode())) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isEmpty(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
dto.setMemberId(memberId);
// 生成订单
dto.setStartMode(Constants.ONE); // 启动方式 1-app启动
String orderCode = orderService.generateOrder(dto);
response = new RestApiResponse<>(ImmutableMap.of("orderCode", orderCode));
} catch (BusinessException e) {
logger.warn("生成订单 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("生成订单 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GENERATE_ORDER_ERROR);
}
logger.info("生成订单 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 停止充电
* http://localhost:8080/uniapp/order/stopCharging
*/
@PostMapping ("/stopCharging")
public RestApiResponse<?> stopCharging(HttpServletRequest request, @RequestBody StopChargingDTO dto) {
logger.info("停止充电 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response;
try {
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isEmpty(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
dto.setMemberId(memberId);
orderService.stopCharging(dto);
response = new RestApiResponse<>();
} catch (BusinessException e) {
logger.warn("停止充电 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("停止充电 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_STOP_CHARGING_ERROR);
}
return response;
}
/**
* 结算订单
* http://localhost:8080/uniapp/order/settleOrder
* @param dto 结算订单DTO
* @return
*/
@PostMapping("/settleOrderForWeb")
public RestApiResponse<?> settleOrder(HttpServletRequest request, @RequestBody SettleOrderDTO dto) {
logger.info("结算订单 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response;
try {
orderService.settleOrderForWeb(dto);
response = new RestApiResponse<>();
} catch (Exception e) {
logger.error("结算订单错误", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_SETTLE_ORDER_ERROR);
}
return response;
}
/**
* 查询订单信息
* http://localhost:8080/uniapp/order/getOrderList
* @return
*/
@PostMapping("/getOrderList")
public RestApiResponse<?> getOrderInfo(HttpServletRequest request, @RequestBody UniAppQueryOrderDTO dto) {
logger.info("查询订单信息 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
// 通过memberId查询某状态订单列表
PageResponse pageInfoList = orderService.getListByMemberIdAndOrderStatus(memberId, dto);
response = new RestApiResponse<>(pageInfoList);
} catch (BusinessException e) {
logger.warn("查询订单信息 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("查询订单信息 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_ORDER_INFO_BY_MEMBER_ID_ERROR);
}
logger.info("查询订单信息, result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 小程序获取订单详情
* http://localhost:8080/uniapp/order/getOrderDetail
* @param request
* @param dto
* @return
*/
@PostMapping("/getOrderDetail")
public RestApiResponse<?> getOrderDetail(HttpServletRequest request, @RequestBody UniAppQueryOrderDTO dto) {
logger.info("小程序获取订单详情 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
UniAppOrderVO uniAppOrderDetail = orderService.getUniAppOrderDetail(dto.getOrderCode());
response = new RestApiResponse<>(uniAppOrderDetail);
} catch (BusinessException e) {
logger.warn("小程序获取订单详情 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("小程序获取订单详情 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_ORDER_DETAIL_ERROR);
}
logger.info("小程序获取订单详情, result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 根据订单号查询充电桩启动状态
* http://localhost:8080/uniapp/order/selectPileStarterStatus
*/
@PostMapping("/selectPileStarterStatus")
public RestApiResponse<?> selectPileStarterStatus(HttpServletRequest request, @RequestBody UniAppQueryOrderDTO dto) {
logger.info("根据订单号查询充电桩启动状态 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
// String memberId = getMemberIdByAuthorization(request);
String status = orderService.selectPileStarterStatus(dto.getOrderCode());
response = new RestApiResponse<>(ImmutableMap.of("status", status));
} catch (Exception e) {
logger.error("根据订单号查询充电桩启动状态 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_ORDER_DETAIL_ERROR);
}
logger.info("根据订单号查询充电桩启动状态 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 微信小程序发送启动充电推送消息
* http://localhost:8080/uniapp/order/uniAppStartChargingSendMsg
* @param dto
* @return
*/
@PostMapping("/uniAppStartChargingSendMsg")
public RestApiResponse<?> uniAppStartChargingSendMsg(@RequestBody WechatSendMsgDTO dto) {
logger.info("微信小程序发送启动充电推送消息 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
Map<String, String> resultMap = wxAppletRemoteService.startChargingSendMsg(dto);
response = new RestApiResponse<>(resultMap);
} catch (Exception e){
logger.error("微信小程序发送启动充电推送消息 error", e);
response = new RestApiResponse<>("00300001", "微信小程序发送启动充电推送消息异常");
}
logger.info("微信小程序发送启动充电推送消息 result:{}", response);
return response;
}
/**
* 关闭支付未启动的订单
* http://localhost:8080/uniapp/order/closeStartFailedOrder
*/
@PostMapping("/closeStartFailedOrder")
public RestApiResponse<?> closeStartFailedOrder(@RequestBody QueryOrderDTO dto) {
logger.info("关闭支付未启动的订单 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
orderService.closeStartFailedOrder(dto);
response = new RestApiResponse<>();
} catch (Exception e){
logger.error("关闭支付未启动的订单 error", e);
response = new RestApiResponse<>("00300002", "关闭支付未启动的订单异常");
}
logger.info("关闭支付未启动的订单 result:{}", response);
return response;
}
}

View File

@@ -0,0 +1,204 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.enums.ykc.ScenarioEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.pile.dto.PayOrderDTO;
import com.jsowell.pile.dto.PaymentScenarioDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.service.MemberService;
import com.jsowell.service.OrderService;
import com.jsowell.wxpay.dto.WeChatRefundDTO;
import com.jsowell.wxpay.response.WechatPayNotifyParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 支付相关controller
*/
@Anonymous
@RestController
@RequestMapping("/uniapp/pay")
public class PayController extends BaseController {
@Autowired
private MemberService memberService;
@Autowired
private OrderService orderService;
@Autowired
private RedisCache redisCache;
/**
* 充值余额支付
* 提供给小程序使用
* http://localhost:8080/uniapp/pay/weixinPay
*/
@PostMapping("/weixinPay")
public RestApiResponse<?> weixinPay(HttpServletRequest request, @RequestBody WeixinPayDTO dto) {
logger.info("微信支付 param:{}", dto.toString());
RestApiResponse<?> response;
try {
if (StringUtils.isBlank(dto.getCode()) || StringUtils.isBlank(dto.getAmount())) {
return new RestApiResponse<>(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
// 鉴权
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
dto.setMemberId(memberId);
String openId = memberService.getOpenIdByCode(dto.getCode());
if (StringUtils.isBlank(openId)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
}
dto.setOpenId(openId);
// 充值余额 附加参数
PaymentScenarioDTO paymentScenarioDTO = new PaymentScenarioDTO();
paymentScenarioDTO.setType(ScenarioEnum.BALANCE.getValue());
paymentScenarioDTO.setMemberId(memberId);
dto.setAttach(JSONObject.toJSONString(paymentScenarioDTO));
dto.setDescription("会员充值余额");
Map<String, Object> weixinMap = orderService.weixinPayV3(dto);
response = new RestApiResponse<>(ImmutableMap.of("weixinMap", weixinMap));
} catch (Exception e) {
response = new RestApiResponse<>();
}
return response;
}
/**
* 支付订单
* http://localhost:8080/uniapp/pay/payOrder
*
* @param request
* @param dto
* @return
*/
@PostMapping("/payOrder")
public RestApiResponse<?> payOrder(HttpServletRequest request, @RequestBody PayOrderDTO dto) {
logger.info("支付订单 param:{}", dto.toString());
RestApiResponse<?> response;
// 支付订单加锁
String lockKey = "pay_order_" + dto.getOrderCode();
String lockValue = IdUtils.fastUUID();
try {
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
dto.setMemberId(memberId);
dto.setLockValue(lockValue);
// redis锁
Boolean isLock = redisCache.lock(lockKey, lockValue, 60);
Map<String, Object> map = null;
if (isLock) {
map = orderService.payOrder(dto);
}
// Map<String, Object> map = orderService.payOrder(dto);
response = new RestApiResponse<>(map);
} catch (BusinessException e) {
logger.warn("支付订单 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("支付订单 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_ERROR);
} finally {
// 支付订单解锁
if (lockValue.equals(redisCache.getCacheObject(lockKey).toString())) {
redisCache.unLock(lockKey);
}
}
logger.info("支付订单 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 微信支付回调接口
* http://localhost:8080/uniapp/pay/callback
* https://api.jsowellcloud.com/uniapp/pay/wechatPayCallback
*/
@PostMapping("/wechatPayCallback")
public RestApiResponse<?> wechatPayCallback(HttpServletRequest request, @RequestBody WechatPayNotifyParameter body) {
logger.info("1----------->微信支付回调开始 body:{}", JSONObject.toJSONString(body));
RestApiResponse<?> response;
try {
orderService.wechatPayCallback(request, body);
response = new RestApiResponse<>();
} catch (BusinessException e) {
logger.warn("微信支付回调接口warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("微信支付回调接口error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_CALLBACK_ERROR);
}
return response;
}
/**
* 微信退款回调接口
* @param request
* @param body
* @return
*/
@PostMapping("/wechatPayRefundCallback")
public RestApiResponse<?> wechatPayRefundCallback(HttpServletRequest request, @RequestBody WechatPayNotifyParameter body) {
logger.info("微信退款回调接口 body:{}", JSONObject.toJSONString(body));
RestApiResponse<?> response;
try {
orderService.wechatPayRefundCallback(request, body);
response = new RestApiResponse<>();
} catch (BusinessException e) {
logger.warn("微信退款回调接口warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("微信退款回调接口error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_ORDER_PAY_CALLBACK_ERROR);
}
return response;
}
/**
* 微信退款接口
* https://api.jsowellcloud.com/uniapp/pay/refund
*/
@PostMapping("/refund")
public RestApiResponse<?> weChatRefund(HttpServletRequest request, @RequestBody WeChatRefundDTO dto) {
RestApiResponse<?> response;
try {
if (dto.getRefundAmount() == null) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
String memberId = getMemberIdByAuthorization(request);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
dto.setMemberId(memberId);
dto.setRefundType("2");
orderService.weChatRefund(dto);
response = new RestApiResponse<>();
} catch (BusinessException e) {
logger.warn("微信退款接口 warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("微信退款接口 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_WEIXIN_REFUND_ERROR);
}
return response;
}
}

View File

@@ -0,0 +1,213 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.pile.dto.PileMemberBindingDTO;
import com.jsowell.pile.dto.QueryPersonPileDTO;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileMemberRelationService;
import com.jsowell.pile.vo.uniapp.OrderVO;
import com.jsowell.pile.vo.uniapp.PersonPileConnectorSumInfoVO;
import com.jsowell.pile.vo.uniapp.PersonPileRealTimeVO;
import com.jsowell.pile.vo.uniapp.PersonalPileInfoVO;
import com.jsowell.service.PileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 个人桩controller
*
* @author JS-ZZA
* @date 2023/2/23 15:36
*/
@Anonymous
@RestController
@RequestMapping("/uniapp/personalPile")
public class PersonPileController extends BaseController {
@Autowired
private IPileMemberRelationService pileMemberRelationService;
@Autowired
private PileService pileService;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
/**
* 用户绑定个人桩
*
* http://localhost:8080/uniapp/personalPile/pileMemberBinding
*
* @param dto
* @return
*/
@RequestMapping("/pileMemberBinding")
public RestApiResponse<?> pileMemberBinding(HttpServletRequest request, @RequestBody PileMemberBindingDTO dto){
logger.info("绑定个人桩信息 params:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
int i = pileService.pileMemberBinding(dto);
response = new RestApiResponse<>(i);
}catch (BusinessException e){
logger.error("绑定个人桩信息 error,", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception exception){
logger.error("绑定个人桩信息 error,", exception);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_BINDING_PERSONAL_PILE_ERROR);
}
logger.info("绑定个人桩信息 result:{}", response);
return response;
}
/**
* 个人桩管理员下发给其他用户
*
* http://localhost:8080/uniapp/personalPile/adminIssuePile
*
* @param request
* @param dto
* @return
*/
@RequestMapping("/adminIssuePile")
public RestApiResponse<?> adminIssuePile(HttpServletRequest request, @RequestBody PileMemberBindingDTO dto){
logger.info("桩管理员下发个人桩 params: {}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
pileService.adminIssuePile(dto);
response = new RestApiResponse<>();
}catch (BusinessException e) {
logger.error("桩管理员下发个人桩 error", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception e){
logger.error("桩管理员下发个人桩 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_ADMIN_ISSUE_ERROR);
}
logger.info("桩管理员下发个人桩 result: {}", response);
return response;
}
/**
* 通过memberId查个人桩列表
*
* http://localhost:8080/uniapp/personalPile/getPersonalPileList
*
* @return
*/
@GetMapping("/getPersonalPileList")
public RestApiResponse<?> getPersonalPileList(HttpServletRequest request){
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
logger.info("通过memberId查个人桩列表 params: {}", memberId);
List<PersonalPileInfoVO> list = pileBasicInfoService.getPileInfoByMemberId(memberId);
response = new RestApiResponse<>(list);
}catch (Exception e){
logger.error("通过memberId查个人桩列表异常", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PERSONAL_PILE_BY_MEMBER_ID_ERROR);
}
logger.info("通过memberId查个人桩列表 result:{}", response);
return response;
}
/**
* 获取枪口实时数据
*
* http://localhost:8080/uniapp/personalPile/getConnectorRealTimeInfo
*
* @param request
* @param dto
* @return
*/
@PostMapping("/getConnectorRealTimeInfo")
public RestApiResponse<?> getConnectorRealTimeInfo(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto){
logger.info("获取个人桩枪口实时数据 params:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
PersonPileRealTimeVO connectorRealTimeInfo = pileService.getConnectorRealTimeInfo(dto);
response = new RestApiResponse<>(connectorRealTimeInfo);
}catch (BusinessException e){
logger.error("获取个人桩枪口实时数据 error", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception e){
logger.error("获取个人桩枪口实时数据 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PERSONAL_PILE_CONNECTOR_INFO_ERROR);
}
logger.info("获取个人桩枪口实时数据 result:{}", response);
return response;
}
/**
* 获取某枪口某段时间内累计信息
*
* http://localhost:8080/uniapp/personalPile/getAccumulativeInfo
*
* @param dto
* @return
*/
@RequestMapping("/getAccumulativeInfo")
public RestApiResponse<?> getAccumulativeInfo(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto) {
logger.info("获取某枪口某段时间内累计信息 params:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
PersonPileConnectorSumInfoVO accumulativeInfo = pileService.getAccumulativeInfo(dto);
response = new RestApiResponse<>(accumulativeInfo);
} catch (BusinessException e){
logger.error("获取某枪口某段时间内累计信息 error", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception e){
logger.error("获取某枪口某段时间内累计信息 error", e);
response = new RestApiResponse<>(e);
}
logger.info("获取某枪口某段时间内累计信息 result:{}", response);
return response;
}
/**
* 获取充电记录
*
* http://localhost:8080/uniapp/personalPile/getChargingRecord
*
* @param request
* @param dto
* @return
*/
@RequestMapping("/getChargingRecord")
public RestApiResponse<?> getChargingRecord(HttpServletRequest request, @RequestBody QueryPersonPileDTO dto){
logger.info("获取个人桩充电记录 params:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
String memberId = getMemberIdByAuthorization(request);
dto.setMemberId(memberId);
PageResponse chargingRecord = pileService.getChargingRecord(dto);
response = new RestApiResponse<>(chargingRecord);
}catch (BusinessException e){
logger.error("获取个人桩充电记录 error", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
}catch (Exception e){
logger.error("获取个人桩充电记录 error", e);
response = new RestApiResponse<>(e);
}
logger.info("获取个人桩充电记录 result:{}", response);
return response;
}
}

View File

@@ -0,0 +1,91 @@
package com.jsowell.api.uniapp;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.dto.QueryStationDTO;
import com.jsowell.pile.service.IPileConnectorInfoService;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.vo.uniapp.PersonalPileInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* 充电桩相关接口
* 提供给小程序调用
*/
// 不登录直接访问
@Anonymous
@RestController
@RequestMapping("/uniapp/pile")
public class PileController extends BaseController {
@Autowired
private IPileStationInfoService pileStationInfoService;
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
/**
* 查询充电站信息列表(主页)
*
* http://localhost:8080/uniapp/pile/queryStationInfos
*/
@PostMapping("/queryStationInfos")
public RestApiResponse<?> queryStationInfos(HttpServletRequest request, @RequestBody QueryStationDTO queryStationDTO) {
logger.info("查询充电站信息列表 param:{}", JSONObject.toJSONString(queryStationDTO));
RestApiResponse<?> response = null;
try {
getMemberIdByAuthorization(request);
// startPage();
// List<PileStationVO> list = pileStationInfoService.uniAppQueryStationInfos(queryStationDTO);
PageResponse pageResponse = pileStationInfoService.uniAppQueryStationInfoList(queryStationDTO);
response = new RestApiResponse<>(pageResponse);
} catch (BusinessException e) {
logger.warn("查询充电站信息列表warn", e);
response = new RestApiResponse<>(e.getCode(), e.getMessage());
} catch (Exception e) {
logger.error("查询充电站信息列表异常 error", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_PILE_STATION_INFO_ERROR);
}
logger.info("查询充电站信息列表 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 通过前端参数查询充电枪口列表
*
* http://localhost:8080/uniapp/pile/selectConnectorListByParams
*
* @param dto
* @return
*/
@PostMapping("/selectConnectorListByParams")
public RestApiResponse<?> selectConnectorListByParams(HttpServletRequest request, @RequestBody QueryConnectorListDTO dto) {
logger.info("查询充电枪口列表 params:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response = null;
try {
PageResponse pageResponse = pileConnectorInfoService.getUniAppConnectorInfoListByParams(dto);
response = new RestApiResponse<>(pageResponse);
} catch (Exception e) {
logger.error("查询充电枪口列表异常", e);
response = new RestApiResponse<>(ReturnCodeEnum.CODE_GET_CONNECTOR_INFO_BY_STATION_ID_ERROR);
}
logger.info("查询充电枪口列表 result:{}", response);
return response;
}
}

View File

@@ -0,0 +1,234 @@
package com.jsowell.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.uniapp.BalanceChangesEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.domain.MemberWalletInfo;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.MemberRegisterDTO;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.dto.WechatLoginDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IPileMerchantInfoService;
import com.jsowell.pile.transaction.dto.MemberTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.pile.vo.uniapp.MemberWalletLogVO;
import com.jsowell.wxpay.service.WxAppletRemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;
@Service
public class MemberService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private RedisCache redisCache;
@Autowired
private TransactionService transactionService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private IPileMerchantInfoService pileMerchantInfoService;
@Autowired
private WxAppletRemoteService wxAppletRemoteService;
/**
* 校验短信验证码
* @param dto
*/
public void checkVerificationCode(MemberRegisterAndLoginDTO dto) {
// 取出缓存中的验证码进行对比,如果缓存中没有,则超时
String captchaCode = redisCache.getCacheObject(CacheConstants.SMS_VERIFICATION_CODE_KEY + dto.getMobileNumber());
if (StringUtils.isEmpty(captchaCode)) {
throw new BusinessException(ReturnCodeEnum.CODE_VERIFICATION_CODE_TIMEOUT_ERROR);
}
// 如果缓存中有,但与实际不一致,则为验证码错误
if (!StringUtils.equals(captchaCode, dto.getVerificationCode())) {
throw new BusinessException(ReturnCodeEnum.CODE_VERIFICATION_CODE_ERROR);
}
}
/**
* 短信验证码登录注册
* @param dto
* @return
*/
public String memberRegisterAndLogin(MemberRegisterAndLoginDTO dto) {
// 校验短信验证码 两种情况不能通过校验1-验证码错误2-超时 验证码10分钟有效
checkVerificationCode(dto);
String merchantId = "";
return memberRegisterAndLogin(dto.getMobileNumber(), merchantId, null);
}
/**
* 公共登陆注册方法
* @param phoneNumber 手机号
* @param merchantId 商户id
* @return
*/
private String memberRegisterAndLogin(String phoneNumber, String merchantId, String openId) {
if (StringUtils.isBlank(phoneNumber)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_MOBILE_NUMBER_BY_CODE_ERROR);
}
// if (Objects.isNull(merchantId)) {
// throw new BusinessException(ReturnCodeEnum.CODE_GET_MERCHANT_ID_BY_APP_ID_ERROR);
// }
// 查询手机号码是否注册过
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumberAndMerchantId(phoneNumber, merchantId);
if (Objects.isNull(memberBasicInfo)) {
// 不存在则新增数据
String memberId = IdUtils.getMemberId();
memberBasicInfo = new MemberBasicInfo();
memberBasicInfo.setStatus(Constants.ONE);
memberBasicInfo.setMemberId(memberId);
memberBasicInfo.setNickName("会员" + memberId);
memberBasicInfo.setMobileNumber(phoneNumber);
memberBasicInfo.setMerchantId(Long.valueOf(merchantId));
memberBasicInfo.setOpenId(openId);
// 首次新建会员,同时新建会员钱包
MemberWalletInfo memberWalletInfo = MemberWalletInfo.builder().memberId(memberId).build();
MemberTransactionDTO memberTransactionDTO = MemberTransactionDTO.builder()
.memberBasicInfo(memberBasicInfo)
.memberWalletInfo(memberWalletInfo)
.build();
transactionService.createMember(memberTransactionDTO);
} else {
if (StringUtils.isBlank(memberBasicInfo.getOpenId()) && StringUtils.isNotBlank(openId)) {
memberBasicInfo.setOpenId(openId);
memberBasicInfoService.updateMemberBasicInfo(memberBasicInfo);
}
}
// 服务器生成token返给前端
String memberToken = JWTUtils.createMemberToken(memberBasicInfo.getMemberId(), memberBasicInfo.getNickName());
// log.info("memToken:{}", memberToken);
return memberToken;
}
/**
* 微信一键登录
* @param dto
*/
public String wechatLogin(WechatLoginDTO dto) {
// 通过微信传的code获取手机号码
String mobileNumber = wxAppletRemoteService.getMobileNumberByCode(dto.getCode());
if (StringUtils.isBlank(mobileNumber)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_MOBILE_NUMBER_BY_CODE_ERROR);
}
// 通过appid获取运营商id
String merchantId = pileMerchantInfoService.getMerchantIdByAppId(dto.getAppId());
// if (Objects.isNull(merchantId)) {
// throw new BusinessException(ReturnCodeEnum.CODE_GET_MERCHANT_ID_BY_APP_ID_ERROR);
// }
// 通过code获取openId
String openId = "";
try {
openId = getOpenIdByCode(dto.getOpenIdCode());
} catch (Exception e) {
log.error("getOpenIdByCode发生异常", e);
}
// 查询手机号码是否注册过
return memberRegisterAndLogin(mobileNumber, merchantId, openId);
}
/**
* 获取openId
* @param code
* @return
*/
public String getOpenIdByCode(String code) {
return wxAppletRemoteService.getOpenIdByCode(code);
}
/**
* 处理用户信息
*
* @param dto 用户个人信息
*/
public void handleUserInfo(MemberRegisterDTO dto) {
// 通过用户手机号查询数据库,如果数据库中存在,则更新
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getMobileNumber());
if (Objects.nonNull(memberBasicInfo)) {
MemberBasicInfo memberInfo = MemberBasicInfo.builder()
.avatarUrl(dto.getAvatarUrl())
.mobileNumber(dto.getMobileNumber())
.nickName(dto.getNickName())
.build();
memberBasicInfoService.updateMemberBasicInfo(memberInfo);
}
}
/**
* 通过memberToken获取用户账户信息
*
* @param memberId
* @return
*/
public MemberVO getMemberInfoByMemberId(String memberId) {
MemberVO memberVO = memberBasicInfoService.queryMemberInfoByMemberId(memberId);
if (Objects.nonNull(memberVO)) {
memberVO.setTotalAccountAmount(memberVO.getPrincipalBalance().add(memberVO.getGiftBalance()));
}
return memberVO;
}
/**
* 查询用户账户余额变动信息
*
* @param dto
*/
public PageResponse getMemberBalanceChanges(UniAppQueryMemberBalanceDTO dto) {
// 获取分页信息以及memberId
int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();
String memberId = dto.getMemberId();
String type = dto.getType();
if (!StringUtils.equals("1", type) && !StringUtils.equals("2", type)) {
type = "";
}
// 分页
PageHelper.startPage(pageNum, pageSize);
List<MemberWalletLogVO> list = memberBasicInfoService.getMemberBalanceChanges(memberId, type);
PageInfo<MemberWalletLogVO> pageInfo = new PageInfo<>(list);
for (MemberWalletLogVO walletLogVO : pageInfo.getList()) {
String subType = walletLogVO.getSubType();
String subTypeValue = BalanceChangesEnum.getValueByCode(subType);
if (StringUtils.isNotBlank(subTypeValue)) {
walletLogVO.setSubType(subTypeValue);
}
// walletLogVO.setTotalAccountAmount(walletLogVO.getPrincipalBalance().add(walletLogVO.getGiftBalance()));
}
PageResponse pageResponse = PageResponse.builder()
.pageSize(pageSize)
.pageNum(pageNum)
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
return pageResponse;
}
}

View File

@@ -0,0 +1,780 @@
package com.jsowell.service;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.MemberWalletEnum;
import com.jsowell.common.enums.ykc.ActionTypeEnum;
import com.jsowell.common.enums.ykc.OrderPayModeEnum;
import com.jsowell.common.enums.ykc.OrderPayRecordEnum;
import com.jsowell.common.enums.ykc.OrderPayStatusEnum;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.PayModeEnum;
import com.jsowell.common.enums.ykc.ScenarioEnum;
import com.jsowell.common.enums.ykc.PileConnectorDataBaseStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.netty.command.ykc.StartChargingCommand;
import com.jsowell.netty.service.yunkuaichong.YKCPushCommandService;
import com.jsowell.pile.domain.MemberTransactionRecord;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.OrderDetail;
import com.jsowell.pile.domain.OrderPayRecord;
import com.jsowell.pile.domain.WxpayCallbackRecord;
import com.jsowell.pile.dto.BasicPileDTO;
import com.jsowell.pile.dto.GenerateOrderDTO;
import com.jsowell.pile.dto.PayOrderDTO;
import com.jsowell.pile.dto.PayOrderSuccessCallbackDTO;
import com.jsowell.pile.dto.PaymentScenarioDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.dto.SettleOrderDTO;
import com.jsowell.pile.dto.StopChargingDTO;
import com.jsowell.pile.dto.UniAppQueryOrderDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IMemberTransactionRecordService;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IOrderPayRecordService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.service.IPileConnectorInfoService;
import com.jsowell.pile.service.WechatPayService;
import com.jsowell.pile.service.WxpayCallbackRecordService;
import com.jsowell.pile.transaction.dto.OrderTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.base.PileInfoVO;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.pile.vo.uniapp.OrderVO;
import com.jsowell.pile.vo.uniapp.PileConnectorDetailVO;
import com.jsowell.pile.vo.uniapp.UniAppOrderVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import com.jsowell.pile.vo.web.OrderDetailInfoVO;
import com.jsowell.pile.vo.web.UpdateMemberBalanceDTO;
import com.jsowell.wxpay.dto.WeChatRefundDTO;
import com.jsowell.wxpay.response.WechatPayNotifyParameter;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class OrderService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private TransactionService pileTransactionService;
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
@Autowired
private PileRemoteService pileRemoteService;
@Autowired
private YKCPushCommandService ykcPushCommandService;
@Autowired
private PileService pileService;
@Autowired
private MemberService memberService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private IOrderPayRecordService orderPayRecordService;
@Autowired
private WechatPayService wechatPayService;
@Autowired
private WxpayCallbackRecordService wxpayCallbackRecordService;
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
@Autowired
private IMemberTransactionRecordService memberTransactionRecordService;
@Autowired
private RedisCache redisCache;
/**
* 生成订单
*
* @param dto
* @return
*/
public String generateOrder(GenerateOrderDTO dto) {
log.info("generateOrder param:{}", JSONObject.toJSONString(dto));
// 处理前端传的参数
analysisPileParameter(dto);
// 校验充电桩相关的信息
checkPileInfo(dto);
// 保存订单到数据库 saveOrder2Database
String orderCode = saveOrder2Database(dto);
return orderCode;
}
/**
* 订单支付
*
* @param dto
*/
public Map<String, Object> payOrder(PayOrderDTO dto) throws Exception {
Map<String, Object> resultMap = Maps.newHashMap();
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
if (!StringUtils.equals(orderInfo.getPayStatus(), "0")) {
// 订单已支付
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_IS_NOT_TO_BE_PAID_ERROR);
}
String orderCode = orderInfo.getOrderCode();
// 该订单充电金额
BigDecimal chargeAmount = dto.getPayAmount();
// 记录支付流水
List<OrderPayRecord> payRecordList = Lists.newArrayList();
if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_BALANCE.getValue())) { // 余额支付
// 查询该会员的余额
MemberVO memberVO = memberService.getMemberInfoByMemberId(dto.getMemberId());
BigDecimal totalAccountAmount = memberVO.getTotalAccountAmount();
if (totalAccountAmount.compareTo(chargeAmount) < 0) {
// 总余额小于充电金额
throw new BusinessException(ReturnCodeEnum.CODE_BALANCE_IS_INSUFFICIENT);
}
BigDecimal principalAmount = memberVO.getPrincipalBalance(); // 会员剩余本金金额
BigDecimal giftAmount = memberVO.getGiftBalance(); // 会员剩余赠送余额
BigDecimal principalPay = null; // 30
BigDecimal giftPay = null; // 10
// 先扣除本金金额,再扣除赠送金额
BigDecimal subtract = principalAmount.subtract(chargeAmount);
if (subtract.compareTo(BigDecimal.ZERO) >= 0) {
principalPay = chargeAmount;
} else {
if (principalAmount.compareTo(BigDecimal.ZERO) > 0) {
principalPay = principalAmount;
}
giftPay = subtract.negate();
}
// 更新会员钱包
UpdateMemberBalanceDTO updateMemberBalanceDTO = UpdateMemberBalanceDTO.builder()
.memberId(dto.getMemberId())
.type(MemberWalletEnum.TYPE_OUT.getValue())
.subType(MemberWalletEnum.SUBTYPE_PAYMENT_FOR_ORDER.getValue())
.updatePrincipalBalance(principalPay)
.updateGiftBalance(giftPay)
.relatedOrderCode(orderCode)
.build();
memberBasicInfoService.updateMemberBalance(updateMemberBalanceDTO);
// 记录流水
if (principalPay != null) {
payRecordList.add(OrderPayRecord.builder()
.orderCode(dto.getOrderCode())
.payMode(OrderPayRecordEnum.PRINCIPAL_BALANCE_PAYMENT.getValue())
.payAmount(principalPay)
.createBy(dto.getMemberId())
.build());
}
if (giftPay != null) {
payRecordList.add(OrderPayRecord.builder()
.orderCode(dto.getOrderCode())
.payMode(OrderPayRecordEnum.GIFT_BALANCE_PAYMENT.getValue())
.payAmount(giftPay)
.createBy(dto.getMemberId())
.build());
}
// 余额支付可以直接调支付回调方法
PayOrderSuccessCallbackDTO callbackDTO = PayOrderSuccessCallbackDTO.builder()
.orderCode(orderCode)
.payAmount(chargeAmount)
.payMode(dto.getPayMode())
.build();
payOrderSuccessCallback(callbackDTO);
// 余额支付订单 记录会员交易流水
MemberTransactionRecord record = MemberTransactionRecord.builder()
.orderCode(orderCode)
.scenarioType(ScenarioEnum.ORDER.getValue())
.memberId(memberVO.getMemberId())
.actionType(ActionTypeEnum.FORWARD.getValue())
.payMode(PayModeEnum.PAYMENT_OF_BALANCE.getValue())
.amount(dto.getPayAmount()) // 单位元
.build();
memberTransactionRecordService.insertSelective(record);
} else if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue())) { // 微信支付
String openId = memberService.getOpenIdByCode(dto.getCode());
if (StringUtils.isBlank(openId)) {
throw new BusinessException(ReturnCodeEnum.CODE_GET_OPEN_ID_BY_CODE_ERROR);
}
WeixinPayDTO weixinPayDTO = new WeixinPayDTO();
weixinPayDTO.setOpenId(openId);
weixinPayDTO.setAmount(dto.getPayAmount().toString());
// 支付订单 附加参数
PaymentScenarioDTO paymentScenarioDTO = PaymentScenarioDTO.builder()
.type(ScenarioEnum.ORDER.getValue())
.orderCode(dto.getOrderCode())
.memberId(orderInfo.getMemberId())
.build();
weixinPayDTO.setAttach(JSONObject.toJSONString(paymentScenarioDTO));
weixinPayDTO.setDescription("充电费用");
Map<String, Object> weixinMap = this.weixinPayV3(weixinPayDTO);
// 返回微信支付参数
resultMap.put("weixinMap", weixinMap);
} else if (StringUtils.equals(dto.getPayMode(), OrderPayModeEnum.PAYMENT_OF_ALIPAY.getValue())) { // 支付宝支付
// TODO 返回支付宝支付参数
}
// 订单支付流水入库
if (CollectionUtils.isNotEmpty(payRecordList)) {
orderPayRecordService.batchInsert(payRecordList);
}
return resultMap;
}
/**
* 订单支付成功 支付回调
* 支付成功后掉用这个方法
* 1. 修改订单支付状态
* 2. 发送启动充电指令
*/
public void payOrderSuccessCallback(PayOrderSuccessCallbackDTO dto) {
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
BigDecimal payAmount = dto.getPayAmount();
// 修改订单
orderInfo.setPayMode(dto.getPayMode());
orderInfo.setPayStatus("1");
orderInfo.setPayAmount(payAmount);
orderInfo.setPayTime(new Date());
orderBasicInfoService.updateOrderBasicInfo(orderInfo);
// 发送启动指令
StartChargingCommand startChargingCommand = StartChargingCommand.builder()
.pileSn(orderInfo.getPileSn())
.connectorCode(orderInfo.getConnectorCode())
.orderCode(dto.getOrderCode())
.chargeAmount(payAmount)
.build();
ykcPushCommandService.pushStartChargingCommand(startChargingCommand);
}
/**
* 保存订单信息到数据库
*
* @param dto
* @return
*/
private String saveOrder2Database(GenerateOrderDTO dto) {
String orderCode = IdUtils.generateOrderCode(dto.getPileSn(), dto.getConnectorCode());
// 订单基本信息
OrderBasicInfo orderBasicInfo = OrderBasicInfo.builder()
.orderCode(orderCode)
.orderStatus(OrderStatusEnum.NOT_START.getValue())
.memberId(dto.getMemberId())
.stationId(dto.getPileConnector().getStationId())
.pileSn(dto.getPileSn())
.connectorCode(dto.getConnectorCode())
.pileConnectorCode(dto.getPileSn() + dto.getConnectorCode())
.startMode(dto.getStartMode())
.payStatus(Constants.ZERO)
.payAmount(dto.getChargeAmount())
.payMode(dto.getPayMode())
.orderAmount(BigDecimal.ZERO)
.build();
// 订单详情
OrderDetail orderDetail = OrderDetail.builder()
.orderCode(orderCode)
.sharpElectricityPrice(dto.getBillingTemplate().getSharpElectricityPrice())
.sharpServicePrice(dto.getBillingTemplate().getSharpServicePrice())
.peakElectricityPrice(dto.getBillingTemplate().getPeakElectricityPrice())
.peakServicePrice(dto.getBillingTemplate().getPeakServicePrice())
.flatElectricityPrice(dto.getBillingTemplate().getFlatElectricityPrice())
.flatServicePrice(dto.getBillingTemplate().getFlatServicePrice())
.valleyElectricityPrice(dto.getBillingTemplate().getValleyElectricityPrice())
.valleyServicePrice(dto.getBillingTemplate().getValleyServicePrice())
.build();
OrderTransactionDTO createOrderTransactionDTO = OrderTransactionDTO.builder()
.orderBasicInfo(orderBasicInfo)
.orderDetail(orderDetail)
.build();
pileTransactionService.doCreateOrder(createOrderTransactionDTO);
return orderCode;
}
/**
* 校验充电桩相关的信息
*
* @param dto
*/
private void checkPileInfo(GenerateOrderDTO dto) {
// 查询充电桩状态 是否空闲 枪口是否占用
PileConnectorDetailVO pileConnector = pileService.queryPileConnectorDetail(dto.getPileSn() + dto.getConnectorCode());
if (pileConnector == null) {
log.error("checkPileInfo充电枪口为空 pileSn:{}, connectorCode:{}", dto.getPileSn(), dto.getConnectorCode());
throw new BusinessException(ReturnCodeEnum.CODE_CONNECTOR_INFO_NULL_ERROR);
}
// 判断枪口状态
if (!(StringUtils.equals(pileConnector.getConnectorStatus(), PileConnectorDataBaseStatusEnum.FREE.getValue())
|| StringUtils.equals(pileConnector.getConnectorStatus(), PileConnectorDataBaseStatusEnum.OCCUPIED_NOT_CHARGED.getValue()))) {
log.error("checkPileInfo充电枪口状态不正确当前状态为:{}", pileConnector.getConnectorStatus());
throw new BusinessException(ReturnCodeEnum.CODE_PILE_CONNECTOR_STATUS_ERROR);
}
// 查询充电桩的计费模板
BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(dto.getPileSn());
if (billingTemplateVO == null) {
throw new BusinessException(ReturnCodeEnum.CODE_BILLING_TEMPLATE_NULL_ERROR);
}
dto.setPileConnector(pileConnector);
dto.setBillingTemplate(billingTemplateVO);
}
/**
* 处理前端传的参数
* pileConnectorCode = pileSn + connectorCode
*
* @param dto
*/
public void analysisPileParameter(BasicPileDTO dto) {
if (StringUtils.isBlank(dto.getPileSn()) || StringUtils.isBlank(dto.getConnectorCode())) {
// 从pileConnectorCode解析
String pileConnectorCode = dto.getPileConnectorCode();
if (StringUtils.isNotEmpty(pileConnectorCode) && pileConnectorCode.length() == Constants.PILE_CONNECTOR_CODE_LENGTH) {
dto.setPileSn(StringUtils.substring(pileConnectorCode, 0, pileConnectorCode.length() - 2));
dto.setConnectorCode(StringUtils.substring(pileConnectorCode, pileConnectorCode.length() - 2, pileConnectorCode.length()));
} else {
throw new BusinessException(ReturnCodeEnum.CODE_DATA_LENGTH_ERROR);
}
} else {
// 说明pileSn 和 connectorCode前端传了那就校验一下长度
if (dto.getPileSn().length() != Constants.PILE_SN_LENGTH || dto.getConnectorCode().length() != Constants.CONNECTOR_CODE_LENGTH) {
throw new BusinessException(ReturnCodeEnum.CODE_DATA_LENGTH_ERROR);
}
}
}
/**
* 结算订单
* endCharging
*
* @param dto 结算订单参数
*/
public void settleOrderForWeb(SettleOrderDTO dto) {
analysisPileParameter(dto);
// 查询订单详情,验证订单中的桩编号是否正确
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderBasicInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
if (!(StringUtils.equals(orderBasicInfo.getPileSn(), dto.getPileSn())
&& StringUtils.equals(orderBasicInfo.getConnectorCode(), dto.getConnectorCode()))) {
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_PILE_MAPPING_ERROR);
}
// push远程停机指令
pileRemoteService.remoteStopCharging(dto.getPileSn(), dto.getConnectorCode());
// 桩计算的消费金额
// 对比一下,是否需要退款
}
/**
* 通过会员Id查询订单列表
*
* @param memberId 会员Id
* @return 订单信息集合
*/
public PageResponse getListByMemberIdAndOrderStatus(String memberId, UniAppQueryOrderDTO dto) throws ParseException {
String orderStatus = dto.getOrderStatus();
if (StringUtils.isBlank(orderStatus)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
ArrayList<String> orderStatusList = Lists.newArrayList();
if (StringUtils.equals("2", orderStatus)) {
// 查未完成订单
CollectionUtils.addAll(orderStatusList, "0", "1", "2", "3", "4", "5");
} else if (StringUtils.equals("3", orderStatus)) {
// 查已完成订单
orderStatusList.add("6");
}
// 分页
PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
List<OrderVO> list = orderBasicInfoService.getListByMemberIdAndOrderStatus(memberId, orderStatusList);
PageInfo<OrderVO> pageInfo = new PageInfo<>(list);
for (OrderVO orderVO : pageInfo.getList()) {
orderVO.setPileConnectorCode(orderVO.getPileSn() + orderVO.getConnectorCode());
Date endTimeDate;
Date startTimeDate = sdf.parse(orderVO.getStartTime());
if (StringUtils.isNotBlank(orderVO.getEndTime())) {
endTimeDate = sdf.parse(orderVO.getEndTime());
} else {
endTimeDate = new Date();
}
// 计算出两个时间差
orderVO.setChargingTime(DateUtils.getDatePoor(endTimeDate, startTimeDate));
}
// 返回结果集
PageResponse pageResponse = PageResponse.builder()
.pageNum(dto.getPageNum())
.pageSize(dto.getPageSize())
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
return pageResponse;
}
/**
* 微信支付v3
*
* @param dto
* @return
* @throws Exception
*/
public Map<String, Object> weixinPayV3(WeixinPayDTO dto) throws Exception {
return wechatPayService.weixinPayV3(dto);
}
/**
* 用户停止充电
*
* @param dto
*/
public void stopCharging(StopChargingDTO dto) {
// 查订单
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode(dto.getOrderCode());
if (orderInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
// 校验订单中的会员与操作会员是否一致
if (!StringUtils.equals(orderInfo.getMemberId(), dto.getMemberId())) {
throw new BusinessException(ReturnCodeEnum.CODE_ORDER_MEMBER_NOT_MATCH_ERROR);
}
// 发送停止指令
pileRemoteService.remoteStopCharging(orderInfo.getPileSn(), orderInfo.getConnectorCode());
log.info("订单号:{}发送停机指令成功", dto.getOrderCode());
}
/**
* 微信支付回调
*
* @param request
* @param body
* @throws Exception
*/
public void wechatPayCallback(HttpServletRequest request, WechatPayNotifyParameter body) throws Exception {
// 获取微信支付成功返回的信息
Map<String, Object> map = wechatPayService.wechatPayCallbackInfo(request, body);
String type = (String) map.get("type");
BigDecimal amount = (BigDecimal) map.get("amount"); // 微信给的amount单位是分
amount = amount.divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP); // 转换为元
String orderCode = (String) map.get("orderCode");
String memberId = (String) map.get("memberId");
if (StringUtils.equals(type, ScenarioEnum.ORDER.getValue())) { // 1-订单支付
// 支付订单成功
// orderCode = (String) map.get("orderCode");
PayOrderSuccessCallbackDTO callbackDTO = PayOrderSuccessCallbackDTO.builder()
.orderCode(orderCode)
.payAmount(amount)
.payMode(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue())
.build();
// 订单支付成功 支付回调
payOrderSuccessCallback(callbackDTO);
// 记录订单支付流水
OrderPayRecord orderPayRecord = OrderPayRecord.builder()
.orderCode(orderCode)
.payMode(OrderPayRecordEnum.WECHATPAY_PAYMENT.getValue())
.payAmount(amount)
.createBy(null)
.build();
orderPayRecordService.batchInsert(Lists.newArrayList(orderPayRecord));
} else if (StringUtils.equals(type, ScenarioEnum.BALANCE.getValue())) { // 2-充值余额
// 充值余额成功
// memberId = (String) map.get("memberId");
UpdateMemberBalanceDTO dto = new UpdateMemberBalanceDTO();
dto.setMemberId(memberId);
dto.setType(MemberWalletEnum.TYPE_IN.getValue());
dto.setSubType(MemberWalletEnum.SUBTYPE_TOP_UP.getValue());
dto.setUpdatePrincipalBalance(amount);
memberBasicInfoService.updateMemberBalance(dto);
}
// 微信支付订单 记录会员交易流水
MemberTransactionRecord record = MemberTransactionRecord.builder()
.orderCode(orderCode)
.scenarioType(type)
.memberId(memberId)
.actionType(ActionTypeEnum.FORWARD.getValue())
.payMode(PayModeEnum.PAYMENT_OF_WECHATPAY.getValue())
.amount(amount) // 单位元
.outTradeNo(String.valueOf(map.get("out_trade_no")))
.transactionId(String.valueOf(map.get("transaction_id")))
.build();
memberTransactionRecordService.insertSelective(record);
}
public void weChatRefund(WeChatRefundDTO dto) {
log.info("微信退款接口 param:{}", JSONObject.toJSONString(dto));
orderBasicInfoService.weChatRefund(dto);
}
/**
* 查询订单详情信息
* @param orderCode 订单编号
* @return
*/
public OrderDetailInfoVO queryOrderDetailInfo(String orderCode) {
OrderDetailInfoVO vo = new OrderDetailInfoVO();
// 订单信息
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
if (orderBasicInfo == null) {
return vo;
}
OrderDetailInfoVO.OrderInfo order = new OrderDetailInfoVO.OrderInfo();
order.setOrderCode(orderBasicInfo.getOrderCode());
order.setOrderStatus(orderBasicInfo.getOrderStatus());
order.setStartTime(DateUtils.formatDateTime(orderBasicInfo.getChargeStartTime()));
order.setEndTime(DateUtils.formatDateTime(orderBasicInfo.getChargeEndTime()));
order.setCreateTime(DateUtils.formatDateTime(orderBasicInfo.getCreateTime()));
order.setStopReasonMsg(orderBasicInfo.getReason());
order.setStartSOC(orderBasicInfo.getStartSOC());
order.setEndSOC(orderBasicInfo.getEndSOC());
vo.setOrderInfo(order);
// 设备信息
PileInfoVO pileInfoVO = pileService.selectPileInfoBySn(orderBasicInfo.getPileSn());
vo.setPileInfo(pileInfoVO);
// 枪口实时数据信息
String pileConnectorCode = orderBasicInfo.getPileSn() + orderBasicInfo.getConnectorCode();
QueryConnectorListDTO dto = new QueryConnectorListDTO();
dto.setConnectorCodeList(Lists.newArrayList(pileConnectorCode));
List<RealTimeMonitorData> chargingRealTimeDataList = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isNotEmpty(chargingRealTimeDataList)) {
List<OrderDetailInfoVO.RealTimeMonitorData> infoList = Lists.newArrayList();
for (RealTimeMonitorData realTimeMonitorData : chargingRealTimeDataList) {
OrderDetailInfoVO.RealTimeMonitorData info = new OrderDetailInfoVO.RealTimeMonitorData();
info.setInstantCurrent(realTimeMonitorData.getOutputCurrent()); // 电流
info.setInstantVoltage(realTimeMonitorData.getOutputVoltage()); // 电压
info.setInstantPower(realTimeMonitorData.getOutputPower()); // 功率
info.setSOC(realTimeMonitorData.getSOC());
info.setTime(realTimeMonitorData.getDateTime()); // 时间
infoList.add(info);
}
// 监控信息
OrderDetailInfoVO.OrderRealTimeInfo realTimeInfo = new OrderDetailInfoVO.OrderRealTimeInfo();
RealTimeMonitorData realTimeMonitorData = chargingRealTimeDataList.get(0);
realTimeInfo.setOrderAmount(realTimeMonitorData.getChargingAmount());
// realTimeInfo.setTotalElectricityAmount();
// realTimeInfo.setTotalServiceAmount();
realTimeInfo.setChargedDegree(realTimeMonitorData.getChargingDegree());
// realTimeInfo.setSOC(realTimeMonitorData.getSOC());
realTimeInfo.setChargingTime(realTimeMonitorData.getSumChargingTime());
vo.setOrderRealTimeInfo(realTimeInfo);
// 根据时间进行正序排序
infoList = infoList.stream()
.sorted(Comparator.comparing(OrderDetailInfoVO.RealTimeMonitorData::getTime))
.collect(Collectors.toList());
vo.setRealTimeMonitorDataList(infoList);
}
// 支付流水
List<OrderPayRecord> orderPayRecordList = orderPayRecordService.getOrderPayRecordList(orderCode);
if (CollectionUtils.isNotEmpty(orderPayRecordList)) {
OrderPayRecord orderPayRecord = orderPayRecordList.get(0);
List<OrderDetailInfoVO.PayRecord> payRecordList = Lists.newArrayList();
OrderDetailInfoVO.PayRecord payInfo = new OrderDetailInfoVO.PayRecord();
// 余额支付如果是由本金和赠送一起支付的,合并为一个
BigDecimal bigDecimal = orderPayRecordList.stream()
.map(OrderPayRecord::getPayAmount)
.reduce(BigDecimal.ZERO, BigDecimal::add);
payInfo.setPayAmount(bigDecimal.toString());
payInfo.setPayStatus(orderBasicInfo.getPayStatus());
payInfo.setPayTime(DateUtils.formatDateTime(orderBasicInfo.getPayTime()));
String payMode = orderPayRecord.getPayMode();
if (StringUtils.equals(payMode, OrderPayRecordEnum.PRINCIPAL_BALANCE_PAYMENT.getValue())
|| StringUtils.equals(payMode, OrderPayRecordEnum.GIFT_BALANCE_PAYMENT.getValue())) {
// 使用余额支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_BALANCE.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_BALANCE.getLabel());
} else if (StringUtils.equals(payMode, OrderPayRecordEnum.WECHATPAY_PAYMENT.getValue())){
// 使用微信支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WECHATPAY.getLabel());
// 查微信支付回调记录
WxpayCallbackRecord wxpayCallbackRecord = wxpayCallbackRecordService.selectByOrderCode(orderCode);
if (wxpayCallbackRecord != null) {
payInfo.setOutTradeNo(wxpayCallbackRecord.getOutTradeNo());
payInfo.setTransactionId(wxpayCallbackRecord.getTransactionId());
}
} else if (StringUtils.equals(payMode, OrderPayRecordEnum.WHITELIST_PAYMENT.getValue())){
// 使用白名单支付
payInfo.setPayMode(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getValue());
payInfo.setPayModeDesc(OrderPayModeEnum.PAYMENT_OF_WHITELIST.getLabel());
}
payRecordList.add(payInfo);
vo.setPayRecordList(payRecordList);
}
// 用户信息
MemberVO memberVO = memberService.getMemberInfoByMemberId(orderBasicInfo.getMemberId());
vo.setMemberInfo(memberVO);
return vo;
}
public void wechatPayRefundCallback(HttpServletRequest request, WechatPayNotifyParameter body) throws Exception {
// 获取微信退款成功返回的信息
Map<String, Object> map = wechatPayService.wechatPayRefundCallbackInfo(request, body);
}
/**
* 获取小程序订单详情
* @param orderCode
* @return
*/
public UniAppOrderVO getUniAppOrderDetail(String orderCode) {
OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);
if (orderBasicInfo == null) {
throw new BusinessException(ReturnCodeEnum.CODE_QUERY_ORDER_NULL_ERROR);
}
UniAppOrderVO vo = new UniAppOrderVO();
vo.setOrderCode(orderBasicInfo.getOrderCode());
vo.setPileSn(orderBasicInfo.getPileSn());
vo.setConnectorCode(orderBasicInfo.getConnectorCode());
vo.setPileConnectorCode(orderBasicInfo.getPileSn() + orderBasicInfo.getConnectorCode());
String orderStatus = orderBasicInfo.getOrderStatus();
vo.setOrderStatus(orderStatus);
// 订单状态描述
String orderStatusDescribe;
if (StringUtils.equals(orderStatus, OrderStatusEnum.NOT_START.getValue())) {
// 未启动还有两种情况 待支付 / 支付成功
String payStatus = orderBasicInfo.getPayStatus();
if (StringUtils.equals(payStatus, OrderPayStatusEnum.paid.getValue())) {
// 支付成功,未启动
orderStatusDescribe = OrderPayStatusEnum.paid.getLabel() + ", " + OrderStatusEnum.getOrderStatus(orderStatus);
} else {
// 待支付
orderStatusDescribe = OrderPayStatusEnum.unpaid.getLabel();
}
} else {
orderStatusDescribe = OrderStatusEnum.getOrderStatus(orderStatus);
}
vo.setOrderStatusDescribe(orderStatusDescribe);
// 获取充电桩枪口信息
PileConnectorDetailVO pileConnectorDetailVO = pileService.queryPileConnectorDetail(vo.getPileConnectorCode());
if (pileConnectorDetailVO != null) {
vo.setPileConnectorStatus(pileConnectorDetailVO.getConnectorStatus());
}
// 获取订单充电数据
List<RealTimeMonitorData> monitorDataList = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isNotEmpty(monitorDataList)) {
List<UniAppOrderVO.ChargingData> chargingDataList = Lists.newArrayList();
UniAppOrderVO.ChargingData data = null;
for (int i = 0; i < monitorDataList.size(); i++) {
RealTimeMonitorData monitorData = monitorDataList.get(i);
data = new UniAppOrderVO.ChargingData();
data.setDateTime(monitorData.getDateTime());
String outputVoltage = monitorData.getOutputVoltage();
data.setOutputVoltage(outputVoltage);
String outputCurrent = monitorData.getOutputCurrent();
data.setOutputCurrent(outputCurrent);
BigDecimal power = new BigDecimal(outputCurrent).multiply(new BigDecimal(outputVoltage))
.divide(new BigDecimal("1000"), 2, BigDecimal.ROUND_HALF_UP);
data.setPower(power.toString());
data.setSOC(monitorData.getSOC());
data.setBatteryMaxTemperature(monitorData.getBatteryMaxTemperature());
chargingDataList.add(data);
// vo中的实时数据最新一条就取monitorDataList第一个
if (i == 0) {
vo.setBatteryMaxTemperature(data.getBatteryMaxTemperature());
vo.setOutputPower(data.getPower());
vo.setOutputCurrent(data.getOutputCurrent());
vo.setOutputVoltage(data.getOutputVoltage());
vo.setSOC(data.getSOC());
BigDecimal chargingAmount = new BigDecimal(monitorData.getChargingAmount()).setScale(2, BigDecimal.ROUND_HALF_UP); // 充电金额
vo.setChargingAmount(chargingAmount.toString());
BigDecimal chargingDegree = new BigDecimal(monitorData.getChargingDegree()).setScale(2, BigDecimal.ROUND_HALF_UP); // 充电度数
vo.setChargingDegree(chargingDegree.toString());
vo.setSumChargingTime(monitorData.getSumChargingTime());
vo.setTimeRemaining(monitorData.getTimeRemaining());
}
}
// monitorDataList是按照时间倒序的chargingDataList需要按照时间正序
Collections.reverse(chargingDataList);
vo.setChargingDataList(chargingDataList);
}
return vo;
}
/**
* 根据订单号查询充电桩启动状态
* @param orderCode
* @return
*/
public String selectPileStarterStatus(String orderCode) {
List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderCode);
// 只有充电桩上传的实时数据中的状态为充电,才能查到实时数据列表
return CollectionUtils.isNotEmpty(chargingRealTimeData) ? Constants.ONE : Constants.ZERO;
}
public void closeStartFailedOrder(QueryOrderDTO dto) {
orderBasicInfoService.closeStartFailedOrder(dto.getStartTime(), dto.getEndTime());
}
}

View File

@@ -0,0 +1,203 @@
package com.jsowell.service;
import com.google.common.collect.Lists;
import com.jsowell.common.util.StringUtils;
import com.jsowell.netty.command.ykc.GetRealTimeMonitorDataCommand;
import com.jsowell.netty.command.ykc.IssueQRCodeCommand;
import com.jsowell.netty.command.ykc.ProofreadTimeCommand;
import com.jsowell.netty.command.ykc.PublishPileBillingTemplateCommand;
import com.jsowell.netty.command.ykc.RebootCommand;
import com.jsowell.netty.command.ykc.StartChargingCommand;
import com.jsowell.netty.command.ykc.StopChargingCommand;
import com.jsowell.netty.command.ykc.UpdateFileCommand;
import com.jsowell.netty.service.yunkuaichong.YKCPushCommandService;
import com.jsowell.pile.domain.PileBillingRelation;
import com.jsowell.pile.domain.PileBillingTemplate;
import com.jsowell.pile.dto.PublishBillingTemplateDTO;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.vo.web.PileDetailVO;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
@Service
public class PileRemoteService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private YKCPushCommandService ykcPushCommandService;
/**
* 获取充电桩实时数据信息
*
* @param pileSn 充电桩sn
* @param connectorCode 枪口号
*/
public void getRealTimeMonitorData(String pileSn, String connectorCode) {
if (StringUtils.isNotEmpty(pileSn) || StringUtils.isNotEmpty(connectorCode)) {
GetRealTimeMonitorDataCommand command = GetRealTimeMonitorDataCommand.builder()
.pileSn(pileSn)
.connectorCode(connectorCode)
.build();
ykcPushCommandService.pushGetRealTimeMonitorDataCommand(command);
}
}
/**
* 重启指令
*
* @param pileSn 充电桩sn
*/
public void reboot(String pileSn) {
RebootCommand command = RebootCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushRebootCommand(command);
}
/**
* 远程启动充电 0x34
*
* @param pileSn 充电桩sn
*/
// public void remoteStartCharging(String orderCode, String pileSn, String connectorCode, BigDecimal accountBalance) {
// // String s = "550314127823050120180619144446808800000000000101000000100000057300000000D14B0A54A0860100";
// if (StringUtils.isEmpty(pileSn) || StringUtils.isEmpty(connectorCode)) {
// log.warn("远程启动充电, 充电桩编号和枪口号不能为空");
// return;
// }
// log.info("=====平台下发指令=====: 远程启动充电, 桩号:{}, 枪口号:{}", pileSn, connectorCode);
// StartChargingCommand startChargingCommand = StartChargingCommand.builder()
// .pileSn(pileSn)
// .connectorCode(connectorCode)
// .orderCode(orderCode)
// .chargeAmount(accountBalance)
// .build();
// ykcPushCommandService.pushStartChargingCommand(startChargingCommand);
// }
/**
* 远程停止充电
*/
public void remoteStopCharging(String pileSn, String connectorCode) {
StopChargingCommand command = StopChargingCommand.builder()
.pileSn(pileSn)
.connectorCode(connectorCode)
.build();
ykcPushCommandService.pushStopChargingCommand(command);
}
/**
* 下发充电桩二维码
*
* @param pileSn 充电桩sn
*/
public void issueQRCode(String pileSn) {
IssueQRCodeCommand command = IssueQRCodeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushIssueQRCodeCommand(command);
}
/**
* 充电桩对时
*
* @param pileSn 充电桩sn
*/
public void proofreadTime(String pileSn) {
ProofreadTimeCommand command = ProofreadTimeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushProofreadTimeCommand(command);
}
/**
* 下发充电桩计费模型
*/
public void publishPileBillingTemplate(String pileSn, BillingTemplateVO billingTemplateVO) {
PublishPileBillingTemplateCommand command = PublishPileBillingTemplateCommand.builder()
.billingTemplateVO(billingTemplateVO)
.pileSn(pileSn)
.build();
ykcPushCommandService.pushPublishPileBillingTemplate(command);
}
/**
* 下发计费模板
* @param dto
* @return
*/
public boolean publishBillingTemplate(PublishBillingTemplateDTO dto) {
// 获取计费模板信息
BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateByTemplateId(dto.getTemplateId());
if (billingTemplateVO == null) {
log.warn("获取计费模板信息, 通过模板id:{}查询计费模板为null", dto.getTemplateId());
return false;
}
// 更新计费模板的发布时间
PileBillingTemplate pileBillingTemplate = new PileBillingTemplate();
pileBillingTemplate.setId(Long.valueOf(billingTemplateVO.getTemplateId()));
pileBillingTemplate.setPublishTime(new Date());
pileBillingTemplateService.updatePileBillingTemplate(pileBillingTemplate);
// 获取到站点下所有的桩
List<PileDetailVO> pileList = pileBasicInfoService.selectPileListByStationIds(Lists.newArrayList(Long.valueOf(dto.getStationId())));
if (CollectionUtils.isEmpty(pileList)) {
log.warn("获取到站点下所有的桩, 通过站点id:{}查询充电桩列表为空", dto.getStationId());
return false;
}
// 保存计费模板和桩的关系
List<PileBillingRelation> relationList = Lists.newArrayList();
for (PileDetailVO pileInfoVO : pileList) {
// push
publishPileBillingTemplate(pileInfoVO.getPileSn(), billingTemplateVO);
// 入库
relationList.add(PileBillingRelation.builder()
.pileSn(pileInfoVO.getPileSn())
.billingTemplateCode(billingTemplateVO.getTemplateCode())
.stationId(dto.getStationId())
.build());
}
if (CollectionUtils.isNotEmpty(relationList)) {
pileBillingTemplateService.insertPileBillingRelation(relationList);
}
return true;
}
public static void main(String[] args) {
/*Date date = new Date();
String encodeCP56Time2a = DateUtils.encodeCP56Time2a(date);
System.out.println(encodeCP56Time2a);
System.out.println(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date));
String decodeCP56Time2a = DateUtils.decodeCP56Time2a(encodeCP56Time2a);
System.out.println(decodeCP56Time2a);*/
}
/**
* 远程更新
*
* @param pileSns 前台传的桩号集合
*/
public void updateFile(List<String> pileSns) {
//
UpdateFileCommand command = UpdateFileCommand.builder().pileSnList(pileSns).build();
ykcPushCommandService.pushUpdateFileCommand(command);
}
}

View File

@@ -0,0 +1,438 @@
package com.jsowell.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.core.page.PageResponse;
import com.jsowell.common.enums.ykc.BusinessTypeEnum;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.id.SnUtils;
import com.jsowell.pile.domain.*;
import com.jsowell.pile.dto.BatchCreatePileDTO;
import com.jsowell.pile.dto.MemberRegisterAndLoginDTO;
import com.jsowell.pile.dto.PileMemberBindingDTO;
import com.jsowell.pile.dto.QueryPersonPileDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.transaction.dto.PileTransactionDTO;
import com.jsowell.pile.transaction.service.TransactionService;
import com.jsowell.pile.vo.base.ConnectorInfoVO;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.base.PileInfoVO;
import com.jsowell.pile.vo.uniapp.*;
import com.jsowell.pile.vo.web.PileStationVO;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
@Service
public class PileService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private TransactionService pileTransactionService;
@Resource
private SnUtils snUtils;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
@Autowired
private IPileStationInfoService pileStationInfoService;
@Autowired
private IPileMerchantInfoService pileMerchantInfoService;
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private IPileMemberRelationService pileMemberRelationService;
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private MemberService memberService;
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
/**
* 查询设备信息
*
* @param pileConnectorCode 充电枪编号 880000000000000101
* @return 设备信息集合
*/
public PileConnectorDetailVO queryPileConnectorDetail(String pileConnectorCode) {
return pileBasicInfoService.queryPileConnectorDetail(pileConnectorCode);
}
/**
* 查询设备信息
*
* @param pileSn 充电枪编号 8800000000000001
* @param connectorCode 充电枪口号 01
* @return 设备信息集合
*/
public PileConnectorDetailVO queryPileConnectorDetail(String pileSn, String connectorCode) {
return queryPileConnectorDetail(pileSn + connectorCode);
}
public int batchCreatePile(BatchCreatePileDTO dto) {
// 批量生成sn号
List<String> snList = snUtils.generateSN(dto.getNum());
//
List<PileBasicInfo> basicInfoList = Lists.newArrayList();
List<PileConnectorInfo> connectorInfoList = Lists.newArrayList();
PileBasicInfo basicInfo = null;
PileConnectorInfo connectorInfo = null;
for (String sn : snList) {
// 组装pile_basic_info表数据
basicInfo = new PileBasicInfo();
basicInfo.setSn(sn); // sn号
basicInfo.setBusinessType(BusinessTypeEnum.OPERATING_PILE.getValue()); // 经营类型 默认运营桩
basicInfo.setSoftwareProtocol(dto.getSoftwareProtocol()); // 软件协议
basicInfo.setMerchantId(Long.valueOf(dto.getMerchantId())); // 运营商id
basicInfo.setStationId(Long.valueOf(dto.getStationId())); // 站点id
basicInfo.setModelId(Long.valueOf(dto.getModelId())); // 型号id
basicInfo.setProductionDate(dto.getProductionDate()); // 生产日期
basicInfo.setLicenceId(null); // TODO 证书编号
basicInfo.setSimId(null); // TODO sim卡
basicInfo.setRemark(dto.getRemark()); // 备注
basicInfo.setCreateBy(SecurityUtils.getUsername()); // 创建人
basicInfo.setDelFlag(Constants.DEL_FLAG_NORMAL); // 删除标识
basicInfoList.add(basicInfo);
for (int i = 1; i < dto.getConnectorNum() + 1; i++) {
// 组装pile_connector_info表数据
connectorInfo = new PileConnectorInfo();
connectorInfo.setPileSn(sn); // sn号
String connectorCode = String.format("%1$02d", i);
connectorInfo.setPileConnectorCode(sn + connectorCode); // 枪口号
connectorInfo.setStatus(Constants.ZERO); //状态,默认 0-离网
connectorInfo.setCreateBy(SecurityUtils.getUsername()); // 创建人
connectorInfo.setDelFlag(Constants.DEL_FLAG_NORMAL); // 删除标识
connectorInfoList.add(connectorInfo);
}
}
// 批量入库
PileTransactionDTO transactionDTO = PileTransactionDTO.builder()
.pileBasicInfoList(basicInfoList)
.pileConnectorInfoList(connectorInfoList)
.build();
return pileTransactionService.doCreatePileTransaction(transactionDTO);
}
/**
* 前端扫码跳转接口
*/
public PileConnectorVO getPileDetailByPileSn(String param) throws ExecutionException, InterruptedException {
if (StringUtils.isBlank(param)) {
throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
}
String pileSn;
if (param.length() == 16) {
pileSn = StringUtils.substring(param, 0, param.length() - 2);
} else {
pileSn = param;
}
// 查询充电桩信息
PileInfoVO pileInfoVO = pileBasicInfoService.selectPileInfoBySn(pileSn);
if (pileInfoVO == null) {
return null;
}
// 查询充电桩下枪口信息
CompletableFuture<List<ConnectorInfoVO>> connectorInfoListFuture = CompletableFuture.supplyAsync(() -> pileConnectorInfoService.selectConnectorInfoList(pileSn));
// 查计费模板信息
CompletableFuture<List<BillingPriceVO>> billingPriceFuture = CompletableFuture.supplyAsync(() -> pileBillingTemplateService.queryBillingPrice(pileInfoVO.getStationId()));
// 查询站点信息
CompletableFuture<PileStationVO> pileStationVOFuture = CompletableFuture.supplyAsync(() -> pileStationInfoService.getStationInfo(pileInfoVO.getStationId()));
// 查询运营商信息
CompletableFuture<MerchantInfoVO> merchantInfoVOFuture = CompletableFuture.supplyAsync(() -> pileMerchantInfoService.getMerchantInfo(pileInfoVO.getMerchantId()));
CompletableFuture<Void> all = CompletableFuture.allOf(connectorInfoListFuture, pileStationVOFuture, merchantInfoVOFuture, billingPriceFuture);
// .join()和.get()都会阻塞并获取线程的执行情况
// .join()会抛出未经检查的异常,不会强制开发者处理异常 .get()会抛出检查异常,需要开发者处理
all.join();
all.get();
List<ConnectorInfoVO> connectorInfoList = connectorInfoListFuture.get();
PileStationVO pileStationVO = pileStationVOFuture.get();
MerchantInfoVO merchantInfoVO = merchantInfoVOFuture.get();
List<BillingPriceVO> billingPriceVOS = billingPriceFuture.get();
PileConnectorVO vo = PileConnectorVO.builder()
.pileInfo(pileInfoVO)
.connectorInfoList(connectorInfoList)
.merchantInfo(merchantInfoVO)
.stationInfo(pileStationVO)
.billingPriceList(billingPriceVOS)
.build();
return vo;
}
public PileConnectorVO getConnectorDetail(String pileConnectorCode) throws ExecutionException, InterruptedException {
PileConnectorDetailVO pileConnectorDetailVO = queryPileConnectorDetail(pileConnectorCode);
if (pileConnectorDetailVO == null) {
return null;
}
String pileSn = pileConnectorDetailVO.getPileSn();
PileConnectorVO resultVO = getPileDetailByPileSn(pileSn);
List<ConnectorInfoVO> connectorInfoList = resultVO.getConnectorInfoList();
if (connectorInfoList.size() > 1) {
List<ConnectorInfoVO> list = Lists.newArrayList();
// 枪口大于1个此充电桩非单枪设备根据参数展示对应枪口的信息
for (ConnectorInfoVO connectorInfoVO : connectorInfoList) {
if (StringUtils.equals(pileConnectorCode, pileSn + connectorInfoVO.getConnectorCode())) {
list.add(connectorInfoVO);
}
}
resultVO.setConnectorInfoList(list);
}
return resultVO;
}
public PileInfoVO selectPileInfoBySn(String pileSn) {
return pileBasicInfoService.selectPileInfoBySn(pileSn);
}
/**
* 用户绑定个人桩
*
* @param dto
* @return
*/
public int pileMemberBinding(PileMemberBindingDTO dto){
// 校验短信验证码
MemberRegisterAndLoginDTO registerAndLoginDTO = MemberRegisterAndLoginDTO.builder()
.mobileNumber(dto.getPhoneNumber())
.verificationCode(dto.getVerificationCode())
.build();
memberService.checkVerificationCode(registerAndLoginDTO);
// 检查桩是否已经被绑定
PileMemberRelation pileMemberRelation = new PileMemberRelation();
pileMemberRelation.setPileSn(dto.getPileSn());
List<PileMemberRelation> list = pileMemberRelationService.selectPileMemberRelationList(pileMemberRelation);
if (CollectionUtils.isNotEmpty(list)){
// 说明已经被绑定过,抛出异常
throw new BusinessException(ReturnCodeEnum.CODE_PILE_HAS_BEEN_BINDING_ERROR);
}
// 如果没被绑定,则此用户为管理员
pileMemberRelation.setMemberId(dto.getMemberId());
pileMemberRelation.setType("1"); // 1-管理员
return pileMemberRelationService.insertPileMemberRelation(pileMemberRelation);
}
/**
* 个人桩管理员下发给其他用户使用
*
* @param dto
*/
public void adminIssuePile(PileMemberBindingDTO dto) {
List<PileMemberRelation> relationList = pileMemberRelationService.selectPileMemberRelationByPileSn(dto.getPileSn());
if (CollectionUtils.isEmpty(relationList)) {
// 充电桩没有绑定任何人
}
List<String> adminList = relationList.stream()
.filter(x -> x.getType().equals("1"))
.map(PileMemberRelation::getMemberId)
.collect(Collectors.toList());
if (CollectionUtils.isEmpty(adminList)) {
// 没有管理员
}
// 校验身份
if (!adminList.contains(dto.getMemberId())) {
// 如果为空,说明此用户身份有误,不是管理员,抛出异常
throw new BusinessException(ReturnCodeEnum.CODE_AUTHENTICATION_ERROR);
}
List<String> userList = relationList.stream()
.filter(x -> !x.getType().equals("1"))
.map(PileMemberRelation::getMemberId)
.collect(Collectors.toList());
// 通过前端传的手机号查询是否有此用户
MemberBasicInfo memberBasicInfo = memberBasicInfoService.selectInfoByMobileNumber(dto.getPhoneNumber());
if (memberBasicInfo == null) {
// 为空说明此用户未注册平台账号
throw new BusinessException(ReturnCodeEnum.CODE_USER_IS_NOT_REGISTER);
}
if (userList.contains(memberBasicInfo.getMemberId())) {
// 不为空说明已绑定
throw new BusinessException(ReturnCodeEnum.CODE_USER_HAS_BEEN_THIS_PILE);
} else {
// 进行绑定,此用户为普通用户
PileMemberRelation info = new PileMemberRelation();
info.setPileSn(dto.getPileSn());
info.setMemberId(memberBasicInfo.getMemberId());
info.setType("2");
pileMemberRelationService.insertPileMemberRelation(info);
}
}
/**
* 获取枪口实时数据
* @param dto
* @return
*/
public PersonPileRealTimeVO getConnectorRealTimeInfo(QueryPersonPileDTO dto) {
// 根据memberId查出该用户 正在充电、个人桩启动(白名单支付方式)的订单号
OrderBasicInfo orderBasicInfo = OrderBasicInfo.builder()
.memberId(dto.getMemberId())
.orderStatus(OrderStatusEnum.IN_THE_CHARGING.getValue())
.pileConnectorCode(dto.getPileConnectorCode())
.startMode("3") // 3- 白名单支付
.build();
OrderBasicInfo basicInfo = orderBasicInfoService.getOrderBasicInfo(orderBasicInfo);
if (basicInfo == null){
throw new BusinessException(ReturnCodeEnum.CODE_NO_CHARGING_ORDER_ERROR);
}
String orderCode = basicInfo.getOrderCode();
// 根据订单号从redis中获取实时数据信息(默认时间倒叙排列,所以取第一条)
List<RealTimeMonitorData> chargingRealTimeData = orderBasicInfoService.getChargingRealTimeData(orderCode);
if (CollectionUtils.isEmpty(chargingRealTimeData)) {
throw new BusinessException(ReturnCodeEnum.CODE_NO_REAL_TIME_INFO);
}
RealTimeMonitorData realTimeMonitorData = chargingRealTimeData.get(0);
// 将需要的数据set
PersonPileRealTimeVO vo = PersonPileRealTimeVO.builder()
.chargingDegree(realTimeMonitorData.getChargingDegree())
.chargingTime(realTimeMonitorData.getSumChargingTime())
.startTime(DateUtils.formatDateTime(orderBasicInfo.getChargeStartTime()))
.instantCurrent(realTimeMonitorData.getOutputCurrent())
.instantVoltage(realTimeMonitorData.getOutputVoltage())
.instantPower(realTimeMonitorData.getOutputPower())
.build();
return vo;
}
/**
* 获取某枪口某段时间内累计信息
* @param dto
* @return
*/
public PersonPileConnectorSumInfoVO getAccumulativeInfo(QueryPersonPileDTO dto) {
List<PersonPileConnectorSumInfoVO> accumulativeInfo = orderBasicInfoService.getAccumulativeInfo(dto);
if (CollectionUtils.isEmpty(accumulativeInfo)) {
throw new BusinessException("00400011", "未查到相关订单信息!");
}
// BigDecimal sumChargingTime = BigDecimal.ZERO;
// BigDecimal sumUsedElectricity = BigDecimal.ZERO;
// // 将返回的结果进行for循环将总充电量、总充电时长进行累加充电时长需要通过 充电开始时间 和 充电结束时间 进行计算)
// for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : accumulativeInfo) {
// if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
// long longChargingTime = DateUtils.intervalTime(personPileConnectorSumInfoVO.getChargeStartTime(), personPileConnectorSumInfoVO.getChargeEndTime());
// BigDecimal chargingTime = new BigDecimal(String.valueOf(longChargingTime));
// sumChargingTime = sumChargingTime.add(chargingTime);
// }
// BigDecimal chargingDegree = StringUtils.isBlank(personPileConnectorSumInfoVO.getSumChargingDegree())
// ? BigDecimal.ZERO
// : new BigDecimal(personPileConnectorSumInfoVO.getSumChargingDegree());
// sumUsedElectricity = sumUsedElectricity.add(chargingDegree);
// }
Map<String, String> sumInfo = getSumInfo(accumulativeInfo);
// set 对象
PersonPileConnectorSumInfoVO vo = new PersonPileConnectorSumInfoVO();
vo.setStartTime(dto.getStartTime());
vo.setEndTime(dto.getEndTime());
vo.setMemberId(dto.getMemberId());
vo.setSumChargingDegree(sumInfo.get("sumUsedElectricity"));
vo.setSumChargingTime(sumInfo.get("sumChargingTime"));
return vo;
}
/**
* 获取充电记录默认30天
*
* @param dto
*/
public PageResponse getChargingRecord(QueryPersonPileDTO dto) {
int pageNum = dto.getPageNum() == 0 ? 1 : dto.getPageNum();
int pageSize = dto.getPageSize() == 0 ? 10 : dto.getPageSize();
// 获取三十天前的数据
Date date = DateUtils.addMonths(new Date(), -1);
String dateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, date);
dto.setStartTime(dateStr);
dto.setEndTime(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()));
// 分页查询
PageHelper.startPage(pageNum, pageSize);
List<PersonPileConnectorSumInfoVO> accumulativeInfo = orderBasicInfoService.getAccumulativeInfo(dto);
if (CollectionUtils.isEmpty(accumulativeInfo)) {
throw new BusinessException("00400011", "未查到相关订单信息!");
}
PageInfo<PersonPileConnectorSumInfoVO> pageInfo = new PageInfo<>(accumulativeInfo);
for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : pageInfo.getList()) {
if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
String datePoor = DateUtils.getDatePoor(DateUtils.parseDate(personPileConnectorSumInfoVO.getChargeEndTime()),
DateUtils.parseDate(personPileConnectorSumInfoVO.getChargeStartTime()));
personPileConnectorSumInfoVO.setSumChargingTime(datePoor);
}
}
return PageResponse.builder()
.pageNum(pageInfo.getPageNum())
.pageSize(pageInfo.getPageSize())
.list(pageInfo.getList())
.pages(pageInfo.getPages())
.total(pageInfo.getTotal())
.build();
}
/**
* 获取总充电时长、总充电量
*
* @param accumulativeInfo
* @return
*/
private Map<String, String> getSumInfo(List<PersonPileConnectorSumInfoVO> accumulativeInfo){
Map<String, String> resultMap = new HashMap<>();
BigDecimal sumChargingTime = BigDecimal.ZERO;
BigDecimal sumUsedElectricity = BigDecimal.ZERO;
// 将返回的结果进行for循环将总充电量、总充电时长进行累加充电时长需要通过 充电开始时间 和 充电结束时间 进行计算)
for (PersonPileConnectorSumInfoVO personPileConnectorSumInfoVO : accumulativeInfo) {
if (StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeStartTime()) && StringUtils.isNotBlank(personPileConnectorSumInfoVO.getChargeEndTime())){
long longChargingTime = DateUtils.intervalTime(personPileConnectorSumInfoVO.getChargeStartTime(), personPileConnectorSumInfoVO.getChargeEndTime());
BigDecimal chargingTime = new BigDecimal(String.valueOf(longChargingTime));
sumChargingTime = sumChargingTime.add(chargingTime);
}
BigDecimal chargingDegree = StringUtils.isBlank(personPileConnectorSumInfoVO.getSumChargingDegree())
? BigDecimal.ZERO
: new BigDecimal(personPileConnectorSumInfoVO.getSumChargingDegree());
sumUsedElectricity = sumUsedElectricity.add(chargingDegree);
}
resultMap.put("sumChargingTime", String.valueOf(sumChargingTime));
resultMap.put("sumUsedElectricity", String.valueOf(sumUsedElectricity));
return resultMap;
}
}

View File

@@ -0,0 +1,91 @@
package com.jsowell.web.controller.common;
import com.google.code.kaptcha.Producer;
import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.util.sign.Base64;
import com.jsowell.common.util.id.IdUtils;
import com.jsowell.system.service.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* 验证码操作处理
*
* @author jsowell
*/
@RestController
public class CaptchaController {
@Resource(name = "captchaProducer")
private Producer captchaProducer;
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
@Autowired
private RedisCache redisCache;
@Autowired
private SysConfigService configService;
Logger log = LoggerFactory.getLogger(CaptchaController.class);
/**
* 生成验证码
*/
@GetMapping("/captchaImage")
public AjaxResult getCode(HttpServletResponse response) throws IOException {
AjaxResult ajax = AjaxResult.success();
boolean captchaEnabled = configService.selectCaptchaEnabled();
ajax.put("captchaEnabled", captchaEnabled);
if (!captchaEnabled) {
return ajax;
}
// 保存验证码信息
String uuid = IdUtils.simpleUUID();
String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成验证码
String captchaType = JsowellConfig.getCaptchaType();
if ("math".equals(captchaType)) {
String capText = captchaProducerMath.createText();
capStr = capText.substring(0, capText.lastIndexOf("@"));
code = capText.substring(capText.lastIndexOf("@") + 1);
image = captchaProducerMath.createImage(capStr);
} else if ("char".equals(captchaType)) {
capStr = code = captchaProducer.createText();
image = captchaProducer.createImage(capStr);
}
log.info("获取验证码 uuid:{}, captcha:{}", uuid, capStr);
redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try {
ImageIO.write(image, "jpg", os);
} catch (IOException e) {
return AjaxResult.error(e.getMessage());
}
ajax.put("uuid", uuid);
ajax.put("img", Base64.encode(os.toByteArray()));
return ajax;
}
}

View File

@@ -0,0 +1,143 @@
package com.jsowell.web.controller.common;
import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.file.FileUploadUtils;
import com.jsowell.common.util.file.FileUtils;
import com.jsowell.framework.config.ServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
/**
* 通用请求处理
*
* @author jsowell
*/
@RestController
@RequestMapping("/common")
public class CommonController {
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Autowired
private ServerConfig serverConfig;
private static final String FILE_DELIMETER = ",";
/**
* 通用下载请求
*
* @param fileName 文件名称
* @param delete 是否删除
*/
@GetMapping("/download")
public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
try {
if (!FileUtils.checkAllowDownload(fileName)) {
throw new Exception(StringUtils.format("文件名称({})非法,不允许下载。 ", fileName));
}
String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
String filePath = JsowellConfig.getDownloadPath() + fileName;
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, realFileName);
FileUtils.writeBytes(filePath, response.getOutputStream());
if (delete) {
FileUtils.deleteFile(filePath);
}
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception {
try {
// 上传文件路径
String filePath = JsowellConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 通用上传请求(多个)
*/
@PostMapping("/uploads")
public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
try {
// 上传文件路径
String filePath = JsowellConfig.getUploadPath();
List<String> urls = new ArrayList<String>();
List<String> fileNames = new ArrayList<String>();
List<String> newFileNames = new ArrayList<String>();
List<String> originalFilenames = new ArrayList<String>();
for (MultipartFile file : files) {
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
urls.add(url);
fileNames.add(fileName);
newFileNames.add(FileUtils.getName(fileName));
originalFilenames.add(file.getOriginalFilename());
}
AjaxResult ajax = AjaxResult.success();
ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
/**
* 本地资源通用下载
*/
@GetMapping("/download/resource")
public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
if (!FileUtils.checkAllowDownload(resource)) {
throw new Exception(StringUtils.format("资源文件({})非法,不允许下载。 ", resource));
}
// 本地资源路径
String localPath = JsowellConfig.getProfile();
// 数据库资源地址
String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
// 下载名称
String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
FileUtils.setAttachmentResponseHeader(response, downloadName);
FileUtils.writeBytes(downloadPath, response.getOutputStream());
} catch (Exception e) {
log.error("下载文件失败", e);
}
}
}

View File

@@ -0,0 +1,71 @@
package com.jsowell.web.controller.index;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.vo.web.IndexGeneralSituationVO;
import com.jsowell.pile.dto.IndexQueryDTO;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.vo.web.IndexOrderInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 首页数据展示Controller
*
* @author JS-ZZA
* @date 2023/2/3 10:11
*/
@RestController
@RequestMapping("/index")
public class indexController extends BaseController {
@Autowired
IPileBasicInfoService pileBasicInfoService;
@Autowired
IOrderBasicInfoService orderBasicInfoService;
@PostMapping("/getGeneralSituation")
public RestApiResponse<?> getGeneralSituation(@RequestBody IndexQueryDTO dto) {
logger.info("首页基础数据查询 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response;
try {
IndexGeneralSituationVO generalSituation = pileBasicInfoService.getGeneralSituation(dto);
response = new RestApiResponse<>(generalSituation);
}catch (Exception e) {
logger.error("首页数据查询错误:{}", e.getMessage());
response = new RestApiResponse<>("00200001", "首页基础数据查询错误");
}
logger.info("首页数据查询 result:{}", JSONObject.toJSONString(response));
return response;
}
/**
* 首页订单数据汇总信息
*
* @param dto
* @return
*/
@PostMapping("/getOrderInfo")
public RestApiResponse<?> getOrderInfo(@RequestBody IndexQueryDTO dto) {
logger.info("首页订单相关信息查询 param:{}", JSONObject.toJSONString(dto));
RestApiResponse<?> response;
try {
List<IndexOrderInfoVO> indexOrderInfo = orderBasicInfoService.getIndexOrderInfo(dto);
response = new RestApiResponse<>(indexOrderInfo);
} catch (Exception e) {
logger.error("首页订单相关信息查询错误!{}", e.getMessage());
response = new RestApiResponse<>("00200002", "首页订单数据查询错误");
}
logger.info("首页订单相关信息查询 result:{}", JSONObject.toJSONString(response));
return response;
}
}

View File

@@ -0,0 +1,114 @@
package com.jsowell.web.controller.monitor;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.util.StringUtils;
import com.jsowell.system.domain.SysCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
/**
* 缓存监控
*
* @author jsowell
*/
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {
@Autowired
private RedisTemplate<String, String> redisTemplate;
private final static List<SysCache> caches = new ArrayList<SysCache>();
{
caches.add(new SysCache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
caches.add(new SysCache(CacheConstants.SYS_CONFIG_KEY, "配置信息"));
caches.add(new SysCache(CacheConstants.SYS_DICT_KEY, "数据字典"));
caches.add(new SysCache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
caches.add(new SysCache(CacheConstants.REPEAT_SUBMIT_KEY, "防重提交"));
caches.add(new SysCache(CacheConstants.RATE_LIMIT_KEY, "限流处理"));
caches.add(new SysCache(CacheConstants.PWD_ERR_CNT_KEY, "密码错误次数"));
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception {
Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());
Map<String, Object> result = new HashMap<>(3);
result.put("info", info);
result.put("dbSize", dbSize);
List<Map<String, String>> pieList = new ArrayList<>();
commandStats.stringPropertyNames().forEach(key -> {
Map<String, String> data = new HashMap<>(2);
String property = commandStats.getProperty(key);
data.put("name", StringUtils.removeStart(key, "cmdstat_"));
data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
pieList.add(data);
});
result.put("commandStats", pieList);
return AjaxResult.success(result);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getNames")
public AjaxResult cache() {
return AjaxResult.success(caches);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getKeys/{cacheName}")
public AjaxResult getCacheKeys(@PathVariable String cacheName) {
Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
return AjaxResult.success(cacheKeys);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@GetMapping("/getValue/{cacheName}/{cacheKey}")
public AjaxResult getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
String cacheValue = redisTemplate.opsForValue().get(cacheKey);
SysCache sysCache = new SysCache(cacheName, cacheKey, cacheValue);
return AjaxResult.success(sysCache);
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheName/{cacheName}")
public AjaxResult clearCacheName(@PathVariable String cacheName) {
Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheKey/{cacheKey}")
public AjaxResult clearCacheKey(@PathVariable String cacheKey) {
redisTemplate.delete(cacheKey);
return AjaxResult.success();
}
@PreAuthorize("@ss.hasPermi('monitor:cache:list')")
@DeleteMapping("/clearCacheAll")
public AjaxResult clearCacheAll() {
Collection<String> cacheKeys = redisTemplate.keys("*");
redisTemplate.delete(cacheKeys);
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,25 @@
package com.jsowell.web.controller.monitor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.framework.web.domain.Server;
/**
* 服务器监控
*
* @author jsowell
*/
@RestController
@RequestMapping("/monitor/server")
public class ServerController {
@PreAuthorize("@ss.hasPermi('monitor:server:list')")
@GetMapping()
public AjaxResult getInfo() throws Exception {
Server server = new Server();
server.copyTo();
return AjaxResult.success(server);
}
}

View File

@@ -0,0 +1,72 @@
package com.jsowell.web.controller.monitor;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.framework.web.service.SysPasswordService;
import com.jsowell.system.domain.SysLogininfor;
import com.jsowell.system.service.SysLogininforService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 系统访问记录
*
* @author jsowell
*/
@RestController
@RequestMapping("/monitor/logininfor")
public class SysLogininforController extends BaseController {
@Autowired
private SysLogininforService logininforService;
@Autowired
private SysPasswordService passwordService;
@PreAuthorize("@ss.hasPermi('monitor:logininfor:list')")
@GetMapping("/list")
public TableDataInfo list(SysLogininfor logininfor) {
startPage();
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
return getDataTable(list);
}
@Log(title = "登录日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:logininfor:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysLogininfor logininfor) {
List<SysLogininfor> list = logininforService.selectLogininforList(logininfor);
ExcelUtil<SysLogininfor> util = new ExcelUtil<SysLogininfor>(SysLogininfor.class);
util.exportExcel(response, list, "登录日志");
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.DELETE)
@DeleteMapping("/{infoIds}")
public AjaxResult remove(@PathVariable Long[] infoIds) {
return toAjax(logininforService.deleteLogininforByIds(infoIds));
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:remove')")
@Log(title = "登录日志", businessType = BusinessType.CLEAN)
@DeleteMapping("/clean")
public AjaxResult clean() {
logininforService.cleanLogininfor();
return success();
}
@PreAuthorize("@ss.hasPermi('monitor:logininfor:unlock')")
@Log(title = "账户解锁", businessType = BusinessType.OTHER)
@GetMapping("/unlock/{userName}")
public AjaxResult unlock(@PathVariable("userName") String userName) {
passwordService.clearLoginRecordCache(userName);
return success();
}
}

View File

@@ -0,0 +1,65 @@
package com.jsowell.web.controller.monitor;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.domain.SysOperLog;
import com.jsowell.system.service.SysOperLogService;
/**
* 操作日志记录
*
* @author jsowell
*/
@RestController
@RequestMapping("/monitor/operlog")
public class SysOperlogController extends BaseController {
@Autowired
private SysOperLogService operLogService;
@PreAuthorize("@ss.hasPermi('monitor:operlog:list')")
@GetMapping("/list")
public TableDataInfo list(SysOperLog operLog) {
startPage();
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
return getDataTable(list);
}
@Log(title = "操作日志", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('monitor:operlog:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysOperLog operLog) {
List<SysOperLog> list = operLogService.selectOperLogList(operLog);
ExcelUtil<SysOperLog> util = new ExcelUtil<SysOperLog>(SysOperLog.class);
util.exportExcel(response, list, "操作日志");
}
@Log(title = "操作日志", businessType = BusinessType.DELETE)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/{operIds}")
public AjaxResult remove(@PathVariable Long[] operIds) {
return toAjax(operLogService.deleteOperLogByIds(operIds));
}
@Log(title = "操作日志", businessType = BusinessType.CLEAN)
@PreAuthorize("@ss.hasPermi('monitor:operlog:remove')")
@DeleteMapping("/clean")
public AjaxResult clean() {
operLogService.cleanOperLog();
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,75 @@
package com.jsowell.web.controller.monitor;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.model.LoginUser;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.system.domain.SysUserOnline;
import com.jsowell.system.service.SysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* 在线用户监控
*
* @author jsowell
*/
@RestController
@RequestMapping("/monitor/online")
public class SysUserOnlineController extends BaseController {
@Autowired
private SysUserOnlineService userOnlineService;
@Autowired
private RedisCache redisCache;
@PreAuthorize("@ss.hasPermi('monitor:online:list')")
@GetMapping("/list")
public TableDataInfo list(String ipaddr, String userName) {
Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
for (String key : keys) {
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)) {
if (StringUtils.equals(ipaddr, user.getIpaddr()) && StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByInfo(ipaddr, userName, user));
}
} else if (StringUtils.isNotEmpty(ipaddr)) {
if (StringUtils.equals(ipaddr, user.getIpaddr())) {
userOnlineList.add(userOnlineService.selectOnlineByIpaddr(ipaddr, user));
}
} else if (StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) {
if (StringUtils.equals(userName, user.getUsername())) {
userOnlineList.add(userOnlineService.selectOnlineByUserName(userName, user));
}
} else {
userOnlineList.add(userOnlineService.loginUserToUserOnline(user));
}
}
Collections.reverse(userOnlineList);
userOnlineList.removeAll(Collections.singleton(null));
return getDataTable(userOnlineList);
}
/**
* 强退用户
*/
@PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
@Log(title = "在线用户", businessType = BusinessType.FORCE)
@DeleteMapping("/{tokenId}")
public AjaxResult forceLogout(@PathVariable String tokenId) {
redisCache.deleteObject(CacheConstants.LOGIN_TOKEN_KEY + tokenId);
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,159 @@
package com.jsowell.web.controller.pile;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.enums.uniapp.BalanceChangesEnum;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.MemberBasicInfo;
import com.jsowell.pile.dto.UniAppQueryMemberBalanceDTO;
import com.jsowell.pile.service.IMemberBasicInfoService;
import com.jsowell.pile.service.IMemberTransactionRecordService;
import com.jsowell.pile.vo.uniapp.MemberVO;
import com.jsowell.pile.vo.uniapp.MemberWalletLogVO;
import com.jsowell.pile.vo.web.MemberTransactionVO;
import com.jsowell.pile.vo.web.UpdateMemberBalanceDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 会员基础信息Controller
*
* @author jsowell
* @date 2022-10-12
*/
@RestController
@RequestMapping("/member/info")
public class MemberBasicInfoController extends BaseController {
@Autowired
private IMemberBasicInfoService memberBasicInfoService;
@Autowired
private IMemberTransactionRecordService memberTransactionRecordService;
/**
* 查询会员基础信息列表
*/
@PreAuthorize("@ss.hasPermi('member:info:list')")
@GetMapping("/list")
public TableDataInfo list(MemberBasicInfo memberBasicInfo) {
startPage();
List<MemberVO> list = memberBasicInfoService.selectMemberList(memberBasicInfo.getMobileNumber(), memberBasicInfo.getNickName());
return getDataTable(list);
}
/**
* 导出会员基础信息列表
*/
/*@PreAuthorize("@ss.hasPermi('member:info:export')")
@Log(title = "会员基础信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, MemberBasicInfo memberBasicInfo) {
List<MemberBasicInfo> list = memberBasicInfoService.selectMemberBasicInfoList(memberBasicInfo);
ExcelUtil<MemberBasicInfo> util = new ExcelUtil<MemberBasicInfo>(MemberBasicInfo.class);
util.exportExcel(response, list, "会员基础信息数据");
}*/
/**
* 获取会员基础信息详细信息
*/
@PreAuthorize("@ss.hasPermi('member:info:query')")
@GetMapping(value = "/{memberId}")
public AjaxResult getInfo(@PathVariable("memberId") String memberId) {
return AjaxResult.success(memberBasicInfoService.queryMemberInfoByMemberId(memberId));
}
@PreAuthorize("@ss.hasPermi('member:info:query')")
@GetMapping(value = "/getMemberPersonPileInfo/{memberId}")
public AjaxResult getMemberPersonPileInfo(@PathVariable("memberId") String memberId){
return AjaxResult.success(memberBasicInfoService.getMemberPersonPileInfo(memberId));
}
/**
* 新增会员基础信息
*/
@PreAuthorize("@ss.hasPermi('member:info:add')")
@Log(title = "会员基础信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody MemberBasicInfo memberBasicInfo) {
return toAjax(memberBasicInfoService.insertMemberBasicInfo(memberBasicInfo));
}
/**
* 修改会员基础信息
*/
@PreAuthorize("@ss.hasPermi('member:info:edit')")
@Log(title = "会员基础信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody MemberBasicInfo memberBasicInfo) {
return toAjax(memberBasicInfoService.updateMemberBasicInfo(memberBasicInfo));
}
/**
* 删除会员基础信息
*/
@PreAuthorize("@ss.hasPermi('member:info:remove')")
@Log(title = "会员基础信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Integer[] ids) {
return toAjax(memberBasicInfoService.deleteMemberBasicInfoByIds(Lists.newArrayList(ids)));
}
/**
* 充值/扣款余额
*/
@PreAuthorize("@ss.hasPermi('member:balance:update')")
@Log(title = "会员充值/扣款余额", businessType = BusinessType.UPDATE)
@PutMapping("/updateGiftBalance")
public AjaxResult updateGiftBalance(@RequestBody UpdateMemberBalanceDTO dto) {
logger.info("后管充值/扣款余额 param:{}", dto.toString());
// 判断入参
return toAjax(memberBasicInfoService.updateMemberBalance(dto));
}
/**
* 查询会员钱包流水
*/
@PostMapping("/queryMemberBalanceChanges")
public TableDataInfo queryMemberBalanceChanges(@RequestBody UniAppQueryMemberBalanceDTO dto) {
String type = dto.getType();
if (!StringUtils.equals("1", type) && !StringUtils.equals("2", type)) {
type = "";
}
PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
List<MemberWalletLogVO> list = memberBasicInfoService.getMemberBalanceChanges(dto.getMemberId(), type);
for (MemberWalletLogVO walletLogVO : list) {
String subType = walletLogVO.getSubType();
String subTypeValue = BalanceChangesEnum.getValueByCode(subType);
if (StringUtils.isNotBlank(subTypeValue)) {
walletLogVO.setSubType(subTypeValue);
}
}
return getDataTable(list);
}
/**
* 查询会员交易流水
* IMemberTransactionRecordService
*/
@PostMapping("/selectMemberTransactionRecordList")
public TableDataInfo selectMemberTransactionRecordList(@RequestBody UniAppQueryMemberBalanceDTO dto) {
startPage();
List<MemberTransactionVO> list = memberTransactionRecordService.selectMemberTransactionRecordList(dto.getMemberId());
return getDataTable(list);
}
}

View File

@@ -0,0 +1,98 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.OrderAbnormalRecord;
import com.jsowell.pile.service.IOrderAbnormalRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 订单异常记录Controller
*
* @author jsowell
* @date 2023-02-13
*/
@RestController
@RequestMapping("/order/abnormalRecord")
public class OrderAbnormalRecordController extends BaseController {
@Autowired
private IOrderAbnormalRecordService orderAbnormalRecordService;
/**
* 查询订单异常记录列表
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:list')")
@GetMapping("/list")
public TableDataInfo list(OrderAbnormalRecord orderAbnormalRecord) {
startPage();
List<OrderAbnormalRecord> list = orderAbnormalRecordService.selectOrderAbnormalRecordList(orderAbnormalRecord);
return getDataTable(list);
}
/**
* 导出订单异常记录列表
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:export')")
@Log(title = "订单异常记录", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, OrderAbnormalRecord orderAbnormalRecord) {
List<OrderAbnormalRecord> list = orderAbnormalRecordService.selectOrderAbnormalRecordList(orderAbnormalRecord);
ExcelUtil<OrderAbnormalRecord> util = new ExcelUtil<OrderAbnormalRecord>(OrderAbnormalRecord.class);
util.exportExcel(response, list, "订单异常记录数据");
}
/**
* 获取订单异常记录详细信息
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Integer id) {
return AjaxResult.success(orderAbnormalRecordService.selectOrderAbnormalRecordById(id));
}
/**
* 新增订单异常记录
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:add')")
@Log(title = "订单异常记录", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody OrderAbnormalRecord orderAbnormalRecord) {
return toAjax(orderAbnormalRecordService.insertOrderAbnormalRecord(orderAbnormalRecord));
}
/**
* 修改订单异常记录
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:edit')")
@Log(title = "订单异常记录", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody OrderAbnormalRecord orderAbnormalRecord) {
return toAjax(orderAbnormalRecordService.updateOrderAbnormalRecord(orderAbnormalRecord));
}
/**
* 删除订单异常记录
*/
@PreAuthorize("@ss.hasPermi('order:abnormalRecord:remove')")
@Log(title = "订单异常记录", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Integer[] ids) {
return toAjax(orderAbnormalRecordService.deleteOrderAbnormalRecordByIds(ids));
}
}

View File

@@ -0,0 +1,104 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.vo.web.OrderListVO;
import com.jsowell.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 订单Controller
*
* @author jsowell
* @date 2022-09-30
*/
@RestController
@RequestMapping("/order")
public class OrderBasicInfoController extends BaseController {
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
@Autowired
private OrderService orderService;
/**
* 查询订单列表
*/
@PreAuthorize("@ss.hasPermi('order:order:list')")
@GetMapping("/order/list")
public TableDataInfo list(QueryOrderDTO orderBasicInfo) {
startPage();
List<OrderListVO> list = orderBasicInfoService.selectOrderBasicInfoList(orderBasicInfo);
return getDataTable(list);
}
/**
* 根据参数查询用电度数和消费金额
*/
@PreAuthorize("@ss.hasPermi('order:order:list')")
@GetMapping("/order/totalData")
public AjaxResult getOrderTotalData(QueryOrderDTO orderBasicInfo) {
return AjaxResult.success(orderBasicInfoService.getOrderTotalData(orderBasicInfo));
}
/**
* 导出订单列表
*/
@PreAuthorize("@ss.hasPermi('order:order:export')")
@Log(title = "订单", businessType = BusinessType.EXPORT)
@PostMapping("/order/export")
public void export(HttpServletResponse response, QueryOrderDTO orderBasicInfo) {
List<OrderListVO> list = orderBasicInfoService.selectOrderBasicInfoList(orderBasicInfo);
ExcelUtil<OrderListVO> util = new ExcelUtil<OrderListVO>(OrderListVO.class);
util.exportExcel(response, list, "订单数据");
}
/**
* 获取订单详细信息
* http://localhost:8080/order/orderDetail/88000000000001012211161342359448
*/
@PreAuthorize("@ss.hasPermi('order:order:query')")
@GetMapping(value = "/orderDetail/{orderCode}")
public AjaxResult getInfo(@PathVariable("orderCode") String orderCode) {
return AjaxResult.success(orderService.queryOrderDetailInfo(orderCode));
}
/**
* 修改订单 后管调用
*/
@PreAuthorize("@ss.hasPermi('order:order:edit')")
@Log(title = "订单", businessType = BusinessType.UPDATE)
@PutMapping("/order")
public AjaxResult edit(@RequestBody OrderBasicInfo orderBasicInfo) {
return toAjax(orderBasicInfoService.updateOrderBasicInfo(orderBasicInfo));
}
/**
* 删除订单
*/
@PreAuthorize("@ss.hasPermi('order:order:remove')")
@Log(title = "订单", businessType = BusinessType.DELETE)
@DeleteMapping("/order/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(orderBasicInfoService.deleteOrderBasicInfoByIds(ids));
}
}

View File

@@ -0,0 +1,163 @@
package com.jsowell.web.controller.pile;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.dto.BatchCreatePileDTO;
import com.jsowell.pile.dto.QueryPileDTO;
import com.jsowell.pile.dto.ReplaceMerchantStationDTO;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileMsgRecordService;
import com.jsowell.pile.vo.web.PileDetailVO;
import com.jsowell.service.PileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 设备管理Controller
*
* @author jsowell
* @date 2022-08-26
*/
@RestController
@RequestMapping("/pile/basic")
public class PileBasicInfoController extends BaseController {
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private PileService pileService;
@Autowired
private IPileMsgRecordService pileMsgRecordService;
/**
* 查询设备管理列表
*/
@PreAuthorize("@ss.hasPermi('pile:basic:list')")
@GetMapping("/list")
public TableDataInfo list(QueryPileDTO queryPileDTO) {
// startPage(); // 在方法中分页
List<PileDetailVO> list = pileBasicInfoService.queryPileInfos(queryPileDTO);
return getDataTable(list);
}
/**
* 导出设备管理列表
*/
@PreAuthorize("@ss.hasPermi('pile:basic:export')")
@Log(title = "设备管理", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileBasicInfo pileBasicInfo) {
List<PileBasicInfo> list = pileBasicInfoService.selectPileBasicInfoList(pileBasicInfo);
ExcelUtil<PileBasicInfo> util = new ExcelUtil<PileBasicInfo>(PileBasicInfo.class);
util.exportExcel(response, list, "设备管理数据");
}
/**
* 获取设备管理详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:basic:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(pileBasicInfoService.selectPileBasicInfoById(id));
}
/**
* 新增设备管理
*/
@PreAuthorize("@ss.hasPermi('pile:basic:add')")
@Log(title = "设备管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileBasicInfo pileBasicInfo) {
return toAjax(pileBasicInfoService.insertPileBasicInfo(pileBasicInfo));
}
/**
* 批量生成充电桩
* @param dto
* @return
*/
@PreAuthorize("@ss.hasPermi('pile:basic:add')")
@Log(title = "设备管理", businessType = BusinessType.INSERT)
@PostMapping("/batchAdd")
public AjaxResult batchAdd(@RequestBody BatchCreatePileDTO dto) {
logger.info("批量生成充电桩 param:{}", JSONObject.toJSONString(dto));
return toAjax(pileService.batchCreatePile(dto));
}
/**
* 修改设备管理
*/
@PreAuthorize("@ss.hasPermi('pile:basic:edit')")
@Log(title = "设备管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileBasicInfo pileBasicInfo) {
return toAjax(pileBasicInfoService.updatePileBasicInfo(pileBasicInfo));
}
/**
* 删除设备管理
*/
@PreAuthorize("@ss.hasPermi('pile:basic:remove')")
@Log(title = "设备管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileBasicInfoService.deletePileBasicInfoByIds(ids));
}
/**
* 批量更新充电桩
* 运营商 站点
*/
@PostMapping("/batchUpdatePileList")
public AjaxResult batchUpdatePileList( @RequestBody ReplaceMerchantStationDTO dto) {
logger.info("批量更新充电桩 param:{}", JSONObject.toJSONString(dto));
return toAjax(pileBasicInfoService.replaceMerchantStationByPileIds(dto));
}
/**
* 查询充电桩详情
* @return
*/
@PostMapping("/getPileDetailById")
public AjaxResult getPileDetailById(@RequestBody QueryPileDTO queryPileDTO) {
logger.info("查询充电桩详情 param:{}", JSONObject.toJSONString(queryPileDTO));
if (StringUtils.isBlank(queryPileDTO.getPileId())) {
return AjaxResult.error("充电桩id不能为空");
}
return AjaxResult.success(pileBasicInfoService.selectBasicInfoById(Long.valueOf(queryPileDTO.getPileId())));
}
/**
* 查询充电桩通讯日志
*
* @param dto
* @return
*/
@PostMapping("/getPileFeedList")
public AjaxResult getPileFeedList(@RequestBody QueryPileDTO dto) {
// logger.info("查询充电桩通信日志 param:{}", dto.getPileSn());
if (StringUtils.isBlank(dto.getPileSn())) {
return AjaxResult.error("充电桩Sn不能为空");
}
return AjaxResult.success(pileMsgRecordService.getPileFeedList(dto));
}
}

View File

@@ -0,0 +1,167 @@
package com.jsowell.web.controller.pile;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileBillingTemplate;
import com.jsowell.pile.dto.CreateOrUpdateBillingTemplateDTO;
import com.jsowell.pile.dto.ImportBillingTemplateDTO;
import com.jsowell.pile.dto.PublishBillingTemplateDTO;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.vo.web.BillingTemplateVO;
import com.jsowell.service.PileRemoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 计费模板Controller
*
* @author jsowell
* @date 2022-09-20
*/
@Api(value = "计费模板Controller", tags = { "计费模板" })
@RestController
@RequestMapping("/billing/template")
public class PileBillingTemplateController extends BaseController {
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private PileRemoteService pileRemoteService;
/**
* 查询计费模板列表
*/
@PreAuthorize("@ss.hasPermi('billing:template:list')")
@GetMapping("/list")
public TableDataInfo list(PileBillingTemplate pileBillingTemplate) {
startPage();
// 只查询公共的
pileBillingTemplate.setPublicFlag(Constants.ONE);
List<PileBillingTemplate> list = pileBillingTemplateService.selectPileBillingTemplateList(pileBillingTemplate);
return getDataTable(list);
}
/**
* 导出计费模板列表
*/
@PreAuthorize("@ss.hasPermi('billing:template:export')")
@Log(title = "计费模板", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileBillingTemplate pileBillingTemplate) {
List<PileBillingTemplate> list = pileBillingTemplateService.selectPileBillingTemplateList(pileBillingTemplate);
ExcelUtil<PileBillingTemplate> util = new ExcelUtil<PileBillingTemplate>(PileBillingTemplate.class);
util.exportExcel(response, list, "计费模板数据");
}
/**
* 获取计费模板详细信息
*/
@PreAuthorize("@ss.hasPermi('billing:template:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfoById(@PathVariable("id") Long id) {
return AjaxResult.success(pileBillingTemplateService.queryPileBillingTemplateById(id));
}
/**
* 修改计费模板
*/
@PreAuthorize("@ss.hasPermi('billing:template:edit')")
@Log(title = "计费模板", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileBillingTemplate pileBillingTemplate) {
return toAjax(pileBillingTemplateService.updatePileBillingTemplate(pileBillingTemplate));
}
/**
* 删除计费模板
*/
@PreAuthorize("@ss.hasPermi('billing:template:remove')")
@Log(title = "计费模板", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileBillingTemplateService.deletePileBillingTemplateByIds(ids));
}
/**
* 新增计费模板
* http://localhost:8080/billing/template/createBillingTemplate
*/
@ApiOperation("新增计费模板")
@PreAuthorize("@ss.hasPermi('billing:template:add')")
@Log(title = "计费模板", businessType = BusinessType.INSERT)
@PostMapping("/createBillingTemplate")
public AjaxResult createBillingTemplate(@RequestBody CreateOrUpdateBillingTemplateDTO dto) {
logger.info("新增计费模板 param:{}", JSONObject.toJSONString(dto));
pileBillingTemplateService.createBillingTemplate(dto);
return AjaxResult.success();
}
/**
* 更新计费模板 前端
* @param dto
* @return
*/
@PostMapping("/updateBillingTemplate")
public AjaxResult updateBillingTemplate(@RequestBody CreateOrUpdateBillingTemplateDTO dto) {
logger.info("修改计费模板 param:{}", JSONObject.toJSONString(dto));
pileBillingTemplateService.updateBillingTemplate(dto);
return AjaxResult.success();
}
/**
* 查询公共计费模板
*/
@GetMapping("/queryPublicBillingTemplateList")
public TableDataInfo queryPublicBillingTemplateList() {
List<BillingTemplateVO> list = pileBillingTemplateService.queryPublicBillingTemplateList();
return getDataTable(list);
}
/**
* 站点导入计费模板接口
* http://localhost:8080/billing/template/stationImportBillingTemplate
*/
@PostMapping("/stationImportBillingTemplate")
public AjaxResult stationImportBillingTemplate(@RequestBody ImportBillingTemplateDTO dto) {
logger.info("站点导入计费模板 param:{}", JSONObject.toJSONString(dto));
return toAjax(pileBillingTemplateService.stationImportBillingTemplate(dto));
}
/**
* 查询站点计费模板
*/
@GetMapping("/queryStationBillingTemplateList/{stationId}")
public TableDataInfo queryStationBillingTemplateList(@PathVariable("stationId") String stationId) {
logger.info("查询站点计费模板 param:{}", stationId);
List<BillingTemplateVO> list = pileBillingTemplateService.queryStationBillingTemplateList(stationId);
logger.info("查询站点计费模板 result{}", JSONObject.toJSONString(list));
return getDataTable(list);
}
/**
* 发布计费模板
*/
@PostMapping("/publishBillingTemplate")
public AjaxResult publishBillingTemplate(@RequestBody PublishBillingTemplateDTO dto) {
return toAjax(pileRemoteService.publishBillingTemplate(dto));
}
}

View File

@@ -0,0 +1,113 @@
package com.jsowell.web.controller.pile;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileConnectorInfo;
import com.jsowell.pile.dto.QueryConnectorDTO;
import com.jsowell.pile.dto.QueryConnectorListDTO;
import com.jsowell.pile.service.IPileConnectorInfoService;
import com.jsowell.pile.vo.web.PileConnectorInfoVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电桩枪口信息Controller
*
* @author jsowell
* @date 2022-08-31
*/
@RestController
@RequestMapping("/pile/connector")
public class PileConnectorInfoController extends BaseController {
@Autowired
private IPileConnectorInfoService pileConnectorInfoService;
/**
* 查询充电桩枪口信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:connector:list')")
@GetMapping("/list")
public TableDataInfo list(QueryConnectorDTO queryConnectorDTO) {
startPage();
List<PileConnectorInfoVO> list = pileConnectorInfoService.getConnectorInfoListByParams(queryConnectorDTO);
return getDataTable(list);
}
/**
* 导出充电桩枪口信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:connector:export')")
@Log(title = "充电桩枪口信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileConnectorInfo pileConnectorInfo) {
List<PileConnectorInfo> list = pileConnectorInfoService.selectPileConnectorInfoList(pileConnectorInfo);
ExcelUtil<PileConnectorInfo> util = new ExcelUtil<PileConnectorInfo>(PileConnectorInfo.class);
util.exportExcel(response, list, "充电桩枪口信息数据");
}
/**
* 通过入参 查询接口列表
* http://localhost:8080/pile/connector/getConnectorInfoListByParams?pileIds=1,2
* 多id使用逗号拼接
*/
@PostMapping("/getConnectorInfoListByParams")
public TableDataInfo getConnectorInfoListByParams(@RequestBody QueryConnectorListDTO dto) {
logger.info("查询接口列表 param:{}", JSONObject.toJSONString(dto));
List<PileConnectorInfoVO> list = pileConnectorInfoService.getConnectorInfoListByParams(dto);
logger.info("查询接口列表 result:{}", JSONObject.toJSONString(list));
return getDataTable(list);
}
/**
* 获取充电桩枪口信息详细信息
*/
// @PreAuthorize("@ss.hasPermi('pile:connector:query')")
// @GetMapping(value = "/{id}")
// public AjaxResult getInfo(@PathVariable("id") Integer id) {
// return AjaxResult.success(pileConnectorInfoService.selectPileConnectorInfoById(id));
// }
/**
* 新增充电桩枪口信息
*/
// @PreAuthorize("@ss.hasPermi('pile:connector:add')")
// @Log(title = "充电桩枪口信息", businessType = BusinessType.INSERT)
// @PostMapping
// public AjaxResult add(@RequestBody PileConnectorInfo pileConnectorInfo) {
// return toAjax(pileConnectorInfoService.insertPileConnectorInfo(pileConnectorInfo));
// }
/**
* 修改充电桩枪口信息
*/
// @PreAuthorize("@ss.hasPermi('pile:connector:edit')")
// @Log(title = "充电桩枪口信息", businessType = BusinessType.UPDATE)
// @PutMapping
// public AjaxResult edit(@RequestBody PileConnectorInfo pileConnectorInfo) {
// return toAjax(pileConnectorInfoService.updatePileConnectorInfo(pileConnectorInfo));
// }
/**
* 删除充电桩枪口信息
*/
// @PreAuthorize("@ss.hasPermi('pile:connector:remove')")
// @Log(title = "充电桩枪口信息", businessType = BusinessType.DELETE)
// @DeleteMapping("/{ids}")
// public AjaxResult remove(@PathVariable Integer[] ids) {
// return toAjax(pileConnectorInfoService.deletePileConnectorInfoByIds(ids));
// }
}

View File

@@ -0,0 +1,98 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileLicenceInfo;
import com.jsowell.pile.service.IPileLicenceInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电桩证书信息Controller
*
* @author jsowell
* @date 2022-08-27
*/
@RestController
@RequestMapping("/pile/licence")
public class PileLicenceInfoController extends BaseController
{
@Autowired
private IPileLicenceInfoService pileLicenceInfoService;
/**
* 查询充电桩证书信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:licence:list')")
@GetMapping("/list")
public TableDataInfo list(PileLicenceInfo pileLicenceInfo)
{
startPage();
List<PileLicenceInfo> list = pileLicenceInfoService.selectPileLicenceInfoList(pileLicenceInfo);
return getDataTable(list);
}
/**
* 导出充电桩证书信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:licence:export')")
@Log(title = "充电桩证书信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileLicenceInfo pileLicenceInfo)
{
List<PileLicenceInfo> list = pileLicenceInfoService.selectPileLicenceInfoList(pileLicenceInfo);
ExcelUtil<PileLicenceInfo> util = new ExcelUtil<PileLicenceInfo>(PileLicenceInfo.class);
util.exportExcel(response, list, "充电桩证书信息数据");
}
/**
* 获取充电桩证书信息详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:licence:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id)
{
return AjaxResult.success(pileLicenceInfoService.selectPileLicenceInfoById(id));
}
/**
* 新增充电桩证书信息
*/
@PreAuthorize("@ss.hasPermi('pile:licence:add')")
@Log(title = "充电桩证书信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileLicenceInfo pileLicenceInfo)
{
return toAjax(pileLicenceInfoService.insertPileLicenceInfo(pileLicenceInfo));
}
/**
* 修改充电桩证书信息
*/
@PreAuthorize("@ss.hasPermi('pile:licence:edit')")
@Log(title = "充电桩证书信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileLicenceInfo pileLicenceInfo)
{
return toAjax(pileLicenceInfoService.updatePileLicenceInfo(pileLicenceInfo));
}
/**
* 删除充电桩证书信息
*/
@PreAuthorize("@ss.hasPermi('pile:licence:remove')")
@Log(title = "充电桩证书信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids)
{
return toAjax(pileLicenceInfoService.deletePileLicenceInfoByIds(ids));
}
}

View File

@@ -0,0 +1,103 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileMerchantInfo;
import com.jsowell.pile.service.IPileMerchantInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电桩运营商信息Controller
*
* @author jsowell
* @date 2022-08-27
*/
@RestController
@RequestMapping("/pile/merchant")
public class PileMerchantInfoController extends BaseController {
@Autowired
private IPileMerchantInfoService pileMerchantInfoService;
/**
* 查询充电桩运营商信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:list')")
@GetMapping("/list")
public TableDataInfo list(PileMerchantInfo pileMerchantInfo) {
startPage();
List<PileMerchantInfo> list = pileMerchantInfoService.selectPileMerchantInfoList(pileMerchantInfo);
return getDataTable(list);
}
/**
* 获取运营商列表 不分页
* @param pileMerchantInfo
* @return
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:list')")
@GetMapping("/getMerchantList")
public TableDataInfo getMerchantList(PileMerchantInfo pileMerchantInfo) {
List<PileMerchantInfo> list = pileMerchantInfoService.selectPileMerchantInfoList(pileMerchantInfo);
return getDataTable(list);
}
/**
* 导出充电桩运营商信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:export')")
@Log(title = "充电桩运营商信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileMerchantInfo pileMerchantInfo) {
List<PileMerchantInfo> list = pileMerchantInfoService.selectPileMerchantInfoList(pileMerchantInfo);
ExcelUtil<PileMerchantInfo> util = new ExcelUtil<PileMerchantInfo>(PileMerchantInfo.class);
util.exportExcel(response, list, "充电桩运营商信息数据");
}
/**
* 获取充电桩运营商信息详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(pileMerchantInfoService.selectPileMerchantInfoById(id));
}
/**
* 新增充电桩运营商信息
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:add')")
@Log(title = "充电桩运营商信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileMerchantInfo pileMerchantInfo) {
return toAjax(pileMerchantInfoService.insertPileMerchantInfo(pileMerchantInfo));
}
/**
* 修改充电桩运营商信息
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:edit')")
@Log(title = "充电桩运营商信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileMerchantInfo pileMerchantInfo) {
return toAjax(pileMerchantInfoService.updatePileMerchantInfo(pileMerchantInfo));
}
/**
* 删除充电桩运营商信息
*/
@PreAuthorize("@ss.hasPermi('pile:merchant:remove')")
@Log(title = "充电桩运营商信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileMerchantInfoService.deletePileMerchantInfoByIds(ids));
}
}

View File

@@ -0,0 +1,91 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileModelInfo;
import com.jsowell.pile.service.IPileModelInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电桩型号信息Controller
*
* @author jsowell
* @date 2022-08-26
*/
@RestController
@RequestMapping("/pile/model")
public class PileModelInfoController extends BaseController {
@Autowired
private IPileModelInfoService pileModelInfoService;
/**
* 查询充电桩型号信息列表
*/
// @PreAuthorize("@ss.hasPermi('pile:model:list')")
@GetMapping("/list")
public TableDataInfo list(PileModelInfo pileModelInfo) {
startPage();
List<PileModelInfo> list = pileModelInfoService.selectPileModelInfoList(pileModelInfo);
return getDataTable(list);
}
/**
* 导出充电桩型号信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:model:export')")
@Log(title = "充电桩型号信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileModelInfo pileModelInfo) {
List<PileModelInfo> list = pileModelInfoService.selectPileModelInfoList(pileModelInfo);
ExcelUtil<PileModelInfo> util = new ExcelUtil<PileModelInfo>(PileModelInfo.class);
util.exportExcel(response, list, "充电桩型号信息数据");
}
/**
* 获取充电桩型号信息详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:model:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(pileModelInfoService.selectPileModelInfoById(id));
}
/**
* 新增充电桩型号信息
*/
@PreAuthorize("@ss.hasPermi('pile:model:add')")
@Log(title = "充电桩型号信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileModelInfo pileModelInfo) {
return toAjax(pileModelInfoService.insertPileModelInfo(pileModelInfo));
}
/**
* 修改充电桩型号信息
*/
@PreAuthorize("@ss.hasPermi('pile:model:edit')")
@Log(title = "充电桩型号信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileModelInfo pileModelInfo) {
return toAjax(pileModelInfoService.updatePileModelInfo(pileModelInfo));
}
/**
* 删除充电桩型号信息
*/
@PreAuthorize("@ss.hasPermi('pile:model:remove')")
@Log(title = "充电桩型号信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileModelInfoService.deletePileModelInfoByIds(ids));
}
}

View File

@@ -0,0 +1,109 @@
package com.jsowell.web.controller.pile;
import com.google.common.collect.ImmutableMap;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.pile.dto.GenerateOrderDTO;
import com.jsowell.pile.dto.QueryPileDTO;
import com.jsowell.service.OrderService;
import com.jsowell.service.PileRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 远程控制controller
*/
@RestController
@RequestMapping("/remote")
public class PileRemoteController {
@Autowired
private PileRemoteService pileRemoteService;
@Autowired
private OrderService orderService;
/**
* 获取实时上传数据
* http://localhost:8080/remote/getRealTimeMonitorData
* @return
*/
@PostMapping("/getRealTimeMonitorData")
public AjaxResult getRealTimeMonitorData(@RequestBody QueryPileDTO queryPileDTO) {
pileRemoteService.getRealTimeMonitorData(queryPileDTO.getPileSn(), queryPileDTO.getConnectorCode());
return AjaxResult.success();
}
/**
* 远程重启
* http://localhost:8080/remote/reboot
* @return
*/
@PostMapping("/reboot")
public AjaxResult reboot(@RequestBody QueryPileDTO queryPileDTO) {
pileRemoteService.reboot(queryPileDTO.getPileSn());
return AjaxResult.success();
}
/**
* 后管-远程启动充电
* http://localhost:8080/remote/remoteStartChargingForWeb
*/
@PostMapping("/remoteStartChargingForWeb")
public AjaxResult remoteStartCharging(@RequestBody GenerateOrderDTO dto) {
// pileRemoteService.remoteStartCharging(queryPileDTO.getPileSn(), queryPileDTO.getConnectorCode());
// 生成订单并远程启动充电
dto.setStartMode(Constants.ZERO);
String orderCode = orderService.generateOrder(dto);
return AjaxResult.success(ImmutableMap.of("orderCode", orderCode));
}
/**
* 远程停止充电
* http://localhost:8080/remote/remoteStopCharging
* @param dto
* @return
*/
@PostMapping("/remoteStopCharging")
public AjaxResult remoteStopCharging(@RequestBody QueryPileDTO dto) {
pileRemoteService.remoteStopCharging(dto.getPileSn(), dto.getConnectorCode());
return AjaxResult.success();
}
/**
* 远程下发二维码
* http://localhost:8080/remote/issueQRCode
*/
@PostMapping("/issueQRCode")
public AjaxResult issueQRCode(@RequestBody QueryPileDTO queryPileDTO) {
pileRemoteService.issueQRCode(queryPileDTO.getPileSn());
return AjaxResult.success();
}
/**
* 对时
* http://localhost:8080/remote/proofreadTime
*/
@PostMapping("/proofreadTime")
public AjaxResult proofreadTime(@RequestBody QueryPileDTO queryPileDTO) {
pileRemoteService.proofreadTime(queryPileDTO.getPileSn());
return AjaxResult.success();
}
/**
* 远程升级
* http://localhost:8080/remote/updateFile
* @return
*/
@PostMapping("/updateFile")
public AjaxResult updateFile(@RequestBody QueryPileDTO queryPileDTO) {
pileRemoteService.updateFile(queryPileDTO.getPileSns());
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,142 @@
package com.jsowell.web.controller.pile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileSimInfo;
import com.jsowell.pile.dto.QuerySimInfoDTO;
import com.jsowell.pile.dto.SimRenewDTO;
import com.jsowell.pile.service.IPileSimInfoService;
import com.jsowell.pile.service.SimCardService;
import com.jsowell.pile.vo.web.SimCardInfoVO;
import com.jsowell.pile.vo.web.SimRenewResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电桩SIM卡信息Controller
*
* @author jsowell
* @date 2022-08-26
*/
@RestController
@RequestMapping("/pile/sim")
public class PileSimInfoController extends BaseController {
@Autowired
private IPileSimInfoService pileSimInfoService;
@Autowired
private SimCardService simCardService;
/**
* 查询充电桩SIM卡信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:sim:list')")
@GetMapping("/list")
public TableDataInfo list(PileSimInfo pileSimInfo) {
startPage();
List<PileSimInfo> list = pileSimInfoService.selectPileSimInfoList(pileSimInfo);
// List<SimCardInfoVO> list = pileSimInfoService.getSimInfoList(pileSimInfo);
return getDataTable(list);
}
@PreAuthorize("@ss.hasPermi('pile:sim:list')")
@PostMapping("/getSimInfo")
public TableDataInfo getSimInfo(QuerySimInfoDTO dto) {
startPage();
List<SimCardInfoVO> simInfoList = pileSimInfoService.getSimInfoList(dto);
return getDataTable(simInfoList);
}
/**
* 导出充电桩SIM卡信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:sim:export')")
@Log(title = "充电桩SIM卡信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileSimInfo pileSimInfo) {
List<PileSimInfo> list = pileSimInfoService.selectPileSimInfoList(pileSimInfo);
ExcelUtil<PileSimInfo> util = new ExcelUtil<PileSimInfo>(PileSimInfo.class);
util.exportExcel(response, list, "充电桩SIM卡信息数据");
}
/**
* 获取充电桩SIM卡信息详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:sim:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(pileSimInfoService.selectPileSimInfoById(id));
}
/**
* 新增充电桩SIM卡信息
*/
@PreAuthorize("@ss.hasPermi('pile:sim:add')")
@Log(title = "充电桩SIM卡信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileSimInfo pileSimInfo) {
return toAjax(pileSimInfoService.insertPileSimInfo(pileSimInfo));
}
/**
* 修改充电桩SIM卡信息
*/
@PreAuthorize("@ss.hasPermi('pile:sim:edit')")
@Log(title = "充电桩SIM卡信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileSimInfo pileSimInfo) {
return toAjax(pileSimInfoService.updatePileSimInfo(pileSimInfo));
}
/**
* 删除充电桩SIM卡信息
*/
@PreAuthorize("@ss.hasPermi('pile:sim:remove')")
@Log(title = "充电桩SIM卡信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileSimInfoService.deletePileSimInfoByIds(ids));
}
/**
* 续费sim卡周期
* @param dto
* @return
*/
@PreAuthorize("@ss.hasPermi('pile:sim:edit')")
@PostMapping("/simRenew")
public AjaxResult simRenew(@RequestBody SimRenewDTO dto) {
List<SimRenewResultVO> list = simCardService.renewSimByLoop(dto.getIccIds(), dto.getCycleNumber());
return AjaxResult.success(list);
// AjaxResult result;
// try {
// List<SimRenewResultVO> list = simCardService.renewSimByLoop(dto.getIccIds(), dto.getCycleNumber());
// result = AjaxResult.
// } catch (BusinessException e) {
// result = AjaxResult.error(Integer.parseInt(e.getCode()), e.getMessage());
// } catch (Exception e) {
// result = AjaxResult.error();
// }
// return result;
}
}

View File

@@ -0,0 +1,148 @@
package com.jsowell.web.controller.pile;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.dto.FastCreateStationDTO;
import com.jsowell.pile.dto.QueryStationDTO;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.vo.web.PileStationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 充电站信息Controller
*
* @author jsowell
* @date 2022-08-30
*/
@RestController
@RequestMapping("/pile/station")
public class PileStationInfoController extends BaseController {
@Autowired
private IPileStationInfoService pileStationInfoService;
/**
* 查询充电站信息列表NEW
*/
@PreAuthorize("@ss.hasPermi('pile:station:list')")
@GetMapping("/list")
public TableDataInfo list(QueryStationDTO queryStationDTO) {
startPage();
// List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
List<PileStationVO> list = pileStationInfoService.queryStationInfos(queryStationDTO);
return getDataTable(list);
}
/**
* 快速建站接口
*/
// @PreAuthorize("@ss.hasPermi('pile:station:add')")
@PostMapping("/fastCreateStation")
public AjaxResult fastCreateStation(@RequestBody FastCreateStationDTO dto) {
logger.info("快速建站接口 param:{}", JSONObject.toJSONString(dto));
int i = 0;
try {
i = pileStationInfoService.fastCreateStation(dto);
} catch (BusinessException e) {
logger.warn("快速建站接口 warn", e);
} catch (Exception e) {
logger.error("快速建站接口 error", e);
}
return toAjax(i);
}
/**
* 查询充电站信息列表
*/
/*@PreAuthorize("@ss.hasPermi('pile:station:list')")
@GetMapping("/list")
public TableDataInfo list(PileStationInfo pileStationInfo) {
startPage();
List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
return getDataTable(list);
}*/
/**
* 导出充电站信息列表
*/
@PreAuthorize("@ss.hasPermi('pile:station:export')")
@Log(title = "充电站信息", businessType = BusinessType.EXPORT)
@PostMapping("/export")
public void export(HttpServletResponse response, PileStationInfo pileStationInfo) {
List<PileStationInfo> list = pileStationInfoService.selectPileStationInfoList(pileStationInfo);
ExcelUtil<PileStationInfo> util = new ExcelUtil<PileStationInfo>(PileStationInfo.class);
util.exportExcel(response, list, "充电站信息数据");
}
/**
* 获取充电站信息详细信息
*/
@PreAuthorize("@ss.hasPermi('pile:station:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
return AjaxResult.success(pileStationInfoService.selectPileStationInfoById(id));
}
/**
* 后管站点基本资料页面
* @return
*/
@PreAuthorize("@ss.hasPermi('pile:station:query')")
@GetMapping(value = "/getStationInfo/{stationId}")
public AjaxResult getStationInfo(@PathVariable("stationId") String stationId) {
return AjaxResult.success(pileStationInfoService.getStationInfo(stationId));
}
/**
* 新增充电站信息
*/
@PreAuthorize("@ss.hasPermi('pile:station:add')")
@Log(title = "充电站信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody PileStationInfo pileStationInfo) {
return toAjax(pileStationInfoService.insertPileStationInfo(pileStationInfo));
}
/**
* 修改充电站信息
*/
@PreAuthorize("@ss.hasPermi('pile:station:edit')")
@Log(title = "充电站信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody PileStationInfo pileStationInfo) {
logger.info("修改充电站信息 param:{}", pileStationInfo.toString());
return toAjax(pileStationInfoService.updatePileStationInfo(pileStationInfo));
}
/**
* 删除充电站信息
*/
@PreAuthorize("@ss.hasPermi('pile:station:remove')")
@Log(title = "充电站信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) {
return toAjax(pileStationInfoService.deletePileStationInfoByIds(ids));
}
/**
* 根据运营商id获取充电站列表
*/
@PreAuthorize("@ss.hasPermi('pile:station:query')")
@PostMapping(value = "/selectStationListByMerchantId")
public AjaxResult selectStationListByMerchantId(@RequestBody QueryStationDTO dto) {
return AjaxResult.success(pileStationInfoService.selectStationListByMerchantId(Long.valueOf(dto.getMerchantId())));
}
}

View File

@@ -0,0 +1,124 @@
package com.jsowell.web.controller.system;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.domain.SysConfig;
import com.jsowell.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 参数配置 信息操作处理
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController {
@Autowired
private SysConfigService configService;
/**
* 获取参数配置列表
*/
@PreAuthorize("@ss.hasPermi('system:config:list')")
@GetMapping("/list")
public TableDataInfo list(SysConfig config) {
startPage();
List<SysConfig> list = configService.selectConfigList(config);
return getDataTable(list);
}
@Log(title = "参数管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:config:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysConfig config) {
List<SysConfig> list = configService.selectConfigList(config);
ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
util.exportExcel(response, list, "参数数据");
}
/**
* 根据参数编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:config:query')")
@GetMapping(value = "/{configId}")
public AjaxResult getInfo(@PathVariable Long configId) {
return AjaxResult.success(configService.selectConfigById(configId));
}
/**
* 根据参数键名查询参数值
*/
@GetMapping(value = "/configKey/{configKey}")
public AjaxResult getConfigKey(@PathVariable String configKey) {
return AjaxResult.success(configService.selectConfigByKey(configKey));
}
/**
* 新增参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:add')")
@Log(title = "参数管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysConfig config) {
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setCreateBy(getUsername());
return toAjax(configService.insertConfig(config));
}
/**
* 修改参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:edit')")
@Log(title = "参数管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysConfig config) {
if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) {
return AjaxResult.error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在");
}
config.setUpdateBy(getUsername());
return toAjax(configService.updateConfig(config));
}
/**
* 删除参数配置
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{configIds}")
public AjaxResult remove(@PathVariable Long[] configIds) {
configService.deleteConfigByIds(configIds);
return success();
}
/**
* 刷新参数缓存
*/
@PreAuthorize("@ss.hasPermi('system:config:remove')")
@Log(title = "参数管理", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache() {
configService.resetConfigCache();
return AjaxResult.success();
}
}

View File

@@ -0,0 +1,140 @@
package com.jsowell.web.controller.system;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysDept;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.system.service.SysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.Iterator;
import java.util.List;
/**
* 部门信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
@Autowired
private SysDeptService deptService;
/**
* 获取部门列表
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list")
public AjaxResult list(SysDept dept) {
List<SysDept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(depts);
}
/**
* 查询部门列表(排除节点)
*/
@PreAuthorize("@ss.hasPermi('system:dept:list')")
@GetMapping("/list/exclude/{deptId}")
public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
List<SysDept> depts = deptService.selectDeptList(new SysDept());
Iterator<SysDept> it = depts.iterator();
while (it.hasNext()) {
SysDept d = (SysDept) it.next();
if (d.getDeptId().intValue() == deptId
|| ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
it.remove();
}
}
return AjaxResult.success(depts);
}
/**
* 根据部门编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:dept:query')")
@GetMapping(value = "/{deptId}")
public AjaxResult getInfo(@PathVariable Long deptId) {
deptService.checkDeptDataScope(deptId);
return AjaxResult.success(deptService.selectDeptById(deptId));
}
/**
* 获取部门下拉树列表
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(SysDept dept) {
List<SysDept> depts = deptService.selectDeptList(dept);
return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
}
/**
* 加载对应角色部门列表树
*/
@GetMapping(value = "/roleDeptTreeselect/{roleId}")
public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
List<SysDept> depts = deptService.selectDeptList(new SysDept());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
ajax.put("depts", deptService.buildDeptTreeSelect(depts));
return ajax;
}
/**
* 新增部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:add')")
@Log(title = "部门管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDept dept) {
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
}
dept.setCreateBy(getUsername());
return toAjax(deptService.insertDept(dept));
}
/**
* 修改部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:edit')")
@Log(title = "部门管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDept dept) {
Long deptId = dept.getDeptId();
deptService.checkDeptDataScope(deptId);
if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
} else if (dept.getParentId().equals(deptId)) {
return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
} else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
return AjaxResult.error("该部门包含未停用的子部门!");
}
dept.setUpdateBy(getUsername());
return toAjax(deptService.updateDept(dept));
}
/**
* 删除部门
*/
@PreAuthorize("@ss.hasPermi('system:dept:remove')")
@Log(title = "部门管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{deptId}")
public AjaxResult remove(@PathVariable Long deptId) {
if (deptService.hasChildByDeptId(deptId)) {
return AjaxResult.error("存在下级部门,不允许删除");
}
if (deptService.checkDeptExistUser(deptId)) {
return AjaxResult.error("部门存在用户,不允许删除");
}
deptService.checkDeptDataScope(deptId);
return toAjax(deptService.deleteDeptById(deptId));
}
}

View File

@@ -0,0 +1,113 @@
package com.jsowell.web.controller.system;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysDictData;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.service.SysDictDataService;
import com.jsowell.system.service.SysDictTypeService;
/**
* 数据字典信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/dict/data")
public class SysDictDataController extends BaseController {
@Autowired
private SysDictDataService dictDataService;
@Autowired
private SysDictTypeService dictTypeService;
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(SysDictData dictData) {
startPage();
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
return getDataTable(list);
}
@Log(title = "字典数据", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictData dictData) {
List<SysDictData> list = dictDataService.selectDictDataList(dictData);
ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
util.exportExcel(response, list, "字典数据");
}
/**
* 查询字典数据详细
*/
@PreAuthorize("@ss.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictCode}")
public AjaxResult getInfo(@PathVariable Long dictCode) {
return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
}
/**
* 根据字典类型查询字典数据信息
*/
@GetMapping(value = "/type/{dictType}")
public AjaxResult dictType(@PathVariable String dictType) {
List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
if (StringUtils.isNull(data)) {
data = new ArrayList<SysDictData>();
}
return AjaxResult.success(data);
}
/**
* 新增字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:add')")
@Log(title = "字典数据", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictData dict) {
dict.setCreateBy(getUsername());
return toAjax(dictDataService.insertDictData(dict));
}
/**
* 修改保存字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:edit')")
@Log(title = "字典数据", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictData dict) {
dict.setUpdateBy(getUsername());
return toAjax(dictDataService.updateDictData(dict));
}
/**
* 删除字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictCodes}")
public AjaxResult remove(@PathVariable Long[] dictCodes) {
dictDataService.deleteDictDataByIds(dictCodes);
return success();
}
}

View File

@@ -0,0 +1,122 @@
package com.jsowell.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysDictType;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.service.SysDictTypeService;
/**
* 数据字典信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController {
@Autowired
private SysDictTypeService dictTypeService;
@PreAuthorize("@ss.hasPermi('system:dict:list')")
@GetMapping("/list")
public TableDataInfo list(SysDictType dictType) {
startPage();
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
return getDataTable(list);
}
@Log(title = "字典类型", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:dict:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysDictType dictType) {
List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
ExcelUtil<SysDictType> util = new ExcelUtil<SysDictType>(SysDictType.class);
util.exportExcel(response, list, "字典类型");
}
/**
* 查询字典类型详细
*/
@PreAuthorize("@ss.hasPermi('system:dict:query')")
@GetMapping(value = "/{dictId}")
public AjaxResult getInfo(@PathVariable Long dictId) {
return AjaxResult.success(dictTypeService.selectDictTypeById(dictId));
}
/**
* 新增字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:add')")
@Log(title = "字典类型", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysDictType dict) {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setCreateBy(getUsername());
return toAjax(dictTypeService.insertDictType(dict));
}
/**
* 修改字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:edit')")
@Log(title = "字典类型", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysDictType dict) {
if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
return AjaxResult.error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在");
}
dict.setUpdateBy(getUsername());
return toAjax(dictTypeService.updateDictType(dict));
}
/**
* 删除字典类型
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.DELETE)
@DeleteMapping("/{dictIds}")
public AjaxResult remove(@PathVariable Long[] dictIds) {
dictTypeService.deleteDictTypeByIds(dictIds);
return success();
}
/**
* 刷新字典缓存
*/
@PreAuthorize("@ss.hasPermi('system:dict:remove')")
@Log(title = "字典类型", businessType = BusinessType.CLEAN)
@DeleteMapping("/refreshCache")
public AjaxResult refreshCache() {
dictTypeService.resetDictCache();
return AjaxResult.success();
}
/**
* 获取字典选择框列表
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
return AjaxResult.success(dictTypes);
}
}

View File

@@ -0,0 +1,29 @@
package com.jsowell.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.util.StringUtils;
/**
* 首页
*
* @author jsowell
*/
@RestController
public class SysIndexController {
/**
* 系统基础配置
*/
@Autowired
private JsowellConfig jsowellConfig;
/**
* 访问首页,提示语
*/
@RequestMapping("/")
public String index() {
return StringUtils.format("欢迎使用{}后台管理框架当前版本v{},请通过前端地址访问。", jsowellConfig.getName(), jsowellConfig.getVersion());
}
}

View File

@@ -0,0 +1,90 @@
package com.jsowell.web.controller.system;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysMenu;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.domain.model.LoginBody;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.framework.web.service.SysLoginService;
import com.jsowell.framework.web.service.SysPermissionService;
import com.jsowell.system.service.SysMenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Set;
/**
* 登录验证
*
* @author jsowell
*/
@RestController
public class SysLoginController {
Logger logs = LoggerFactory.getLogger(this.getClass());
@Autowired
private SysLoginService loginService;
@Autowired
private SysMenuService menuService;
@Autowired
private SysPermissionService permissionService;
/**
* 登录方法
*
* @param loginBody 登录信息
* @return 结果
*/
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody) {
logs.info("登录param{}", JSONObject.toJSONString(loginBody));
AjaxResult ajax = AjaxResult.success();
// 生成令牌
String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
loginBody.getUuid());
ajax.put(Constants.TOKEN, token);
logs.info("登录 result:{}", ajax.toString());
return ajax;
}
/**
* 获取用户信息
*
* @return 用户信息
*/
@GetMapping("getInfo")
public AjaxResult getInfo() {
SysUser user = SecurityUtils.getLoginUser().getUser();
// 角色集合
Set<String> roles = permissionService.getRolePermission(user);
// 权限集合
Set<String> permissions = permissionService.getMenuPermission(user);
AjaxResult ajax = AjaxResult.success();
ajax.put("user" , user);
ajax.put("roles" , roles);
ajax.put("permissions" , permissions);
return ajax;
}
/**
* 获取路由信息
*
* @return 路由信息
*/
@GetMapping("getRouters")
public AjaxResult getRouters() {
Long userId = SecurityUtils.getUserId();
List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
logs.info("获取路由信息userId:{}, menus:{}, 菜单数量:{}", userId, menus, menus.size());
return AjaxResult.success(menuService.buildMenus(menus));
}
}

View File

@@ -0,0 +1,125 @@
package com.jsowell.web.controller.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysMenu;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.system.service.SysMenuService;
/**
* 菜单信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/menu")
public class SysMenuController extends BaseController {
@Autowired
private SysMenuService menuService;
/**
* 获取菜单列表
*/
@PreAuthorize("@ss.hasPermi('system:menu:list')")
@GetMapping("/list")
public AjaxResult list(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return AjaxResult.success(menus);
}
/**
* 根据菜单编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:menu:query')")
@GetMapping(value = "/{menuId}")
public AjaxResult getInfo(@PathVariable Long menuId) {
return AjaxResult.success(menuService.selectMenuById(menuId));
}
/**
* 获取菜单下拉树列表
*/
@GetMapping("/treeselect")
public AjaxResult treeselect(SysMenu menu) {
List<SysMenu> menus = menuService.selectMenuList(menu, getUserId());
return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
}
/**
* 加载对应角色菜单列表树
*/
@GetMapping(value = "/roleMenuTreeselect/{roleId}")
public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
List<SysMenu> menus = menuService.selectMenuList(getUserId());
AjaxResult ajax = AjaxResult.success();
ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
ajax.put("menus", menuService.buildMenuTreeSelect(menus));
return ajax;
}
/**
* 新增菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:add')")
@Log(title = "菜单管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysMenu menu) {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.isHttp(menu.getPath())) {
return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
}
menu.setCreateBy(getUsername());
return toAjax(menuService.insertMenu(menu));
}
/**
* 修改菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:edit')")
@Log(title = "菜单管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysMenu menu) {
if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在");
} else if (UserConstants.YES_FRAME.equals(menu.getIsFrame()) && !StringUtils.isHttp(menu.getPath())) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败地址必须以http(s)://开头");
} else if (menu.getMenuId().equals(menu.getParentId())) {
return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败,上级菜单不能选择自己");
}
menu.setUpdateBy(getUsername());
return toAjax(menuService.updateMenu(menu));
}
/**
* 删除菜单
*/
@PreAuthorize("@ss.hasPermi('system:menu:remove')")
@Log(title = "菜单管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{menuId}")
public AjaxResult remove(@PathVariable("menuId") Long menuId) {
if (menuService.hasChildByMenuId(menuId)) {
return AjaxResult.error("存在子菜单,不允许删除");
}
if (menuService.checkMenuExistRole(menuId)) {
return AjaxResult.error("菜单已分配,不允许删除");
}
return toAjax(menuService.deleteMenuById(menuId));
}
}

View File

@@ -0,0 +1,86 @@
package com.jsowell.web.controller.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.system.domain.SysNotice;
import com.jsowell.system.service.SysNoticeService;
/**
* 公告 信息操作处理
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController {
@Autowired
private SysNoticeService noticeService;
/**
* 获取通知公告列表
*/
@PreAuthorize("@ss.hasPermi('system:notice:list')")
@GetMapping("/list")
public TableDataInfo list(SysNotice notice) {
startPage();
List<SysNotice> list = noticeService.selectNoticeList(notice);
return getDataTable(list);
}
/**
* 根据通知公告编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:notice:query')")
@GetMapping(value = "/{noticeId}")
public AjaxResult getInfo(@PathVariable Long noticeId) {
return AjaxResult.success(noticeService.selectNoticeById(noticeId));
}
/**
* 新增通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:add')")
@Log(title = "通知公告", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysNotice notice) {
notice.setCreateBy(getUsername());
return toAjax(noticeService.insertNotice(notice));
}
/**
* 修改通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:edit')")
@Log(title = "通知公告", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysNotice notice) {
notice.setUpdateBy(getUsername());
return toAjax(noticeService.updateNotice(notice));
}
/**
* 删除通知公告
*/
@PreAuthorize("@ss.hasPermi('system:notice:remove')")
@Log(title = "通知公告", businessType = BusinessType.DELETE)
@DeleteMapping("/{noticeIds}")
public AjaxResult remove(@PathVariable Long[] noticeIds) {
return toAjax(noticeService.deleteNoticeByIds(noticeIds));
}
}

View File

@@ -0,0 +1,117 @@
package com.jsowell.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.domain.SysPost;
import com.jsowell.system.service.SysPostService;
/**
* 岗位信息操作处理
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/post")
public class SysPostController extends BaseController {
@Autowired
private SysPostService postService;
/**
* 获取岗位列表
*/
@PreAuthorize("@ss.hasPermi('system:post:list')")
@GetMapping("/list")
public TableDataInfo list(SysPost post) {
startPage();
List<SysPost> list = postService.selectPostList(post);
return getDataTable(list);
}
@Log(title = "岗位管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:post:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysPost post) {
List<SysPost> list = postService.selectPostList(post);
ExcelUtil<SysPost> util = new ExcelUtil<SysPost>(SysPost.class);
util.exportExcel(response, list, "岗位数据");
}
/**
* 根据岗位编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:post:query')")
@GetMapping(value = "/{postId}")
public AjaxResult getInfo(@PathVariable Long postId) {
return AjaxResult.success(postService.selectPostById(postId));
}
/**
* 新增岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:add')")
@Log(title = "岗位管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysPost post) {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setCreateBy(getUsername());
return toAjax(postService.insertPost(post));
}
/**
* 修改岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:edit')")
@Log(title = "岗位管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysPost post) {
if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) {
return AjaxResult.error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在");
}
post.setUpdateBy(getUsername());
return toAjax(postService.updatePost(post));
}
/**
* 删除岗位
*/
@PreAuthorize("@ss.hasPermi('system:post:remove')")
@Log(title = "岗位管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{postIds}")
public AjaxResult remove(@PathVariable Long[] postIds) {
return toAjax(postService.deletePostByIds(postIds));
}
/**
* 获取岗位选择框列表
*/
@GetMapping("/optionselect")
public AjaxResult optionselect() {
List<SysPost> posts = postService.selectPostAll();
return AjaxResult.success(posts);
}
}

View File

@@ -0,0 +1,131 @@
package com.jsowell.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.config.JsowellConfig;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.domain.model.LoginUser;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.file.FileUploadUtils;
import com.jsowell.common.util.file.MimeTypeUtils;
import com.jsowell.framework.web.service.TokenService;
import com.jsowell.system.service.SysUserService;
/**
* 个人信息 业务处理
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {
@Autowired
private SysUserService userService;
@Autowired
private TokenService tokenService;
/**
* 个人信息
*/
@GetMapping
public AjaxResult profile() {
LoginUser loginUser = getLoginUser();
SysUser user = loginUser.getUser();
AjaxResult ajax = AjaxResult.success(user);
ajax.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
ajax.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
return ajax;
}
/**
* 修改用户
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult updateProfile(@RequestBody SysUser user) {
LoginUser loginUser = getLoginUser();
SysUser sysUser = loginUser.getUser();
user.setUserName(sysUser.getUserName());
if (StringUtils.isNotEmpty(user.getPhone())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
}
if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUserId(sysUser.getUserId());
user.setPassword(null);
user.setAvatar(null);
user.setDeptId(null);
if (userService.updateUserProfile(user) > 0) {
// 更新缓存用户信息
sysUser.setNickName(user.getNickName());
sysUser.setPhone(user.getPhone());
sysUser.setEmail(user.getEmail());
sysUser.setSex(user.getSex());
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改个人信息异常,请联系管理员");
}
/**
* 重置密码
*/
@Log(title = "个人信息", businessType = BusinessType.UPDATE)
@PutMapping("/updatePwd")
public AjaxResult updatePwd(String oldPassword, String newPassword) {
LoginUser loginUser = getLoginUser();
String userName = loginUser.getUsername();
String password = loginUser.getPassword();
if (!SecurityUtils.matchesPassword(oldPassword, password)) {
return AjaxResult.error("修改密码失败,旧密码错误");
}
if (SecurityUtils.matchesPassword(newPassword, password)) {
return AjaxResult.error("新密码不能与旧密码相同");
}
if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0) {
// 更新缓存用户密码
loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
tokenService.setLoginUser(loginUser);
return AjaxResult.success();
}
return AjaxResult.error("修改密码异常,请联系管理员");
}
/**
* 头像上传
*/
@Log(title = "用户头像", businessType = BusinessType.UPDATE)
@PostMapping("/avatar")
public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws Exception {
if (!file.isEmpty()) {
LoginUser loginUser = getLoginUser();
String avatar = FileUploadUtils.upload(JsowellConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
if (userService.updateUserAvatar(loginUser.getUsername(), avatar)) {
AjaxResult ajax = AjaxResult.success();
ajax.put("imgUrl", avatar);
// 更新缓存用户头像
loginUser.getUser().setAvatar(avatar);
tokenService.setLoginUser(loginUser);
return ajax;
}
}
return AjaxResult.error("上传图片异常,请联系管理员");
}
}

View File

@@ -0,0 +1,35 @@
package com.jsowell.web.controller.system;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.model.RegisterBody;
import com.jsowell.common.util.StringUtils;
import com.jsowell.framework.web.service.SysRegisterService;
import com.jsowell.system.service.SysConfigService;
/**
* 注册验证
*
* @author jsowell
*/
@RestController
public class SysRegisterController extends BaseController {
@Autowired
private SysRegisterService registerService;
@Autowired
private SysConfigService configService;
@PostMapping("/register")
public AjaxResult register(@RequestBody RegisterBody user) {
if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
return error("当前系统没有开启注册功能!");
}
String msg = registerService.register(user);
return StringUtils.isEmpty(msg) ? success() : error(msg);
}
}

View File

@@ -0,0 +1,223 @@
package com.jsowell.web.controller.system;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysRole;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.domain.model.LoginUser;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.framework.web.service.SysPermissionService;
import com.jsowell.framework.web.service.TokenService;
import com.jsowell.system.domain.SysUserRole;
import com.jsowell.system.service.SysRoleService;
import com.jsowell.system.service.SysUserService;
/**
* 角色信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
@Autowired
private SysRoleService roleService;
@Autowired
private TokenService tokenService;
@Autowired
private SysPermissionService permissionService;
@Autowired
private SysUserService userService;
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/list")
public TableDataInfo list(SysRole role) {
startPage();
List<SysRole> list = roleService.selectRoleList(role);
return getDataTable(list);
}
@Log(title = "角色管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:role:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysRole role) {
List<SysRole> list = roleService.selectRoleList(role);
ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
util.exportExcel(response, list, "角色数据");
}
/**
* 根据角色编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping(value = "/{roleId}")
public AjaxResult getInfo(@PathVariable Long roleId) {
roleService.checkRoleDataScope(roleId);
return AjaxResult.success(roleService.selectRoleById(roleId));
}
/**
* 新增角色
*/
@PreAuthorize("@ss.hasPermi('system:role:add')")
@Log(title = "角色管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysRole role) {
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setCreateBy(getUsername());
return toAjax(roleService.insertRole(role));
}
/**
* 修改保存角色
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在");
} else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在");
}
role.setUpdateBy(getUsername());
if (roleService.updateRole(role) > 0) {
// 更新缓存用户权限
LoginUser loginUser = getLoginUser();
if (StringUtils.isNotNull(loginUser.getUser()) && !loginUser.getUser().isAdmin()) {
loginUser.setPermissions(permissionService.getMenuPermission(loginUser.getUser()));
loginUser.setUser(userService.selectUserByUserName(loginUser.getUser().getUserName()));
tokenService.setLoginUser(loginUser);
}
return AjaxResult.success();
}
return AjaxResult.error("修改角色'" + role.getRoleName() + "'失败,请联系管理员");
}
/**
* 修改保存数据权限
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/dataScope")
public AjaxResult dataScope(@RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
return toAjax(roleService.authDataScope(role));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysRole role) {
roleService.checkRoleAllowed(role);
roleService.checkRoleDataScope(role.getRoleId());
role.setUpdateBy(getUsername());
return toAjax(roleService.updateRoleStatus(role));
}
/**
* 删除角色
*/
@PreAuthorize("@ss.hasPermi('system:role:remove')")
@Log(title = "角色管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{roleIds}")
public AjaxResult remove(@PathVariable Long[] roleIds) {
return toAjax(roleService.deleteRoleByIds(roleIds));
}
/**
* 获取角色选择框列表
*/
@PreAuthorize("@ss.hasPermi('system:role:query')")
@GetMapping("/optionselect")
public AjaxResult optionselect() {
return AjaxResult.success(roleService.selectRoleAll());
}
/**
* 查询已分配用户角色列表
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/allocatedList")
public TableDataInfo allocatedList(SysUser user) {
startPage();
List<SysUser> list = userService.selectAllocatedList(user);
return getDataTable(list);
}
/**
* 查询未分配用户角色列表
*/
@PreAuthorize("@ss.hasPermi('system:role:list')")
@GetMapping("/authUser/unallocatedList")
public TableDataInfo unallocatedList(SysUser user) {
startPage();
List<SysUser> list = userService.selectUnallocatedList(user);
return getDataTable(list);
}
/**
* 取消授权用户
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancel")
public AjaxResult cancelAuthUser(@RequestBody SysUserRole userRole) {
return toAjax(roleService.deleteAuthUser(userRole));
}
/**
* 批量取消授权用户
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/cancelAll")
public AjaxResult cancelAuthUserAll(Long roleId, Long[] userIds) {
return toAjax(roleService.deleteAuthUsers(roleId, userIds));
}
/**
* 批量选择用户授权
*/
@PreAuthorize("@ss.hasPermi('system:role:edit')")
@Log(title = "角色管理", businessType = BusinessType.GRANT)
@PutMapping("/authUser/selectAll")
public AjaxResult selectAuthUserAll(Long roleId, Long[] userIds) {
roleService.checkRoleDataScope(roleId);
return toAjax(roleService.insertAuthUsers(roleId, userIds));
}
}

View File

@@ -0,0 +1,212 @@
package com.jsowell.web.controller.system;
import com.jsowell.common.annotation.Log;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.entity.SysRole;
import com.jsowell.common.core.domain.entity.SysUser;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.poi.ExcelUtil;
import com.jsowell.system.service.SysPostService;
import com.jsowell.system.service.SysRoleService;
import com.jsowell.system.service.SysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;
/**
* 用户信息
*
* @author jsowell
*/
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
@Autowired
private SysUserService userService;
@Autowired
private SysRoleService roleService;
@Autowired
private SysPostService postService;
/**
* 获取用户列表
*/
@PreAuthorize("@ss.hasPermi('system:user:list')")
@GetMapping("/list")
public TableDataInfo list(SysUser user) {
startPage();
List<SysUser> list = userService.selectUserList(user);
return getDataTable(list);
}
@Log(title = "用户管理", businessType = BusinessType.EXPORT)
@PreAuthorize("@ss.hasPermi('system:user:export')")
@PostMapping("/export")
public void export(HttpServletResponse response, SysUser user) {
List<SysUser> list = userService.selectUserList(user);
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.exportExcel(response, list, "用户数据");
}
@Log(title = "用户管理", businessType = BusinessType.IMPORT)
@PreAuthorize("@ss.hasPermi('system:user:import')")
@PostMapping("/importData")
public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
List<SysUser> userList = util.importExcel(file.getInputStream());
String operName = getUsername();
String message = userService.importUser(userList, updateSupport, operName);
return AjaxResult.success(message);
}
@PostMapping("/importTemplate")
public void importTemplate(HttpServletResponse response) {
ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
util.importTemplateExcel(response, "用户数据");
}
/**
* 根据用户编号获取详细信息
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping(value = {"/", "/{userId}"})
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
userService.checkUserDataScope(userId);
AjaxResult ajax = AjaxResult.success();
List<SysRole> roles = roleService.selectRoleAll();
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
ajax.put("posts", postService.selectPostAll());
if (StringUtils.isNotNull(userId)) {
SysUser sysUser = userService.selectUserById(userId);
ajax.put(AjaxResult.DATA_TAG, sysUser);
ajax.put("postIds", postService.selectPostListByUserId(userId));
ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
}
return ajax;
}
/**
* 新增用户
*/
@PreAuthorize("@ss.hasPermi('system:user:add')")
@Log(title = "用户管理", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@Validated @RequestBody SysUser user) {
if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,登录账号已存在");
} else if (StringUtils.isNotEmpty(user.getPhone())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setCreateBy(getUsername());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
return toAjax(userService.insertUser(user));
}
/**
* 修改用户
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@Validated @RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
if (StringUtils.isNotEmpty(user.getPhone())
&& UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,手机号码已存在");
} else if (StringUtils.isNotEmpty(user.getEmail())
&& UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
return AjaxResult.error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在");
}
user.setUpdateBy(getUsername());
return toAjax(userService.updateUser(user));
}
/**
* 删除用户
*/
@PreAuthorize("@ss.hasPermi('system:user:remove')")
@Log(title = "用户管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{userIds}")
public AjaxResult remove(@PathVariable Long[] userIds) {
if (ArrayUtils.contains(userIds, getUserId())) {
return error("当前用户不能删除");
}
return toAjax(userService.deleteUserByIds(userIds));
}
/**
* 重置密码
*/
@PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/resetPwd")
public AjaxResult resetPwd(@RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
user.setUpdateBy(getUsername());
return toAjax(userService.resetPwd(user));
}
/**
* 状态修改
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.UPDATE)
@PutMapping("/changeStatus")
public AjaxResult changeStatus(@RequestBody SysUser user) {
userService.checkUserAllowed(user);
userService.checkUserDataScope(user.getUserId());
user.setUpdateBy(getUsername());
return toAjax(userService.updateUserStatus(user));
}
/**
* 根据用户编号获取授权角色
*/
@PreAuthorize("@ss.hasPermi('system:user:query')")
@GetMapping("/authRole/{userId}")
public AjaxResult authRole(@PathVariable("userId") Long userId) {
AjaxResult ajax = AjaxResult.success();
SysUser user = userService.selectUserById(userId);
List<SysRole> roles = roleService.selectRolesByUserId(userId);
ajax.put("user", user);
ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
return ajax;
}
/**
* 用户授权角色
*/
@PreAuthorize("@ss.hasPermi('system:user:edit')")
@Log(title = "用户管理", businessType = BusinessType.GRANT)
@PutMapping("/authRole")
public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
userService.checkUserDataScope(userId);
userService.insertUserAuth(userId, roleIds);
return success();
}
public static void main(String[] args) {
System.out.println(SecurityUtils.encryptPassword("admin123"));
}
}

View File

@@ -0,0 +1,23 @@
package com.jsowell.web.controller.tool;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jsowell.common.core.controller.BaseController;
/**
* swagger 接口
*
* @author jsowell
*/
@Controller
@RequestMapping("/tool/swagger")
public class SwaggerController extends BaseController {
@PreAuthorize("@ss.hasPermi('tool:swagger:view')")
@GetMapping()
public String index() {
return redirect("/swagger-ui.html");
}
}

View File

@@ -0,0 +1,147 @@
package com.jsowell.web.controller.tool;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.R;
import com.jsowell.common.util.StringUtils;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* swagger 用户测试方法
*
* @author jsowell
*/
@Api("用户信息管理123")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController {
private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
{
users.put(1, new UserEntity(1, "thinkgem" , "admin123" , "15888888888"));
users.put(2, new UserEntity(2, "jsowell-test" , "admin123" , "15666666666"));
}
@ApiOperation("获取用户列表")
@GetMapping("/list")
public R<List<UserEntity>> userList() {
List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
return R.ok(userList);
}
@ApiOperation("获取用户详细123")
@ApiImplicitParam(name = "userId" , value = "用户ID" , required = true, dataType = "int" , paramType = "path" , dataTypeClass = Integer.class)
@GetMapping("/{userId}")
public R<UserEntity> getUser(@PathVariable Integer userId) {
if (!users.isEmpty() && users.containsKey(userId)) {
return R.ok(users.get(userId));
} else {
return R.fail("用户不存在");
}
}
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId" , value = "用户id" , dataType = "Integer" , dataTypeClass = Integer.class),
@ApiImplicitParam(name = "username" , value = "用户名称" , dataType = "String" , dataTypeClass = String.class),
@ApiImplicitParam(name = "password" , value = "用户密码" , dataType = "String" , dataTypeClass = String.class),
@ApiImplicitParam(name = "mobile" , value = "用户手机" , dataType = "String" , dataTypeClass = String.class)
})
@PostMapping("/save")
public R<String> save(UserEntity user) {
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
return R.fail("用户ID不能为空");
}
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("更新用户")
@PutMapping("/update")
public R<String> update(@RequestBody UserEntity user) {
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId())) {
return R.fail("用户ID不能为空");
}
if (users.isEmpty() || !users.containsKey(user.getUserId())) {
return R.fail("用户不存在");
}
users.remove(user.getUserId());
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("删除用户信息")
@ApiImplicitParam(name = "userId" , value = "用户ID" , required = true, dataType = "int" , paramType = "path" , dataTypeClass = Integer.class)
@DeleteMapping("/{userId}")
public R<String> delete(@PathVariable Integer userId) {
if (!users.isEmpty() && users.containsKey(userId)) {
users.remove(userId);
return R.ok();
} else {
return R.fail("用户不存在");
}
}
}
@ApiModel(value = "UserEntity" , description = "用户实体")
class UserEntity {
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
public UserEntity() {
}
public UserEntity(Integer userId, String username, String password, String mobile) {
this.userId = userId;
this.username = username;
this.password = password;
this.mobile = mobile;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}

View File

@@ -0,0 +1,122 @@
package com.jsowell.web.core.config;
import com.jsowell.common.config.JsowellConfig;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;
/**
* Swagger2的接口配置
*
* @author jsowell
*/
@Configuration
public class SwaggerConfig {
/**
* 系统基础配置
*/
@Autowired
private JsowellConfig jsowellConfig;
/**
* 是否开启swagger
*/
@Value("${swagger.enabled}")
private boolean enabled;
/**
* 设置请求的统一前缀
*/
@Value("${swagger.pathMapping}")
private String pathMapping;
/**
* 创建API
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.OAS_30)
// 是否启用Swagger
.enable(enabled)
// 用来创建该API的基本信息展示在文档的页面中自定义展示的信息
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
// .apis(RequestHandlerSelectors.basePackage("com.jsowell.project.tool.swagger"))
// 扫描所有
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
/* 设置安全模式swagger可以设置访问token */
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping(pathMapping);
}
/**
* 安全模式这里指定token通过Authorization头请求头传递
*/
private List<SecurityScheme> securitySchemes() {
List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
apiKeyList.add(new ApiKey("Authorization" , "Authorization" , In.HEADER.toValue()));
return apiKeyList;
}
/**
* 安全上下文
*/
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.operationSelector(o -> o.requestMappingPattern().matches("/.*"))
.build());
return securityContexts;
}
/**
* 默认的安全上引用
*/
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global" , "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization" , authorizationScopes));
return securityReferences;
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("标题举视后台管理系统_接口文档")
// 描述
// .description("描述:用于管理集团旗下公司的人员信息,具体包括XXX,XXX模块...")
// 作者信息
.contact(new Contact(jsowellConfig.getName(), null, null))
// 版本
.version("版本号:" + jsowellConfig.getVersion())
.build();
}
}

View File

@@ -0,0 +1 @@
restart.include.json=/com.alibaba.fastjson.*.jar

View File

@@ -0,0 +1,132 @@
# 数据源配置
spring:
# redis 配置
redis:
# 地址
host: 192.168.2.2
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
# 数据源配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://192.168.2.2:3306/jsowell_dev?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
# 初始连接数
initialSize: 10
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: jsowell
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
# Swagger配置
swagger:
# 是否开启swagger
enabled: true
# 请求前缀
pathMapping: /dev-api
# 日志配置
logging:
level:
com.jsowell: debug
org.springframework: warn
# 二维码前缀
qrcodeurl:
prefix: https://api.jsowellcloud.com
########################微信支付参数#######################################
#微信商户号
wechat:
mchId: 1632405339
#商家API证书序列号
mchSerialNo: 7596EF543159D21D25F199F82B9045FB9A82D7E0
#商户在微信公众平台申请服务号对应的APPID
appId: wxbb3e0d474569481d
#回调报文解密V3密钥key
v3Key: bbac689f4654b209de4d6944808ec80b
#微信获取平台证书列表地址
certificates:
url: https://api.mch.weixin.qq.com/v3/certificates
#微信统一下单Navtive的API地址用于二维码支付
unifiedOrder:
url: https://api.mch.weixin.qq.com/v3/pay/transactions/native
#微信统一下单JSAPI的API地址用于微信小程序
jsurl: https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi
# 申请退款API
refund:
jsurl: https://api.mch.weixin.qq.com/v3/refund/domestic/refunds
#异步接收微信支付结果通知的回调地址
callback: https://api.jsowellcloud.com/uniapp/pay/wechatPayCallback
#异步接收微信退款结果通知的回调地址
refundCallback: https://api.jsowellcloud.com/uniapp/pay/wechatPayRefundCallback
#商户证书私钥路径
key:
path: D:/WechatCert/apiclient_key.pem
########################微信支付参数#######################################
# C:/Users/autum/Desktop/work/1632405339_20221125_cert/apiclient_key.pem
# E://key/1632405339_20221125_cert/apiclient_key.pem

View File

@@ -0,0 +1,130 @@
# 数据源配置
spring:
# redis 配置
redis:
# 地址
host: r-uf6k0uet7mihr5z78f.redis.rds.aliyuncs.com
# 端口默认为6379
port: 6379
# 数据库索引
database: 0
# 账号
username: jsowell
# 密码
password: js@160829
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.cj.jdbc.Driver
druid:
# 主库数据源
master:
url: jdbc:mysql://rm-uf6ra51u33dc3798l.mysql.rds.aliyuncs.com:3306/jsowell_prd?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: jsowell
password: js@160829
# 从库数据源
slave:
# 从数据源开关/默认关闭
enabled: false
url:
username:
password:
# 初始连接数
initialSize: 5
# 最小连接池数量
minIdle: 10
# 最大连接池数量
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
webStatFilter:
enabled: true
statViewServlet:
enabled: true
# 设置白名单,不填则允许所有访问
allow:
url-pattern: /druid/*
# 控制台管理用户名和密码
login-username: jsowell
login-password: 123456
filter:
stat:
enabled: true
# 慢SQL记录
log-slow-sql: true
slow-sql-millis: 1000
merge-sql: true
wall:
config:
multi-statement-allow: true
# Swagger配置
swagger:
# 是否开启swagger
enabled: false
# 请求前缀
pathMapping: /dev-api
# 日志配置
logging:
level:
com.jsowell: info
org.springframework: warn
# 二维码前缀
qrcodeurl:
prefix: https://api.jsowellcloud.com
########################微信支付参数#######################################
#微信商户号
wechat:
mchId: 1632405339
#商家API证书序列号
mchSerialNo: 7596EF543159D21D25F199F82B9045FB9A82D7E0
#商户在微信公众平台申请服务号对应的APPID
appId: wxbb3e0d474569481d
#回调报文解密V3密钥key
v3Key: bbac689f4654b209de4d6944808ec80b
#微信获取平台证书列表地址
certificates:
url: https://api.mch.weixin.qq.com/v3/certificates
#微信统一下单Navtive的API地址用于二维码支付
unifiedOrder:
url: https://api.mch.weixin.qq.com/v3/pay/transactions/native
#微信统一下单JSAPI的API地址用于微信小程序
jsurl: https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi
# 申请退款API
refund:
jsurl: https://api.mch.weixin.qq.com/v3/refund/domestic/refunds
#异步接收微信支付结果通知的回调地址
callback: https://api.jsowellcloud.com/uniapp/pay/wechatPayCallback
#异步接收微信退款结果通知的回调地址
refundCallback: https://api.jsowellcloud.com/uniapp/pay/wechatPayRefundCallback
#商户证书私钥路径
key:
path: /usr/local/1632405339_20221125_cert/apiclient_key.pem
########################微信支付参数#######################################

View File

@@ -0,0 +1,128 @@
# 项目相关配置
jsowell:
# 名称
name: jsowell-service
# 版本
version: 1.0.0
# 版权年份
copyrightYear: 2022
# 实例演示开关
demoEnabled: true
# 文件路径 示例( Windows配置D:/jsowell/uploadPathLinux配置 /home/jsowell/uploadPath
profile: D:/jsowell/uploadPath
# 获取ip地址开关
addressEnabled: false
# 验证码类型 math 数组计算 char 字符验证
captchaType: char
# 开发环境配置
server:
# 服务器的HTTP端口默认为8080
port: 8080
servlet:
# 应用的访问路径
context-path: /
tomcat:
# tomcat的URI编码
uri-encoding: UTF-8
# 连接数满后的排队数默认为100
accept-count: 1000
threads:
# tomcat最大线程数默认为200
max: 800
# Tomcat启动初始化的线程数默认值10
min-spare: 100
# token配置
token:
# 令牌自定义标识
header: Authorization
# 令牌密钥
secret: cdnflglzjoxjovuusklsqjtuup
# 令牌有效期默认300分钟
expireTime: 300
# 接口令牌有效期 一个月
serviceExpireTime: 43200
# 用户配置
user:
password:
# 密码最大错误次数
maxRetryCount: 5
# 密码锁定时间默认10分钟
lockTime: 10
# Spring配置
spring:
# 资源信息
messages:
# 国际化资源文件路径
basename: i18n/messages
profiles:
active: { profile }
# 文件上传
servlet:
multipart:
# 单个文件大小
max-file-size: 10MB
# 设置总上传的文件大小
max-request-size: 20MB
# 服务模块
devtools:
restart:
# 热部署开关
enabled: true
# MyBatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: com.jsowell.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
# PageHelper分页插件
pagehelper:
helperDialect: mysql
supportMethodsArguments: true
params: count=countSql
# 防止XSS攻击
xss:
# 过滤开关
enabled: true
# 排除链接(多个用逗号分隔)
excludes: /system/notice
# 匹配链接
urlPatterns: /system/*,/monitor/*,/tool/*
# 微信登录相关
weixin:
login:
# gateway: https://api.weixin.qq.com/sns/oauth2/access_token
gateway: https://api.weixin.qq.com/sns/jscode2session
appid: wxbb3e0d474569481d
appsecret: bbac689f4654b209de4d6944808ec80b
redirectUrl: http://www.kuangstudy.com/login/api/wx/callback
sendMsg:
startChargingTmpId: BGgZe98QHr0I1S1GrtGps5_rLX6n9cW1AsXhL4YkHHc
stopChargingTmpId: UyBPbADlZfsCj89rh_xvfZGlxTW5J5KURpZtt9CNFrY
#Sim卡信息
xunzhong:
apiId: 1126135385835987
apiSecret: 9dT9iz0bfYx6UljzKj3pJEodjTvjd1lF
sim:
getSimCardDetailURL: https://iot.commchina.net/api/customer/v1/sim_cards/get_sim_card_detail
renewURL: https://iot.commchina.net/api/customer/v1/sim_cards/renew
trafficPool:
poolListURL: https://iot.commchina.net/api/customer/v1/traffic_pools/pool_list
wulian:
appId: 23178072739
appSecret: 9cf4e28037ca5ea1a8ea8e63959d454b
getWay: https://api.wl1688.net/iotc/getway
name:
getSimInfo: api.v2.card.info
WuLianSimRenew: api.v2.order.renew

View File

@@ -0,0 +1,9 @@
_ _____ ______ ________ _ _
| |/ ____|/ __ \ \ / / ____| | | |
| | (___ | | | \ \ /\ / /| |__ | | | |
_ | |\___ \| | | |\ \/ \/ / | __| | | | |
| |__| |____) | |__| | \ /\ / | |____| |____| |____
\____/|_____/ \____/ \/ \/ |______|______|______|
Application Version: ${jsowell.version}
Spring Boot Version: ${spring-boot.version}

View File

@@ -0,0 +1,37 @@
#错误消息
not.null=* 必须填写
user.jcaptcha.error=验证码错误
user.jcaptcha.expire=验证码已失效
user.not.exists=用户不存在/密码错误
user.password.not.match=用户不存在/密码错误
user.password.retry.limit.count=密码输入错误{0}次
user.password.retry.limit.exceed=密码输入错误{0}次,帐户锁定{1}分钟
user.password.delete=对不起,您的账号已被删除
user.blocked=用户已封禁,请联系管理员
role.blocked=角色已封禁,请联系管理员
user.logout.success=退出成功
length.not.valid=长度必须在{min}到{max}个字符之间
user.username.not.valid=* 2到20个汉字、字母、数字或下划线组成且必须以非数字开头
user.password.not.valid=* 5-50个字符
user.email.not.valid=邮箱格式错误
user.mobile.phone.number.not.valid=手机号格式错误
user.login.success=登录成功
user.register.success=注册成功
user.notfound=请重新登录
user.forcelogout=管理员强制退出,请重新登录
user.unknown.error=未知错误,请重新登录
##文件上传消息
upload.exceed.maxSize=上传的文件大小超出限制的文件大小!<br/>允许的文件最大大小是:{0}MB
upload.filename.exceed.length=上传的文件名最长{0}个字符
##权限
no.permission=您没有数据的权限,请联系管理员添加权限 [{0}]
no.create.permission=您没有创建数据的权限,请联系管理员添加权限 [{0}]
no.update.permission=您没有修改数据的权限,请联系管理员添加权限 [{0}]
no.delete.permission=您没有删除数据的权限,请联系管理员添加权限 [{0}]
no.export.permission=您没有导出数据的权限,请联系管理员添加权限 [{0}]
no.view.permission=您没有查看数据的权限,请联系管理员添加权限 [{0}]

View File

@@ -0,0 +1,123 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 日志存放路径 -->
<property name="log.path" value="/opt/app/spring/logs" />
<!-- 日志输出格式 -->
<property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />
<!-- 日志最大的历史 90天 -->
<property name="maxHistory" value="90"/>
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统日志输出 -->
<appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-info.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史-->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- netty日志单独输出 -->
<appender name="netty9011" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/netty9011.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/netty9011.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史-->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>INFO</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 错误日志输出 -->
<appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-error.log</file>
<!-- 循环政策:基于时间创建日志文件 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 日志文件名格式 -->
<fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史-->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<!-- 过滤的级别 -->
<level>ERROR</level>
<!-- 匹配时的操作:接收(记录) -->
<onMatch>ACCEPT</onMatch>
<!-- 不匹配时的操作:拒绝(不记录) -->
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 用户访问日志输出 -->
<appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/sys-user.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 按天回滚 daily -->
<fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 日志最大的历史-->
<maxHistory>${maxHistory}</maxHistory>
</rollingPolicy>
<encoder>
<pattern>${log.pattern}</pattern>
</encoder>
</appender>
<!-- 系统模块日志级别控制 -->
<logger name="com.jsowell" level="info" />
<!-- Spring日志级别控制 -->
<logger name="org.springframework" level="warn" />
<!-- netty日志 additivity="false"netty日志不会输出到控制台 -->
<logger name="com.jsowell.netty" level="info" additivity="true">
<appender-ref ref="netty9011" />
</logger>
<root level="info">
<appender-ref ref="console" />
</root>
<!--系统操作日志-->
<root level="info">
<appender-ref ref="file_info" />
<appender-ref ref="file_error" />
</root>
<!--系统用户操作日志-->
<logger name="sys-user" level="info">
<appender-ref ref="sys-user"/>
</logger>
</configuration>

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
</configuration>

View File

@@ -0,0 +1,688 @@
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.ImmutableMap;
import com.jsowell.JsowellApplication;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.core.domain.ykc.LoginRequestData;
import com.jsowell.common.core.domain.ykc.TransactionRecordsData;
import com.jsowell.common.core.redis.RedisCache;
import com.jsowell.common.enums.ykc.OrderStatusEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.*;
import com.jsowell.common.util.id.SnUtils;
import com.jsowell.common.util.id.SnowflakeIdWorker;
import com.jsowell.common.util.ip.AddressUtils;
import com.jsowell.netty.command.ykc.IssueQRCodeCommand;
import com.jsowell.netty.command.ykc.ProofreadTimeCommand;
import com.jsowell.netty.handler.HeartbeatRequestHandler;
import com.jsowell.netty.service.yunkuaichong.YKCBusinessService;
import com.jsowell.netty.service.yunkuaichong.YKCPushCommandService;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.PileBillingDetail;
import com.jsowell.pile.domain.PileBillingTemplate;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.domain.WxpayCallbackRecord;
import com.jsowell.pile.dto.BasicPileDTO;
import com.jsowell.pile.dto.BatchCreatePileDTO;
import com.jsowell.pile.dto.ImportBillingTemplateDTO;
import com.jsowell.pile.dto.QueryOrderDTO;
import com.jsowell.pile.dto.QueryPileDTO;
import com.jsowell.pile.dto.QueryStationDTO;
import com.jsowell.pile.dto.WeixinPayDTO;
import com.jsowell.pile.mapper.MemberBasicInfoMapper;
import com.jsowell.pile.mapper.PileBillingTemplateMapper;
import com.jsowell.pile.service.IOrderBasicInfoService;
import com.jsowell.pile.service.IPileBasicInfoService;
import com.jsowell.pile.service.IPileBillingTemplateService;
import com.jsowell.pile.service.IPileMsgRecordService;
import com.jsowell.pile.service.IPileStationInfoService;
import com.jsowell.pile.service.SimCardService;
import com.jsowell.pile.service.WechatPayService;
import com.jsowell.pile.service.WxpayCallbackRecordService;
import com.jsowell.pile.vo.web.*;
import com.jsowell.service.MemberService;
import com.jsowell.service.OrderService;
import com.jsowell.service.PileRemoteService;
import com.jsowell.service.PileService;
import com.jsowell.wxpay.common.WeChatPayParameter;
import com.jsowell.wxpay.dto.AppletTemplateMessageSendDTO;
import com.jsowell.wxpay.dto.WeChatRefundDTO;
import com.jsowell.wxpay.response.WechatPayRefundRequest;
import com.jsowell.wxpay.service.WxAppletRemoteService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.StopWatch;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ActiveProfiles("dev")
@SpringBootTest(classes = JsowellApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class SpringBootTestController {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
@Autowired
private SnUtils snUtils;
@Autowired
private PileService pileService;
@Autowired
private YKCPushCommandService ykcPushCommandService;
@Autowired
private IPileMsgRecordService pileMsgRecordService;
@Autowired
private IPileStationInfoService pileStationInfoService;
@Autowired
private YKCPushCommandService ykcPushBusinessService;
@Autowired
private HeartbeatRequestHandler heartbeatRequestHandler;
@Autowired
private YKCBusinessService ykcBusinessService;
@Autowired
private PileBillingTemplateMapper pileBillingTemplateMapper;
@Autowired
private PileRemoteService pileRemoteService;
@Autowired
private MemberService memberService;
@Autowired
private OrderService orderService;
@Autowired
private IPileBillingTemplateService pileBillingTemplateService;
@Autowired
private MemberBasicInfoMapper memberBasicInfoMapper;
@Autowired
private SimCardService simCardService;
@Autowired
private IPileBasicInfoService pileBasicInfoService;
@Autowired
private WechatPayService wechatPayService;
@Autowired
private IOrderBasicInfoService orderBasicInfoService;
@Autowired
private WxpayCallbackRecordService wxpayCallbackRecordService;
@Autowired
private WxAppletRemoteService wxAppletRemoteService;
@Autowired
private RedisCache redisCache;
@Test
public void testCloseStartFailedOrder() {
String startTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(new Date(), -2));
String endTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date());
orderBasicInfoService.closeStartFailedOrder(startTime, endTime);
}
@Test
public void testRedisSaveRealTimeData() {
String pileSn = "88000000000001";
String connectorCode = "01";
String orderCode = "88000000000001012211161342359448";
String pileConnectorCode = pileSn + connectorCode;
String redisKey = CacheConstants.PILE_REAL_TIME_MONITOR_DATA + pileConnectorCode + "_" + orderCode;
// for (int i = 0; i < 10; i++) {
// try {
// Thread.sleep(10000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Date now = new Date();
// redisCache.hset(redisKey, DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:00", now), i + ":" + DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", now));
// }
orderBasicInfoService.getChargingRealTimeData(orderCode);
}
@Test
public void testuniformMessageSend() {
AppletTemplateMessageSendDTO appletTemplateMessageSendDTO = new AppletTemplateMessageSendDTO();
// String openId = wxAppletRemoteService.getOpenIdByCode("0537u2100jTXsP1Y0Y300j426t47u210");
// System.out.println("openId:" + openId);
appletTemplateMessageSendDTO.setTouser("o4REX5MprZfTaLnVNxfdOY-wnwGI"); // openid
String templateId = "UyBPbADlZfsCj89rh_xvfZGlxTW5J5KURpZtt9CNFrY";
appletTemplateMessageSendDTO.setTemplate_id(templateId);
// appletTemplateMessageSendDTO.setPage("跳转的页面");
Map<String, Object> map = new HashMap<>();
map.put("amount17", ImmutableMap.of("value", "¥100")); // 结束时间
map.put("time3", ImmutableMap.of("value", "2022-12-30")); // 结束时间
map.put("thing7", ImmutableMap.of("value", "thing7")); // 结束原因
// map.put("thing5", ImmutableMap.of("value", "thing5")); // 结束原因
// map.put("time2", ImmutableMap.of("value", "time2")); // 结束原因
appletTemplateMessageSendDTO.setData(map);
wxAppletRemoteService.uniformMessageSend(appletTemplateMessageSendDTO);
}
@Test
public void testWeChatRefund() {
WeChatRefundDTO dto = new WeChatRefundDTO();
dto.setRefundType("2");
dto.setMemberId("82100864");
dto.setRefundAmount(new BigDecimal("1.23"));
orderBasicInfoService.weChatRefund(dto);
}
@Test
public void testSelectBalanceRechargeRecord() {
List<WxpayCallbackRecord> list = wxpayCallbackRecordService.queryBalanceRechargeRecordOfTheLatestYear("82100864");
System.out.println(list);
}
@Test
public void testSelectOrderBasicInfoList() {
QueryOrderDTO orderBasicInfo = new QueryOrderDTO();
orderBasicInfo.setPileSn("88000000000001");
orderBasicInfo.setOrderStatus(OrderStatusEnum.IN_THE_CHARGING.getValue());
List<OrderListVO> orderListVOS = orderBasicInfoService.selectOrderBasicInfoList(orderBasicInfo);
System.out.println(orderListVOS);
for (OrderListVO orderListVO : orderListVOS) {
if (StringUtils.equals(orderListVO.getOrderStatus(), OrderStatusEnum.IN_THE_CHARGING.getValue())) {
// 修改数据库订单状态
OrderBasicInfo info = OrderBasicInfo.builder()
.id(Long.parseLong(orderListVO.getId()))
.orderStatus(OrderStatusEnum.ABNORMAL.getValue())
.build();
orderBasicInfoService.updateOrderBasicInfo(info);
}
}
}
@Test
public void testWechatRefund() throws JsonProcessingException {
WechatPayRefundRequest request = new WechatPayRefundRequest();
request.setTransaction_id("4200001656202212302746036536"); // 微信支付单号
request.setOut_trade_no("768677222373363712"); // 商户订单号
// 生成退款单号
request.setOut_refund_no(SnowflakeIdWorker.getSnowflakeId()); // 商户退款单号
request.setNotify_url(WeChatPayParameter.refundNotifyUrl); // 回调接口
WechatPayRefundRequest.Amount amount = new WechatPayRefundRequest.Amount();
amount.setRefund(10 * 100); // 退款金额
amount.setTotal(10 * 100); // 原订单金额
request.setAmount(amount);
request.setReason("结算退款");
request.setFunds_account("AVAILABLE");
wechatPayService.ApplyForWechatPayRefundV3(request);
// 退款方法
}
@Test
public void testUpdatePileSimInfo() {
String pileSn = "88000000000001";
String iccid = "898604940121C1385725";
pileBasicInfoService.updatePileSimInfo(pileSn, iccid);
}
@Test
public void testPay() {
String code = "081zIoGa11GamE0iVVIa1aaJ4G0zIoGE";
String openId = memberService.getOpenIdByCode(code);
Map<String, Object> pay = null;
try {
WeixinPayDTO dto = new WeixinPayDTO();
dto.setOpenId(openId);
dto.setAmount("0.01");
pay = orderService.weixinPayV3(dto);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(JSONObject.toJSONString(pay));
}
@Test
public void testMemberRegisterAndLogin() {
// String phone = "18512341234";
// String merchantId = "18512341234";
// String token = memberService.memberRegisterAndLogin(phone, merchantId);
// System.out.println(token);
// String memberId = JWTUtils.getMemberId(token);
// System.out.println(memberId);
}
@Test
public void testMemberBasicInfoMapper() {
// String memberId = "21772870";
// BigDecimal principalBalance = new BigDecimal("-10");
// BigDecimal giftBalance = new BigDecimal("-110");
// Integer version = 2;
// int i = memberBasicInfoMapper.updateMemberBalance(memberId, principalBalance, giftBalance, version);
// if (i == 1) {
// System.out.println("更新余额成功");
// } else {
// System.out.println("更新余额失败");
// }
}
@Test
public void testGenerateBillingTemplateMsgBody() {
String pileSn = "88000000000001";
// 根据桩号查询计费模板
BillingTemplateVO billingTemplateVO = pileBillingTemplateService.selectBillingTemplateDetailByPileSn(pileSn);
byte[] messageBody = pileBillingTemplateService.generateBillingTemplateMsgBody(pileSn, billingTemplateVO);
System.out.println(BytesUtil.binary(messageBody, 16));
}
@Test
public void testAnalysisPileParameter() {
BasicPileDTO dto = new BasicPileDTO();
// 3个都不传的情况
try {
System.out.println("3个都不传的情况");
dto.setPileSn("");
dto.setConnectorCode("");
dto.setPileConnectorCode("");
orderService.analysisPileParameter(dto);
System.out.println("数据正确");
} catch (BusinessException e) {
System.out.println(e.getMessage());
}
System.out.println();
// 只传sn的情况
try {
System.out.println("只传sn的情况");
dto.setConnectorCode("");
dto.setPileConnectorCode("");
dto.setPileSn("88000000000001");
orderService.analysisPileParameter(dto);
System.out.println("数据正确");
} catch (BusinessException e) {
System.out.println(e.getMessage());
}
System.out.println();
//
try {
System.out.println("只穿枪口号的情况");
dto.setConnectorCode("01");
dto.setPileConnectorCode("");
dto.setPileSn("");
orderService.analysisPileParameter(dto);
System.out.println("数据正确");
} catch (BusinessException e) {
System.out.println(e.getMessage());
}
System.out.println();
// 只传充电桩枪口编号的情况
try {
System.out.println("只传充电桩枪口编号的情况");
dto.setPileConnectorCode("8800000000000101");
dto.setConnectorCode("");
dto.setPileSn("");
orderService.analysisPileParameter(dto);
System.out.println("数据正确");
} catch (BusinessException e) {
System.out.println(e.getMessage());
}
try {
System.out.println();
System.out.println("传充电桩枪sn+枪口号的情况");
dto.setPileConnectorCode("");
dto.setConnectorCode("01");
dto.setPileSn("88000000000001");
orderService.analysisPileParameter(dto);
System.out.println("数据正确");
} catch (BusinessException e) {
System.out.println(e.getMessage());
}
}
@Test
public void testImportBillingTemplate() {
ImportBillingTemplateDTO dto = new ImportBillingTemplateDTO();
dto.setBillingTemplateId("1");
// 查询公共计费模板是否存在
PileBillingTemplate pileBillingTemplate = pileBillingTemplateMapper.selectPileBillingTemplateById(Long.valueOf(dto.getBillingTemplateId()));
if (pileBillingTemplate == null) {
}
List<PileBillingDetail> billingDetailList = pileBillingTemplate.getPileBillingDetailList();
}
@Test
public void testProcess() {
// 62 68
String msgString = "680da300000388000000000001010020d06840a40000130000000000000000000000000000000088000000000001010202000000000000000000000000000000000000000000000000000000000000000000001516";
byte[] msg = BytesUtil.str2Bcd(msgString);
boolean b = YKCUtils.checkMsg(msg);
// ykcBusinessService.process(msg, null);
}
@Test
public void testHeartbeat() {
// heartbeatRequestHandler.updateStatus("88000000000001", "01", "0");
// heartbeatRequestHandler.updateStatus("88000000000001", "02", "0");
}
@Test
public void testPush() {
byte[] msg = new byte[]{};
String pileSn = "88000000000001";
// ykcPushBusinessService.push(msg, pileSn, YKCFrameTypeCode.READ_REAL_TIME_MONITOR_DATA_CODE);
}
@Test
public void TestMapUtils() {
String address = "淀山湖镇黄浦江南路278号";
String areaCode = "320000,320500,320583";
Map<String, String> longitudeAndLatitude = AddressUtils.getLongitudeAndLatitude(areaCode, address);
System.out.println(longitudeAndLatitude);
}
@Test
public void testCreatePile() {
BatchCreatePileDTO dto = BatchCreatePileDTO.builder()
.merchantId("1")
.stationId("1")
.softwareProtocol("1")
// .connectorNum(1)
// .num(10)
// .productionDate(new Date())
.build();
pileService.batchCreatePile(dto);
}
@Test
public void testGetIncre() {
StopWatch stopWatch = new StopWatch();
// 生成100个
stopWatch.start("生成100个sn号");
List<String> list2 = snUtils.generateSN(1);
stopWatch.stop();
System.out.println(list2);
System.out.println(stopWatch.getLastTaskTimeMillis());
}
@Test
public void testDict() {
String dictValue = DictUtils.getDictValue("query_pile_info", "url");
String station_type = DictUtils.getDictLabel("station_type", "1");
System.out.println(station_type);
System.out.println("123");
}
@Test
public void testSelectByMerchantId() {
List<PileStationInfo> list = pileStationInfoService.selectStationListByMerchantId(Long.valueOf(Constants.ONE));
System.out.println(list);
}
@Test
public void testStr2Bcd() {
String logicCardNum = "00000000";
byte[] logicCardNumByteArr = BytesUtil.str2Bcd(logicCardNum);
System.out.println(Arrays.toString(logicCardNumByteArr));
}
@Test
public void testBigDecimalMultiply() {
BigDecimal a = new BigDecimal("216.5");
BigDecimal b = new BigDecimal("11.5");
BigDecimal result = a.multiply(b).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(result);
}
@Test
public void testRemoteUpdate() {
ArrayList<String> list = new ArrayList<>();
list.add("88000000000001");
pileRemoteService.updateFile(list);
}
@Test
public void testGetUserPhoneNum() {
String code = "0e5394cfa4eb41c6181ed257f2368a86dfe4ebdac0a4fac85df63657637e6cc3";
wxAppletRemoteService.getMobileNumberByCode(code);
}
@Test
public void testDistance() {
QueryStationDTO dto = new QueryStationDTO();
dto.setStationLat("123.2222");
dto.setStationLng("55.6232");
// pileStationInfoService.uniAppQueryStationInfos(dto);
}
/**
* 生成英文字母随机数 RandomStringUtils.randomAlphabetic(10);
* 生成数字随机数 RandomStringUtils.randomNumeric(10);
* 字母+数字结合 RandomStringUtils.randomAlphanumeric(10);
*/
@Test
public void Test() throws ParseException {
/*String s = RandomStringUtils.randomAlphanumeric(32);
System.out.println(s); // PuLe4Tyyg1jSFNPhF5d2Ts9ejRn6E8KQ
String str = "JS160829";
System.out.println(Md5Utils.hash(str).toUpperCase(Locale.ROOT));
*/
Date startTimeDate = sdf.parse("2022-11-26 10:44:11");
Date endTimeDate = sdf.parse("2022-11-27 12:45:11");
System.out.println(DateUtils.getDatePoor(endTimeDate, startTimeDate)); // 1天2小时1分钟
/*String stra = "sp_mchid=1632405339&sub_mchid=1632405339&out_trade_no=1217752501201407033233368318&sp_appid=wxbb3e0d474569481d&sub_appid=wxbb3e0d474569481d" +
"bbac689f4654b209de4d6944808ec80b";
System.out.println(Md5Utils.hash(stra).toUpperCase(Locale.ROOT));*/
}
@Test
public void testSimCard() throws ParseException {
ArrayList<String> list = Lists.newArrayList();
Collections.addAll(list, "898607B9102090253556", "898607B9102090253560");
// String s = list.toString().replaceAll("(?:\\[|null|\\]| +)", "");
// System.out.println(s);
// List<SimCardVO> simCardVOList = simCardService.selectSimCardInfoByIccId(list);
// System.out.println(simCardVOList.toString());
// simCardService.XunZhongSimRenewal(list, 12);
// System.out.println(s);
// SimCardVO simCardVO = simCardService.searchByLoop("898607B9102090253556");
//
// System.out.println(simCardVO.toString());
simCardService.WuLianSimRenew(list, 1);
}
@Test
public void testRefund() {
OrderBasicInfo orderInfo = orderBasicInfoService.getOrderInfoByOrderCode("88000000000001012212171045412218");
orderInfo.setReason("充电异常中止,急停开入");
TransactionRecordsData data = TransactionRecordsData.builder()
.orderCode("88000000000001012212171045412218")
.consumptionAmount(String.valueOf(0.00))
.stopReasonMsg(orderInfo.getReason())
.totalElectricity("0")
.sharpUsedElectricity("0")
.peakUsedElectricity("0")
.flatUsedElectricity("0")
.valleyUsedElectricity("0")
.build();
orderBasicInfoService.settleOrder(data, orderInfo);
}
@Test
public void testLoginHandler() {
String msg = "8800000000001001010f63362d333000000000898604b319227036282200";
byte[] msgBody = BytesUtil.str2Bcd(msg);
int startIndex = 0;
int length = 7;
// 桩编码
byte[] pileSnByte = BytesUtil.copyBytes(msgBody, startIndex, length);
String pileSn = BytesUtil.binary(pileSnByte, 16);
// log.info("桩号:{}", pileSn);
// 桩类型 0 表示直流桩, 1 表示交流桩
startIndex += length;
length = 1;
byte[] pileTypeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String pileType = BytesUtil.bcd2Str(pileTypeByteArr);
// 充电枪数量
startIndex += length;
byte[] connectorNumByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String connectorNum = BytesUtil.bcd2Str(connectorNumByteArr);
// 通信协议版本 版本号乘 10v1.0 表示 0x0A
startIndex += length;
byte[] communicationVersionByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
// int i = Integer.parseInt(BytesUtil.bcd2Str(communicationVersionByteArr)); // 0F --> 15
BigDecimal bigDecimal = new BigDecimal(BytesUtil.bcd2Str(communicationVersionByteArr));
BigDecimal communicationVersionTemp = bigDecimal.divide(new BigDecimal(10));
String communicationVersion = "v" + communicationVersionTemp;
// 程序版本
startIndex += length;
length = 8;
byte[] programVersionByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String programVersion = BytesUtil.bcd2Str(programVersionByteArr);
// 网络连接类型 0x00 SIM 卡 0x01 LAN 0x02 WAN 0x03 其他
startIndex += length;
length = 1;
byte[] internetConnectionTypeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String internetConnection = BytesUtil.bcd2Str(internetConnectionTypeByteArr);
// sim卡
startIndex += length;
length = 10;
byte[] simCardNumByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String iccid = BytesUtil.bin2HexStr(simCardNumByteArr);
// 运营商 0x00 移动 0x02 电信 0x03 联通 0x04 其他
startIndex += length;
length = 1;
byte[] businessTypeByteArr = BytesUtil.copyBytes(msgBody, startIndex, length);
String business = BytesUtil.bcd2Str(businessTypeByteArr);
LoginRequestData loginRequestData = LoginRequestData.builder()
.pileSn(pileSn)
.pileType(pileType)
.connectorNum(connectorNum)
.communicationVersion(communicationVersion)
.programVersion(programVersion)
.internetConnection(internetConnection)
.iccid(iccid)
.business(business)
.build();
// 结果(默认 0x01:登录失败)
byte[] flag = Constants.oneByteArray;
// 通过桩编码SN查询数据库如果有数据则登录成功否则登录失败
QueryPileDTO dto = new QueryPileDTO();
dto.setPileSn(pileSn);
List<PileDetailVO> list = pileBasicInfoService.queryPileInfos(dto);
if (CollectionUtils.isNotEmpty(list)) {
flag = Constants.zeroByteArray;
// 登录成功保存桩号和channel的关系
// PileChannelEntity.put(pileSn, channel);
// 更改桩和该桩下的枪口状态分别为 在线、空闲
// pileBasicInfoService.updatePileStatus(pileSn, PileStatusEnum.ON_LINE.getValue());
// pileConnectorInfoService.updateConnectorStatusByPileSn(pileSn, PileConnectorDataBaseStatusEnum.FREE.getValue());
// 对时
ProofreadTimeCommand command = ProofreadTimeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushProofreadTimeCommand(command);
// 公共方法修改状态
pileBasicInfoService.updateStatus(BytesUtil.bcd2Str(new byte[]{0x01}), pileSn, null, null, null);
// 下发二维码
IssueQRCodeCommand issueQRCodeCommand = IssueQRCodeCommand.builder().pileSn(pileSn).build();
ykcPushCommandService.pushIssueQRCodeCommand(issueQRCodeCommand);
}
// 充电桩使用的sim卡把信息存库
if (StringUtils.equals("00", internetConnection)) {
try {
pileBasicInfoService.updatePileSimInfo(pileSn, iccid);
} catch (Exception e) {
// log.error("更新充电桩sim卡信息失败", e);
System.out.println(e.getMessage());
}
}
// 保存报文
String jsonMsg = JSONObject.toJSONString(loginRequestData);
// pileMsgRecordService.save(pileSn, pileSn, type, jsonMsg, ykcDataProtocol.getHEXString());
// // 消息体
// byte[] messageBody = Bytes.concat(pileSnByte, flag);
// return getResult(ykcDataProtocol, messageBody);
}
@Test
public void testGetMemberToken(){
String memberId = JWTUtils.getMemberId("eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NzY1MTY5MzgsImV4cCI6MTY3OTEwODkzOH0.4MwhZIOpnCfQloR7zEm2hwPOh2yyI2qxbBbTcv_SnZ4");
System.out.println(memberId);
}
}

181
jsowell-common/pom.xml Normal file
View File

@@ -0,0 +1,181 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.jsowell</groupId>
<artifactId>jsowell-charger-web</artifactId>
<version>1.0.0</version>
</parent>
<artifactId>jsowell-common</artifactId>
<description>
common通用工具
</description>
<dependencies>
<!-- Spring框架基本的核心工具 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<!-- SpringWeb模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- spring security 安全认证 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- pagehelper 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!-- 自定义验证注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- JSON工具类 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
</dependency>
<!-- io常用工具类 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- 文件上传工具类 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
</dependency>
<!-- excel工具 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
</dependency>
<!-- yml解析器 -->
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
<!-- Token生成与解析-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
</dependency>
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
<!-- redis 缓存操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- pool 对象池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- 解析客户端操作系统、浏览器等 -->
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
</dependency>
<!-- servlet包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
</dependency>
<dependency>
<groupId>com.github.qcloudsms</groupId>
<artifactId>qcloudsms</artifactId>
</dependency>
<dependency>
<groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<testExcludes>
<testExclude>/src/test/**</testExclude>
</testExcludes>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,18 @@
package com.jsowell.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 匿名访问不鉴权注解
*
* @author jsowell
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Anonymous {
}

View File

@@ -0,0 +1,27 @@
package com.jsowell.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 数据权限过滤注解
*
* @author jsowell
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataScope {
/**
* 部门表的别名
*/
public String deptAlias() default "";
/**
* 用户表的别名
*/
public String userAlias() default "";
}

View File

@@ -0,0 +1,28 @@
package com.jsowell.common.annotation;
import com.jsowell.common.enums.DataSourceType;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义多数据源切换注解
* <p>
* 优先级:先方法,后类,如果方法覆盖了类上的数据源类型,以方法的为准,否则以类上的为准
*
* @author jsowell
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface DataSource {
/**
* 切换数据源名称
*/
public DataSourceType value() default DataSourceType.MASTER;
}

View File

@@ -0,0 +1,181 @@
package com.jsowell.common.annotation;
import com.jsowell.common.util.poi.ExcelHandlerAdapter;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.math.BigDecimal;
/**
* 自定义导出Excel数据注解
*
* @author jsowell
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Excel {
/**
* 导出时在excel中排序
*/
public int sort() default Integer.MAX_VALUE;
/**
* 导出到Excel中的名字.
*/
public String name() default "";
/**
* 日期格式, 如: yyyy-MM-dd
*/
public String dateFormat() default "";
/**
* 如果是字典类型请设置字典的type值 (如: sys_user_sex)
*/
public String dictType() default "";
/**
* 读取内容转表达式 (如: 0=男,1=女,2=未知)
*/
public String readConverterExp() default "";
/**
* 分隔符,读取字符串组内容
*/
public String separator() default ",";
/**
* BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化)
*/
public int scale() default -1;
/**
* BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN
*/
public int roundingMode() default BigDecimal.ROUND_HALF_EVEN;
/**
* 导出时在excel中每个列的高度 单位为字符
*/
public double height() default 14;
/**
* 导出时在excel中每个列的宽 单位为字符
*/
public double width() default 16;
/**
* 文字后缀,如% 90 变成90%
*/
public String suffix() default "";
/**
* 当值为空时,字段的默认值
*/
public String defaultValue() default "";
/**
* 提示信息
*/
public String prompt() default "";
/**
* 设置只能选择不能输入的列内容.
*/
public String[] combo() default {};
/**
* 是否需要纵向合并单元格,应对需求:含有list集合单元格)
*/
public boolean needMerge() default false;
/**
* 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写.
*/
public boolean isExport() default true;
/**
* 另一个类中的属性名称,支持多级获取,以小数点隔开
*/
public String targetAttr() default "";
/**
* 是否自动统计数据,在最后追加一行统计数据总和
*/
public boolean isStatistics() default false;
/**
* 导出类型0数字 1字符串 2图片
*/
public ColumnType cellType() default ColumnType.STRING;
/**
* 导出列头背景色
*/
public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT;
/**
* 导出列头字体颜色
*/
public IndexedColors headerColor() default IndexedColors.WHITE;
/**
* 导出单元格背景色
*/
public IndexedColors backgroundColor() default IndexedColors.WHITE;
/**
* 导出单元格字体颜色
*/
public IndexedColors color() default IndexedColors.BLACK;
/**
* 导出字段对齐方式
*/
public HorizontalAlignment align() default HorizontalAlignment.CENTER;
/**
* 自定义数据处理器
*/
public Class<?> handler() default ExcelHandlerAdapter.class;
/**
* 自定义数据处理器参数
*/
public String[] args() default {};
/**
* 字段类型0导出导入1仅导出2仅导入
*/
Type type() default Type.ALL;
public enum Type {
ALL(0), EXPORT(1), IMPORT(2);
private final int value;
Type(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
public enum ColumnType {
NUMERIC(0), STRING(1), IMAGE(2);
private final int value;
ColumnType(int value) {
this.value = value;
}
public int value() {
return this.value;
}
}
}

View File

@@ -0,0 +1,17 @@
package com.jsowell.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解集
*
* @author jsowell
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels {
public Excel[] value();
}

View File

@@ -0,0 +1,41 @@
package com.jsowell.common.annotation;
import com.jsowell.common.enums.BusinessType;
import com.jsowell.common.enums.OperatorType;
import java.lang.annotation.*;
/**
* 自定义操作日志记录注解
*
* @author jsowell
*/
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
/**
* 模块
*/
public String title() default "";
/**
* 功能
*/
public BusinessType businessType() default BusinessType.OTHER;
/**
* 操作人类别
*/
public OperatorType operatorType() default OperatorType.MANAGE;
/**
* 是否保存请求的参数
*/
public boolean isSaveRequestData() default true;
/**
* 是否保存响应的参数
*/
public boolean isSaveResponseData() default true;
}

View File

@@ -0,0 +1,40 @@
package com.jsowell.common.annotation;
import com.jsowell.common.constant.CacheConstants;
import com.jsowell.common.enums.LimitType;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 限流注解
*
* @author jsowell
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RateLimiter {
/**
* 限流key
*/
public String key() default CacheConstants.RATE_LIMIT_KEY;
/**
* 限流时间,单位秒
*/
public int time() default 60;
/**
* 限流次数
*/
public int count() default 100;
/**
* 限流类型
*/
public LimitType limitType() default LimitType.DEFAULT;
}

View File

@@ -0,0 +1,29 @@
package com.jsowell.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解防止表单重复提交
*
* @author jsowell
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit {
/**
* 间隔时间(ms),小于此时间视为重复提交
*/
public int interval() default 5000;
/**
* 提示消息
*/
public String message() default "不允许重复提交,请稍候再试";
}

View File

@@ -0,0 +1,132 @@
package com.jsowell.common.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 读取项目相关配置
*
* @author jsowell
*/
@Component
@ConfigurationProperties(prefix = "jsowell")
public class JsowellConfig {
/**
* 项目名称
*/
private String name;
/**
* 版本
*/
private String version;
/**
* 版权年份
*/
private String copyrightYear;
/**
* 实例演示开关
*/
private boolean demoEnabled;
/**
* 上传路径
*/
private static String profile;
/**
* 获取地址开关
*/
private static boolean addressEnabled;
/**
* 验证码类型
*/
private static String captchaType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getCopyrightYear() {
return copyrightYear;
}
public void setCopyrightYear(String copyrightYear) {
this.copyrightYear = copyrightYear;
}
public boolean isDemoEnabled() {
return demoEnabled;
}
public void setDemoEnabled(boolean demoEnabled) {
this.demoEnabled = demoEnabled;
}
public static String getProfile() {
return profile;
}
public void setProfile(String profile) {
JsowellConfig.profile = profile;
}
public static boolean isAddressEnabled() {
return addressEnabled;
}
public void setAddressEnabled(boolean addressEnabled) {
JsowellConfig.addressEnabled = addressEnabled;
}
public static String getCaptchaType() {
return captchaType;
}
public void setCaptchaType(String captchaType) {
JsowellConfig.captchaType = captchaType;
}
/**
* 获取导入上传路径
*/
public static String getImportPath() {
return getProfile() + "/import";
}
/**
* 获取头像上传路径
*/
public static String getAvatarPath() {
return getProfile() + "/avatar";
}
/**
* 获取下载路径
*/
public static String getDownloadPath() {
return getProfile() + "/download/";
}
/**
* 获取上传路径
*/
public static String getUploadPath() {
return getProfile() + "/upload";
}
}

View File

@@ -0,0 +1,102 @@
package com.jsowell.common.constant;
/**
* 缓存的key 常量
*
* @author jsowell
*/
public class CacheConstants {
/**
*
*/
public static final int cache_expire_time_1m = 60;
public static final int cache_expire_time_5m = 60 * 5;
public static final int cache_expire_time_10m = 60 * 10;
public static final int cache_expire_time_1h = 60 * 60;
public static final int cache_expire_time_12h = 60 * 60 * 12;
public static final int cache_expire_time_1d = 60 * 60 * 24;
public static final String PILE_PROGRAM_VERSION = "pile_program_version";
/**
* 通过订单号查询订单信息Key
*/
public static final String GET_ORDER_INFO_BY_ORDER_CODE = "get_order_info_by_order_code:";
/**
* 充电枪口实时监控数据
*/
public static final String PILE_REAL_TIME_MONITOR_DATA = "pile_real_time_monitor_data:";
/**
* 充电桩最后连接时间
*/
public static final String PILE_LAST_CONNECTION = "pile_last_connection:";
/**
* 查询枪口信息列表前缀
*/
public static final String SELECT_PILE_CONNECTOR_INFO_LIST = "select_pile_connector_info_list:";
/**
* 充电桩枪口状态前缀
*/
public static final String PILE_CONNECTOR_STATUS_KEY = "pile_connector_status:";
/**
* 充电桩sn生成 key
*/
public static final String PILE_SN_GENERATE_KEY = "pile_sn_generate_";
/**
* 充电桩详情key
*/
public static final String PILE_DETAIL_KEY = "pile_detail:";
/**
* 登录用户 redis key
*/
public static final String LOGIN_TOKEN_KEY = "login_tokens:";
/**
* 验证码 redis key
*/
public static final String CAPTCHA_CODE_KEY = "captcha_codes:";
/**
* 参数管理 cache key
*/
public static final String SYS_CONFIG_KEY = "sys_config:";
/**
* 字典管理 cache key
*/
public static final String SYS_DICT_KEY = "sys_dict:";
/**
* 防重提交 redis key
*/
public static final String REPEAT_SUBMIT_KEY = "repeat_submit:";
/**
* 限流 redis key
*/
public static final String RATE_LIMIT_KEY = "rate_limit:";
/**
* 登录账户密码错误次数 redis key
*/
public static final String PWD_ERR_CNT_KEY = "pwd_err_cnt:";
/**
* 验证码有效期时长 redis key
*/
public static final String SMS_VERIFICATION_CODE_KEY = "sms_verification_code:";
}

View File

@@ -0,0 +1,210 @@
package com.jsowell.common.constant;
import io.jsonwebtoken.Claims;
/**
* 通用常量信息
*
* @author jsowell
*/
public class Constants {
// 充电桩sn号长度
public static final int PILE_SN_LENGTH = 14;
// 充电桩枪口号长度
public static final int CONNECTOR_CODE_LENGTH = 2;
// 充电桩枪口编号长度
public static final int PILE_CONNECTOR_CODE_LENGTH = PILE_SN_LENGTH + CONNECTOR_CODE_LENGTH;
public static final String SOCKET_IP = "127.0.0.1";
public static final Integer SOCKET_PORT = 9011;
public static final String updateServerIP = "192.168.2.5";
public static final int port = 0x15;
public static final byte[] updateServerPort = new byte[]{port};
public static final String updateServerUserName = "ftpuser";
public static final String updateServerPassword = "ftp123456";
public static final String filePath = "/pile/test.bin";
public static final String partnerId = "1632405339"; // 商户号Id
// public static final String APP_ID = "wxbb3e0d474569481d"; // 举视充电网 wxbb3e0d474569481d
//
// public static final String APP_SECRET = "bbac689f4654b209de4d6944808ec80b"; // 举视充电网 bbac689f4654b209de4d6944808ec80b
public static final String ZERO = "0";
public static final String ONE = "1";
public static final String TWO = "2";
public static final String THREE = "3";
public static final int zero = 0;
public static final int one = 1;
public static final byte zeroByte = 0x00;
public static final byte[] zeroByteArray = new byte[]{zeroByte};
public static final byte oneByte = 0x01;
public static final byte[] oneByteArray = new byte[]{oneByte};
public static final byte twoByte = 0x02;
public static final byte[] twoByteArray = new byte[]{twoByte};
public static final String FAULT_CODE = "255";
public static final String DOUBLE_ZERO = "00";
public static final String ZERO_ONE = "01";
public static final String ZERO_THREE = "03";
/**
* 删除标识 0标识正常
*/
public static final String DEL_FLAG_NORMAL = "0";
/**
* 删除标识 1标识被删除
*/
public static final String DEL_FLAG_DELETE = "1";
/**
* UTF-8 字符集
*/
public static final String UTF8 = "UTF-8";
/**
* GBK 字符集
*/
public static final String GBK = "GBK";
/**
* http请求
*/
public static final String HTTP = "http://";
/**
* https请求
*/
public static final String HTTPS = "https://";
/**
* 通用成功标识
*/
public static final String SUCCESS = "0";
/**
* 通用失败标识
*/
public static final String FAIL = "1";
/**
* 登录成功
*/
public static final String LOGIN_SUCCESS = "Success";
/**
* 注销
*/
public static final String LOGOUT = "Logout";
/**
* 注册
*/
public static final String REGISTER = "Register";
/**
* 登录失败
*/
public static final String LOGIN_FAIL = "Error";
/**
* 登录验证码有效期
*/
public static final Integer VERIFICATION_CODE_EXPIRATION_TIME = 10;
/**
* 验证码有效期(分钟)
*/
public static final Integer CAPTCHA_EXPIRATION = 2;
/**
* 令牌
*/
public static final String TOKEN = "token";
/**
* 令牌前缀
*/
public static final String TOKEN_PREFIX = "Bearer";
/**
* 令牌前缀
*/
public static final String LOGIN_USER_KEY = "login_user_key";
/**
* 用户ID
*/
public static final String JWT_USERID = "userid";
/**
* 用户名称
*/
public static final String JWT_USERNAME = Claims.SUBJECT;
/**
* 用户头像
*/
public static final String JWT_AVATAR = "avatar";
/**
* 创建时间
*/
public static final String JWT_CREATED = "created";
/**
* 用户权限
*/
public static final String JWT_AUTHORITIES = "authorities";
/**
* 资源映射路径 前缀
*/
public static final String RESOURCE_PREFIX = "/profile";
/**
* RMI 远程方法调用
*/
public static final String LOOKUP_RMI = "rmi:";
/**
* LDAP 远程方法调用
*/
public static final String LOOKUP_LDAP = "ldap:";
/**
* LDAPS 远程方法调用
*/
public static final String LOOKUP_LDAPS = "ldaps:";
/**
* 定时任务白名单配置(仅允许访问的包名,如其他需要可以自行添加)
*/
public static final String[] JOB_WHITELIST_STR = {"com.jsowell"};
/**
* 定时任务违规的字符
*/
public static final String[] JOB_ERROR_STR = {"java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.jsowell.common.util.file"};
}

View File

@@ -0,0 +1,186 @@
package com.jsowell.common.constant;
/**
* 代码生成通用常量
*
* @author jsowell
*/
public class GenConstants {
/**
* 单表(增删改查)
*/
public static final String TPL_CRUD = "crud";
/**
* 树表(增删改查)
*/
public static final String TPL_TREE = "tree";
/**
* 主子表(增删改查)
*/
public static final String TPL_SUB = "sub";
/**
* 树编码字段
*/
public static final String TREE_CODE = "treeCode";
/**
* 树父编码字段
*/
public static final String TREE_PARENT_CODE = "treeParentCode";
/**
* 树名称字段
*/
public static final String TREE_NAME = "treeName";
/**
* 上级菜单ID字段
*/
public static final String PARENT_MENU_ID = "parentMenuId";
/**
* 上级菜单名称字段
*/
public static final String PARENT_MENU_NAME = "parentMenuName";
/**
* 数据库字符串类型
*/
public static final String[] COLUMNTYPE_STR = {"char", "varchar", "nvarchar", "varchar2"};
/**
* 数据库文本类型
*/
public static final String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"};
/**
* 数据库时间类型
*/
public static final String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"};
/**
* 数据库数字类型
*/
public static final String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer",
"bit", "bigint", "float", "double", "decimal"};
/**
* 页面不需要编辑字段
*/
public static final String[] COLUMNNAME_NOT_EDIT = {"id", "create_by", "create_time", "del_flag"};
/**
* 页面不需要显示的列表字段
*/
public static final String[] COLUMNNAME_NOT_LIST = {"id", "create_by", "create_time", "del_flag", "update_by",
"update_time"};
/**
* 页面不需要查询字段
*/
public static final String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark"};
/**
* Entity基类字段
*/
public static final String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime", "remark"};
/**
* Tree基类字段
*/
public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors", "children"};
/**
* 文本框
*/
public static final String HTML_INPUT = "input";
/**
* 文本域
*/
public static final String HTML_TEXTAREA = "textarea";
/**
* 下拉框
*/
public static final String HTML_SELECT = "select";
/**
* 单选框
*/
public static final String HTML_RADIO = "radio";
/**
* 复选框
*/
public static final String HTML_CHECKBOX = "checkbox";
/**
* 日期控件
*/
public static final String HTML_DATETIME = "datetime";
/**
* 图片上传控件
*/
public static final String HTML_IMAGE_UPLOAD = "imageUpload";
/**
* 文件上传控件
*/
public static final String HTML_FILE_UPLOAD = "fileUpload";
/**
* 富文本控件
*/
public static final String HTML_EDITOR = "editor";
/**
* 字符串类型
*/
public static final String TYPE_STRING = "String";
/**
* 整型
*/
public static final String TYPE_INTEGER = "Integer";
/**
* 长整型
*/
public static final String TYPE_LONG = "Long";
/**
* 浮点型
*/
public static final String TYPE_DOUBLE = "Double";
/**
* 高精度计算类型
*/
public static final String TYPE_BIGDECIMAL = "BigDecimal";
/**
* 时间类型
*/
public static final String TYPE_DATE = "Date";
/**
* 模糊查询
*/
public static final String QUERY_LIKE = "LIKE";
/**
* 相等查询
*/
public static final String QUERY_EQ = "EQ";
/**
* 需要
*/
public static final String REQUIRE = "1";
}

View File

@@ -0,0 +1,88 @@
package com.jsowell.common.constant;
/**
* 返回状态码
*
* @author jsowell
*/
public class HttpStatus {
/**
* 操作成功
*/
public static final int SUCCESS = 200;
/**
* 对象创建成功
*/
public static final int CREATED = 201;
/**
* 请求已经被接受
*/
public static final int ACCEPTED = 202;
/**
* 操作已经执行成功,但是没有返回数据
*/
public static final int NO_CONTENT = 204;
/**
* 资源已被移除
*/
public static final int MOVED_PERM = 301;
/**
* 重定向
*/
public static final int SEE_OTHER = 303;
/**
* 资源没有被修改
*/
public static final int NOT_MODIFIED = 304;
/**
* 参数列表错误(缺少,格式不匹配)
*/
public static final int BAD_REQUEST = 400;
/**
* 未授权
*/
public static final int UNAUTHORIZED = 401;
/**
* 访问受限,授权过期
*/
public static final int FORBIDDEN = 403;
/**
* 资源,服务未找到
*/
public static final int NOT_FOUND = 404;
/**
* 不允许的http方法
*/
public static final int BAD_METHOD = 405;
/**
* 资源冲突,或者资源被锁
*/
public static final int CONFLICT = 409;
/**
* 不支持的数据,媒体类型
*/
public static final int UNSUPPORTED_TYPE = 415;
/**
* 系统内部错误
*/
public static final int ERROR = 500;
/**
* 接口未实现
*/
public static final int NOT_IMPLEMENTED = 501;
}

View File

@@ -0,0 +1,56 @@
package com.jsowell.common.constant;
/**
* 任务调度通用常量
*
* @author jsowell
*/
public class ScheduleConstants {
public static final String TASK_CLASS_NAME = "TASK_CLASS_NAME";
/**
* 执行目标key
*/
public static final String TASK_PROPERTIES = "TASK_PROPERTIES";
/**
* 默认
*/
public static final String MISFIRE_DEFAULT = "0";
/**
* 立即触发执行
*/
public static final String MISFIRE_IGNORE_MISFIRES = "1";
/**
* 触发一次执行
*/
public static final String MISFIRE_FIRE_AND_PROCEED = "2";
/**
* 不触发立即执行
*/
public static final String MISFIRE_DO_NOTHING = "3";
public enum Status {
/**
* 正常
*/
NORMAL("0"),
/**
* 暂停
*/
PAUSE("1");
private String value;
private Status(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
}

View File

@@ -0,0 +1,111 @@
package com.jsowell.common.constant;
/**
* 用户常量信息
*
* @author jsowell
*/
public class UserConstants {
/**
* 平台内系统用户的唯一标志
*/
public static final String SYS_USER = "SYS_USER";
/**
* 正常状态
*/
public static final String NORMAL = "0";
/**
* 异常状态
*/
public static final String EXCEPTION = "1";
/**
* 用户封禁状态
*/
public static final String USER_DISABLE = "1";
/**
* 角色封禁状态
*/
public static final String ROLE_DISABLE = "1";
/**
* 部门正常状态
*/
public static final String DEPT_NORMAL = "0";
/**
* 部门停用状态
*/
public static final String DEPT_DISABLE = "1";
/**
* 字典正常状态
*/
public static final String DICT_NORMAL = "0";
/**
* 是否为系统默认(是)
*/
public static final String YES = "Y";
/**
* 是否菜单外链(是)
*/
public static final String YES_FRAME = "0";
/**
* 是否菜单外链(否)
*/
public static final String NO_FRAME = "1";
/**
* 菜单类型(目录)
*/
public static final String TYPE_DIR = "M";
/**
* 菜单类型(菜单)
*/
public static final String TYPE_MENU = "C";
/**
* 菜单类型(按钮)
*/
public static final String TYPE_BUTTON = "F";
/**
* Layout组件标识
*/
public final static String LAYOUT = "Layout";
/**
* ParentView组件标识
*/
public final static String PARENT_VIEW = "ParentView";
/**
* InnerLink组件标识
*/
public final static String INNER_LINK = "InnerLink";
/**
* 校验返回结果码
*/
public final static String UNIQUE = "0";
public final static String NOT_UNIQUE = "1";
/**
* 用户名长度限制
*/
public static final int USERNAME_MIN_LENGTH = 2;
public static final int USERNAME_MAX_LENGTH = 20;
/**
* 密码长度限制
*/
public static final int PASSWORD_MIN_LENGTH = 5;
public static final int PASSWORD_MAX_LENGTH = 20;
}

View File

@@ -0,0 +1,64 @@
package com.jsowell.common.constant;
/**
* 微信支付常量
* WeiXinConstants<BR>
* 创建人:小威 <BR>
* 时间2015年10月19日-下午7:14:15 <BR>
*
* @version 1.0.0
*/
public class WeiXinConstants {
public static final String URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";//统一下单url
public static final String MCH_URL = "https://api.mch.weixin.qq.com/secapi/pay/profitsharing";//统一分账url
public static final String MCH_URL_MULTIPRO = "https://api.mch.weixin.qq.com/secapi/pay/multiprofitsharing";//统一分账url(多次分账)
public static final String PROFIT_SHARING_QUERY = "https://api.mch.weixin.qq.com/pay/profitsharingquery"; //统一分账结果查询
public static final String MCH_URL_FINISH = "https://api.mch.weixin.qq.com/secapi/pay/profitsharingfinish";//统一分账url
public static final String MCH_STATUS_URL = "https://api.mch.weixin.qq.com/pay/profitsharingquery";//统一分账查询url
public static final String MCH_ADD_RELATION_URL = "https://api.mch.weixin.qq.com/pay/profitsharingaddreceiver";//分账关系绑定地址
public static final String REFUND = "https://api.mch.weixin.qq.com/secapi/pay/refund";//退款
public static final String RETURN_CODE = "return_code"; // SUCCESS/FAIL 此字段是通信标识,非交易标识
public static final String SUCCESS = "SUCCESS"; // SUCCESS/FAIL 此字段是通信标识,非交易标识
public static final int WIDTH = 200;//二维码宽度
public static final int HEIGHT = 200;//二维码高度
public static final String RESULT = "result_code";//返回结果
public static final String ORDER_PAID = "orderPaid";//已经支付
public static final String WEIXINPAY = "weixinPay";//可以支付
public static final String CODE_URL = "code_url";//微信支付url
public static final String ERROR_CODE = "err_code";//错误码
public static final String ATTACH = "attach";//商家数据包
public static final String BODY = "body";//商品名称
public static final String NOTIFY_URL = "notify_url";//异步回调地址
public static final String OUT_TRADE_NO = "out_trade_no";//商家订单号
public static final String TRANSACTION_ID = "transaction_id";//微信订单号
public static final String PRODUCT_ID = "product_id";//商品ID
public static final String SPBILL_CREATE_IP = "spbill_create_ip";//支付用户IP地址
public static final String TOTAL_FEE = "total_fee";//支付金额
}

View File

@@ -0,0 +1,187 @@
package com.jsowell.common.core.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jsowell.common.constant.HttpStatus;
import com.jsowell.common.core.domain.AjaxResult;
import com.jsowell.common.core.domain.model.LoginUser;
import com.jsowell.common.core.page.PageDomain;
import com.jsowell.common.core.page.TableDataInfo;
import com.jsowell.common.core.page.TableSupport;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.SecurityUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.common.util.sql.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;
import java.util.List;
/**
* web层通用数据处理
*
* @author jsowell
*/
public class BaseController {
protected final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 将前台传递过来的日期格式的字符串自动转化为Date类型
*/
@InitBinder
public void initBinder(WebDataBinder binder) {
// Date 类型转换
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
setValue(DateUtils.parseDate(text));
}
});
}
/**
* 设置请求分页数据
*/
protected void startPage() {
PageUtils.startPage();
}
/**
* 设置请求排序数据
*/
protected void startOrderBy() {
PageDomain pageDomain = TableSupport.buildPageRequest();
if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
PageHelper.orderBy(orderBy);
}
}
/**
* 清理分页的线程变量
*/
protected void clearPage() {
PageUtils.clearPage();
}
/**
* 响应请求分页数据
*/
@SuppressWarnings({"rawtypes", "unchecked"})
protected TableDataInfo getDataTable(List<?> list) {
TableDataInfo rspData = new TableDataInfo();
rspData.setCode(HttpStatus.SUCCESS);
rspData.setMsg("查询成功");
rspData.setRows(list);
rspData.setTotal(new PageInfo(list).getTotal());
return rspData;
}
/**
* 返回成功
*/
public AjaxResult success() {
return AjaxResult.success();
}
/**
* 返回失败消息
*/
public AjaxResult error() {
return AjaxResult.error();
}
/**
* 返回成功消息
*/
public AjaxResult success(String message) {
return AjaxResult.success(message);
}
/**
* 返回失败消息
*/
public AjaxResult error(String message) {
return AjaxResult.error(message);
}
/**
* 响应返回结果
*
* @param rows 影响行数
* @return 操作结果
*/
protected AjaxResult toAjax(int rows) {
return rows > 0 ? AjaxResult.success() : AjaxResult.error();
}
/**
* 响应返回结果
*
* @param result 结果
* @return 操作结果
*/
protected AjaxResult toAjax(boolean result) {
return result ? success() : error();
}
/**
* 页面跳转
*/
public String redirect(String url) {
return StringUtils.format("redirect:{}", url);
}
/**
* 获取用户缓存信息
*/
public LoginUser getLoginUser() {
return SecurityUtils.getLoginUser();
}
/**
* 获取登录用户id
*/
public Long getUserId() {
return getLoginUser().getUserId();
}
/**
* 获取登录部门id
*/
public Long getDeptId() {
return getLoginUser().getDeptId();
}
/**
* 获取登录用户名
*/
public String getUsername() {
return getLoginUser().getUsername();
}
public String getMemberIdByAuthorization(String authorization) {
if (StringUtils.isBlank(authorization)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
String memberId = JWTUtils.getMemberId(authorization);
if (StringUtils.isBlank(memberId)) {
throw new BusinessException(ReturnCodeEnum.CODE_TOKEN_ERROR);
}
// logger.info("authorization:{}, memberId:{}", authorization, memberId);
return memberId;
}
public String getMemberIdByAuthorization(HttpServletRequest request) {
return getMemberIdByAuthorization(request.getHeader("Authorization"));
}
}

View File

@@ -0,0 +1,155 @@
package com.jsowell.common.core.domain;
import com.jsowell.common.constant.HttpStatus;
import com.jsowell.common.util.StringUtils;
import java.util.HashMap;
/**
* 操作消息提醒
*
* @author jsowell
*/
public class AjaxResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
public static final String CODE_TAG = "code";
/**
* 返回内容
*/
public static final String MSG_TAG = "msg";
/**
* 数据对象
*/
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult() {
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data)) {
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success() {
return AjaxResult.success("操作成功");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data) {
return AjaxResult.success("操作成功", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg) {
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data) {
return new AjaxResult(HttpStatus.SUCCESS, msg, data);
}
/**
* 返回错误消息
*
* @return
*/
public static AjaxResult error() {
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(String msg) {
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult error(String msg, Object data) {
return new AjaxResult(HttpStatus.ERROR, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult error(int code, String msg) {
return new AjaxResult(code, msg, null);
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}
}

View File

@@ -0,0 +1,114 @@
package com.jsowell.common.core.domain;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Entity基类
*
* @author jsowell
*/
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 搜索值
*/
private String searchValue;
/**
* 创建者
*/
private String createBy;
/**
* 创建时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新者
*/
private String updateBy;
/**
* 更新时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**
* 备注
*/
private String remark;
/**
* 请求参数
*/
private Map<String, Object> params;
public String getSearchValue() {
return searchValue;
}
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getCreateBy() {
return createBy;
}
public void setCreateBy(String createBy) {
this.createBy = createBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getUpdateBy() {
return updateBy;
}
public void setUpdateBy(String updateBy) {
this.updateBy = updateBy;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public Map<String, Object> getParams() {
if (params == null) {
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}

View File

@@ -0,0 +1,94 @@
package com.jsowell.common.core.domain;
import com.jsowell.common.constant.HttpStatus;
import java.io.Serializable;
/**
* 响应信息主体
*
* @author jsowell
*/
public class R<T> implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 成功
*/
public static final int SUCCESS = HttpStatus.SUCCESS;
/**
* 失败
*/
public static final int FAIL = HttpStatus.ERROR;
private int code;
private String msg;
private T data;
public static <T> R<T> ok() {
return restResult(null, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data) {
return restResult(data, SUCCESS, "操作成功");
}
public static <T> R<T> ok(T data, String msg) {
return restResult(data, SUCCESS, msg);
}
public static <T> R<T> fail() {
return restResult(null, FAIL, "操作失败");
}
public static <T> R<T> fail(String msg) {
return restResult(null, FAIL, msg);
}
public static <T> R<T> fail(T data) {
return restResult(data, FAIL, "操作失败");
}
public static <T> R<T> fail(T data, String msg) {
return restResult(data, FAIL, msg);
}
public static <T> R<T> fail(int code, String msg) {
return restResult(null, code, msg);
}
private static <T> R<T> restResult(T data, int code, String msg) {
R<T> apiResult = new R<>();
apiResult.setCode(code);
apiResult.setData(data);
apiResult.setMsg(msg);
return apiResult;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

View File

@@ -0,0 +1,78 @@
package com.jsowell.common.core.domain;
import java.util.ArrayList;
import java.util.List;
/**
* Tree基类
*
* @author jsowell
*/
public class TreeEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 父菜单名称
*/
private String parentName;
/**
* 父菜单ID
*/
private Long parentId;
/**
* 显示顺序
*/
private Integer orderNum;
/**
* 祖级列表
*/
private String ancestors;
/**
* 子部门
*/
private List<?> children = new ArrayList<>();
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public String getAncestors() {
return ancestors;
}
public void setAncestors(String ancestors) {
this.ancestors = ancestors;
}
public List<?> getChildren() {
return children;
}
public void setChildren(List<?> children) {
this.children = children;
}
}

View File

@@ -0,0 +1,74 @@
package com.jsowell.common.core.domain;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.jsowell.common.core.domain.entity.SysDept;
import com.jsowell.common.core.domain.entity.SysMenu;
import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;
/**
* Treeselect树结构实体类
*
* @author jsowell
*/
public class TreeSelect implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 节点ID
*/
private Long id;
/**
* 节点名称
*/
private String label;
/**
* 子节点
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private List<TreeSelect> children;
public TreeSelect() {
}
public TreeSelect(SysDept dept) {
this.id = dept.getDeptId();
this.label = dept.getDeptName();
this.children = dept.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
public TreeSelect(SysMenu menu) {
this.id = menu.getMenuId();
this.label = menu.getMenuName();
this.children = menu.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<TreeSelect> getChildren() {
return children;
}
public void setChildren(List<TreeSelect> children) {
this.children = children;
}
}

View File

@@ -0,0 +1,203 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
/**
* 部门表 sys_dept
*
* @author jsowell
*/
public class SysDept extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 部门ID
*/
private Long deptId;
/**
* 父部门ID
*/
private Long parentId;
/**
* 祖级列表
*/
private String ancestors;
/**
* 部门名称
*/
private String deptName;
/**
* 显示顺序
*/
private Integer orderNum;
/**
* 负责人
*/
private String leader;
/**
* 联系电话
*/
private String phone;
/**
* 邮箱
*/
private String email;
/**
* 部门状态:0正常,1停用
*/
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
private String delFlag;
/**
* 父部门名称
*/
private String parentName;
/**
* 子部门
*/
private List<SysDept> children = new ArrayList<SysDept>();
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getAncestors() {
return ancestors;
}
public void setAncestors(String ancestors) {
this.ancestors = ancestors;
}
@NotBlank(message = "部门名称不能为空")
@Size(min = 0, max = 30, message = "部门名称长度不能超过30个字符")
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
@NotNull(message = "显示顺序不能为空")
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
public String getLeader() {
return leader;
}
public void setLeader(String leader) {
this.leader = leader;
}
@Size(min = 0, max = 11, message = "联系电话长度不能超过11个字符")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public List<SysDept> getChildren() {
return children;
}
public void setChildren(List<SysDept> children) {
this.children = children;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("deptId", getDeptId())
.append("parentId", getParentId())
.append("ancestors", getAncestors())
.append("deptName", getDeptName())
.append("orderNum", getOrderNum())
.append("leader", getLeader())
.append("phone", getPhone())
.append("email", getEmail())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.toString();
}
}

View File

@@ -0,0 +1,175 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.annotation.Excel;
import com.jsowell.common.annotation.Excel.ColumnType;
import com.jsowell.common.constant.UserConstants;
import com.jsowell.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* 字典数据表 sys_dict_data
*
* @author jsowell
*/
public class SysDictData extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 字典编码
*/
@Excel(name = "字典编码", cellType = ColumnType.NUMERIC)
private Long dictCode;
/**
* 字典排序
*/
@Excel(name = "字典排序", cellType = ColumnType.NUMERIC)
private Long dictSort;
/**
* 字典标签
*/
@Excel(name = "字典标签")
private String dictLabel;
/**
* 字典键值
*/
@Excel(name = "字典键值")
private String dictValue;
/**
* 字典类型
*/
@Excel(name = "字典类型")
private String dictType;
/**
* 样式属性(其他样式扩展)
*/
private String cssClass;
/**
* 表格字典样式
*/
private String listClass;
/**
* 是否默认Y是 N否
*/
@Excel(name = "是否默认", readConverterExp = "Y=是,N=否")
private String isDefault;
/**
* 状态0正常 1停用
*/
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status;
public Long getDictCode() {
return dictCode;
}
public void setDictCode(Long dictCode) {
this.dictCode = dictCode;
}
public Long getDictSort() {
return dictSort;
}
public void setDictSort(Long dictSort) {
this.dictSort = dictSort;
}
@NotBlank(message = "字典标签不能为空")
@Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符")
public String getDictLabel() {
return dictLabel;
}
public void setDictLabel(String dictLabel) {
this.dictLabel = dictLabel;
}
@NotBlank(message = "字典键值不能为空")
@Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符")
public String getDictValue() {
return dictValue;
}
public void setDictValue(String dictValue) {
this.dictValue = dictValue;
}
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符")
public String getDictType() {
return dictType;
}
public void setDictType(String dictType) {
this.dictType = dictType;
}
@Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符")
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
public String getListClass() {
return listClass;
}
public void setListClass(String listClass) {
this.listClass = listClass;
}
public boolean getDefault() {
return UserConstants.YES.equals(this.isDefault) ? true : false;
}
public String getIsDefault() {
return isDefault;
}
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("dictCode", getDictCode())
.append("dictSort", getDictSort())
.append("dictLabel", getDictLabel())
.append("dictValue", getDictValue())
.append("dictType", getDictType())
.append("cssClass", getCssClass())
.append("listClass", getListClass())
.append("isDefault", getIsDefault())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

View File

@@ -0,0 +1,96 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.annotation.Excel;
import com.jsowell.common.annotation.Excel.ColumnType;
import com.jsowell.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
/**
* 字典类型表 sys_dict_type
*
* @author jsowell
*/
public class SysDictType extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 字典主键
*/
@Excel(name = "字典主键", cellType = ColumnType.NUMERIC)
private Long dictId;
/**
* 字典名称
*/
@Excel(name = "字典名称")
private String dictName;
/**
* 字典类型
*/
@Excel(name = "字典类型")
private String dictType;
/**
* 状态0正常 1停用
*/
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String status;
public Long getDictId() {
return dictId;
}
public void setDictId(Long dictId) {
this.dictId = dictId;
}
@NotBlank(message = "字典名称不能为空")
@Size(min = 0, max = 100, message = "字典类型名称长度不能超过100个字符")
public String getDictName() {
return dictName;
}
public void setDictName(String dictName) {
this.dictName = dictName;
}
@NotBlank(message = "字典类型不能为空")
@Size(min = 0, max = 100, message = "字典类型类型长度不能超过100个字符")
@Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "字典类型必须以字母开头,且只能为(小写字母,数字,下滑线)")
public String getDictType() {
return dictType;
}
public void setDictType(String dictType) {
this.dictType = dictType;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("dictId", getDictId())
.append("dictName", getDictName())
.append("dictType", getDictType())
.append("status", getStatus())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

View File

@@ -0,0 +1,259 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.List;
/**
* 菜单权限表 sys_menu
*
* @author jsowell
*/
public class SysMenu extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 菜单ID
*/
private Long menuId;
/**
* 菜单名称
*/
private String menuName;
/**
* 父菜单名称
*/
private String parentName;
/**
* 父菜单ID
*/
private Long parentId;
/**
* 显示顺序
*/
private Integer orderNum;
/**
* 路由地址
*/
private String path;
/**
* 组件路径
*/
private String component;
/**
* 路由参数
*/
private String query;
/**
* 是否为外链0是 1否
*/
private String isFrame;
/**
* 是否缓存0缓存 1不缓存
*/
private String isCache;
/**
* 类型M目录 C菜单 F按钮
*/
private String menuType;
/**
* 显示状态0显示 1隐藏
*/
private String visible;
/**
* 菜单状态0显示 1隐藏
*/
private String status;
/**
* 权限字符串
*/
private String perms;
/**
* 菜单图标
*/
private String icon;
/**
* 子菜单
*/
private List<SysMenu> children = new ArrayList<SysMenu>();
public Long getMenuId() {
return menuId;
}
public void setMenuId(Long menuId) {
this.menuId = menuId;
}
@NotBlank(message = "菜单名称不能为空")
@Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符")
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
@NotNull(message = "显示顺序不能为空")
public Integer getOrderNum() {
return orderNum;
}
public void setOrderNum(Integer orderNum) {
this.orderNum = orderNum;
}
@Size(min = 0, max = 200, message = "路由地址不能超过200个字符")
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
@Size(min = 0, max = 200, message = "组件路径不能超过255个字符")
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public String getIsFrame() {
return isFrame;
}
public void setIsFrame(String isFrame) {
this.isFrame = isFrame;
}
public String getIsCache() {
return isCache;
}
public void setIsCache(String isCache) {
this.isCache = isCache;
}
@NotBlank(message = "菜单类型不能为空")
public String getMenuType() {
return menuType;
}
public void setMenuType(String menuType) {
this.menuType = menuType;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
@Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符")
public String getPerms() {
return perms;
}
public void setPerms(String perms) {
this.perms = perms;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public List<SysMenu> getChildren() {
return children;
}
public void setChildren(List<SysMenu> children) {
this.children = children;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("menuId", getMenuId())
.append("menuName", getMenuName())
.append("parentId", getParentId())
.append("orderNum", getOrderNum())
.append("path", getPath())
.append("component", getComponent())
.append("isFrame", getIsFrame())
.append("IsCache", getIsCache())
.append("menuType", getMenuType())
.append("visible", getVisible())
.append("status ", getStatus())
.append("perms", getPerms())
.append("icon", getIcon())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

View File

@@ -0,0 +1,222 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.annotation.Excel;
import com.jsowell.common.annotation.Excel.ColumnType;
import com.jsowell.common.core.domain.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
/**
* 角色表 sys_role
*
* @author jsowell
*/
public class SysRole extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 角色ID
*/
@Excel(name = "角色序号", cellType = ColumnType.NUMERIC)
private Long roleId;
/**
* 角色名称
*/
@Excel(name = "角色名称")
private String roleName;
/**
* 角色权限
*/
@Excel(name = "角色权限")
private String roleKey;
/**
* 角色排序
*/
@Excel(name = "角色排序")
private String roleSort;
/**
* 数据范围1所有数据权限2自定义数据权限3本部门数据权限4本部门及以下数据权限5仅本人数据权限
*/
@Excel(name = "数据范围", readConverterExp = "1=所有数据权限,2=自定义数据权限,3=本部门数据权限,4=本部门及以下数据权限,5=仅本人数据权限")
private String dataScope;
/**
* 菜单树选择项是否关联显示( 0父子不互相关联显示 1父子互相关联显示
*/
private boolean menuCheckStrictly;
/**
* 部门树选择项是否关联显示0父子不互相关联显示 1父子互相关联显示
*/
private boolean deptCheckStrictly;
/**
* 角色状态0正常 1停用
*/
@Excel(name = "角色状态", readConverterExp = "0=正常,1=停用")
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
private String delFlag;
/**
* 用户是否存在此角色标识 默认不存在
*/
private boolean flag = false;
/**
* 菜单组
*/
private Long[] menuIds;
/**
* 部门组(数据权限)
*/
private Long[] deptIds;
public SysRole() {
}
public SysRole(Long roleId) {
this.roleId = roleId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public boolean isAdmin() {
return isAdmin(this.roleId);
}
public static boolean isAdmin(Long roleId) {
return roleId != null && 1L == roleId;
}
@NotBlank(message = "角色名称不能为空")
@Size(min = 0, max = 30, message = "角色名称长度不能超过30个字符")
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@NotBlank(message = "权限字符不能为空")
@Size(min = 0, max = 100, message = "权限字符长度不能超过100个字符")
public String getRoleKey() {
return roleKey;
}
public void setRoleKey(String roleKey) {
this.roleKey = roleKey;
}
@NotBlank(message = "显示顺序不能为空")
public String getRoleSort() {
return roleSort;
}
public void setRoleSort(String roleSort) {
this.roleSort = roleSort;
}
public String getDataScope() {
return dataScope;
}
public void setDataScope(String dataScope) {
this.dataScope = dataScope;
}
public boolean isMenuCheckStrictly() {
return menuCheckStrictly;
}
public void setMenuCheckStrictly(boolean menuCheckStrictly) {
this.menuCheckStrictly = menuCheckStrictly;
}
public boolean isDeptCheckStrictly() {
return deptCheckStrictly;
}
public void setDeptCheckStrictly(boolean deptCheckStrictly) {
this.deptCheckStrictly = deptCheckStrictly;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public boolean isFlag() {
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
public Long[] getMenuIds() {
return menuIds;
}
public void setMenuIds(Long[] menuIds) {
this.menuIds = menuIds;
}
public Long[] getDeptIds() {
return deptIds;
}
public void setDeptIds(Long[] deptIds) {
this.deptIds = deptIds;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("roleId", getRoleId())
.append("roleName", getRoleName())
.append("roleKey", getRoleKey())
.append("roleSort", getRoleSort())
.append("dataScope", getDataScope())
.append("menuCheckStrictly", isMenuCheckStrictly())
.append("deptCheckStrictly", isDeptCheckStrictly())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.toString();
}
}

View File

@@ -0,0 +1,322 @@
package com.jsowell.common.core.domain.entity;
import com.jsowell.common.annotation.Excel;
import com.jsowell.common.annotation.Excel.ColumnType;
import com.jsowell.common.annotation.Excel.Type;
import com.jsowell.common.annotation.Excels;
import com.jsowell.common.core.domain.BaseEntity;
import com.jsowell.common.xss.Xss;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
/**
* 用户对象 sys_user
*
* @author jsowell
*/
public class SysUser extends BaseEntity {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
@Excel(name = "用户序号", cellType = ColumnType.NUMERIC, prompt = "用户编号")
private Long userId;
/**
* 部门ID
*/
@Excel(name = "部门编号", type = Type.IMPORT)
private Long deptId;
/**
* 用户账号
*/
@Excel(name = "登录名称")
private String userName;
/**
* 用户昵称
*/
@Excel(name = "用户名称")
private String nickName;
/**
* 用户邮箱
*/
@Excel(name = "用户邮箱")
private String email;
/**
* 手机号码
*/
@Excel(name = "手机号码")
private String phone;
/**
* 用户性别
*/
@Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
private String sex;
/**
* 用户头像
*/
private String avatar;
/**
* 密码
*/
private String password;
/**
* 帐号状态0正常 1停用
*/
@Excel(name = "帐号状态", readConverterExp = "0=正常,1=停用")
private String status;
/**
* 删除标志0代表存在 2代表删除
*/
private String delFlag;
/**
* 最后登录IP
*/
@Excel(name = "最后登录IP", type = Type.EXPORT)
private String loginIp;
/**
* 最后登录时间
*/
@Excel(name = "最后登录时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss", type = Type.EXPORT)
private Date loginDate;
/**
* 部门对象
*/
@Excels({
@Excel(name = "部门名称", targetAttr = "deptName", type = Type.EXPORT),
@Excel(name = "部门负责人", targetAttr = "leader", type = Type.EXPORT)
})
private SysDept dept;
/**
* 角色对象
*/
private List<SysRole> roles;
/**
* 角色组
*/
private Long[] roleIds;
/**
* 岗位组
*/
private Long[] postIds;
/**
* 角色ID
*/
private Long roleId;
public SysUser() {
}
public SysUser(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public boolean isAdmin() {
return isAdmin(this.userId);
}
public static boolean isAdmin(Long userId) {
return userId != null && 1L == userId;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
@Xss(message = "用户昵称不能包含脚本字符")
@Size(min = 0, max = 30, message = "用户昵称长度不能超过30个字符")
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Xss(message = "用户账号不能包含脚本字符")
@NotBlank(message = "用户账号不能为空")
@Size(min = 0, max = 30, message = "用户账号长度不能超过30个字符")
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Email(message = "邮箱格式不正确")
@Size(min = 0, max = 50, message = "邮箱长度不能超过50个字符")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Size(min = 0, max = 11, message = "手机号码长度不能超过11个字符")
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDelFlag() {
return delFlag;
}
public void setDelFlag(String delFlag) {
this.delFlag = delFlag;
}
public String getLoginIp() {
return loginIp;
}
public void setLoginIp(String loginIp) {
this.loginIp = loginIp;
}
public Date getLoginDate() {
return loginDate;
}
public void setLoginDate(Date loginDate) {
this.loginDate = loginDate;
}
public SysDept getDept() {
return dept;
}
public void setDept(SysDept dept) {
this.dept = dept;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
public Long[] getRoleIds() {
return roleIds;
}
public void setRoleIds(Long[] roleIds) {
this.roleIds = roleIds;
}
public Long[] getPostIds() {
return postIds;
}
public void setPostIds(Long[] postIds) {
this.postIds = postIds;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.JSON_STYLE)
.append("userId", getUserId())
.append("deptId", getDeptId())
.append("userName", getUserName())
.append("nickName", getNickName())
.append("email", getEmail())
.append("phone", getPhone())
.append("sex", getSex())
.append("avatar", getAvatar())
.append("password", getPassword())
.append("status", getStatus())
.append("delFlag", getDelFlag())
.append("loginIp", getLoginIp())
.append("loginDate", getLoginDate())
.append("createBy", getCreateBy())
.append("createTime", getCreateTime())
.append("updateBy", getUpdateBy())
.append("updateTime", getUpdateTime())
.append("remark", getRemark())
.append("dept", getDept())
.toString();
}
}

View File

@@ -0,0 +1,32 @@
package com.jsowell.common.core.domain.model;
import lombok.Data;
/**
* 用户登录对象
*
* @author jsowell
*/
@Data
public class LoginBody {
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String password;
/**
* 验证码
*/
private String code;
/**
* 唯一标识
*/
private String uuid;
}

View File

@@ -0,0 +1,234 @@
package com.jsowell.common.core.domain.model;
import com.alibaba.fastjson2.annotation.JSONField;
import com.jsowell.common.core.domain.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.Set;
/**
* 登录用户身份权限
*
* @author jsowell
*/
public class LoginUser implements UserDetails {
private static final long serialVersionUID = 1L;
/**
* 用户ID
*/
private Long userId;
/**
* 部门ID
*/
private Long deptId;
/**
* 用户唯一标识
*/
private String token;
/**
* 登录时间
*/
private Long loginTime;
/**
* 过期时间
*/
private Long expireTime;
/**
* 登录IP地址
*/
private String ipaddr;
/**
* 登录地点
*/
private String loginLocation;
/**
* 浏览器类型
*/
private String browser;
/**
* 操作系统
*/
private String os;
/**
* 权限列表
*/
private Set<String> permissions;
/**
* 用户信息
*/
private SysUser user;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getDeptId() {
return deptId;
}
public void setDeptId(Long deptId) {
this.deptId = deptId;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public LoginUser() {
}
public LoginUser(SysUser user, Set<String> permissions) {
this.user = user;
this.permissions = permissions;
}
public LoginUser(Long userId, Long deptId, SysUser user, Set<String> permissions) {
this.userId = userId;
this.deptId = deptId;
this.user = user;
this.permissions = permissions;
}
@JSONField(serialize = false)
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUserName();
}
/**
* 账户是否未过期,过期无法验证
*/
@JSONField(serialize = false)
@Override
public boolean isAccountNonExpired() {
return true;
}
/**
* 指定用户是否解锁,锁定的用户无法进行身份验证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isAccountNonLocked() {
return true;
}
/**
* 指示是否已过期的用户的凭据(密码),过期的凭据防止认证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isCredentialsNonExpired() {
return true;
}
/**
* 是否可用 ,禁用的用户不能身份验证
*
* @return
*/
@JSONField(serialize = false)
@Override
public boolean isEnabled() {
return true;
}
public Long getLoginTime() {
return loginTime;
}
public void setLoginTime(Long loginTime) {
this.loginTime = loginTime;
}
public String getIpaddr() {
return ipaddr;
}
public void setIpaddr(String ipaddr) {
this.ipaddr = ipaddr;
}
public String getLoginLocation() {
return loginLocation;
}
public void setLoginLocation(String loginLocation) {
this.loginLocation = loginLocation;
}
public String getBrowser() {
return browser;
}
public void setBrowser(String browser) {
this.browser = browser;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
public Long getExpireTime() {
return expireTime;
}
public void setExpireTime(Long expireTime) {
this.expireTime = expireTime;
}
public Set<String> getPermissions() {
return permissions;
}
public void setPermissions(Set<String> permissions) {
this.permissions = permissions;
}
public SysUser getUser() {
return user;
}
public void setUser(SysUser user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
}

View File

@@ -0,0 +1,10 @@
package com.jsowell.common.core.domain.model;
/**
* 用户注册对象
*
* @author jsowell
*/
public class RegisterBody extends LoginBody {
}

View File

@@ -0,0 +1,58 @@
package com.jsowell.common.core.domain.ykc;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class LoginRequestData {
/**
* 桩编码 BCD 码 7 不足 7 位补 0
*/
private String pileSn;
/**
* 桩类型 BIN 码 1 0 表示直流桩, 1 表示交流桩
*/
private String pileType;
/**
* 充电枪数量 BIN 码 1
*/
private String connectorNum;
/**
* 通信协议版本 BIN 码 1 版本号乘 10v1.0 表示 0x0A
*/
private String communicationVersion;
/**
* 程序版本 ASCII 码 8 不足 8 位补零
*/
private String programVersion;
/**
* 网络链接类型 BIN 码 1 0x00 SIM 卡
* 0x01 LAN
* 0x02 WAN
* 0x03 其他
*/
private String internetConnection;
/**
* Sim 卡 BCD 码 10 不足 10 位补零,取不到置零
*/
private String iccid;
/**
* 运营商 BIN 码 1 0x00 移动
* 0x02 电信
* 0x03 联通
* 0x04 其他
*/
private String business;
}

View File

@@ -0,0 +1,124 @@
package com.jsowell.common.core.domain.ykc;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 实时监测数据
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class RealTimeMonitorData {
/**
* 交易流水号
*/
private String orderCode;
/**
* 桩编号
*/
private String pileSn;
/**
* 枪口编号
*/
private String connectorCode;
/**
* 状态
*/
private String connectorStatus;
/**
* 枪是否归位
*/
private String homingFlag;
/**
* 充电枪编号
*/
private String pileConnectorCode;
/**
* 是否插枪 0x00否 0x01
*/
private String putGunType;
/**
* 输出电压
*/
private String outputVoltage;
/**
* 输出电流
*/
private String outputCurrent;
/**
* 输出功率(由输出电压,输出电流计算得出)
*/
private String outputPower;
/**
* 枪线温度
*/
private String gunLineTemperature;
/**
* 枪线编码 没有置零
*/
private String gunLineCode;
/**
* SOC 待机置零;交流桩置零
*/
private String SOC;
/**
* 电池组最高温度
*/
private String batteryMaxTemperature;
/**
* 累计充电时间 单位: min待机置零
*/
private String sumChargingTime;
/**
* 剩余时间 单位: min待机置零、交流桩置零
*/
private String timeRemaining;
/**
* 充电度数 精确到小数点后四位;待机置零
*/
private String chargingDegree;
/**
* 计损充电度数 精确到小数点后四位;待机置零 未设置计损比例时等于充电度数
*/
private String lossDegree;
/**
* 已充金额 精确到小数点后四位;待机置零 (电费+服务费) *计损充电度数
*/
private String chargingAmount;
/**
* 硬件故障
*/
private String hardwareFault;
/**
* 时间
*/
private String dateTime;
public String getPileConnectorCode() {
return this.pileSn + this.getConnectorCode();
}
}

Some files were not shown because too many files have changed in this diff Show More