new:新增withdraw请求,该暂无真实数据

This commit is contained in:
ZiHangQin 2023-07-18 16:07:56 +08:00
parent 7f2ec68197
commit 648fc0f370
14 changed files with 165 additions and 31 deletions

11
.idea/dataSources.xml generated Normal file
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
<data-source source="LOCAL" name="PostgreSQL - postgres@39.105.39.8" uuid="996b1b9f-5c40-4bd6-8c3c-0af67aaaa15d">
<driver-ref>postgresql</driver-ref>
<synchronize>true</synchronize>
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
<jdbc-url>jdbc:postgresql://39.105.39.8:9432/postgres</jdbc-url>
</data-source>
</component>
</project>

8
.idea/electricity_bill_calc_service.iml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

6
.idea/misc.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
</component>
</project>

8
.idea/modules.xml generated Normal file
View File

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/electricity_bill_calc_service.iml" filepath="$PROJECT_DIR$/.idea/electricity_bill_calc_service.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@ -42,34 +42,35 @@ type _LoginForm struct {
} }
func doLogin(c *fiber.Ctx) error { func doLogin(c *fiber.Ctx) error {
result := response.NewResult(c) result := response.NewResult(c) //创建一个相应结果对象
loginData := new(_LoginForm) loginData := new(_LoginForm) //创建一个解析登录表单数据的实体
if err := c.BodyParser(loginData); err != nil { if err := c.BodyParser(loginData); err != nil { //解析请求体中的Json数据到loginData里如果解析出错就返回错误
userLog.Error("表单解析失败!", zap.Error(err)) userLog.Error("表单解析失败!", zap.Error(err))
return result.Error(http.StatusInternalServerError, "表单解析失败。") return result.Error(http.StatusInternalServerError, "表单解析失败。") //返回一个内部服务器错误的相应结果
} }
var ( var (
session *model.Session session *model.Session
err error err error
) )
userLog.Info("有用户请求登录。", zap.String("username", loginData.Username), zap.Int16("type", loginData.Type)) userLog.Info("有用户请求登录。", zap.String("username", loginData.Username), zap.Int16("type", loginData.Type)) //记录日志相关信息
if loginData.Type == model.USER_TYPE_ENT { if loginData.Type == model.USER_TYPE_ENT { //根据登录类型选择不同的处理方法
session, err = service.UserService.ProcessEnterpriseUserLogin(loginData.Username, loginData.Password) session, err = service.UserService.ProcessEnterpriseUserLogin(loginData.Username, loginData.Password) //企业用户
} else { } else {
session, err = service.UserService.ProcessManagementUserLogin(loginData.Username, loginData.Password) userLog.Info("该用户是管理用户")
session, err = service.UserService.ProcessManagementUserLogin(loginData.Username, loginData.Password) //管理用户
} }
if err != nil { if err != nil {
if authError, ok := err.(*exceptions.AuthenticationError); ok { if authError, ok := err.(*exceptions.AuthenticationError); ok { //检查错误是否为身份验证错误
if authError.NeedReset { if authError.NeedReset { //如果需要重置密码则返回对应结果
return result.LoginNeedReset() return result.LoginNeedReset()
} }
return result.Error(int(authError.Code), authError.Message) return result.Error(int(authError.Code), authError.Message) //返回身份验证错误相应
} else { } else {
userLog.Error("用户登录请求处理失败!", zap.Error(err)) userLog.Error("用户登录请求处理失败!", zap.Error(err))
return result.Error(http.StatusInternalServerError, err.Error()) return result.Error(http.StatusInternalServerError, err.Error()) //返回内部服务器错误
} }
} }
return result.LoginSuccess(session) return result.LoginSuccess(session) //返回登录成功相应结果,包含会话信息
} }
func doLogout(c *fiber.Ctx) error { func doLogout(c *fiber.Ctx) error {

74
controller/withdraw.go Normal file
View File

@ -0,0 +1,74 @@
package controller
import (
"electricity_bill_calc/logger"
"electricity_bill_calc/response"
"github.com/gofiber/fiber/v2"
"go.uber.org/zap"
)
var withdrawLog = logger.Named("Handler", "Withdraw")
func InitializeWithdrawHandlers(router *fiber.App) {
router.Get("/withdraw", withdraw)
}
//用于检索用户的核算报表
func withdraw(c *fiber.Ctx) error {
//记录日志
withdrawLog.Info("带分页的待审核的核算撤回申请列表")
//获取请求参数
result := response.NewResult(c)
keyword := c.Query("keyword", "")
page := c.QueryInt("page", 1)
withdrawLog.Info("参数为: ", zap.String("keyword", keyword), zap.Int("page", page))
//中间数据库操作暂且省略。。。。
//首先进行核算报表的分页查询
//TODO: 2023-07-18 此处的data需要经过上面数据库查询后进行数据返回此处只是作于演示
data := fiber.Map{
"report": fiber.Map{
"id": "string",
"parkId": "string",
"periodBegin": "string",
"periodEnd": "string",
"published": true,
"publishedAt": "string",
"withdraw": 0,
"lastWithdrawAppliedAt": "string",
"lastWithdrawAuditAt": "string",
"status": 0,
"message": "string",
},
"park": fiber.Map{
"id": "string",
"userId": "string",
"name": "string",
"tenement": "string",
"area": "string",
"capacity": "string",
"category": 0,
"meter04kvType": 0,
"region": "string",
"address": "string",
"contact": "string",
"phone": "string",
},
"user": fiber.Map{
"id": "string",
"name": "string",
"contact": "string",
"phone": "string",
"region": "string",
"address": "string",
},
}
datas := make([]interface{}, 0)
datas = append(datas, data)
//TODO: 2023-07-18 此处返回值是个示例,具体返回值需要查询数据库
return result.Success(
"withdraw请求成功",
response.NewPagedResponse(page, 20).ToMap(),
fiber.Map{"records": datas},
)
}

13
doc/routerSetting.md Normal file
View File

@ -0,0 +1,13 @@
## fiber
#### fiber实例
- app是fiber创建的实例通常用app表示其中有可选配置选项
- BodyLimit 设置请求正文允许的最大大小默认为4 * 1024 * 1024
- EnablePrintRoutes 不打印框架自带日志默认false)
- EnableTrustedProxyCheck 禁用受信代理默认false)
- Prefork 预处理配置默认false)
- ErrorHandler 全局错误处理 默认false)
- JSONEncoder json编码 默认json.Marshal)
- JSONDecoder json解码 (默认json.Unmarshal)
- 。。。。。。。。(还有很多配置)
- Use中间件设置一个或者多个
- Group类似于gin框架中的路由分组

View File

@ -53,6 +53,9 @@ func (ql QueryLogger) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data
ql.logger.Info("查询参数", lo.Map(data.Args, func(elem any, index int) zap.Field { ql.logger.Info("查询参数", lo.Map(data.Args, func(elem any, index int) zap.Field {
return zap.Any(fmt.Sprintf("[Arg %d]: ", index), elem) return zap.Any(fmt.Sprintf("[Arg %d]: ", index), elem)
})...) })...)
// for index, arg := range data.Args {
// ql.logger.Info(fmt.Sprintf("[Arg %d]: %v", index, arg))
// }
return ctx return ctx
} }

View File

@ -15,10 +15,13 @@ var (
func SetupRedisConnection() error { func SetupRedisConnection() error {
var err error var err error
a := fmt.Sprintf("%s:%d", config.RedisSettings.Host, config.RedisSettings.Port)
fmt.Println(a)
Rd, err = rueidis.NewClient(rueidis.ClientOption{ Rd, err = rueidis.NewClient(rueidis.ClientOption{
InitAddress: []string{fmt.Sprintf("%s:%d", config.RedisSettings.Host, config.RedisSettings.Port)}, InitAddress: []string{"127.0.0.1:6379"},
Password: config.RedisSettings.Password, Password: "",
SelectDB: config.RedisSettings.DB, SelectDB: config.RedisSettings.DB,
DisableCache:true,
}) })
if err != nil { if err != nil {
return err return err

View File

@ -16,7 +16,7 @@ type LoginResponse struct {
func (r Result) LoginSuccess(session *model.Session) error { func (r Result) LoginSuccess(session *model.Session) error {
res := &LoginResponse{} res := &LoginResponse{}
res.Code = http.StatusOK res.Code = http.StatusOK
res.Message = "用户已成功登录。" res.Message = "用户已成功登录。"+ "👋!"
res.NeedReset = false res.NeedReset = false
res.Session = session res.Session = session
return r.Ctx.Status(fiber.StatusOK).JSON(res) return r.Ctx.Status(fiber.StatusOK).JSON(res)

View File

@ -25,24 +25,24 @@ func init() {
} }
func App() *fiber.App { func App() *fiber.App {
app := fiber.New(fiber.Config{ app := fiber.New(fiber.Config{ //创建fiber实例的时候选择配置选项
BodyLimit: 30 * 1024 * 1024, BodyLimit: 30 * 1024 * 1024, //设置请求正文允许的最大大小。
EnablePrintRoutes: true, EnablePrintRoutes: true, //自定义方案,用于启动消息
EnableTrustedProxyCheck: false, EnableTrustedProxyCheck: false, //禁用受信代理
Prefork: false, Prefork: false, //禁止预处理如果要启用预处理则需要通过shell脚本运行
ErrorHandler: errorHandler, ErrorHandler: errorHandler, //相应全局处理错误
JSONEncoder: json.Marshal, JSONEncoder: json.Marshal, //json编码
JSONDecoder: json.Unmarshal, JSONDecoder: json.Unmarshal, //json解码
}) })
app.Use(compress.New()) app.Use(compress.New()) //压缩中间件
app.Use(recover.New(recover.Config{ app.Use(recover.New(recover.Config{
EnableStackTrace: true, EnableStackTrace: true,
StackTraceHandler: stackTraceHandler, StackTraceHandler: stackTraceHandler,
})) })) //恢复中间件
app.Use(logger.NewLogMiddleware(logger.LogMiddlewareConfig{ app.Use(logger.NewLogMiddleware(logger.LogMiddlewareConfig{
Logger: logger.Named("App"), Logger: logger.Named("App"),
})) })) //日志中间件
app.Use(security.SessionRecovery) app.Use(security.SessionRecovery) //会话恢复中间件
controller.InitializeUserHandlers(app) controller.InitializeUserHandlers(app)
controller.InitializeRegionHandlers(app) controller.InitializeRegionHandlers(app)
@ -53,6 +53,7 @@ func App() *fiber.App {
controller.InitializeInvoiceHandler(app) controller.InitializeInvoiceHandler(app)
controller.InitializeTopUpHandlers(app) controller.InitializeTopUpHandlers(app)
controller.InitializeReportHandlers(app) controller.InitializeReportHandlers(app)
controller.InitializeWithdrawHandlers(app)
return app return app
} }

View File

@ -80,7 +80,7 @@ func (us _UserService) ProcessEnterpriseUserLogin(username, password string) (*m
us.log.Error("处理企业用户登录失败。", zap.String("username", username), zap.Error(err)) us.log.Error("处理企业用户登录失败。", zap.String("username", username), zap.Error(err))
return nil, err return nil, err
} }
token, _ := uuid.NewRandom() token, _ := uuid.NewRandom() //生成uuid作为会话的token使用
userSession := &model.Session{ userSession := &model.Session{
Uid: user.Id, Uid: user.Id,
Name: user.Username, Name: user.Username,

View File

@ -1,8 +1,8 @@
Database: Database:
User: electricity User: electricity
Pass: nLgxPO5s8gK2tR0OL0Q Pass: nLgxPO5s8gK2tR0OL0Q
Host: postgres Host: 39.105.39.8
Port: 5432 Port: 9432
DB: electricity DB: electricity
MaxIdleConns: 0 MaxIdleConns: 0
MaxOpenConns: 20 MaxOpenConns: 20