Explorar o código

FUNC:H5下单公司列表

zoie hai 11 meses
pai
achega
88c187d9a8

+ 172 - 0
app/admin/controller/applet_customer.go

@@ -1,11 +1,14 @@
 package controller
 
 import (
+	"gas-cylinder-api/app/admin/model"
 	"gas-cylinder-api/app/admin/service"
 	"gas-cylinder-api/app/admin/service/dto"
+	"gas-cylinder-api/common/actions"
 	"github.com/gin-gonic/gin"
 	"github.com/gin-gonic/gin/binding"
 	"gogs.baozhida.cn/zoie/OAuth-core/api"
+	"gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth/user"
 	_ "gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
 )
 
@@ -74,3 +77,172 @@ func (e AppletCustomerController) Register(c *gin.Context) {
 	}
 	e.OK(nil, "注册成功")
 }
+
+// GetProfile 获取个人中心用户
+// @Summary 获取个人中心用户
+// @Description 获取个人中心用户
+// @Tags 个人中心
+// @Success 200 {object} response.Response{user=model.SysUser,role=model.SysRole}  "{"code": 200, "data": {"user":[...],"role":[...]}}"
+// @Router /api/user/profile [get]
+// @Security Bearer
+func (e AppletCustomerController) GetProfile(c *gin.Context) {
+	s := service.Customer{}
+	err := e.MakeContext(c).
+		MakeOrm().
+		//Bind(&req, nil).
+		MakeService(&s.Service).
+		Errors
+	if err != nil {
+		e.Logger.Error(err)
+		e.Error(500, err, err.Error())
+		return
+	}
+	var object model.Customer
+
+	//数据权限检查
+	err = s.Get(&dto.CustomerGetReq{Id: service.GetAppletCustomerId(c)}, &object)
+	if err != nil {
+		e.Error(500, err, err.Error())
+		return
+	}
+
+	e.OK(object, "查询成功")
+}
+
+// GetOrderPage 获取订单列表
+// @Summary 获取订单列表
+// @Description 获取订单列表
+// @Tags 订单
+// @Param state          query int false "订单状态 1-已下单 2-已派送 3-已送达 4-已取消"
+// @Param source         query int false "订单状态 1-坐席下单 2-小程序"
+// @Param orderStartTime query string false "下单开始时间"
+// @Param orderEndTime   query string false "下单结束时间"
+// @Param phone          query string false "客户电话"
+// @Param customerId     query string false "客户id"
+// @Param pageSize query int false "页条数"
+// @Param page query int false "页码"
+// @Success 200 {object} response.Response{data=response.Page{list=[]model.Order}} "{"code": 200, "data": [...]}"
+// @Router /api/Order [get]
+// @Security Bearer
+func (e AppletCustomerController) GetOrderPage(c *gin.Context) {
+	s := service.Order{}
+	req := dto.OrderGetPageReq{}
+	err := e.MakeContext(c).
+		MakeOrm().
+		Bind(&req, binding.Query).
+		MakeService(&s.Service).
+		Errors
+	if err != nil {
+		e.Logger.Error(err)
+		e.Error(500, err, err.Error())
+		return
+	}
+
+	//数据权限检查
+	p := actions.GetPermissionFromContext(c)
+
+	list := make([]model.Order, 0)
+	var count int64
+	req.CustomerId = service.GetAppletCustomerId(c) + "_"
+	req.Source = 2
+	err = s.GetPage(&req, &list, &count, p)
+	if err != nil {
+		e.Error(500, err, err.Error())
+		return
+	}
+	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
+}
+
+// OrderInsert 订气
+// @Summary 订气
+// @Description 订气
+// @Tags 用户H5订单
+// @Accept  application/json
+// @Product application/json
+// @Param data body dto.OrderInsertReq true "data"
+// @Success 200 {string} string	"{"code": 200, "message": "添加成功"}"
+// @Success 200 {string} string	"{"code": -1, "message": "添加失败"}"
+// @Router /api/order [post]
+// @Security Bearer
+func (e AppletCustomerController) OrderInsert(c *gin.Context) {
+	s := service.Order{}
+	req := dto.OrderAppletInsertReq{}
+	err := e.MakeContext(c).
+		MakeOrm().
+		Bind(&req, binding.JSON).
+		MakeService(&s.Service).
+		Errors
+	if err != nil {
+		e.Logger.Error(err)
+		e.Error(500, err, err.Error())
+		return
+	}
+	req.CustomerId = service.GetAppletCustomerId(c)
+	req.Source = 2
+
+	req.SetDeptId(req.StoreId)
+	err = s.AppletInsert(&req)
+	if err != nil {
+		e.Error(500, err, err.Error())
+		return
+	}
+	e.OK(req.GetId(), "创建成功")
+}
+
+func (e AppletCustomerController) OrderUpdate(c *gin.Context) {
+	s := service.Order{}
+	req := dto.OrderUpdateReq{}
+	err := e.MakeContext(c).
+		MakeOrm().
+		Bind(&req, binding.JSON).
+		MakeService(&s.Service).
+		Errors
+	if err != nil {
+		e.Logger.Error(err)
+		e.Error(500, err, err.Error())
+		return
+	}
+
+	//数据权限检查
+	p := actions.GetPermissionFromContext(c)
+	// 设置创建人
+	req.SetCreateBy(user.GetUserId(c))
+	err = s.Update(&req, p)
+	if err != nil {
+		e.Error(500, err, err.Error())
+		return
+	}
+	e.OK(req.GetId(), "修改成功")
+}
+
+// StoreList 获取销售门店列表
+// @Summary 获取销售门店列表
+// @Description 获取销售门店列表(用户公司及子公司)
+// @Tags 销售门店
+// @Param name query string false "销售门店名称"
+// @Success 200 {object} response.Response{data=response.Page{list=[]model.SysDept}} "{"code": 200, "data": [...]}"
+// @Router /api/store [get]
+// @Security Bearer
+func (e AppletCustomerController) StoreList(c *gin.Context) {
+	s := service.Store{}
+	req := dto.AppletStoreGetPageReq{}
+	err := e.MakeContext(c).
+		MakeOrm().
+		Bind(&req, binding.Query).
+		MakeService(&s.Service).
+		Errors
+	if err != nil {
+		e.Logger.Error(err)
+		e.Error(500, err, err.Error())
+		return
+	}
+
+	req.Type = model.TypeStore
+	list := make([]model.SysDept, 0)
+	list, err = s.SetAppletStorePage(&req)
+	if err != nil {
+		e.Error(500, err, err.Error())
+		return
+	}
+	e.OK(list, "查询成功")
+}

+ 1 - 0
app/admin/model/address.go

@@ -10,6 +10,7 @@ type Address struct {
 	City       string `json:"city" gorm:"size:6;"`        // 所在地市
 	Area       string `json:"area" gorm:"size:6;"`        // 所属区/县
 	Address    string `json:"address" gorm:"size:128"`    // 详细地址
+	IsDefault  bool   `json:"isDefault" gorm:"size:128"`  // 默认
 	model2.ControlBy
 	model2.ModelTime
 }

+ 15 - 0
app/admin/model/customer.go

@@ -3,6 +3,7 @@ package model
 import (
 	model2 "gas-cylinder-api/common/model"
 	"golang.org/x/crypto/bcrypt"
+	"gorm.io/gorm"
 )
 
 type ProvCustomer struct {
@@ -47,6 +48,20 @@ func (CustomerOmit) TableName() string {
 	return "customer"
 }
 
+
+func (e *Customer) BeforeCreate(_ *gorm.DB) error {
+	return e.Encrypt()
+}
+
+func (e *Customer) BeforeUpdate(_ *gorm.DB) error {
+	var err error
+	if e.Password != "" {
+		err = e.Encrypt()
+	}
+	return err
+}
+
+
 // 加密
 func (e *Customer) Encrypt() (err error) {
 	if e.Password == "" {

+ 15 - 0
app/admin/model/store_customer.go

@@ -0,0 +1,15 @@
+package model
+
+import model2 "gas-cylinder-api/common/model"
+
+type StoreCustomer struct {
+	model2.Model
+	CustomerId     string `json:"id" gorm:"size:48"`              // 主键ID
+	PrincipalPhone string `json:"principalPhone" gorm:"size:32;"` // 负责人电话
+	DeptId         int    `json:"deptId" gorm:"size:48"`          //
+	model2.ModelTime
+}
+
+func (StoreCustomer) TableName() string {
+	return "store_customer"
+}

+ 14 - 14
app/admin/model/sys_user.go

@@ -16,20 +16,20 @@ import (
 
 // 省平台用户
 type ProvUser struct {
-	UserId      string `json:"userId" gorm:"size:48;" swaggerignore:"true"` // 用户ID
-	Name        string `json:"name" gorm:"size:128;"`                       // 用户姓名
-	IdCard      string `json:"idCard" gorm:"size:32"`                       // 身份证号
-	No          string `json:"no" gorm:"size:32"`                           // 用户工号
-	Phone       string `json:"phone" gorm:"size:32"`                        // 联系电话
-	UserType    int    `json:"userType" gorm:"size:4"`                      // 用户类型 3-门店人员 4-货车司机 5-充装站人员
-	Description string `json:"description" gorm:"size:255"`                 // 描述
-	HireStatus  string `json:"hireStatus" gorm:"size:64"`                   // 聘用状态
-	HireTime    string `json:"hireTime" gorm:"size:10"`                     // 聘用日期
-	Education   string `json:"education" gorm:"size:64"`                    // 教育程度
-	JobCategory string `json:"jobCategory" gorm:"size:64"`                  // 岗位类别
-	PersonQual  string `json:"personQual" gorm:"size:128"`                  // 资质
-	Isorders    int    `json:"isorders" gorm:"size:4"`                      // 用户类型 0-送气员 1-库管 userType=3时必填
-	CmpCode     string `json:"cmpCode" gorm:"size:48"`                      // 所属机
+	UserId      string `json:"userId" gorm:"size:48;" 钢瓶规格ignore:"true"` // 用户ID
+	Name        string `json:"name" gorm:"size:128;"`                    // 用户姓名
+	IdCard      string `json:"idCard" gorm:"size:32"`                    // 身份证号
+	No          string `json:"no" gorm:"size:32"`                        // 用户工号
+	Phone       string `json:"phone" gorm:"size:32"`                     // 联系电话
+	UserType    int    `json:"userType" gorm:"size:4"`                   // 用户类型 3-门店人员 4-货车司机 5-充装站人员
+	Description string `json:"description" gorm:"size:255"`              // 描述
+	HireStatus  string `json:"hireStatus" gorm:"size:64"`                // 聘用状态
+	HireTime    string `json:"hireTime" gorm:"size:10"`                  // 聘用日期
+	Education   string `json:"education" gorm:"size:64"`                 // 教育程度
+	JobCategory string `json:"jobCategory" gorm:"size:64"`               // 岗位类别
+	PersonQual  string `json:"personQual" gorm:"size:128"`               // 资质
+	Isorders    int    `json:"isorders" gorm:"size:4"`                   // 用户类型 0-送气员 1-库管 userType=3时必填
+	CmpCode     string `json:"cmpCode" gorm:"size:48"`                   // 所属机
 }
 
 // 送气人员绑定资质信息《燃气从业资格证》

+ 3 - 3
app/admin/router/address.go

@@ -6,13 +6,13 @@ import (
 )
 
 func init() {
-	routerNoCheckRole = append(routerNoCheckRole, registerAddressRouter)
+	appletRouterCheck = append(appletRouterCheck, registerAddressRouter)
 }
 
 // 需认证的路由代码
-func registerAddressRouter(v1 *gin.RouterGroup) {
+func registerAddressRouter(v1 *gin.RouterGroup, authMiddleware gin.HandlerFunc) {
 	cont := controller.AddressController{}
-	r := v1.Group("/address").Use(AppletCunJWTMiddleware())
+	r := v1.Group("/address").Use(authMiddleware)
 	{
 		r.GET("", cont.GetPage)
 		r.GET("/:id", cont.Get)

+ 24 - 15
app/admin/router/applet_customer.go

@@ -9,8 +9,12 @@ import (
 	"strings"
 )
 
+var (
+	appletRouterCheck = make([]func(v1 *gin.RouterGroup, authMiddleware gin.HandlerFunc), 0)
+)
+
 func init() {
-	routerNoCheckRole = append(routerNoCheckRole, registerAppletCustomerRouter)
+	appletRouterCheck = append(appletRouterCheck, AppletCustomerRouter)
 }
 
 func AppletCunJWTMiddleware() gin.HandlerFunc {
@@ -64,26 +68,31 @@ func AppletCunJWTMiddleware() gin.HandlerFunc {
 		c.Next()
 	}
 }
-func registerAppletCustomerRouter(v1 *gin.RouterGroup) {
-	//cont := controller.AppletCustomerController{}
-	//r := v1.Group("/applet-customer").Use(AppletCunJWTMiddleware())
-	//{
-	//	r.POST("login", cont.Login)
-	//	//r.GET("", cont.GetPage)
-	//	//r.GET("/:id", cont.Get)
-	//	//r.GET("/phone", cont.GetByPhone)
-	//	//r.POST("/insert-or-update", cont.InsertOrUpdate)
-	//	//r.PUT("", cont.Update)
-	//	//r.DELETE("", cont.Delete)
-	//}
-}
 
 func AppletCustomerRouterInit(v1 *gin.RouterGroup) {
 	cont := controller.AppletCustomerController{}
-	r := v1.Group("/applet")
+	r := v1.Group("/api/applet")
 	{
 		r.POST("/login", cont.Login)
 		r.POST("/register", cont.Register)
 
 	}
+
+	for _, f := range appletRouterCheck {
+		f(r, AppletCunJWTMiddleware())
+	}
+}
+
+func AppletCustomerRouter(v1 *gin.RouterGroup, authMiddleware gin.HandlerFunc) {
+	cont := controller.AppletCustomerController{}
+	order := controller.OrderController{}
+
+	r := v1.Group("").Use(authMiddleware)
+	{
+		r.GET("/profile", cont.GetProfile)
+		r.GET("/order", cont.GetOrderPage)
+		r.POST("/order", cont.OrderInsert)
+		r.PUT("/order", order.Update)
+		r.GET("/store", cont.StoreList)
+	}
 }

+ 0 - 30
app/admin/router/router.go

@@ -2,7 +2,6 @@ package router
 
 import (
 	"github.com/gin-gonic/gin"
-	"gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
 	jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
 )
 
@@ -10,32 +9,3 @@ var (
 	routerNoCheckRole = make([]func(*gin.RouterGroup), 0)
 	routerCheckRole   = make([]func(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddleware), 0)
 )
-
-// 路由示例
-func InitExamplesRouter(r *gin.Engine, authMiddleware *jwt.GinJWTMiddleware) *gin.Engine {
-
-	// 无需认证的路由
-	NoCheckRoleRouter(r)
-	// 需要认证的路由
-	CheckRoleRouter(r, authMiddleware)
-
-	return r
-}
-
-// 无需认证的路由示例
-func NoCheckRoleRouter(r *gin.Engine) {
-	// 可根据业务需求来设置接口版本
-	v1 := r.Group("/api")
-	for _, f := range routerNoCheckRole {
-		f(v1)
-	}
-}
-
-// 需要认证的路由示例
-func CheckRoleRouter(r *gin.Engine, authMiddleware *jwtauth.GinJWTMiddleware) {
-	// 可根据业务需求来设置接口版本
-	v1 := r.Group("/api")
-	for _, f := range routerCheckRole {
-		f(v1, authMiddleware)
-	}
-}

+ 11 - 4
app/admin/router/sys_user.go

@@ -11,6 +11,8 @@ import (
 
 func init() {
 	routerCheckRole = append(routerCheckRole, registerSysUserRouter)
+	routerNoCheckRole = append(routerNoCheckRole, registerSysUserRouter2)
+
 }
 
 // 需认证的路由代码
@@ -35,10 +37,6 @@ func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
 		user.PUT("/pwd/reset", cont.ResetPwd)
 
 	}
-	r2 := v1.Group("")
-	{
-		r2.GET("/verify-code", cont.VerifyCode)
-	}
 
 	r3 := v1.Group("/newest-token").Use(middleware.AuthCheckService())
 	{
@@ -46,3 +44,12 @@ func registerSysUserRouter(v1 *gin.RouterGroup, authMiddleware *jwt.GinJWTMiddle
 	}
 
 }
+func registerSysUserRouter2(v1 *gin.RouterGroup) {
+	cont := controller.SysUser{}
+
+	r2 := v1.Group("")
+	{
+		r2.GET("/verify-code", cont.VerifyCode)
+	}
+
+}

+ 28 - 2
app/admin/service/address.go

@@ -65,7 +65,24 @@ func (e *Address) Insert(c *dto.AddressInsertReq) error {
 		}
 	}()
 
-	// TODO 1.1.1.12新运输增车辆信息
+	// 查询是否有其他默认地址
+	var count int64
+	err = tx.Model(&model.Address{}).Where("is_default = ? and customer_id = ?", 1, c.CustomerId).Count(&count).Error
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.CreateFailedErr
+	}
+
+	if count > 0 && c.IsDefault == true {
+		err = tx.Model(&model.Address{}).Where("customer_id = ?", c.CustomerId).
+			Updates(map[string]interface{}{
+				"is_default": 0,
+			}).Error
+		if err != nil {
+			e.Log.Errorf("db error: %s", err)
+			return global.CreateFailedErr
+		}
+	}
 
 	// 添加角色
 	c.Generate(&data)
@@ -104,7 +121,16 @@ func (e *Address) Update(c *dto.AddressUpdateReq, p *actions.DataPermission) err
 		return global.UpdateFailedErr
 	}
 
-	// TODO 1.1.1.13更新车辆信息
+	if c.IsDefault == true && c.IsDefault != carInfoModel.IsDefault {
+		err = tx.Model(&model.Address{}).Where("customer_id = ?", carInfoModel.CustomerId).
+			Updates(map[string]interface{}{
+				"is_default": 0,
+			}).Error
+		if err != nil {
+			e.Log.Errorf("db error: %s", err)
+			return global.CreateFailedErr
+		}
+	}
 
 	c.Generate(&carInfoModel)
 	err = tx.Save(&carInfoModel).Error

+ 37 - 12
app/admin/service/applet_customer.go

@@ -6,11 +6,14 @@ import (
 	"fmt"
 	"gas-cylinder-api/app/admin/model"
 	"gas-cylinder-api/app/admin/service/dto"
+	"gas-cylinder-api/common/middleware/handler"
+	model2 "gas-cylinder-api/common/model"
 	"gas-cylinder-api/conf"
 	"github.com/dgrijalva/jwt-go"
 	"github.com/gin-gonic/gin"
 	"gogs.baozhida.cn/zoie/OAuth-core/pkg"
 	"gogs.baozhida.cn/zoie/OAuth-core/pkg/utils"
+	"gogs.baozhida.cn/zoie/OAuth-core/sdk"
 	"gogs.baozhida.cn/zoie/OAuth-core/service"
 	"gorm.io/gorm"
 	"net/http"
@@ -92,7 +95,7 @@ func (e *AppletCustomer) WxLogin(c *dto.AppletCustomerWxLoginReq) (token, expire
 func (e *AppletCustomer) Login(c *dto.AppletCustomerLoginReq) (token, expiresAt string, err error) {
 	var data model.Customer
 
-	err = e.Orm.Where("principal_phone = ?", c.Phone).First(&data).Error
+	err = e.Orm.Where("principal_phone = ? and dept_id = -1", c.Phone).First(&data).Error
 	id := data.Id
 	if err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -102,6 +105,22 @@ func (e *AppletCustomer) Login(c *dto.AppletCustomerLoginReq) (token, expiresAt
 		}
 	}
 
+	if len(c.VerifyCode) > 0 {
+		code, err := sdk.Runtime.GetCacheAdapter().Get(handler.GetVerifyCodeCacheKey(c.Phone))
+		if err != nil {
+			e.Log.Errorf("user login error, %s", err.Error())
+			err = errors.New("验证码已过期")
+			return token, expiresAt, err
+		}
+		if code != c.VerifyCode {
+			e.Log.Errorf("user login error, %s", "验证码错误")
+			err = errors.New("验证码错误")
+			return token, expiresAt, err
+		}
+		token, expiresAt, _ = e.GeneratorToken(id)
+		return token, expiresAt, nil
+	}
+
 	_, err = pkg.CompareHashAndPassword(data.Password, c.Password)
 	if err != nil {
 		e.Log.Errorf("user login error, %s", err.Error())
@@ -114,8 +133,19 @@ func (e *AppletCustomer) Login(c *dto.AppletCustomerLoginReq) (token, expiresAt
 }
 func (e *AppletCustomer) Register(c *dto.AppletCustomerRegisterReq) (err error) {
 	var data model.Customer
+	code, err := sdk.Runtime.GetCacheAdapter().Get(handler.GetVerifyCodeCacheKey(c.Phone))
+	if err != nil {
+		e.Log.Errorf("user login error, %s", err.Error())
+		err = errors.New("验证码已过期")
+		return
+	}
+	if code != c.VerifyCode {
+		e.Log.Errorf("user login error, %s", "验证码错误")
+		err = errors.New("验证码错误")
+		return
+	}
 
-	err = e.Orm.Where("principal_phone = ?", c.Phone).First(&data).Error
+	err = e.Orm.Where("principal_phone = ? and dept_id = -1", c.Phone).First(&data).Error
 	id := data.Id
 	if err != nil {
 		if errors.Is(err, gorm.ErrRecordNotFound) {
@@ -134,11 +164,15 @@ func (e *AppletCustomer) Register(c *dto.AppletCustomerRegisterReq) (err error)
 			}
 			err = e.Orm.Create(&model.Customer{
 				ProvCustomer: model.ProvCustomer{
+					Type:           c.Type,
 					Id:             id,
 					PrincipalPhone: c.Phone,
 				},
 				//Openid: wxRes.Openid,
 				Password: c.Password,
+				DeptBy: model2.DeptBy{
+					DeptId: -1,
+				},
 			}).Error
 		} else {
 			return err
@@ -146,16 +180,7 @@ func (e *AppletCustomer) Register(c *dto.AppletCustomerRegisterReq) (err error)
 	}
 
 	if len(data.Id) > 0 {
-		if len(data.Password) > 0 {
-			return errors.New("该手机号已注册")
-		} else {
-			data.Password = c.Password
-			err = e.Orm.Save(&data).Error
-			if err != nil {
-				return err
-			}
-		}
-
+		return errors.New("该手机号已注册")
 	}
 
 	return nil

+ 6 - 6
app/admin/service/customer.go

@@ -162,7 +162,7 @@ func (e *Customer) InsertOrUpdate(c *dto.CustomerInsertReq, p *actions.DataPermi
 
 			c.Generate(&data)
 			data.Id = id
-			data.IsSyncProv = true
+			data.IsSyncProv = true // TODO
 			err = tx.Create(&data).Error
 			if err != nil {
 				e.Log.Errorf("db error: %s", err)
@@ -175,11 +175,11 @@ func (e *Customer) InsertOrUpdate(c *dto.CustomerInsertReq, p *actions.DataPermi
 	}
 
 	// 数据一致则不更新
-	if e.CheckDataConsistency(*c, data) {
+	if CustomerCheckDataConsistency(*c, data) {
 		c.Id = data.Id
 		return nil
 	}
-	dataIntegrity := e.CheckDataIntegrity(data)
+	dataIntegrity := CustomerCheckDataIntegrity(data)
 	if dataIntegrity {
 		data.IsSyncProv = true
 	}
@@ -226,7 +226,7 @@ func (e *Customer) Update(c *dto.CustomerUpdateReq, p *actions.DataPermission) e
 	}
 	c.Generate(&CustomerModel)
 	// 检查数据完整性
-	dataIntegrity := e.CheckDataIntegrity(CustomerModel)
+	dataIntegrity := CustomerCheckDataIntegrity(CustomerModel)
 	if dataIntegrity {
 		CustomerModel.IsSyncProv = true
 	}
@@ -289,7 +289,7 @@ func (e *Customer) Remove(c *dto.CustomerDeleteReq, p *actions.DataPermission) e
 }
 
 // 检查数据完整性,数据完整之后再上传省平台
-func (e *Customer) CheckDataIntegrity(customer model.Customer) bool {
+func CustomerCheckDataIntegrity(customer model.Customer) bool {
 	flag := true
 
 	if customer.Address == "" {
@@ -327,7 +327,7 @@ func (e *Customer) CheckDataIntegrity(customer model.Customer) bool {
 }
 
 // 检查数据一致性,数据一致则不更新,不上传省平台
-func (e *Customer) CheckDataConsistency(req dto.CustomerInsertReq, customer model.Customer) bool {
+func CustomerCheckDataConsistency(req dto.CustomerInsertReq, customer model.Customer) bool {
 	flag := true
 	// 0-商户 1-私人
 	if customer.Type == 1 {

+ 11 - 6
app/admin/service/dto/address.go

@@ -28,6 +28,7 @@ type AddressInsertReq struct {
 	City       string `json:"city"`                                 // 所在地市
 	Area       string `json:"area"`                                 // 所属区/县
 	Address    string `json:"address"`                              // 详细地址
+	IsDefault  bool   `json:"isDefault"`                            // 默认地址
 }
 
 func (s *AddressInsertReq) Generate(m *model.Address) {
@@ -40,6 +41,7 @@ func (s *AddressInsertReq) Generate(m *model.Address) {
 	m.City = s.City
 	m.Area = s.Area
 	m.Address = s.Address
+	m.IsDefault = s.IsDefault
 }
 
 func (e *AddressInsertReq) SetCustomerId(CustomerId string) {
@@ -51,12 +53,14 @@ func (s *AddressInsertReq) GetId() interface{} {
 }
 
 type AddressUpdateReq struct {
-	Id               int    `json:"id" comment:"编码"` // 编码
-	Name             string `json:"name"`            // 收货人名称
-	Phone            string `json:"phone"`           // 联系电话
-	City             string `json:"city"`            // 所在地市
-	Area             string `json:"area"`            // 所属区/县
-	Address          string `json:"address"`         // 详细地址
+	Id        int    `json:"id" comment:"编码"` // 编码
+	Name      string `json:"name"`            // 收货人名称
+	Phone     string `json:"phone"`           // 联系电话
+	City      string `json:"city"`            // 所在地市
+	Area      string `json:"area"`            // 所属区/县
+	Address   string `json:"address"`         // 详细地址
+	IsDefault bool   `json:"isDefault"`       // 默认地址
+
 	common.ControlBy `swaggerignore:"true"`
 }
 
@@ -69,6 +73,7 @@ func (s *AddressUpdateReq) Generate(m *model.Address) {
 	m.City = s.City
 	m.Area = s.Area
 	m.Address = s.Address
+	m.IsDefault = s.IsDefault
 	if s.ControlBy.UpdateBy != 0 {
 		m.UpdateBy = s.UpdateBy
 	}

+ 8 - 4
app/admin/service/dto/applet_customer.go

@@ -2,16 +2,20 @@ package dto
 
 // 小程序客户登录
 type AppletCustomerLoginReq struct {
-	Phone    string `json:"phone"`    // 手机号
-	Password string `json:"password"` // 密码
+	Phone      string `json:"phone"`      // 手机号
+	Password   string `json:"password"`   // 密码
+	VerifyCode string `json:"verifyCode"` // 验证码
 }
 type AppletCustomerWxLoginReq struct {
 	Phone string `json:"phone"` // 手机号
 	Code  string `json:"code"`  // 密码
 }
 type AppletCustomerRegisterReq struct {
-	Phone    string `json:"phone"`    // 手机号
-	Password string `json:"password"` // 密码
+	Type       int    `json:"type"`       // 类型  0-商户 1-私人
+	Phone      string `json:"phone"`      // 手机号
+	Password   string `json:"password"`   // 密码
+	VerifyCode string `json:"verifyCode"` // 验证码
+
 }
 
 type AppletCustomerLoginResp struct {

+ 49 - 0
app/admin/service/dto/order.go

@@ -56,6 +56,26 @@ type OrderInsertReq struct {
 	common.ControlBy `swaggerignore:"true"`
 	common.DeptBy    `swaggerignore:"true"`
 }
+type OrderAppletInsertReq struct {
+	Id               int         `json:"id" comment:"编码" swaggerignore:"true"` // 编码
+	CustomerId       string      `json:"customerId"`                           // 顾客id
+	Address          string      `json:"address"`                              // 顾客地址
+	Lng              float64     `json:"lng"`                                  // 经度
+	Lat              float64     `json:"lat"`                                  // 纬度
+	City             string      `json:"city"`                                 // 所在地市
+	Area             string      `json:"area"`                                 // 所属区/县
+	Phone            string      `json:"phone"`                                // 顾客电话
+	StoreId          int         `json:"storeId"`                              // 门店id
+	GoodsId          int         `json:"goodsId"`                              // 商品id
+	SpecId           int         `json:"specId"`                               // 规格id
+	Quantity         int         `json:"quantity"`                             // 数量
+	Source           int         `json:"source"`                               // 来源 1-坐席下单 2-小程序
+	Remark           string      `json:"remark"`
+	State            int         `json:"state" swaggerignore:"true"` // 状态 已下单
+	OrderTime        common.Time `json:"orderTime" swaggerignore:"true"`
+	common.ControlBy `swaggerignore:"true"`
+	common.DeptBy    `swaggerignore:"true"`
+}
 
 func (s *OrderInsertReq) Generate(order *model.Order) {
 	if s.Id != 0 {
@@ -84,10 +104,39 @@ func (s *OrderInsertReq) Generate(order *model.Order) {
 		order.DeptId = s.DeptId
 	}
 }
+func (s *OrderAppletInsertReq) Generate(order *model.Order) {
+	if s.Id != 0 {
+		order.Id = s.Id
+	}
+	order.CustomerId = s.CustomerId
+	order.Address = s.Address
+	order.Phone = s.Phone
+	order.StoreId = s.StoreId
+	order.GoodsId = s.GoodsId
+	order.SpecId = s.SpecId
+	order.Quantity = s.Quantity
+	order.Remark = s.Remark
+	order.Source = s.Source
+	order.OrderId = util.NewUuid()
+	order.State = model.OrderStateOrder
+	order.OrderTime = common.Time(time.Now())
+	if s.ControlBy.UpdateBy != 0 {
+		order.UpdateBy = s.UpdateBy
+	}
+	if s.ControlBy.CreateBy != 0 {
+		order.CreateBy = s.CreateBy
+	}
+	if s.DeptBy.DeptId != 0 {
+		order.DeptId = s.DeptId
+	}
+}
 
 func (s *OrderInsertReq) GetId() interface{} {
 	return s.Id
 }
+func (s *OrderAppletInsertReq) GetId() interface{} {
+	return s.Id
+}
 
 type OrderUpdateReq struct {
 	Id               int    `json:"id" comment:"编码" swaggerignore:"true"` // 编码

+ 13 - 0
app/admin/service/dto/store.go

@@ -103,3 +103,16 @@ type StoreEnterReq struct {
 func (s *StoreEnterReq) GetId() interface{} {
 	return s.Id
 }
+
+// SysDeptGetPageReq 列表或者搜索使用结构体
+type AppletStoreGetPageReq struct {
+	Name     string `form:"name" search:"type:contains;column:name;table:sys_dept" example:"部门名称"`    //销售门店名称
+	District string `form:"district" search:"-" example:"520100"`                                     //所在地市
+	City     string `form:"city" search:"-" example:"520115"`                                         //所在区县
+	Type     int    `form:"type" search:"type:exact;column:type;table:sys_dept" swaggerignore:"true"` //公司类型
+	StoreOrder
+}
+
+func (m *AppletStoreGetPageReq) GetNeedSearch() interface{} {
+	return *m
+}

+ 1 - 1
app/admin/service/dto/sys_user.go

@@ -317,7 +317,7 @@ type PassWord struct {
 }
 
 type SysUserGetSMSVerifyCodeReq struct {
-	Phone string `json:"phone" example:"13912345678"` //手机号
+	Phone string `form:"phone" example:"13912345678"` //手机号
 }
 type GetNewestTokenReq struct {
 	UserId int64 `uri:"userId" example:"1"` //手机号

+ 109 - 0
app/admin/service/order.go

@@ -11,6 +11,7 @@ import (
 	common "gas-cylinder-api/common/model"
 	"gogs.baozhida.cn/zoie/OAuth-core/service"
 	"gorm.io/gorm"
+	"gorm.io/gorm/utils"
 	"time"
 )
 
@@ -98,6 +99,114 @@ func (e *Order) Insert(c *dto.OrderInsertReq) error {
 	return nil
 
 }
+func (e *Order) AppletInsert(c *dto.OrderAppletInsertReq) error {
+	var err error
+	var data model.Order
+
+	tx := e.Orm.Begin()
+	defer func() {
+		if err != nil {
+			tx.Rollback()
+		} else {
+			tx.Commit()
+		}
+	}()
+	// 查询小程序客户是否存在
+	customerId := c.CustomerId + "_" + utils.ToString(c.DeptId)
+	var customer model.Customer
+	err = e.Orm.
+		Where("id = ?", c.CustomerId).
+		First(&customer).Error
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.CreateFailedErr
+	}
+
+	store, err := model.GetProvCodeById(c.StoreId)
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.CreateFailedErr
+	}
+
+	// 查询门店客户是否存在
+	var storeCustomer model.Customer
+
+	err = e.Orm.
+		Where("id = ?", customerId).
+		First(&storeCustomer).Error
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		if errors.Is(err, gorm.ErrRecordNotFound) {
+			// TODO 1.1.1.16新增客户信息
+			// 添加客户
+			obj := model.Customer{
+				ProvCustomer: model.ProvCustomer{
+					Id:             customerId,
+					PrincipalName:  customer.Name,
+					PrincipalPhone: customer.PrincipalPhone,
+					ShopName:       customer.Name,
+					Address:        c.Address,
+					AddressImg:     customer.AddressImg,
+					Lng:            c.Lng,
+					Lat:            c.Lat,
+					Type:           customer.Type,
+					City:           c.City,
+					Area:           c.Area,
+					Remark:         c.Remark,
+					StoreCode:      store.CmpCode,
+				},
+				Name: customer.Name,
+				DeptBy: common.DeptBy{
+					DeptId: c.StoreId,
+				},
+			}
+			obj.IsSyncProv = true // TODO
+			err = tx.Create(&obj).Error
+			if err != nil {
+				e.Log.Errorf("db error: %s", err)
+				return global.CreateFailedErr
+			}
+			c.Id = data.Id
+
+			dataIntegrity := CustomerCheckDataIntegrity(obj)
+			if dataIntegrity {
+				obj.IsSyncProv = true
+			}
+		} else {
+			return global.CreateFailedErr
+		}
+	}
+
+	if len(storeCustomer.ProvCustomer.Id) > 0 {
+		storeCustomer.Lng = c.Lng
+		storeCustomer.Lat = c.Lat
+		storeCustomer.City = c.City
+		storeCustomer.Area = c.Area
+		storeCustomer.Address = c.Address
+		err = tx.Save(&data).Error
+		dataIntegrity := CustomerCheckDataIntegrity(storeCustomer)
+		if dataIntegrity {
+			storeCustomer.IsSyncProv = true
+		}
+		// TODO 更新客户信息
+		if err != nil {
+			e.Log.Errorf("db error: %s", err)
+			return global.UpdateFailedErr
+		}
+	}
+
+	// 添加订单
+	c.Generate(&data)
+	data.CustomerId = customerId
+	err = tx.Create(&data).Error
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.CreateFailedErr
+	}
+	c.Id = data.Id
+	return nil
+
+}
 
 // Update 修改Order对象
 func (e *Order) Update(c *dto.OrderUpdateReq, p *actions.DataPermission) error {

+ 83 - 0
app/admin/service/store.go

@@ -229,6 +229,58 @@ func (e Store) getList(c *dto.StoreGetPageReq, list *[]model.SysDept, p *actions
 	return nil
 }
 
+func StoreDistrictScopes(area string) func(db *gorm.DB) *gorm.DB {
+
+	return func(db *gorm.DB) *gorm.DB {
+		if len(area) == 0 {
+			return db
+		}
+		return db.Where("JSON_EXTRACT(prov_store, '$.district') = ? ", area)
+	}
+}
+
+func StoreCityScopes(city string) func(db *gorm.DB) *gorm.DB {
+
+	return func(db *gorm.DB) *gorm.DB {
+		if len(city) == 0 {
+			return db
+		}
+		return db.Where("JSON_EXTRACT(prov_store, '$.city') = ? ", city)
+	}
+}
+func (e Store) getAppletList(c *dto.AppletStoreGetPageReq, list *[]model.SysDept) error {
+	var err error
+	var data model.SysDept
+
+	var tempList []model.SysDept
+	err = e.Orm.Model(&data).
+		Scopes(
+			cDto.MakeCondition(c.GetNeedSearch()),
+			StoreDistrictScopes(c.District),
+			StoreCityScopes(c.City),
+		).
+		Find(&tempList).Error
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.GetFailedErr
+	}
+
+	// 获取部门及其子部门下ID
+	for _, dept := range tempList {
+		var deptList = make([]model.SysDept, 0)
+		err = e.Orm.Where("path like ?", dept.Path+"%").Order(fmt.Sprintf("sort %s", c.SortOrder)).Find(&deptList).Error
+		*list = append(*list, deptList...)
+	}
+	if err != nil {
+		e.Log.Errorf("db error: %s", err)
+		return global.GetFailedErr
+	}
+
+	*list = DeduplicateStore(*list)
+
+	return nil
+}
+
 // SetStorePage 设置Dept页面数据
 func (e *Store) SetStorePage(c *dto.StoreGetPageReq, p *actions.DataPermission) (m []model.SysDept, err error) {
 	var list []model.SysDept
@@ -261,6 +313,37 @@ func (e *Store) SetStorePage(c *dto.StoreGetPageReq, p *actions.DataPermission)
 
 	return
 }
+func (e *Store) SetAppletStorePage(c *dto.AppletStoreGetPageReq) (m []model.SysDept, err error) {
+	var list []model.SysDept
+	err = e.getAppletList(c, &list)
+	for i := 0; i < len(list); i++ {
+		if list[i].ParentId != 0 {
+			continue
+		}
+		info := e.StorePageCall(&list, list[i])
+		m = append(m, info)
+	}
+
+	if len(m) == 0 {
+		parentMap, flag := getStoreParent(list)
+		if flag {
+			for i := 0; i < len(list); i++ {
+				if parentMap[list[i].ParentId] {
+					continue
+				}
+				info := e.StorePageCall(&list, list[i])
+				m = append(m, info)
+			}
+		} else {
+			for i := 0; i < len(list); i++ {
+				info := e.StorePageCall(&list, list[i])
+				m = append(m, info)
+			}
+		}
+	}
+
+	return
+}
 
 func getStoreParent(deptList []model.SysDept) (map[int]bool, bool) {
 	list := deptList