瀏覽代碼

first commit

kptcwq911 2 年之前
當前提交
3260e64acd
共有 100 個文件被更改,包括 10700 次插入0 次删除
  1. 二進制
      .DS_Store
  2. 19 0
      .vscode/launch.json
  3. 21 0
      LICENSE
  4. 0 0
      README.md
  5. 173 0
      README2.md
  6. 二進制
      apiserver/.DS_Store
  7. 48 0
      apiserver/config/config.go
  8. 84 0
      apiserver/dao/dao.go
  9. 34 0
      apiserver/dao/db.go
  10. 108 0
      apiserver/model/PartRefund.go
  11. 95 0
      apiserver/model/Partquit.go
  12. 10 0
      apiserver/model/brand.go
  13. 56 0
      apiserver/model/buydetail.go
  14. 58 0
      apiserver/model/contract.go
  15. 20 0
      apiserver/model/department.go
  16. 71 0
      apiserver/model/equipment.go
  17. 130 0
      apiserver/model/http/asset.go
  18. 48 0
      apiserver/model/http/charge_off.go
  19. 10 0
      apiserver/model/http/http.go
  20. 46 0
      apiserver/model/http/material.go
  21. 131 0
      apiserver/model/http/order.go
  22. 250 0
      apiserver/model/http/proof.go
  23. 50 0
      apiserver/model/http/sap.go
  24. 93 0
      apiserver/model/http/supplier.go
  25. 46 0
      apiserver/model/http/transfer.go
  26. 38 0
      apiserver/model/log.go
  27. 90 0
      apiserver/model/mcs.go
  28. 54 0
      apiserver/model/models.go
  29. 45 0
      apiserver/model/part.go
  30. 31 0
      apiserver/model/part_purchase.go
  31. 28 0
      apiserver/model/part_reportery.go
  32. 111 0
      apiserver/model/partlaid.go
  33. 125 0
      apiserver/model/partuse.go
  34. 32 0
      apiserver/model/pasture.go
  35. 39 0
      apiserver/model/proof.go
  36. 28 0
      apiserver/model/provider.go
  37. 48 0
      apiserver/model/transfer.go
  38. 14 0
      apiserver/model/warehouse.go
  39. 二進制
      apiserver/routers/.DS_Store
  40. 57 0
      apiserver/routers/api/api.go
  41. 3263 0
      apiserver/routers/api/db.go
  42. 553 0
      apiserver/routers/api/upload.go
  43. 119 0
      apiserver/routers/api/user.go
  44. 223 0
      apiserver/routers/api/v1/menu.go
  45. 228 0
      apiserver/routers/api/v1/role.go
  46. 34 0
      apiserver/routers/job.go
  47. 31 0
      apiserver/routers/mcs.go
  48. 15 0
      apiserver/routers/part.go
  49. 二進制
      apiserver/routers/restful/.DS_Store
  50. 1322 0
      apiserver/routers/restful/sql_utils.go
  51. 91 0
      apiserver/routers/restful/test.go
  52. 61 0
      apiserver/routers/restful/user.go
  53. 198 0
      apiserver/routers/router.go
  54. 40 0
      apiserver/routers/sap.go
  55. 47 0
      apiserver/routers/server.go
  56. 二進制
      apiserver/service/.DS_Store
  57. 104 0
      apiserver/service/apisql_service/apisql_service.go
  58. 130 0
      apiserver/service/asset.go
  59. 332 0
      apiserver/service/charge_off.go
  60. 43 0
      apiserver/service/eas.go
  61. 30 0
      apiserver/service/job.go
  62. 105 0
      apiserver/service/material.go
  63. 190 0
      apiserver/service/mcs.go
  64. 145 0
      apiserver/service/order.go
  65. 185 0
      apiserver/service/part.go
  66. 439 0
      apiserver/service/proof.go
  67. 50 0
      apiserver/service/sap.go
  68. 72 0
      apiserver/service/service.go
  69. 106 0
      apiserver/service/supplier.go
  70. 160 0
      apiserver/service/transfer.go
  71. 29 0
      apiserver/service/user_service/user.go
  72. 3 0
      bk/bat/arm.bat
  73. 1 0
      bk/bat/doc.bat
  74. 3 0
      bk/bat/linux64.bat
  75. 3 0
      bk/bat/win32.bat
  76. 4 0
      bk/bat/win64.bat
  77. 二進制
      bk/browse/dist0624/.DS_Store
  78. 0 0
      bk/browse/dist0624/datas/myMap.json
  79. 二進制
      bk/browse/dist0624/favicon.ico
  80. 0 0
      bk/browse/dist0624/index.html
  81. 0 0
      bk/browse/dist0624/static/css/app.1c97fb9d.css
  82. 0 0
      bk/browse/dist0624/static/css/chunk-elementUI.45ab9bc1.css
  83. 0 0
      bk/browse/dist0624/static/css/chunk-libs.2e418612.css
  84. 二進制
      bk/browse/dist0624/static/fonts/element-icons.535877f5.woff
  85. 二進制
      bk/browse/dist0624/static/fonts/element-icons.732389de.ttf
  86. 二進制
      bk/browse/dist0624/static/img/1.1ddf085a.png
  87. 二進制
      bk/browse/dist0624/static/img/404.a57b6f31.png
  88. 二進制
      bk/browse/dist0624/static/img/404_cloud.0f4bc32b.png
  89. 二進制
      bk/browse/dist0624/static/img/cow.3495de2a.jpg
  90. 二進制
      bk/browse/dist0624/static/img/login-bg.dfe7c90f.jpg
  91. 二進制
      bk/browse/dist0624/static/img/login-bg1.1f1602f0.jpg
  92. 二進制
      bk/browse/dist0624/static/img/login-bujian.8695940d.png
  93. 二進制
      bk/browse/dist0624/static/img/logo.4a74cb8a.png
  94. 二進制
      bk/browse/dist0624/static/img/logo1.d2343c0f.png
  95. 二進制
      bk/browse/dist0624/static/img/logo_u3.34a9ffae.png
  96. 0 0
      bk/browse/dist0624/static/js/app.1f5f7ce2.js
  97. 0 0
      bk/browse/dist0624/static/js/chunk-581b2547.35f5db31.js
  98. 0 0
      bk/browse/dist0624/static/js/chunk-d17f893e.ab3f161f.js
  99. 0 0
      bk/browse/dist0624/static/js/chunk-elementUI.e7d11236.js
  100. 0 0
      bk/browse/dist0624/static/js/chunk-fb16bab8.723f5a84.js

二進制
.DS_Store


+ 19 - 0
.vscode/launch.json

@@ -0,0 +1,19 @@
+{
+    // Use IntelliSense to learn about possible attributes.
+    // Hover to view descriptions of existing attributes.
+    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
+    "version": "0.2.0",
+    "configurations": [
+    
+    
+
+        {
+            "name": "Launch Package",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": "${fileDirname}",
+            // "args":["--conf","/Users/desire/kptdev/xdmy_mod/cmd/"]
+        }
+    ]
+}

+ 21 - 0
LICENSE

@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) The go-admin Authors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.

+ 0 - 0
README.md


+ 173 - 0
README2.md

@@ -0,0 +1,173 @@
+# KPTYUN
+
+一个go api 后端例子,包含JWT,RBAC(Casbin),增删改查, 一键生成 Restful API接口(不依赖orm)。
+
+## 主要说明
+* v1.1.2
+
+### 表
+* user     
+    * username  password   
+* role      
+    * name 
+* menu     
+    * name path   method
+
+### 目录结构
+* conf:用于存储配置文件
+* docs: 文档(SQL和API注释)
+* logs: 日志
+* middleware:应用中间件
+* models:应用数据库模型
+* pkg:第三方包
+* routers: 路由逻辑处理
+* service: 逻辑处理
+* test: 单元测试
+
+
+### 权限验证说明
+>  利用的casbin库, 将  user  role  menu 进行自动关联
+
+```
+项目启动时,会自动加载权限. 如有更改,会删除对应的权限,重新加载.
+
+用户关联角色  
+角色关联菜单  
+
+权限关系为:
+角色(role.name,menu.path,menu.method)  
+用户(user.username,role.name)
+
+例如:
+test      /api/v1/users       GET
+zhuhongbin     test
+
+当zhuhongbin  GET  /api/v1/users 地址的时候,会去检查权限,因为他属于test组,同时组有对应权限,所以本次请求会通过。
+
+用户 admin 有所有的权限,不进行权限匹配
+
+登录接口 /auth  不进行验证
+```
+
+### 请求
+
+> 请求和接收 都是 传递 json 格式 数据
+```
+例如:
+访问 /auth    获取token
+{
+	"username": "admin",
+	"password": "123456"
+}
+
+访问  /api/v1/users   
+请求头设置  Authorization: Token xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+
+```
+
+## How to run
+
+### Required
+
+- Mysql
+
+### Ready
+
+Create a **go database** and import [SQL](docs/sql/go.sql)
+
+创建一个库,然后导入sql,创建表!
+
+### Conf
+
+You should modify `conf/app.ini`
+
+```
+[database]
+Type = mysql
+User = root
+Password =
+Host = 127.0.0.1:3306
+Name = go
+TablePrefix = go_
+```
+
+## Installation
+```
+
+yum install go -y 
+
+
+cd $GOPATH/src/github.com/kptyun/go-admin
+go build main.go
+go run  main.go 
+
+## 热编译,开发时使用
+
+go get github.com/silenceper/gowatch
+
+gowatch   
+
+```
+
+### Run
+```
+Project information and existing API
+
+[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
+ - using env:	export GIN_MODE=release
+ - using code:	gin.SetMode(gin.ReleaseMode)
+
+Listening port is 8000
+
+默认 账户 密码 都为  123456
+
+```
+
+* 不用orm依赖,直接输入表名字就可以 增删改查 
+
+``` 
+
+get   http://127.0.0.1:8000/api/restful/go_user
+get   http://127.0.0.1:8000/api/restful/go_user/1
+post   http://127.0.0.1:8000/api/restful/go_user
+数据格式  json  支持批量
+[{
+	"username":"hequan",
+	"password":"hequan1",
+	"created_on": "0",
+	"modified_on":"0",
+	"deleted_on":"0"
+}]
+put  http://127.0.0.1:8000/api/restful/go_user/2
+数据格式  json
+{
+	"password":"654321"
+}
+delete http://127.0.0.1:8000/api/restful/go_user/2
+```
+
+###  API  注释
+
+> http://127.0.0.1:8000/swagger/index.html
+
+
+## Features
+```
+- RESTful API
+- Gorm
+- logging
+- Jwt-go
+- Swagger
+- Gin
+- Graceful restart or stop (fvbock/endless)
+- App configurable
+- 一键生成 Restful API接口
+```
+
+## 其他
+```shell
+##更新注释
+swag init
+
+
+```

二進制
apiserver/.DS_Store


+ 48 - 0
apiserver/config/config.go

@@ -0,0 +1,48 @@
+package config
+
+import (
+	"time"
+
+	"github.com/BurntSushi/toml"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/setting"
+)
+
+var (
+	confPath string
+	Conf     = &Config{}
+)
+
+type Http struct {
+	TimeOut time.Duration `toml:"timeout"`
+	SapName string        `toml:"sapname"`
+	SapPwd  string        `toml:"sappwd"`
+}
+type Config struct {
+	DB   *MySQLConfig `toml:"db"`
+	Http *Http        `toml:"http"`
+}
+type MySQLConfig struct {
+	DSN         string        `toml:"dsn"`
+	Active      int           `toml:"active"`
+	Idle        int           `toml:"idle"`
+	IdleTimeout time.Duration `toml:"idle_timeout"`
+}
+
+// func init() {
+// 	flag.StringVar(&confPath, "tconf", "", "default config path")
+// }
+
+func Init(p string) (err error) {
+	if p != "" {
+		confPath = p
+	} else {
+		confPath, err = setting.GetCurrentPath()
+	}
+	confPath += "conf/conf.toml"
+	if _, err = toml.DecodeFile(confPath, &Conf); err != nil {
+		log.Error("config Init : %v", err)
+		return
+	}
+	return
+}

+ 84 - 0
apiserver/dao/dao.go

@@ -0,0 +1,84 @@
+package dao
+
+import (
+	"fmt"
+	"os"
+	"time"
+
+	"gorm.io/gorm/logger"
+	"gorm.io/gorm/schema"
+
+	// "github.com/xormplus/xorm"
+	// "github.com/xormplus/xorm"
+
+	"gorm.io/driver/mysql"
+	"gorm.io/gorm"
+
+	// _ "github.com/jinzhu/gorm/dialects/mysql"
+	// "github.com/jinzhu/gorm"
+	"kpt.xdmy/apiserver/config"
+	"kpt.xdmy/apiserver/routers/restful"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/setting"
+)
+
+var D *Dao
+
+type Dao struct {
+	DB *gorm.DB
+}
+
+func New(conf *config.Config) *Dao {
+	newLogger := logger.New(
+		log.New(os.Stdout, "\r\n"), // io writer
+		logger.Config{
+			SlowThreshold:             time.Second,  // Slow SQL threshold
+			LogLevel:                  logger.Error, // Log level
+			IgnoreRecordNotFoundError: false,        // Ignore ErrRecordNotFound error for logger
+			Colorful:                  true,         // Disable color
+			// LogMode:
+		})
+	gc := &gorm.Config{
+		NamingStrategy: schema.NamingStrategy{
+			SingularTable: true,
+			NoLowerCase:   true,
+		},
+		Logger: newLogger,
+		// Logger: logger.Default.LogMode(logger.Silent),
+	}
+
+	db, err := gorm.Open(mysql.Open(conf.DB.DSN), gc)
+	tx := db.Session(&gorm.Session{Logger: newLogger})
+	// db.LogMode(true)
+	if err != nil {
+		log.Error("model.Setup err: %v", err, conf.DB.DSN)
+	}
+	sqlDB, _ := db.DB()
+	// SetMaxOpenConns 设置打开数据库连接的最大数量。
+	sqlDB.SetMaxOpenConns(100)
+	// SetMaxIdleConns 设置空闲连接池中连接的最大数量
+	sqlDB.SetMaxIdleConns(10)
+	// SetConnMaxLifetime 设置了连接可复用的最大时间。
+	sqlDB.SetConnMaxLifetime(300 * time.Second)
+	D = &Dao{
+		DB: tx,
+	}
+	return D
+}
+func Setup() {
+	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
+		setting.DatabaseSetting.User,
+		setting.DatabaseSetting.Password,
+		setting.DatabaseSetting.Host,
+		setting.DatabaseSetting.Name)
+	// restful  接口的 数据库初始化
+	err := restful.SQLInit("mysql", dsn, 500, 50, setting.DatabaseSetting.ShowXormlog)
+	if err != nil {
+		log.Fatal("dao Setup ", err)
+		fmt.Println("dbs 数据库初始化失败 ")
+	}
+
+	if err != nil {
+		log.Fatal("dao  Setup ", err)
+	}
+}

+ 34 - 0
apiserver/dao/db.go

@@ -0,0 +1,34 @@
+package dao
+
+import "github.com/pkg/errors"
+
+func (d *Dao) First(pi interface{}) error {
+	e := d.DB.Where(pi).First(pi).Error
+	return errors.Wrapf(e, "model First %v", pi)
+}
+func (d *Dao) Insert(pi interface{}) error {
+	e := d.DB.Create(pi).Error
+	return errors.Wrapf(e, "model Insert %v", pi)
+}
+func (d *Dao) Find(c map[string]interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Find(pi).Error
+	return errors.Wrapf(e, "Find %v", c)
+}
+func (d *Dao) Update(c map[string]interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Updates(pi).Error
+	return errors.Wrapf(e, "Update %v \n%v", c, pi)
+}
+func (d *Dao) UpdateAll(c map[string]interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Select("*").Updates(pi).Error
+	return errors.Wrapf(e, "UpdateAll %v \n%v", c, pi)
+}
+
+func (d *Dao) Raw(sql string, args map[string]interface{}, r interface{}) error {
+	e := d.DB.Raw(sql, args).Scan(r).Error
+	return errors.Wrapf(e, "model Raw %s, %v", sql, args)
+}
+
+func (d *Dao) InsertOrUpdate(pi interface{}) {
+	// d.DB.FirstOrCreate(pi)
+	// d.DB.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "id"}}, DoUpdates: clause.AssignmentColumns([]string{"code"})}).Create(&nm)
+}

+ 108 - 0
apiserver/model/PartRefund.go

@@ -0,0 +1,108 @@
+package model
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/pkg/util"
+)
+
+type BigPartRefundReq struct {
+	PastureID  int    `json:"pastureId"`
+	ProviderID int    `json:"providerId"`
+	UseForm    string `json:"useForm"`
+	EmployeID  int    `json:"employeId"`
+	CreateTime string `json:"createTime"`
+	Note       string `json:"note"`
+}
+
+type BigPartRefund struct {
+	// 退货
+	ID            int `gorm:"column:id"`
+	CGChargeID    int `gorm:"column:CGChargeId"`
+	ChargeID      int `gorm:"column:chargeId"`
+	EmployeID     int `gorm:"column:employeId"`
+	BigPartlaidID int `gorm:"column:bigPartlaidId"`
+	PastureID     int `gorm:"column:pastureId"`
+	ProviderID    int `gorm:"column:providerId"`
+
+	UseForm     string `gorm:"column:useForm"`
+	RefundClass int    `gorm:"column:refundClass"`
+	Issync      int    `gorm:"column:issync"`
+
+	CGChargedate string    `gorm:"column:CGChargedate"`
+	ChargeDate   string    `gorm:"column:chargeDate"`
+	CreateTime   time.Time `gorm:"column:createTime"`
+
+	Msg          string `gorm:"column:msg"`
+	Note         string `gorm:"column:note"`
+	Statue       int    `gorm:"column:statue"`
+	WorkflowNote string `gorm:"column:workflowNote"`
+	ProofCode    string `gorm:"column:proofCode"`
+}
+
+type PartRefund struct {
+	// 退货明细
+	ID            int     `gorm:"column:id"`
+	BigID         int     `gorm:"column:bigId"`
+	ContractID    int     `gorm:"column:contractId"`
+	PartID        int     `gorm:"column:partId"`
+	Brand         string  `gorm:"column:brand"`
+	Location      string  `gorm:"column:location"`
+	Note          string  `gorm:"column:note"`
+	PartCode      string  `gorm:"column:partCode"`
+	PartName      string  `gorm:"column:partName"`
+	Price         float32 `gorm:"column:price"`
+	RefundNumber  float32 `gorm:"column:refundNumber"`
+	Reportery     string  `gorm:"column:reportery"`
+	Specification string  `gorm:"column:specification"`
+	SumPrice      float32 `gorm:"column:sumPrice"`
+	Unit          string  `gorm:"column:unit"`
+	Dflag         int     `gorm:"column:dflag"`
+	RowNumber     int     `gorm:"column:rowNumber"`
+}
+
+func (p *PartRefund) ToProofPart() (r *ProofPart) {
+	r = &ProofPart{
+		RowNumber:     p.RowNumber,
+		PartCode:      p.PartCode,
+		PartName:      p.PartName,
+		Specification: p.Specification,
+		PartBrand:     p.Brand,
+		Warehouse:     p.Location,
+		ChangeCount:   p.RefundNumber,
+		UnitPrice:     p.Price,
+		TotalPrice:    p.SumPrice,
+	}
+	return
+}
+
+func (p *BigPartRefund) NewProof(pa *ProofReq) {
+	pa.ChargeDate = p.CreateTime.Format("2006-01-02")
+	pa.ProofCode = p.UseForm
+	pa.ProofYear = p.CreateTime.Format("2006")
+	pa.OrderNumberId = p.ID
+}
+
+func (p *BigPartRefund) NewProofPart() (mps []ProofPart, e error) {
+	path := " BigPartRefund NewProofPart()"
+
+	c := util.NewMap("bigid", p.ID)
+	m := make([]PartRefund, 0)
+	if e = Find(c, &m); e != nil {
+		e = errors.Wrapf(e, path)
+		return
+	}
+	mps = make([]ProofPart, 0)
+	mp := new(ProofPart)
+	for i, v := range m {
+		mp = v.ToProofPart()
+		mp.RowNumber = i
+		mps = append(mps, *mp)
+	}
+	return
+}
+
+type RefundParam struct {
+	ID string `json:"id"`
+}

+ 95 - 0
apiserver/model/Partquit.go

@@ -0,0 +1,95 @@
+package model
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/pkg/util"
+)
+
+type BigPartquit struct {
+	// 退库
+	CreatDate string    `gorm:"column:creatDate"`
+	DeptID    int       `gorm:"column:deptId"`
+	ID        int       `gorm:"column:id"`
+	Issync    int       `gorm:"column:issync"`
+	ListType  int       `gorm:"column:listType"`
+	Msg       string    `gorm:"column:msg"`
+	Note      string    `gorm:"column:note"`
+	OddNumber string    `gorm:"column:oddNumber"`
+	PastureID int       `gorm:"column:pastureId"`
+	QuitDate  time.Time `gorm:"column:quitDate"`
+	QuitID    int       `gorm:"column:quitId"`
+	SumPrice  float32   `gorm:"column:sumPrice"`
+	UseForm   string    `gorm:"column:useForm"` // 出库单号
+	ProofCode string    `gorm:"column:proofCode"`
+}
+
+type Partquit struct {
+	// 退库详情
+	ApplyNumber   string  `gorm:"column:applyNumber"`
+	BigID         int     `gorm:"column:bigId"`
+	Brand         string  `gorm:"column:brand"`
+	ContractID    int     `gorm:"column:contractId"`
+	ID            int     `gorm:"column:id"`
+	Location      string  `gorm:"column:location"`
+	Note          string  `gorm:"column:note"`
+	PartCode      string  `gorm:"column:partCode"`
+	PartID        int     `gorm:"column:partId"`
+	PartName      string  `gorm:"column:partName"`
+	PartUseID     int     `gorm:"column:partUseId"`
+	Price         float32 `gorm:"column:price"`
+	ProviderID    int     `gorm:"column:providerId"`
+	ProviderName  string  `gorm:"column:providerName"`
+	QuitNumber    float32 `gorm:"column:quitNumber"`
+	Reportery     string  `gorm:"column:reportery"`
+	Specification string  `gorm:"column:specification"`
+	SumPrice      float32 `gorm:"column:sumPrice"`
+	Unit          string  `gorm:"column:unit"`
+	UseNumber     string  `gorm:"column:useNumber"`
+	Dflag         int     `gorm:"column:dflag"`
+	RowNumber     int     `gorm:"column:rowNumber"`
+}
+
+func (p *Partquit) ToProofPart() (r *ProofPart) {
+
+	r = &ProofPart{
+		RowNumber:     p.RowNumber,
+		PartCode:      p.PartCode,
+		PartName:      p.PartName,
+		Specification: p.Specification,
+		PartBrand:     p.Brand,
+		Supplier:      p.ProviderName,
+		Warehouse:     p.Location,
+		ChangeCount:   p.QuitNumber,
+		UnitPrice:     p.Price,
+		TotalPrice:    p.SumPrice,
+	}
+	return
+}
+
+func (p *BigPartquit) NewProof(pa *ProofReq) {
+	pa.ChargeDate = p.QuitDate.Format("2006-01-02")
+	pa.ProofCode = p.UseForm
+	pa.ProofYear = p.QuitDate.Format("2006")
+	pa.OrderNumberId = p.ID
+}
+
+func (p *BigPartquit) NewProofPart() (mps []ProofPart, e error) {
+	path := " BigPartquit NewProofPart()"
+
+	c := util.NewMap("bigid", p.ID)
+	m := make([]Partquit, 0)
+	if e = Find(c, &m); e != nil {
+		e = errors.Wrapf(e, path)
+		return
+	}
+	mps = make([]ProofPart, 0)
+	mp := new(ProofPart)
+	for i, v := range m {
+		mp = v.ToProofPart()
+		mp.RowNumber = i
+		mps = append(mps, *mp)
+	}
+	return
+}

+ 10 - 0
apiserver/model/brand.go

@@ -0,0 +1,10 @@
+package model
+
+import "time"
+
+type Brand struct {
+	ID         int       `gorm:"column:id" `
+	BrandName  string    `gorm:"column:brandName" `
+	Enable     int       `gorm:"column:enable" `
+	CreateTime time.Time `gorm:"column:createTime" `
+}

+ 56 - 0
apiserver/model/buydetail.go

@@ -0,0 +1,56 @@
+package model
+
+import (
+	"time"
+)
+
+type BigBuyDetail struct {
+	// 采购订单
+	ID           int       `json:"id"  gorm:"column:id"`
+	DoneDate     time.Time `json:"DoneDate"  gorm:"column:DoneDate"`
+	ArrivalStatu int       `json:"arrivalStatu"  gorm:"column:arrivalStatu"`
+	BuyeCode     string    `json:"buyeCode"  gorm:"column:buyeCode"`
+	BuyerDate    time.Time `json:"buyerDate"  gorm:"column:buyerDate"`
+	BuyerPerson  int       `json:"buyerPerson"  gorm:"column:buyerPerson"`
+	Enable       int       `json:"enable"  gorm:"column:enable"`
+	MatchCode    string    `json:"matchCode"  gorm:"column:matchCode"`
+	Note         string    `json:"note"  gorm:"column:note"`
+	PastureID    int       `json:"pastureId"  gorm:"column:pastureId"`
+	ProviderID   int       `json:"providerId"  gorm:"column:providerId"`
+	Statu        int       `json:"statu"  gorm:"column:statu"`
+	ZeroCou      int       `json:"zeroCou"  gorm:"column:zeroCou"` //配单数量
+
+	SapNumber string `json:"sapNumber"  gorm:"column:sapNumber"`
+	SapStatus int    `json:"sapStatus"  gorm:"column:sapStatus"`
+}
+type BuyDetail struct {
+	// 采购订单明细
+	ID int `json:"id" gorm:"column:id"`
+	// Model
+	Amount         int       `json:"amount" gorm:"column:amount"`
+	BigID          int       `json:"bigId" gorm:"column:bigId"`
+	BrandID        int       `json:"brandId" gorm:"column:brandId"`
+	ContractID     int       `json:"contractId" gorm:"column:contractId"`
+	PastureID      int       `json:"pastureId" gorm:"column:pastureId"`
+	ContractCode   string    `json:"contractCode" gorm:"column:contractCode"`
+	DepartmentName string    `json:"departmentName" gorm:"column:departmentName"`
+	IsStorage      int       `json:"isStorage" gorm:"column:isStorage"`
+	ReceiveDate    time.Time `json:"receiveDate" gorm:"column:receiveDate"`
+	PartCode       string    `json:"partCode" gorm:"column:partCode"`
+	Price          float64   `json:"price" gorm:"column:price"`
+	ReceiveAmount  string    `json:"receiveAmount" gorm:"column:receiveAmount"`
+	Statue         int       `json:"statue" gorm:"column:statue"`
+	Remark         string    `json:"remark" gorm:"column:remark"`
+	Note           string    `json:"note" gorm:"column:note"`
+	StoredQuantity string    `json:"storedQuantity" gorm:"column:storedQuantity"`
+	SumAmount      int       `json:"sumAmount" gorm:"column:sumAmount"`
+	Enable         int       `json:"enable" gorm:"column:enable"`
+	Dflag          int       `json:"dflag" gorm:"column:dflag"`
+	Unit           string
+	IsZeroStock    int
+	RowNumber      int `json:"rowNumber" gorm:"column:rowNumber"`
+}
+type BigBuyDetailReq struct {
+	Code string `json:"matchCode" gorm:"column:matchcode"`
+	ID   string `json:"id" gorm:"column:id"`
+}

+ 58 - 0
apiserver/model/contract.go

@@ -0,0 +1,58 @@
+package model
+
+import "time"
+
+type BigContract struct {
+	ID              int       `gorm:"column:id"`
+	CGChargeID      int       `gorm:"column:CGChargeId"`
+	CGChargedate    time.Time `gorm:"column:CGChargedate"`
+	KGChargeID      int       `gorm:"column:KGChargeId"`
+	KGChargedate    time.Time `gorm:"column:KGChargedate"`
+	SHStatus        int       `gorm:"column:SHStatus"`
+	SHdateTime      time.Time `gorm:"column:SHdateTime"`
+	SHtype          int       `gorm:"column:SHtype"`
+	ChargeDate      time.Time `gorm:"column:chargeDate"`
+	ChargeID        int       `gorm:"column:chargeId"`
+	ContractCode    string    `gorm:"column:contractCode"`
+	CreatorID       int       `gorm:"column:creatorId"`
+	ProviderID      int       `gorm:"column:providerId"`
+	CreatorMan      string    `gorm:"column:creatorMan"`
+	CreatorTime     string    `gorm:"column:creatorTime"`
+	Enable          int       `gorm:"column:enable"`
+	Flag            int       `gorm:"column:flag"`
+	FlowCompeleted  int       `gorm:"column:flowCompeleted"`
+	IsZeroStock     int       `gorm:"column:isZeroStock"`
+	PastureID       int       `gorm:"column:pastureId"`
+	PastureNamesNow string    `gorm:"column:pastureNamesNow"`
+	PastureNamesOld string    `gorm:"column:pastureNamesOld"`
+	PrecontractCode string    `gorm:"column:precontractCode"`
+	ProviderName    string    `gorm:"column:providerName"`
+	Remark          string    `gorm:"column:remark"`
+	StartTime       string    `gorm:"column:startTime"`
+	Statue          int       `gorm:"column:statue"`
+	StopTime        string    `gorm:"column:stopTime"`
+	StopTimeHis     time.Time `gorm:"column:stopTimeHis"`
+	StopTimeTem     time.Time `gorm:"column:stopTimeTem"`
+	WorkflowID      int       `gorm:"column:workflowId"`
+	WorkflowNote    string    `gorm:"column:workflowNote"`
+}
+type Contract struct {
+	ID            int    `gorm:"column:id"`
+	BigID         int    `gorm:"column:bigId"`
+	Brand         string `gorm:"column:brand"`
+	BrandID       int    `gorm:"column:brandId"`
+	ChangeID      int    `gorm:"column:changeId"`
+	Enable        int    `gorm:"column:enable"`
+	InventoryType int    `gorm:"column:inventoryType"`
+	IsZeroStock   int    `gorm:"column:isZeroStock"`
+	PartCode      string `gorm:"column:partCode"`
+	PartID        int    `gorm:"column:partId"`
+	PartName      string `gorm:"column:partName"`
+	PastureID     int    `gorm:"column:pastureId"`
+	PastureName   string `gorm:"column:pastureName"`
+	PlanAmount    string `gorm:"column:planAmount"`
+	Price         string `gorm:"column:price"`
+	Remark        string `gorm:"column:remark"`
+	Specification string `gorm:"column:specification"`
+	Unit          string `gorm:"column:unit"`
+}

+ 20 - 0
apiserver/model/department.go

@@ -0,0 +1,20 @@
+package model
+
+type Department struct {
+	KCcode         string `gorm:"column:KCcode"`
+	XRCode         string `gorm:"column:XRCode"`
+	Address        string `gorm:"column:address"`
+	DeptCode       string `gorm:"column:deptCode"`
+	Enable         int    `gorm:"column:enable"`
+	ID             int    `gorm:"column:id"`
+	IsDel          int    `gorm:"column:isDel"`
+	IsGroupco      int    `gorm:"column:isGroupco"`
+	IsPasture      int    `gorm:"column:isPasture"`
+	Iscal          int    `gorm:"column:iscal"`
+	Name           string `gorm:"column:name"`
+	Parentid       int    `gorm:"column:parentid"`
+	PastureID      int    `gorm:"column:pastureId"`
+	Remark         string `gorm:"column:remark"`
+	Sort           string `gorm:"column:sort"`
+	CostCenterCode string `gorm:"column:costCenter_code"`
+}

+ 71 - 0
apiserver/model/equipment.go

@@ -0,0 +1,71 @@
+package model
+
+import "time"
+
+type Equipment struct {
+	PastureId      int    `gorm:"column:pastureId"`
+	PastureName    string `gorm:"column:pastureName"`
+	EqName         string `gorm:"column:eqName"`
+	AssetCode      string `gorm:"column:assetCode"`
+	EqClassName    string `gorm:"column:eqClassName"`
+	Specification  string `gorm:"column:specification"`
+	DepartmentId   string `gorm:"column:departmentId"`
+	DepartmentName string `gorm:"column:departmentName"`
+	EntranceDate   string `gorm:"column:entranceDate"`
+	Purpose        string `gorm:"column:purpose"`
+	Yuanzhi        string `gorm:"column:yuanzhi"`
+
+	Id           int    `gorm:"column:id"`
+	EqCode       string `gorm:"column:eqCode"`
+	EqClassId    int    `gorm:"column:eqClassId"`
+	FinanceCode  string `gorm:"column:financeCode"`
+	ProName      string `gorm:"column:proName"`
+	ProId        int    `gorm:"column:proId"`
+	BrandId      string `gorm:"column:brandId"`
+	Brand        string `gorm:"column:brand"`
+	PurchaseDate string `gorm:"column:purchaseDate"`
+
+	Subtractvalue    string    `gorm:"column:subtractvalue"`
+	Salvage          string    `gorm:"column:salvage"`
+	Upkeepgrade      string    `gorm:"column:upkeepgrade"`
+	YearMaintainCost string    `gorm:"column:yearMaintainCost"`
+	YearUpkeepCost   string    `gorm:"column:yearUpkeepCost"`
+	Status           int       `gorm:"column:status"`
+	EmployeName      string    `gorm:"column:employeName"`
+	EmployeeId       string    `gorm:"column:employeeId"`
+	InputDatetime    string    `gorm:"column:inputDatetime"`
+	LeaveDate        time.Time `gorm:"column:leaveDate"`
+	InputUser        string    `gorm:"column:inputUser"`
+	EnabledTime      time.Time `gorm:"column:enabledTime"`
+	BlockTime        time.Time `gorm:"column:blockTime"`
+	ChangeStatue     string    `gorm:"column:changeStatue"`
+	EnabledPerson    int       `gorm:"column:enabledPerson"`
+	BlockPerson      int       `gorm:"column:blockPerson"`
+	SttId            int       `gorm:"column:sttId"`
+	BaseHours        string    `gorm:"column:baseHours"`
+	ApplicatId       int       `gorm:"column:applicatId"`
+	ApplicatDate     time.Time `gorm:"column:applicatDate"`
+	WorkflowId       int       `gorm:"column:workflowId"`
+	FlowCompeleted   int       `gorm:"column:flowCompeleted"`
+	Enable           int       `gorm:"column:enable"`
+	ChangeTime       time.Time `gorm:"column:changeTime"`
+	SSTstatue        string    `gorm:"column:SSTstatue"`
+	SHStatus         int       `gorm:"column:SHStatus"`
+	ChargeId         int       `gorm:"column:chargeId"`
+	ChargeDate       time.Time `gorm:"column:chargeDate"`
+	WorkflowNote     string    `gorm:"column:workflowNote"`
+	Picpath          string    `gorm:"column:picpath"`
+	Depreciation     string    `gorm:"column:depreciation"`
+
+	Statue       int       `gorm:"column:statue"`
+	ModifyTime   time.Time `gorm:"column:modifyTime"`
+	CreatedAt    time.Time `gorm:"column:created_at"`
+	UpdatedAt    time.Time `gorm:"column:updated_at"`
+	CompanyCode  string    `gorm:"column:companyCode"`
+	Quantity     string    `gorm:"column:quantity"`
+	CostCenter   string    `gorm:"column:costCenter"`
+	Unit         string    `gorm:"column:unit"`
+	ProfitCenter string    `gorm:"column:profitCenter"`
+
+	SonCode string `gorm:"column:sonCode"`
+}

+ 130 - 0
apiserver/model/http/asset.go

@@ -0,0 +1,130 @@
+package http
+
+import (
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/util"
+)
+
+type AssetResp struct {
+	Dest Dest          `json:"DEST"`
+	Data AssetRespData `json:"DATA"`
+}
+type AssetRespData struct {
+	RespMsg SapRespMsg `json:"MSGER"`
+	Master  []Asset    `json:"TANLA"`
+}
+type Asset struct {
+	CompanyCode string `json:"BUKRS"` //公司代码
+	SonCode     string `json:"ANLN2"` //资产子编号  默认0
+	Quantity    string `json:"MENGE"` //数量
+
+	Name       string `json:"TXT50"` //资产名称
+	AssetCode  string `json:"ANLN1"` //资产编码
+	Type       string `json:"ANLKL"` //资产类型
+	Model      string `json:"TXA50"` //资产规格
+	CostCenter string `json:"KOSTL"` //成本中心
+
+	Unit             string `json:"MEINS"`  //计量单位
+	ProfitCenter     string `json:"PRCTR"`  //利润中心
+	BuyDate          string `json:"ZUGDT"`  //购买日期
+	BuyValue         string `json:"KANSW"`  //购买价值
+	Salvage          string `json:"AHPROZ"` //残值率  百分比
+	Udate            string `json:"UDATE"`  //更新日期
+	Utime            string `json:"UTIME"`  //更新时间
+	NDPER            string `json:"NDPER"`  //计划 使用时间
+	Dflag            string `json:"XSPEB"`  // 删除标记
+	DepreciationYear string `json:"NDJAR"`  //折旧年限
+	Supplier         string `json:"LIFNR"`  //供应商
+	TransferFlag     string `json:"ORD44"`  //传输Y/不传输N ,删除X
+	ORD41            string `json:"ORD41"`  // 资产状态
+
+	Segment string `json:"SEGMENT"` //细分	段
+	ORD42   string `json:"ORD42"`   //资产变动方式	出售/购入/其他/其他减少/其他增加/调拨/在建工程转入
+	RAUMN   string `json:"RAUMN"`   //房间	存储资产的位置
+}
+
+type AssetReq struct {
+	Dest `json:"DEST"`
+	Data AssetReqData `json:"DATA"`
+}
+
+type Company struct {
+	Code string `json:"BUKRS"`
+}
+type AssetReqData struct {
+	BudatB      string        `json:"BUDAT_B"` //查询开始日期	YYYYMMDD,资产创建/变更
+	BudatE      string        `json:"BUDAT_E"` //查询结束日期	YYYYMMDD,资产创建/变更
+	CompanyCode []Company     `json:"TBUKRS"`  //公司代码	现代牧业的法人
+	Codes       []TANLN1      `json:"TANLN1"`  //主资产号	财务资产码
+	EqType      []interface{} `json:"TANLKL"`  //资产类	设备类别
+	Tord41      []interface{} `json:"TORD41"`  //资产状态	在用/转移/报废
+	Tzugdt      []interface{} `json:"TZUGDT"`  //购置日期	购置日期(首次)
+}
+type TANLN1 struct {
+	Code string `json:"ANLN1"` //主资产号,	财务资产码
+}
+
+func (p *AssetReq) NewReq() {
+	p.Dest = Dest{
+		DestID: "EQMAN",
+		BussTp: "FI004",
+		Url:    "https://app.modernfarming.cn:7443/sap/EAM/FI004/QueryAsset",
+	}
+	// s := model.SapLogTime(p.Dest.BussTp)
+	dt := AssetReqData{
+		// BudatB: s.Format("20060102"),
+		// BudatE: time.Now().Format("20060102"),
+		BudatB: "20220823",
+		BudatE: "20220823",
+	}
+	// dt.CompanyCode = []Company{
+	// 	{Code: "9099"},
+	// }
+	p.Data = dt
+}
+func (p *Asset) ToEquipment(m *model.Equipment) (e error) {
+	t, ei := util.ParseDateAndTime(p.Udate, p.Utime)
+	log.Errorf(e, "http asset ToEquipment ParseDateAndTime error %s %s", p.Udate, p.Utime)
+	if ei != nil {
+		return ei
+	}
+	m.PastureId = 18
+	m.SHStatus = 1
+	m.Status = 17
+
+	m.EqName = p.Name
+	m.AssetCode = p.AssetCode
+	m.EqClassName = p.Type
+	m.Specification = p.Model
+	m.EntranceDate = p.BuyDate
+	m.Yuanzhi = p.BuyValue
+	m.ModifyTime = t
+	m.Enable = util.Zero(p.Dflag == "")
+
+	m.CompanyCode = p.CompanyCode
+	m.Quantity = p.Quantity
+	m.CostCenter = p.CostCenter
+	m.Unit = p.Unit
+	m.ProfitCenter = p.ProfitCenter
+
+	m.EqCode = p.AssetCode
+
+	// 	`equipment`
+	// 	INNER JOIN pasture p
+	// 	  ON p.`id` = equipment.`pastureId`
+	// 	left JOIN department d
+	// 	  ON d.`id` = equipment.departmentId
+	// 	  #LEFT JOIN dictlist
+	// 	  #ON equipment.`status` = dictlist.id
+	//   WHERE (equipment.pastureId=? or  ?=18)
+	//    and (equipment.eqName LIKE CONCAT('%',?,'%') OR ?='' )
+	//    AND (equipment.eqCode LIKE CONCAT('%',?,'%') OR ?='')
+	//    AND (equipment.assetCode LIKE CONCAT('%',?,'%') OR ?='')
+	//    AND equipment.`enable` = '1' and (equipment.SHStatus = 3 or equipment.SHStatus=1)
+	//    and equipment.`status`=17
+	return
+	// m.PastureName = p.ProfitCenter
+	// m.DepartmentId = p.CostCenter
+	// m.DepartmentName = p.CostCenter
+}

+ 48 - 0
apiserver/model/http/charge_off.go

@@ -0,0 +1,48 @@
+package http
+
+import (
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/util"
+)
+
+type ChargeOffReq struct {
+	Dest `json:"DEST"`
+	Data ChargeOff `json:"DATA"`
+}
+
+type ChargeOffDetail struct {
+	RowNumber int `json:"ZEILE"`
+}
+
+type ChargeOff struct {
+	ProofCode   string            `json:"MBLNR"`  // 物料凭证号
+	ProofYear   string            `json:"MJAHR"`  // 物料凭证年度
+	ChargeDate  string            `json:"BUDAT"`  // 凭证中的过帐日期 YYYYMMDD
+	OrderNumber string            `json:"FRBNR"`  // 设备管理平台单号
+	RowsNumber  []ChargeOffDetail `json:"TMSEG"`  // 设备管理平台行号
+	HasTicket   string            `json:"ZTHFLG"` // 是否已开票退货单	"是: X ,※仅采购业务需要
+}
+
+func (c *ChargeOffReq) NewDest() {
+	c.Dest = Dest{
+		DestID: "EQMAN",
+		BussTp: "MM015",
+		Url:    "https://app.modernfarming.cn:7443/sap/Common/MM015/CancelMblnr",
+	}
+}
+func (c *ChargeOffReq) NewReq(p *model.ProofReq) {
+	c.NewDest()
+	h := ChargeOff{
+		ProofCode:   p.ProofCode,
+		ProofYear:   p.ProofYear,
+		ChargeDate:  p.ChargeDate,
+		OrderNumber: p.OrderNumber,
+		HasTicket:   util.ZeroStr(p.HasTicket == 1, "X"),
+	}
+	s := make([]ChargeOffDetail, len(p.RowsNumber))
+	for v := range p.RowsNumber {
+		s = append(s, ChargeOffDetail{RowNumber: v})
+	}
+	h.RowsNumber = s
+	c.Data = h
+}

+ 10 - 0
apiserver/model/http/http.go

@@ -0,0 +1,10 @@
+package http
+
+type Response struct {
+	Success bool        `json:"success"`
+	
+	Code    int         `json:"code"`
+	Message string      `json:"message"`
+	Data    interface{} `json:"data"`
+	Msg     string      `json:"msg"`
+}

+ 46 - 0
apiserver/model/http/material.go

@@ -0,0 +1,46 @@
+package http
+
+type MaterialReqData struct {
+	BudatB string  `json:"BUDAT_B"` //起始日期
+	BudatE string  `json:"BUDAT_E"` //结束日期
+	Codes  []MATNR `json:"TMATNR"`  //物料编码
+	Type   MTART   `json:"TMTART"`  //物料类型
+	Group  []MATKL `json:"TMATKL"`  //物料组
+}
+type MATKL struct {
+	MATKL string `json:"MATKL"` //物料组
+}
+type MATNR struct {
+	Code string `json:"MATNR"` //物料编码
+}
+type MTART struct {
+	MTART string `json:"MTART"`
+}
+type MaterialReq struct {
+	Dest `json:"DEST"`
+	Data MaterialReqData `json:"DATA"`
+}
+
+type MaterialResp struct {
+	Dest `json:"DEST"`
+	Data Material `json:"DATA"`
+}
+type Material struct {
+	Master []MaterialDetail `json:"TMARA"`
+	Msger  SapRespMsg       `json:"MSGER"`
+}
+
+type MaterialDetail struct {
+	Code          string `json:"MATNR"` // 物料号
+	Type          string `json:"MTART"` // 物料类型
+	Group         string `json:"MATKL"` // 物料组
+	Description   string `json:"MAKTX"` // 物料描述
+	Unit          string `json:"MEINS"` // 基本计量单位
+	UnitNum       string `json:"UMREZ"` // 基本计量单位数量
+	SwitchUnit    string `json:"MEINH"` // 转换单位
+	SwitchUnitNum string `json:"UMREN"` // 转换单位数量
+	Name          string `json:"ZMINC"` // 物料名称
+	Model         string `json:"ZGUIG"` // 规格型号
+	Dflag         string `json:"LVORM"` // 物料删除标记
+	ModifyTime    string `json:"LAEDA"` // 修改日期
+}

+ 131 - 0
apiserver/model/http/order.go

@@ -0,0 +1,131 @@
+package http
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+
+	"kpt.xdmy/apiserver/dao"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/util"
+)
+
+type OrderResp struct {
+	Dest `json:"DEST"`
+	Data OrderRespData `json:"DATA"`
+}
+
+type OrderRespData struct {
+	Status    string `json:"MSGTY"`
+	MsgText   string `json:"MSGTX"`
+	EqNumber  string `json:"EXT01"`
+	SapNumber string `json:"EXT02"`
+}
+type OrderReq struct {
+	Dest `json:"DEST"`
+	Data Order `json:"DATA"`
+}
+type Order struct {
+	CompanyCode  string `json:"BUKRS"`  // 公司代码
+	SupplierCode string `json:"LIFNR"`  // 供应商编码
+	IsCancle     string `json:"ZKHFLG"` // 是否退货  "是:X
+	ProofType    string `json:"BSART"`  // 采购凭证类型 字典
+	OrderDate    string `json:"BEDAT"`  // 订单日期
+	Organization string `json:"EKORG"`  // 采购组织 字典
+	Group        string `json:"EKGRP"`  // 采购组 字典
+	PayCondition string `json:"ZTERM"`  // 付款条件 字典
+	CurrencyCode string `json:"WAERS"`  // 货币码	默认:CNY
+	EqSysCode    string `json:"ZEBELN"` // 订单编号
+
+	Detail []OrderDetail `json:"TEKPO"`
+}
+type OrderDetail struct {
+	IsOwn        string `json:"PSTYP"` // 自有订单,"自有:空// 寄售:'K' "
+	MaterialCode string `json:"MATNR"` //物料编码
+	Quantity     string `json:"MENGE"` // 数量
+	DeliveryDate string `json:"EINDT"` // 交货日期
+	Unit         string `json:"MEINS"` // 单位
+	NetPrice     string `json:"NETPR"` // 净价
+	Per          string `json:"PEINH"` // 每	默认:1
+	Factory      string `json:"WERKS"` // 工厂
+	Location     string `json:"LGORT"` //库存地点 字典
+	IsFree       string `json:"UMSON"` //是否免费 "是:X
+	TaxCode      string `json:"MWSKZ"` // 税码 字典
+	RowNumber    string `json:"EBELP"` //行号
+	Dflag        string `json:"LOEKZ"` // 删除标识 "是:L// 否:空"
+}
+
+func (o *OrderReq) NewReq(p *model.BigBuyDetail) (e error) {
+	path := "http OrderReq NewReq"
+	o.Dest = Dest{
+		DestID: "EQMAN",
+		BussTp: "MM007",
+		Url:    "https://app.modernfarming.cn:7443/sap/Common/MM007/PurchaseOrder",
+	}
+	pv := &model.Provider{ID: p.ProviderID}
+	ps := &model.Pasture{ID: p.PastureID}
+	bds := make([]model.BuyDetail, 0)
+	c := util.NewMap("bigid", p.ID)
+	sl := make([]OrderDetail, 0)
+	if e = model.First(pv); e != nil {
+		log.Printf("%s:采购订单供应商查不到", path)
+		return
+	}
+	if e = model.First(ps); e != nil {
+		log.Printf("%s:采购订单牧场查不到", path)
+		return
+	}
+	model.Find(c, &bds)
+	if len(bds) == 0 {
+		e = errors.Errorf("%s:采购订单明细查询为空", path)
+		log.Print(e.Error())
+		return
+	}
+	o.Data = Order{
+		IsCancle:     "",
+		SupplierCode: "100224",
+		OrderDate:    p.BuyerDate.Format("20060102"),
+		PayCondition: "",
+		CompanyCode:  "1004",
+		CurrencyCode: "CNY",
+		ProofType:    "ZNB4",
+		EqSysCode:    p.BuyeCode[4:],
+		// EqSysCode:    "A0001",
+		Organization: "9099",
+		Group:        "A02",
+		// CompanyCode:  ps.PastureNumber,
+		// SupplierCode: pv.ProviderNumber,
+		// OrderDate:    p.BuyerDate.Format("20060102"),
+	}
+	for _, v := range bds {
+
+		dao.D.DB.Raw(`SELECT p.partcode from parts p join contract c on c.partid=p.id where 
+		c.id=?`, v.ContractID).Scan(&v.PartCode)
+
+		pd := OrderDetail{
+			// Quantity:     v.Amount,
+			// DeliveryDate: v.ReceiveDate.Format("20060102"),
+			// IsOwn:        util.ZeroStr(c.IsZeroStock == 1, "K"),
+			// NetPrice: v.Price,
+			// Unit:     ps.Unit,
+			// Factory:   p.Data.CompanyCode,
+			// Location: "",
+			// IsFree:   "",
+			MaterialCode: v.PartCode,
+			// MaterialCode: "14.01.07.01.000243",
+			Quantity:     "11",
+			DeliveryDate: p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102"),
+			Unit:         "EA",
+			NetPrice:     "11",
+			Per:          "1",
+			Factory:      "M001",
+			TaxCode:      "J0",
+			RowNumber:    "10",
+		}
+		sl = append(sl, pd)
+	}
+	o.Data.Detail = sl
+	return
+}
+

+ 250 - 0
apiserver/model/http/proof.go

@@ -0,0 +1,250 @@
+package http
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/apiserver/dao"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/util"
+)
+
+type ProofReq struct {
+	Dest `json:"DEST"`
+	Data ProofReqData `json:"DATA"`
+}
+
+type ProofReqData struct {
+	CreateTime string        `json:"BLDAT"` //业务日期
+	PostDate   string        `json:"BUDAT"` //过账日期
+	EqNumber   string        `json:"FRBNR"` //设备管理平台单号(入库、退货、领用、退库)
+	Detail     []ProofDetail `json:"MSEG"`
+}
+type ProofDetail struct {
+	RowNumber   string `json:"ZEILE"` //行号,入库单行号
+	Code        string `json:"MATNR"` //物料编码
+	Factory     string `json:"WERKS"` //工厂
+	Location    string `json:"LGORT"` //库存地点
+	Quantity    string `json:"MENGE"` //数量
+	Unit        string `json:"MEINS"` //单位
+	OrderNumber string `json:"EBELN"` //采购订单号,※仅采购入库业务传输,SAP的采购订单号
+	OrderRowNum string `json:"EBPLP"` //采购订单行项目号,※仅采购入库业务传输,SAP的采购订单行项目号
+	MoveType    string `json:"BWART"` //出入库类型 ,"采购入库:101// 退货:161// 领用:201// 退库:202(字典)// 报废:Z19"
+	SaveType    string `json:"SOBKZ"` //库存类型 特殊库存标识	"自有:空// 寄售:'K' " ,寄售表示零库存,1
+	CostCenter  string `json:"KOSTL"` //成本中心,※仅领用、退库时,输入,编码
+	AssetCode   string `json:"ANLN1"` //资产,※仅领用、退库时,财务资产码
+	AssetSon    string `json:"ANLN2"` //资产子项
+	Provider    string `json:"LIFNR"` //供应商编码,仅寄售入库业务时,输入
+}
+
+// "ZEILE": "1",
+// "MATNR": "14.01.01.01.000071",
+// "WERKS": "",
+// "LGORT": "1001",
+// "MENGE": "11.000000",
+// "MEINS": "M2",
+// "EBELN": "4900000026",
+// "EBPLP": "1",
+// "BWART": "101",
+// "SOBKZ": "",
+// "KOSTL": "",
+// "ANLN1": "",
+// "ANLN2": "",
+// "LIFNR": ""
+type ProofResp struct {
+	Dest Dest          `json:"DEST"`
+	Data ProofRespData `json:"DATA"`
+}
+
+type ProofRespData struct {
+	Status    string `json:"MSGTY"`
+	MsgText   string `json:"MSGTX"`
+	EqNumber  string `json:"EXT01"`
+	SapNumber string `json:"EXT02"`
+	Ext03     string `json:"EXT03"`
+}
+
+type BigPartRefundReq struct {
+	PastureID  int    `json:"pastureId"`
+	ProviderID int    `json:"providerId"`
+	UseForm    string `json:"useForm"`
+	EmployeID  int    `json:"employeId"`
+	CreateTime string `json:"createTime"`
+	Note       string `json:"note"`
+}
+
+type ProofPartReq struct {
+	ID           int    `json:"id"`
+	PastureID    int    `json:"pastureId"`
+	ProviderID   int    `json:"providerId"`
+	DepartmentID int    `json:"departmentId"`
+	EmpID        string `json:"empId"`
+	EmployeID    int    `json:"employeId"`
+	Note         string `json:"note"`
+
+	ApplicatID int `json:"applicatId"`
+	LaidType   int `json:"laidType"` //入库类型
+	UseType    int `json:"useType"`  //出库类型
+
+	LaidCode   string `json:"laidCode"`   // 入库单号
+	PurchaseID string `json:"purchaseId"` // 入库单采购单号
+	BuyCode    string `json:"No1Id"`      // 入库单采购订单号
+	UseForm    string `json:"useForm"`    // 出库单号,退库单号,退货单号
+	OddCode    string `json:"oddCode"`    // 领用单号
+
+	StorageTime string `json:"storageTime"` // 入库时间
+	CreateTime  string `json:"createTime"`  // 退货时间
+	ReceiveTime string `json:"receiveTime"` // 出库时间
+	QuitDate    string `json:"quitDate"`    // 退库时间
+
+	PartCode  string
+	SapNumber string `json:"sapNumber"`
+}
+
+func (p *ProofReq) NewReq(pr *ProofPartReq, orderType int) (e error) {
+
+	p.Dest = Dest{
+		DestID: "EQMAN",
+		BussTp: "MM001",
+		Url:    "https://app.modernfarming.cn:7443/sap/Common/MM001/ModifyMblnr",
+	}
+
+	switch orderType {
+	case 1:
+		t, _ := util.ParseDate(pr.StorageTime)
+		ds := []ProofDetail{}
+
+		data := ProofReqData{
+			PostDate: t.Format("20060102"),
+			EqNumber: pr.LaidCode,
+		}
+		dao.D.DB.Raw(`select bp.partcode,bd.SapNumber from partlaid p 
+		join bigpartlaid bp on p.bigid=bp.id  
+		left join bigBuydetail bd on bp.purchaseId=bd.buyecode
+		 where bp.laidcode=?`, pr.LaidCode).Scan(&pr)
+		// Factory:     ,
+		// Location:    v.LocationID,
+		// Quantity: v.ReceivedAmount,
+		// Unit:     v.Unit,
+		detail := ProofDetail{
+			// RowNumber: 1,
+			// Code:      "14.01.07.01.000243",
+			Code:        pr.PartCode,
+			Factory:     "M001",
+			Location:    "1004",
+			Quantity:    "3",
+			Unit:        "EA",
+			OrderNumber: pr.SapNumber,
+
+			OrderRowNum: "10",
+			MoveType:    "101",
+		}
+		ds = append(ds, detail)
+		data.Detail = ds
+		p.Data = data
+	case 2:
+		if pr.UseForm == "" {
+			e = errors.New("退货单号为空")
+			return
+		}
+		t, e := time.Parse("2006-01-02", pr.CreateTime)
+		if e != nil {
+			log.Errorf(e, "退货时间解析错误")
+		}
+		p.Data = ProofReqData{
+			PostDate: t.Format("20060102"),
+			EqNumber: pr.UseForm,
+		}
+		dao.D.DB.Raw(`select pf.partcode from PartRefund pf 
+		join bigPartRefund bpf on pf.bigid=bpf.id
+		where bpf.useform=?`, pr.UseForm).Scan(&pr.PartCode)
+		ds := []ProofDetail{}
+		detail := ProofDetail{
+			RowNumber:   "1",
+			Code:        pr.PartCode,
+			Factory:     "M001",
+			Location:    "1004",
+			Quantity:    "1",
+			Unit:        "EA",
+			MoveType:    "161",
+			OrderNumber: "4900000005",
+			OrderRowNum: "10",
+		}
+		ds = append(ds, detail)
+		p.Data.Detail = ds
+	case 3:
+		t, e := util.ParseDate(pr.ReceiveTime)
+		if e != nil {
+			return errors.Errorf("出库凭证 时间解析错误 time=%s", pr.ReceiveTime)
+		}
+		data := ProofReqData{
+			PostDate: t.Format("20060102"),
+			EqNumber: pr.UseForm,
+		}
+		dao.D.DB.Raw(`select partcode from partuse p 
+		join bigpartuse bp on p.bigid=bp.id where bp.useForm=?`, pr.UseForm).Scan(&pr.PartCode)
+		ds := []ProofDetail{}
+		detail := ProofDetail{
+			// RowNumber: 1,
+			// Code:      "14.01.07.01.000243",
+			Code:     pr.PartCode,
+			Factory:  "M001",
+			Location: "1004",
+			Quantity: "1",
+			Unit:     "EA",
+			MoveType: "201",
+			// CostCenter: "1004",
+			AssetCode: "40501000000",
+
+			CostCenter: "9099010506",
+		}
+		ds = append(ds, detail)
+		data.Detail = ds
+		p.Data = data
+
+	// Location:    v.LocationID,
+	// OrderNumber: v.BigBuyerID,
+	// Code: v.PartCode,
+	// Quantity: v.ReceivedAmount,
+	// Unit:     v.Unit,
+	// RowNumber:   1,
+
+	// Code:        "14.01.01.01.000001",
+	// Factory:     "M001",
+	// Location:    "1004",
+	// Quantity:    "10",
+	// Unit:        "EA",
+	// OrderNumber: "4900000003",
+	// OrderRowNum: "10",
+	// MoveType:    "101",
+	case 4: //退库
+		t, e := util.ParseDate(pr.QuitDate)
+		if e != nil {
+			return errors.Errorf("退库凭证 时间解析错误 QuitDate=%s,useform=%s", pr.QuitDate, pr.UseForm)
+		}
+		data := ProofReqData{
+			PostDate: t.Format("20060102"),
+			EqNumber: pr.UseForm,
+		}
+		if e := dao.D.DB.Raw(`select partcode from partuse p 
+	join bigpartuse bp on p.bigid=bp.id where bp.useForm=?`, pr.UseForm).Scan(&pr.PartCode).Error; e != nil {
+			return errors.Errorf("退库凭证 备件编号查询错误 useform=%s", pr.UseForm)
+		}
+		ds := []ProofDetail{}
+		detail := ProofDetail{
+			// RowNumber:  1,
+			Code:       pr.PartCode,
+			Factory:    "M001",
+			Location:   "1004",
+			Quantity:   "1",
+			Unit:       "EA",
+			MoveType:   "202",
+			AssetCode:  "40501000000",
+			CostCenter: "9099010506",
+		}
+		ds = append(ds, detail)
+		data.Detail = ds
+		p.Data = data
+	}
+	return
+}

+ 50 - 0
apiserver/model/http/sap.go

@@ -0,0 +1,50 @@
+package http
+
+import "kpt.xdmy/pkg/http"
+
+type Dest struct {
+	DestID   string `json:"DEST_ID"`
+	BussTp   string `json:"BUSS_TP"`
+	MessID   string `json:"MESS_ID"`
+	Status   string `json:"STATUS"`
+	MessText string `json:"MESS_TEXT"`
+	StatusOs string `json:"STATUS_OS"`
+	Url      string
+}
+
+type SapResp struct {
+	Dest `json:"DEST"`
+	Data SapRespMsg `json:"DATA"`
+}
+
+type SapRespMsg struct {
+	Status      string `json:"MSGTY"`
+	Text        string `json:"MSGTX"`
+	ProofNumber string `json:"EXT01"`
+	ProofYear   string `json:"EXT02"`
+	EqNumber    string `json:"EXT03"`
+}
+
+var SapAuth *http.Auth
+
+type SapQueryReq struct {
+	Dest Dest            `json:"DEST"`
+	Data SapQueryReqData `json:"DATA"`
+}
+type SapQueryReqData struct {
+}
+type SapDest interface {
+	GetUrl() string
+	GetName() string
+	GetDest() *Dest
+}
+
+func (d *Dest) GetUrl() string {
+	return d.Url
+}
+func (d *Dest) GetName() string {
+	return d.BussTp
+}
+func (d *Dest) GetDest() *Dest {
+	return d
+}

+ 93 - 0
apiserver/model/http/supplier.go

@@ -0,0 +1,93 @@
+package http
+
+type SupplierReq struct {
+	Dest `json:"DEST"`
+	Data SupplierReqData `json:"DATA"`
+}
+
+type SupplierReqData struct {
+	BudatB      string   `json:"BUDAT_B"` //开始日期
+	BudatE      string   `json:"BUDAT_E"` //结束日期
+	CompanyCode string   `json:"BUKRS"`   //公司代码
+	Code        []string `json:"TLIFNR"`  //供应商编码
+	Types       []ZSORT  `json:"TZSORT"`  //供应商类型
+}
+type ZSORT struct {
+	Type string `json:"ZSORT"`
+}
+type SupplierResp struct {
+	Dest Dest         `json:"DEST"`
+	Data SupplierData `json:"DATA"`
+}
+type SupplierData struct {
+	Master []Supplier `json:"TLFA1"`
+	MSGER  SapRespMsg `json:"MSGER"`
+}
+
+type Supplier struct {
+	Code        string `json:"LIFNR"` //供应商编码
+	Name        string `json:"NAME1"` //供应商名称
+	ShortName   string `json:"SORTL"` //简称
+	Contact     string `json:"ZCONT"` //供应商联系人
+	Phone       string `json:"ZTELP"` //供应商联系方式
+	Mail        string `json:"ZEMAL"` //邮箱
+	Dflag       string `json:"LOEVM"` //删除标记
+	UpDate      string `json:"UDATE"` //修改日期
+	UpTime      string `json:"UTIME"` //修改时间
+	CompanyCode string `json:"BUKRS"` //公司代码
+
+	TAXNUMBER  string `json:"TAXNUMBER"`    //税号
+	COUNTRY    string `json:"COUNTRY"`      //国家
+	REGION     string `json:"REGION"`       //地区
+	POST_CODE1 string `json:"POST_CODE1"`   //邮编
+	ZSORT      string `json:"ZSORT"`        //供应商分类
+	CITY1      string `json:"CITY1"`        //城市
+	STREET     string `json:"STREET"`       //街道门牌号
+	BANKS      string `json:"BANK_COUNTRY"` //开户行国家
+	BANKL      string `json:"BANKL"`        //银行代码
+	BANKN      string `json:"BANKN"`        //银行账号
+	KOINH      string `json:"KOINH"`        //账户持有人
+	ZRESP      string `json:"ZRESP"`        //法人
+}
+
+// func (p *SupplierReq) NewReq() {
+// 	// dest
+// 	p.Dest = Dest{
+// 		DestID: "EQMAN",
+// 		BussTp: "MM004",
+// 		Url:    "https://app.modernfarming.cn:7443/sap/Common/MM004/QuerySupplier/",
+// 	}
+// 	// time
+// 	// s := model.SapLogTime(p.Dest.BussTp)
+// 	// data
+// 	// s := []ZSORT{{ZSORT: "设备"}}
+// 	// s := make([]ZSORT, 0)
+// 	// s = append(s, ZSORT{ZSORT: "设备"})
+// 	d := SupplierReqData{
+// 		// BudatB:      s.Format("20060102"),
+// 		// BudatE:      time.Now().Local().Format("20060102"),
+// 		BudatB:      "20220815",
+// 		BudatE:      "20220816",
+// 		CompanyCode: "1004",
+// 		Type:        []ZSORT{{"设备"}},
+// 	}
+// 	p.Data = d
+// }
+
+// func (s *Supplier) ToProvider(p *model.Provider) error {
+// 	t, e := util.ParseDateAndTime(s.UpDate, s.UpTime)
+// 	if e != nil {
+// 		return errors.Wrapf(e, "http Transfer")
+// 	}
+// 	p.ProviderIntro = s.Name
+// 	p.ProviderName = s.ShortName
+// 	p.ProviderNumber = s.Code
+// 	p.CompanyCode = s.CompanyCode
+// 	p.SortName = s.ZSORT
+// 	p.Linkman = s.Contact
+// 	p.Email = s.Mail
+// 	p.Telphone = s.Phone
+// 	p.ModifyTime = t
+// 	p.Enable = util.Zero(s.Dflag == "")
+// 	return nil
+// }

+ 46 - 0
apiserver/model/http/transfer.go

@@ -0,0 +1,46 @@
+package http
+
+type TransferReq struct {
+	Dest `json:"DEST"`
+	Data TransferMaster `json:"DATA"`
+}
+
+type TransferMaster struct {
+	TransferCode string           `json:"ZEBELN"` //调拨单号
+	OrderDate    string           `json:"BEDAT"`  //订单日期	YYYYMMDD
+	PostDate     string           `json:"BUDAT"`  //过账日期	YYYYMMDD
+	Group        string           `json:"EKGRP"`  //采购组
+	Detail       []TransferDetail `json:"TEKPO"`  //行项目
+	// SupplierCode string           `json:"LIFNR"` //供应商编码
+	// Organization string           `json:"EKGRP"`
+}
+type TransferDetail struct {
+	RowNumber    string `json:"EBELP"` //行号
+	MaterialCode string `json:"MATNR"` //物料编码
+	Quantity     string `json:"MENGE"` //数量
+	Unit         string `json:"MEINS"` //单位
+	NetPrice     string `json:"NETPR"` //净价
+	DeliverDate  string `json:"EINDT"` // 交货日期
+	Per          string `json:"PEINH"`
+	OutFactory   string `json:"UMWRK"` //出厂工厂
+	OutLocation  string `json:"UMLGO"` //出厂库位
+	InFactory    string `json:"WERKS"` //入厂工厂
+	InLocation   string `json:"LGORT"` //入厂库位
+	TaxCode      string `json:"MWSKZ"` //税代码
+}
+
+type TransferResp struct {
+	Data TransferRespData `json:"DATA"`
+	Dest Dest             `json:"DEST"`
+}
+type TransferRespData struct {
+	Proof TransferProof `json:"EKKO"`
+}
+
+type TransferProof struct {
+	SapInCode      string `json:"EBELN"`  //					SAP调拨单号	SAP调入单号
+	SapOutCode     string `json:"VBELN"`  //					SAP交货单号	SAP调出单号
+	ProofCode      string `json:"MBLNR"`  //					SAP物料凭证号	SAP调入/调出凭证号
+	ProofYear      string `json:"MJAHR"`  //					SAP物料凭证年度	SAP调入/调出凭证号年度
+	EqTransferCode string `json:"ZEBELN"` //					设备管理平台的调拨单号
+}

+ 38 - 0
apiserver/model/log.go

@@ -0,0 +1,38 @@
+package model
+
+import (
+	"time"
+
+	"kpt.xdmy/pkg/util"
+)
+
+type SapLog struct {
+	ID        int       `gorm:"column:id" `
+	Flag      int       `gorm:"column:Flag"`
+	SysName   string    `gorm:"column:SysName"`
+	Name      string    `gorm:"column:Name"`
+	Url       string    `gorm:"column:Url"`
+	Status    string    `gorm:"column:Status"`
+	MsgText   string    `gorm:"column:MsgText"`
+	Param     string    `gorm:"column:Param"`
+	CreatedAt time.Time `gorm:"column:Created_At"`
+}
+
+type SapDetailLog struct {
+	ID        int       `gorm:"column:id " `
+	Name      string    `gorm:"column:name"`
+	Code      string    `gorm:"column:code"`
+	ErrorText string    `gorm:"column:error_text"`
+	CreatedAt time.Time `gorm:"column:created_at"`
+}
+
+func SapLogTime(name string) time.Time {
+	sql := "select created_at from saplog where name=@name and flag=1 order by id desc limit 1"
+	c := util.NewMap("name", name)
+	var t time.Time
+	d.Raw(sql, c, &t)
+	if t.IsZero() {
+		return time.Now().Add(-24 * time.Hour)
+	}
+	return t
+}

+ 90 - 0
apiserver/model/mcs.go

@@ -0,0 +1,90 @@
+package model
+
+import (
+	"fmt"
+	"time"
+)
+
+type McsPostDataResp struct {
+	Message string `json:"message"`
+	Error   int    `json:"error"`
+}
+type McsPostDataReq struct {
+	Method string  `json:"method"`
+	Data   McsData `json:"data"`
+	// can be null
+	Token string `json:"token"`
+	// no use param
+	Request bool  `json:"request"`
+	ID      int64 `json:"id"`
+}
+type McsData struct {
+	DevID    string `json:"devId"`
+	PeopleNo int    `json:"peopleNo"`
+	WorkNo   int    `json:"workNo"`
+	StorType int    `json:"storType"`
+}
+type McsVideo struct {
+	Id int `json:"id" gorm:"column:id"`
+
+	EmpId    int    `json:"empId" gorm:"column:empId"`
+	DeviceId string `json:"deviceId" gorm:"column:deviceId"`
+	UpkeepId int    `json:"upkeepId" gorm:"column:upkeepId"`
+
+	CreatedAt    time.Time `json:"createTime" gorm:"column:createTime"`
+	NewCreatedAt time.Time `json:"newCreateTime" gorm:"column:newCreateTime"`
+	Location     string    `json:"location"  gorm:"column:location"`
+	EndRecord    int       `json:"endRecord" gorm:"column:endRecord"`
+}
+type McsFilesRequest struct {
+	Did       string `json:"did"`
+	SessionId string `json:"sessionId"`
+	St        string `json:"St"`
+	Et        string `json:"et"`
+	Ft        string `json:"ft"`
+	Lt        string `json:"lt"`
+	Wno       int    `json:"wno"`
+	Pagesize  string `json:"pagesize"`
+	// can be null
+	Key  string `json:"key"`
+	Page string `json:"page"`
+}
+
+type McsFilesResponse struct {
+	Data []McsFile `json:"data"`
+}
+
+type McsFile struct {
+	Path      string `json:"path" gorm:"location"`
+	PeopleNo  string `json:"peopleNo" gorm:"empId"`
+	WorkNo    string `json:"workNo" gorm:"upkeepId"`
+	StartTime string `json:"startTime" gorm:"createTime"`
+	DevId     string `json:"devId" gorm:"deviceId"`
+	// EmpId     string `json:"empId" gorm:"empId"`
+}
+
+type McsAccount struct {
+	DeviceId string `json:"deviceId"`
+	UserID   string `json:"uId"`
+	Password string `json:"pwd"`
+}
+type McsResponse struct {
+	Success bool        `json:"success"`
+	Code    int         `json:"code"`
+	Message string      `json:"message"`
+	Data    interface{} `json:"data"`
+}
+
+func (m McsPostDataReq) Validate() bool {
+	return true
+}
+
+func (p *McsFilesRequest) Encode() string {
+	return "sessionId=" + p.SessionId + "&st=" + p.St + "&et=" + p.Et + "&did=" + p.Did + "&ft=" + p.Ft + "&lt=" + p.Lt + "&key=" + p.Key + "&page=" + p.Page + "&pagesize=" + p.Pagesize + "&wno=" + fmt.Sprintf("%d", p.Wno)
+}
+func (p *McsFilesRequest) Validate() bool {
+	return true
+}
+func (p *McsVideo) Validate() bool {
+	return true
+}

+ 54 - 0
apiserver/model/models.go

@@ -0,0 +1,54 @@
+package model
+
+import (
+	"github.com/pkg/errors"
+	"kpt.xdmy/apiserver/dao"
+	"kpt.xdmy/pkg/log"
+)
+
+var d *dao.Dao
+var m *Model
+
+type Model struct {
+	d *dao.Dao
+}
+
+func ModelInit(dao *dao.Dao) {
+	d = dao
+}
+
+// type Model struct {
+// 	ID int `json:"id" gorm:"column:id" `
+// }
+type Request interface {
+	Validate() bool
+}
+
+func First(pi interface{}) error {
+	e := d.DB.Where(pi).First(pi).Error
+	return errors.Wrapf(e, "model First ")
+}
+func Insert(pi interface{}) error {
+	e := d.DB.Create(pi).Error
+	return errors.Wrapf(e, "model Insert")
+}
+func Find(c map[string]interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Find(pi).Error
+	log.ErrorJ(e, "model Find ", c)
+	return e
+}
+func Update(c interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Updates(pi).Error
+	log.Errorf(e, "model Update %v, %v", c, pi)
+	return errors.Wrapf(e, "model Update ")
+}
+func UpdateAll(c map[string]interface{}, pi interface{}) error {
+	e := d.DB.Where(c).Select("*").Updates(pi).Error
+	log.ErrorJ(e, "model UpdateAll", c, pi)
+	return e
+}
+
+func Raw(sql string, args map[string]interface{}, r interface{}) error {
+	e := d.DB.Raw(sql, args).Scan(r).Error
+	return errors.Wrapf(e, "model Raw %s, %v", sql, args)
+}

+ 45 - 0
apiserver/model/part.go

@@ -0,0 +1,45 @@
+package model
+
+import (
+	"time"
+	// "kpt.xdmy/apiserver/model/http"
+	// "kpt.xdmy/apiserver/model/http"
+)
+
+type Parts struct {
+	ID            int    `gorm:"column:id" `
+	PartCode      string `gorm:"column:partCode"`      // 物料号
+	Name          string `gorm:"column:name"`          // 物料名称
+	Specification string `gorm:"column:specification"` // 规格型号
+	Unit          string `gorm:"column:unit"`          // 基本计量单位
+	Category      string `gorm:"column:category"`      // 物料类型
+	Note          string `gorm:"column:note"`          // 物料描述
+
+	Purpose      string `gorm:"column:purpose"`
+	Category2    string `gorm:"column:category2"`
+	Category3    string `gorm:"column:category3"`
+	Picpath      string `gorm:"column:picpath"`
+	WorkflowNote string `gorm:"column:workflowNote"`
+	Msg          string `gorm:"column:msg"`
+
+	CategoryId     int       `gorm:"column:categoryId"`
+	CategoryId2    int       `gorm:"column:categoryId2"`
+	CategoryId3    int       `gorm:"column:categoryId3"`
+	IsCommon       int       `gorm:"column:isCommon"`
+	CreatePersonId int       `gorm:"column:createPersonId"`
+	Enable         int       `gorm:"column:enable"`
+	Statue         int       `gorm:"column:statue"`
+	ChargeId       int       `gorm:"column:chargeId"`
+	Issync         int       `gorm:"column:issync"`
+	CreatedAt      time.Time `gorm:"column:created_at"`
+	ModifyTime     time.Time `gorm:"column:modifyTime"`
+	ChargeDate     time.Time `gorm:"column:chargeDate"`
+}
+
+// func (p *Parts) Update() error {
+// 	m := util.NewMap("partcode", p.PartCode)
+// 	return d.UpdateDB("parts", m, p)
+// }
+// func (p *Parts) Insert() error {
+// 	return d.InsertDB("parts", p)
+// }

+ 31 - 0
apiserver/model/part_purchase.go

@@ -0,0 +1,31 @@
+package model
+
+type Bigpartpurchase struct {
+	// 申购单
+	ID             int    `gorm:"column:id"`
+	CGChargeID     int    `gorm:"column:CGChargeId"`
+	CGChargedate   string `gorm:"column:CGChargedate"`
+	KGChargeID     int    `gorm:"column:KGChargeId"`
+	KGChargedate   string `gorm:"column:KGChargedate"`
+	BuyStatu       int    `gorm:"column:buyStatu"`
+	ChargeDate     string `gorm:"column:chargeDate"`
+	ChargeID       int    `gorm:"column:chargeId"`
+	CreateTime     string `gorm:"column:createTime"`
+	DepartmentID   int    `gorm:"column:departmentId"`
+	EmployeID      int    `gorm:"column:employeId"`
+	FlowCompeleted int    `gorm:"column:flowCompeleted"`
+	FlowworkNote   string `gorm:"column:flowworkNote"`
+	IsUrgent       int    `gorm:"column:isUrgent"`
+	MatchCode      string `gorm:"column:matchCode"`
+	OrderNumber    string `gorm:"column:orderNumber"`
+	PastureID      int    `gorm:"column:pastureId"`
+	ProviderID     int    `gorm:"column:providerId"`
+	Statue         int    `gorm:"column:statue"`
+	WorkflowID     int    `gorm:"column:workflowId"`
+	WorkflowNote   string `gorm:"column:workflowNote"`
+}
+
+// func (b *Bigpartpurchase) QueryByID(id int) {
+// 	m := util.NewMap("id", "1")
+// 	Fisrt("Bigpartpurchase", m, b)
+// }

+ 28 - 0
apiserver/model/part_reportery.go

@@ -0,0 +1,28 @@
+package model
+
+type PartRepertory struct {
+	Brand         string `gorm:"column:brand"`
+	BrandID       int    `gorm:"column:brandId"`
+	ContractID    int    `gorm:"column:contractId"`
+	Enable        int    `gorm:"column:enable"`
+	ID            int    `gorm:"column:id"`
+	Location      string `gorm:"column:location"`
+	LocationID    int    `gorm:"column:locationId"`
+	MaxRepertory  string `gorm:"column:maxRepertory"`
+	MinRepertory  string `gorm:"column:minRepertory"`
+	PartCode      string `gorm:"column:partCode"`
+	PartID        int    `gorm:"column:partId"`
+	PartName      string `gorm:"column:partName"`
+	PastureID     int    `gorm:"column:pastureId"`
+	PrecontractID string `gorm:"column:precontractId"`
+	Price         string `gorm:"column:price"`
+	ProviderID    int    `gorm:"column:providerId"`
+	ProviderNames string `gorm:"column:providerNames"`
+	Reportery     string `gorm:"column:reportery"`
+	Specification string `gorm:"column:specification"`
+	Unit          string `gorm:"column:unit"`
+}
+
+func (p PartRepertory) TableName() string {
+	return "Part_repertory"
+}

+ 111 - 0
apiserver/model/partlaid.go

@@ -0,0 +1,111 @@
+package model
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/pkg/util"
+)
+
+type BigPartLaid struct {
+	// 入库单
+	CreatDate   time.Time `gorm:"column:creatDate"`
+	EmpID       int       `gorm:"column:empId"`
+	ID          int       `gorm:"column:id"`
+	Issync      int       `gorm:"column:issync"`
+	LaidCode    string    `gorm:"column:laidCode"`
+	LaidType    int       `gorm:"column:laidType"`
+	Msg         string    `gorm:"column:msg"`
+	PastureID   int       `gorm:"column:pastureId"`
+	PurchaseID  string    `gorm:"column:purchaseId"`
+	StorageTime time.Time `gorm:"column:storageTime"`
+	// add
+	ProofCode string ` gorm:"column:proofCode"`
+	ProofYear string ` gorm:"column:proofYear"`
+}
+
+type PartLaid struct {
+	BigID             int     `gorm:"column:bigId"`
+	BigBuyerId        string  ` gorm:"column:bigBuyerId"`
+	BrandID           int     `gorm:"column:brandId"`
+	BuydetailID       int     `gorm:"column:buydetailId"`
+	ContractID        int     `gorm:"column:contractId"`
+	LocationID        int     `gorm:"column:locationId"`
+	PartID            int     `gorm:"column:partId"`
+	ProviderID        int     `gorm:"column:providerId"`
+	PastureID         int     `gorm:"column:pastureId"`
+	BuyAmount         int     `gorm:"column:buyAmount"`
+	ID                int     `gorm:"column:id"`
+	Note              string  `gorm:"column:note"`
+	OrderNumber       string  `gorm:"column:orderNumber"`
+	PartCode          string  `gorm:"column:partCode"`
+	PartName          string  `gorm:"column:partName"`
+	Price             float32 `gorm:"column:price"`
+	Purpose           string  `gorm:"column:purpose"`
+	ReceivedAmount    string  `gorm:"column:receivedAmount"`
+	Reportery         string  `gorm:"column:reportery"`
+	Specification     string  `gorm:"column:specification"`
+	StorageAmount     float32 `gorm:"column:storageAmount"`
+	StorageType       int     `gorm:"column:storageType"`
+	SubscribePasture  string  `gorm:"column:subscribePasture"`
+	SubscribeProvider string  `gorm:"column:subscribeProvider"`
+	SumPrice          float32 `gorm:"column:sumPrice"`
+	Unit              string  `gorm:"column:unit"`
+	Dflag             int     `gorm:"column:dflag"`
+	RowNumber         int     `gorm:"column:rowNumber"`
+	IsZeroStock       int     `gorm:"column:isZeroStock"`
+}
+
+func (p *PartLaid) ToProofPart() (r *ProofPart, e error) {
+	mb := &Brand{ID: p.BrandID}
+	mp := &Provider{ID: p.ProviderID}
+	mw := &Warehouse{ID: p.LocationID}
+	e = First(mb)
+	e = First(mp)
+	e = First(mw)
+	if e != nil {
+		e = errors.Wrapf(e, " PartLaid ToProofPart()")
+		return
+	}
+	r = &ProofPart{
+		RowNumber:     p.RowNumber,
+		PartCode:      p.PartCode,
+		PartName:      p.PartName,
+		Specification: p.Specification,
+		PartBrand:     mb.BrandName,
+		Supplier:      mp.ProviderName,
+		Warehouse:     mw.WarehoseCode,
+		ChangeCount:   p.StorageAmount,
+		UnitPrice:     p.Price,
+		TotalPrice:    p.SumPrice,
+	}
+	return
+}
+
+func (p *BigPartLaid) NewProofPart() (mps []ProofPart, e error) {
+	path := " BigPartLaid NewProof()"
+
+	c := util.NewMap("bigid", p.ID)
+	m := make([]PartLaid, 0)
+	if e = Find(c, &m); e != nil {
+		e = errors.Wrapf(e, path)
+		return
+	}
+	mps = make([]ProofPart, 0)
+	mp := new(ProofPart)
+	for i, v := range m {
+		if mp, e = v.ToProofPart(); e != nil {
+			continue
+		}
+		mp.RowNumber = i
+		mps = append(mps, *mp)
+	}
+	return
+}
+
+func (p *BigPartLaid) NewProof(pa *ProofReq) {
+	pa.ChargeDate = p.CreatDate.Format("2006-01-02")
+	pa.ProofCode = p.ProofCode
+	pa.ProofYear = p.CreatDate.Format("2006")
+	pa.OrderNumberId = p.ID
+}

+ 125 - 0
apiserver/model/partuse.go

@@ -0,0 +1,125 @@
+package model
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/pkg/util"
+)
+
+type BigPartUse struct {
+	ApplicatID   int `gorm:"column:applicatId"`
+	DepartmentID int `gorm:"column:departmentId"`
+	EmpID        int `gorm:"column:empId"`
+	FClassID     int `gorm:"column:fClassId"`
+	ID           int `gorm:"column:id"`
+	MaintainID   int `gorm:"column:maintainId"`
+	PastureID    int `gorm:"column:pastureId"`
+	WorkflowID   int `gorm:"column:workflowId"`
+	PlanUpkeepID int `gorm:"column:planUpkeepId"`
+	SClassID     int `gorm:"column:sClassId"`
+
+	ReceiveTime    time.Time `gorm:"column:receiveTime"` //'领用时间'
+	CreatDate      time.Time `gorm:"column:creatDate"`
+	FlowworkNote   string    `gorm:"column:flowworkNote"`
+	ListType       string    `gorm:"column:listType"`
+	OddCode        string    `gorm:"column:oddCode"`
+	RefuseStatue   int       `gorm:"column:refuseStatue"`
+	Msg            string    `gorm:"column:msg"`
+	FlowCompeleted int       `gorm:"column:flowCompeleted"`
+	Issync         int       `gorm:"column:issync"`
+	Note           string    `gorm:"column:note"`
+	SumPrice       string    `gorm:"column:sumPrice"`
+	UseType        int       `gorm:"column:useType"`
+	UseForm        string    `gorm:"column:useForm"`
+	UseStatus      int       `gorm:"column:useStatus"`
+	ProofCode      string    `gorm:"column:proofCode"`
+}
+
+type PartUse struct {
+	ID           int    `gorm:"column:id"`
+	BigID        int    `gorm:"column:bigId"`
+	BrandID      int    `gorm:"column:brandId"`
+	ContractID   int    `gorm:"column:contractId"`
+	LocationID   int    `gorm:"column:locationId"`
+	MaintainID   int    `gorm:"column:maintainId"`
+	PlanUpkeepID int    `gorm:"column:planUpkeepId"`
+	PartID       int    `gorm:"column:partId"`
+	ProID        int    `gorm:"column:proId"`
+	EqCode       string `gorm:"column:eqCode"`
+	EqID         int    `gorm:"column:eqId"`
+
+	Cpm            int     `gorm:"column:CPM"`
+	CheckoutNumber float32 `gorm:"column:checkoutNumber"` // 出库数量
+	EqName         string  `gorm:"column:eqName"`
+	IsRefuse       int     `gorm:"column:isRefuse"`
+	Note           string  `gorm:"column:note"`
+	PartCode       string  `gorm:"column:partCode"`
+	PartName       string  `gorm:"column:partName"`
+	Price          float32 `gorm:"column:price"` // 单价
+	ProName        string  `gorm:"column:proName"`
+	QuitNumber     string  `gorm:"column:quitNumber"`
+	RefuseNumber   int     `gorm:"column:refuseNumber"`
+	RefuseStatue   int     `gorm:"column:refuseStatue"`
+	Reportery      string  `gorm:"column:reportery"`
+	Specification  string  `gorm:"column:specification"`
+	SumPrice       float32 `gorm:"column:sumPrice"` // 总价
+	Unit           string  `gorm:"column:unit"`
+	UseNumber      string  `gorm:"column:useNumber"`
+	UseTypeV       string  `gorm:"column:useTypeV"`
+	Dflag          int     `gorm:"column:dflag"`
+	RowNumber      int     `gorm:"column:rowNumber"`
+}
+
+func (p *PartUse) ToProofPart() (r *ProofPart, e error) {
+	mb := &Brand{ID: p.BrandID}
+	mw := &Warehouse{ID: p.LocationID}
+	e = First(mb)
+	e = First(mw)
+	if e != nil {
+		e = errors.Wrapf(e, "model PartLaid ToProofPart()")
+		return
+	}
+	r = &ProofPart{
+		RowNumber:     p.RowNumber,
+		PartCode:      p.PartCode,
+		PartName:      p.PartName,
+		Specification: p.Specification,
+		PartBrand:     mb.BrandName,
+		Supplier:      p.ProName,
+		Warehouse:     mw.WarehoseCode,
+		ChangeCount:   p.CheckoutNumber,
+		UnitPrice:     p.Price,
+		TotalPrice:    p.SumPrice,
+	}
+	return
+}
+
+func (p *BigPartUse) NewProof(pa *ProofReq) {
+	pa.ChargeDate = p.ReceiveTime.Format("2006-01-02")
+	pa.ProofCode = p.UseForm
+	pa.ProofYear = p.ReceiveTime.Format("2006")
+	pa.OrderNumberId = p.ID
+}
+
+func (p *BigPartUse) NewProofPart() (mps []ProofPart, e error) {
+	path := " BigPartUse NewProofPart()"
+
+	c := util.NewMap("bigid", p.ID)
+	m := make([]PartUse, 0)
+	if e = Find(c, &m); e != nil {
+		e = errors.Wrapf(e, path)
+		return
+	}
+	mps = make([]ProofPart, 0)
+	mp := new(ProofPart)
+	for i, v := range m {
+		mp, e = v.ToProofPart()
+		mp.RowNumber = i
+		mps = append(mps, *mp)
+	}
+	if e != e {
+		e = errors.Wrapf(e, path)
+	}
+	return
+}

+ 32 - 0
apiserver/model/pasture.go

@@ -0,0 +1,32 @@
+package model
+
+type Pasture struct {
+	ID         int    `gorm:"column:id" gorm:"column:id" `
+	Address    string `gorm:"column:address"`
+	Center     string `gorm:"column:center"`
+	CenterID   int    `gorm:"column:center_id"`
+	CenterSort int    `gorm:"column:center_sort"`
+
+	EmployeeID    int    `gorm:"column:employeeId"`
+	Enablesync    int    `gorm:"column:enablesync"`
+	IsDel         int    `gorm:"column:isDel"`
+	Latitude      string `gorm:"column:latitude"`
+	Longitude     string `gorm:"column:longitude"`
+	Name          string `gorm:"column:name"`
+	Note          string `gorm:"column:note"`
+	PastureNumber string `gorm:"column:pastureNumber"`
+	Prcode        string `gorm:"column:prcode"`
+	Region        string `gorm:"column:region"`
+	RegionID      int    `gorm:"column:region_id"`
+	ShortName     string `gorm:"column:shortName"`
+	Sort          int    `gorm:"column:sort"`
+
+	CompanyCode string `gorm:"column:company_code"` //公司代码
+	CompanyName string `gorm:"column:company_name"` //公司代码
+	FactoryCode string `gorm:"column:factory_code"` //工厂
+	FactoryName string `gorm:"column:factory_name"` //工厂
+
+	ParchaseOrganization string `gorm:"column:parchase_organization"`
+
+	// CompanyName   string `gorm:"column:companyName"`
+}

+ 39 - 0
apiserver/model/proof.go

@@ -0,0 +1,39 @@
+package model
+
+type ProofReq struct {
+	ProofCode     string      `json:"materialCode"`  // 物料凭证号
+	ProofYear     string      `json:"proofYear"`     // 物料凭证年度
+	ChargeDate    string      `json:"chargeDate"`    // 凭证中的过帐日期 YYYYMMDD
+	OrderNumber   string      `json:"orderNumber"`   // 设备管理平台单号
+	OrderNumberId int         `json:"orderNumberId"` // 设备管理平台单号ID
+	HasTicket     int         `json:"hasTicket"`     // 是否已开票退货单	"是: X ,※仅采购业务需要
+	RowsNumber    []int       `json:"rowsNumber"`    // 设备管理平台行号
+	NumberType    int         `json:"NumberType"`    // 1:采购入库,2:采购退货,3:出库,4:退库
+	ProofPart     []ProofPart `json:"parts"`         // 备件信息
+}
+
+// 序号  备件编号  备件名称  备件规格    备件品牌  供应商    库位    变更数量  单价  总价
+type Proof struct {
+	MaterialCode string   `gorm:"column:materialCode"` // 物料凭证号
+	ProofYear    string   `gorm:"column:proofYear"`    // 物料凭证年度
+	ChargeDate   string   `gorm:"column:chargeDate"`   // 凭证中的过帐日期 YYYYMMDD
+	OrderNumber  string   `gorm:"column:orderNumber"`  // 设备管理平台单号
+	HasTicket    string   `gorm:"column:hasTicket"`    // 是否已开票退货单	"是: X ,※仅采购业务需要
+	RowsNumber   []string `gorm:"column:rowsNumber"`   // 设备管理平台行号
+}
+type ProofPart struct {
+	RowNumber     int     `json:"rowNumber"`     // 行号
+	PartCode      string  `json:"partCode"`      // 备件编号
+	PartName      string  `json:"partName"`      // 备件名称
+	Specification string  `json:"specification"` // 备件规格
+	PartBrand     string  `json:"partBrand"`     // 备件品牌
+	Supplier      string  `json:"supplier"`      // 供应商
+	Warehouse     string  `json:"warehouse"`     // 库位
+	ChangeCount   float32 `json:"changeCount"`   // 变更数量
+	UnitPrice     float32 `json:"unitPrice"`     // 单价
+	TotalPrice    float32 `json:"totalPrice"`    // 总价
+}
+
+func (p *ProofReq) Validate() bool {
+	return true
+}

+ 28 - 0
apiserver/model/provider.go

@@ -0,0 +1,28 @@
+package model
+
+import "time"
+
+type Provider struct {
+	ID             int    `gorm:"column:id" json:"id" `
+	ProviderIntro  string `gorm:"column:providerIntro"`  //供应商全称
+	ProviderName   string `gorm:"column:providerName"`   //供应商简称
+	ProviderNumber string `gorm:"column:providerNumber"` //供应商编码
+	Email          string `gorm:"column:email"`          //邮箱
+	Linkman        string `gorm:"column:linkman"`        //联系人
+	Telphone       string `gorm:"column:telphone"`       //联系电话
+	CompanyCode    string `gorm:"column:company_code"`   //公司代码
+	SortName       string `gorm:"column:sort_name"`      //供应商分类
+
+	Enable int `gorm:"column:enable"` //是否启用
+
+	PastureId        int       `gorm:"column:pastureId"`
+	FlexPrice        int       `gorm:"column:flexPrice"`
+	BusinessLicense  string    `gorm:"column:businessLicense"`
+	OrganizationCode string    `gorm:"column:organizationCode"`
+	OpenLicence      string    `gorm:"column:openLicence"`
+	IRSregister      string    `gorm:"column:IRSregister"`
+	CreateTime       time.Time `gorm:"column:createTime"`
+	ModifyTime       time.Time `gorm:"column:modifyTime"`
+	CreatedAt        time.Time `gorm:"column:created_at"`
+	UpdatedAt        time.Time `gorm:"column:updated_at"`
+}

+ 48 - 0
apiserver/model/transfer.go

@@ -0,0 +1,48 @@
+package model
+
+import "time"
+
+type TransferParam struct {
+	ID       int    `gorm:"column:id"` //调拨单id
+	Statue   int    `gorm:"column:statue"`
+	LaidCode string `gorm:"column:laidCode"` // 入库单号
+	UseCode  string `gorm:"column:useCode"`
+}
+
+type BigPartTransfer struct {
+	ID          int `gorm:"column:id"`
+	EmpID       int `gorm:"column:empId"`
+	InPastureID int `gorm:"column:inPastureId"`
+	PastureID   int `gorm:"column:pastureId"`
+
+	ApplyCode string `gorm:"column:applyCode"` // 调拨单号
+	LaidCode  string `gorm:"column:laidCode"`  //入库单号
+	UseCode   string `gorm:"column:useCode"`   //出库单号
+	Emp       string `gorm:"column:emp"`
+
+	ApplyDate time.Time `gorm:"column:applyDate"`
+	CreatDate time.Time `gorm:"column:creatDate"`
+	Statue    int       `gorm:"column:statue"`
+	DeptId    int       `gorm:"column:deptId"`
+	SapStatus int       `gorm:"column:sapStatus"`
+	SapText   string    `gorm:"column:sapText"`
+}
+type PartTransfer struct {
+	ID            int    `gorm:"column:id"`
+	BigID         int    `gorm:"column:bigId"`
+	BrandID       int    `gorm:"column:brandId"`
+	PartID        int    `gorm:"column:partId"`
+	PartRepID     int    `gorm:"column:partRepId"`
+	PastureID     int    `gorm:"column:pastureId"`
+	ProviderID    int    `gorm:"column:providerId"`
+	BrandName     string `gorm:"column:brandName"`
+	Amount        string `gorm:"column:amount"`
+	Note          string `gorm:"column:note"`
+	PartCode      string `gorm:"column:partCode"`
+	PartName      string `gorm:"column:partName"`
+	Price         string `gorm:"column:price"`
+	ProviderName  string `gorm:"column:providerName"`
+	Specification string `gorm:"column:specification"`
+	SumPrice      string `gorm:"column:sumPrice"`
+	Unit          string `gorm:"column:unit"`
+}

+ 14 - 0
apiserver/model/warehouse.go

@@ -0,0 +1,14 @@
+package model
+
+type Warehouse struct {
+	Enable        int    `gorm:"column:enable"`
+	ID            int    `gorm:"column:id"`
+	IsWhPostion   int    `gorm:"column:isWhPostion"`
+	PastureID     int    `gorm:"column:pastureId"`
+	Pid           int    `gorm:"column:pid"`
+	Remark        string `gorm:"column:remark"`
+	Section       int    `gorm:"column:section"`
+	Sort          int    `gorm:"column:sort"`
+	WarehoseCode  string `gorm:"column:warehoseCode"`
+	WarehosetName string `gorm:"column:warehosetName"`
+}

二進制
apiserver/routers/.DS_Store


+ 57 - 0
apiserver/routers/api/api.go

@@ -0,0 +1,57 @@
+package api
+
+import (
+	"kpt.xdmy/apiserver/service"
+	"kpt.xdmy/pkg/log"
+)
+
+var svc *service.Service
+
+func Init(s *service.Service) {
+	svc = s
+}
+
+func NextService(p []map[string]interface{}) {
+	for _, v := range p {
+		if v["name"] == nil || v["parammaps"] == nil {
+			continue
+		}
+		pf := v["parammaps"].(map[string]interface{})
+		sqlname := v["name"].(string)
+		switch sqlname {
+		case "updatebigbuydetailenable", "createBuydetailBySG":
+			log.Info(v)
+			//采购:线下(申购配单)、线上(申购)
+			svc.PurchaseOrder(pf)
+		case "insertBigPartlaid":
+			log.Info(v)
+			laidType := pf["laidType"].(float64)
+			switch laidType {
+			case 0:
+				// 入库-申购、采购(申购、线上、寄售)
+				svc.LaidProof(pf)
+			}
+		case "insertBigPartUse":
+			log.Info(v)
+			useType := pf["useType"].(float64)
+			// 领用、手动、报废:0、1、5
+			switch useType {
+			case 0, 1, 5:
+				svc.UseProof(pf)
+			}
+		case "updatePartRepertoryTHS":
+			log.Info(v)
+			// 退货
+			svc.RefundProof(pf)
+		case "insertBigPartquit":
+			log.Info(v)
+			// 退库
+			svc.QuitProof(pf)
+		case "updateBigPartTransfer":
+			// 调拨
+			log.Info(v)
+			// svc.ApiTransfer(pf)
+		}
+	}
+
+}

+ 3263 - 0
apiserver/routers/api/db.go

@@ -0,0 +1,3263 @@
+package api
+
+import (
+	"database/sql"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"log"
+	"math"
+	"net/http"
+	"os"
+	"path"
+	"regexp"
+	"strconv"
+	"strings"
+	"time"
+
+	"github.com/360EntSecGroup-Skylar/excelize"
+	"github.com/jmoiron/sqlx"
+	"github.com/pkg/errors"
+
+	// "github.com/360EntSecGroup-Skylar/excelize"
+	"github.com/Anderson-Lu/gofasion/gofasion"
+	"github.com/axetroy/go-fs"
+	"github.com/gin-gonic/gin"
+	"github.com/tealeg/xlsx"
+
+	// "github.com/xormplus/xorm"
+
+	"kpt.xdmy/apiserver/routers/restful"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+	"kpt.xdmy/pkg/logging"
+	"kpt.xdmy/pkg/setting"
+	"kpt.xdmy/pkg/util"
+)
+
+// @Summary   根据SQL执行得到数据集
+// @Tags getData
+// @Accept json
+// @Produce  json
+// @Param  sql  query   string true "sql"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/getdata  [POST]
+func GetData(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlstr := fsion.Get("sql").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+	queryData, err := getDataBySql(sqlstr, offset, pagecount, returntype, nil)
+
+	if err != nil {
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, queryData)
+	}
+}
+func Testpartitions(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	databaseName := fsion.Get("databaseName").ValueStr() //获取新数据库名称
+	user := fsion.Get("user").ValueStr()                 //获取新数据库用户
+	passWord := fsion.Get("passWord").ValueStr()         //获取新数据库名称
+	host := fsion.Get("host").ValueStr()                 //获取新数据库名称
+	port := fsion.Get("port").ValueStr()
+	sqlstr := "SELECT sql FROM sql_new "
+	var sqlname string
+	err1 := restful.BasicList(sqlstr, nil, &sqlname)
+	if err1 != nil {
+		appG.Response(http.StatusOK, e.SUCCESS, "失败:"+err1.Error())
+	}
+	sqlstrs := strings.Split(sqlname, ";") //分割sql
+	// sqlstrs := strings.Split(p["sql"].(string), ";") //分割sql
+	connecting := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, "mysql")
+	mydb, err := sql.Open("mysql", connecting) //连接新连接
+	if err != nil {
+		println("err1", err.Error())
+	}
+	_, err = mydb.Exec("CREATE DATABASE IF NOT EXISTS `" + databaseName + "`") // 创建数据库
+	if err != nil {
+		println("err2", err.Error())
+	}
+
+	mydb.Close()
+
+	connecting = fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", user, passWord, host, port, databaseName) //连接新数据库,创建表格
+	mydb, err = sql.Open("mysql", connecting)
+	if err != nil {
+		println("err3", err.Error())
+	}
+	defer mydb.Close()
+	if err == nil {
+		mydb.SetMaxOpenConns(10)
+		mydb.SetMaxIdleConns(10)
+	}
+	errmsg := ""
+	if err == nil {
+		//tx ,_ :=mydb.Begin()
+
+		for _, sqlstr := range sqlstrs {
+			//println("sqlstr---",sqlstr)
+			if sqlstr == "" {
+				continue
+			}
+			_, err = mydb.Exec(sqlstr)
+			if err != nil {
+				println("err4", err.Error())
+				errmsg = err.Error()
+			}
+		}
+	}
+	if errmsg == "" {
+		appG.Response(http.StatusOK, e.SUCCESS, "成功"+databaseName)
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, "失败"+errmsg)
+	}
+
+}
+func TestData(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlstr := fsion.Get("sql").ValueStr()
+	token := ""
+	if tempv, exists := c.Get("jwt_username"); exists {
+		token = tempv.(string)
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, "你录入的名字是:"+sqlstr+";token:"+token)
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags GetDataByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  body   string true "sqlname"
+// @Param  offset  body   int true "offset"
+// @Param  pagecount  body   int true "pagecount"
+// @Param  returntype  body   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/GetDataByName  [POST]
+func GetDataByName(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+	getTotal := fsion.Get("getTotal").ValueStr()
+	paramsTest := fsion.Get("parammaps")
+
+	fmt.Println(paramsTest.Get("partClass").ValueStr())
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
+				logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			}
+
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			//c.File("c:/dd.xlsx")
+			c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+			c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+
+		} else {
+			// queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params)
+			if getTotal == "total3" {
+				totalData := make(map[string]interface{})
+				queryData1 := queryData.(map[string]interface{})
+				totalData["total3"] = queryData1["total"]
+				appG.Response(http.StatusOK, e.SUCCESS, totalData)
+				return
+			}
+			if err != nil {
+				logging.Error("GetDataByName  err: ", err)
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg)
+			} else {
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+			}
+		}
+
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+	defer c.Request.Body.Close()
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags GetDataByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  body   string true "sqlname"
+// @Param  offset  body   int true "offset"
+// @Param  pagecount  body   int true "pagecount"
+// @Param  returntype  body   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/GetDataByName  [POST]
+func EasSync(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	typeIn := fsion.Get("typeIn").ValueDefaultInt(0)
+	billCode := fsion.Get("billCode").ValueStr()
+	logging.Error("EasSync  date: ", typeIn, billCode)
+	//typeInstr := fsion.Get("typeIn").ValueStr()
+	//println(typeInstr,typeIn)
+	// 用于判断备件干什么的和eas同步
+	err := util.EASBillSync(typeIn, billCode, "1")
+	if err != nil {
+		logging.Error("EasSync  err: ", err)
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, "成功")
+	}
+}
+func GetDataByNameOPEN(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	sqlnamestr = sqlnamestr + "OPEN"
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil)
+	//fmt.Println("sql========\n",sqlnamestr,sql)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
+				logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			}
+
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			//c.File("c:/dd.xlsx")
+			c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+			c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+
+		} else {
+			// queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params)
+
+			if err != nil {
+				logging.Error("GetDataByName  err: ", err)
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg)
+			} else {
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+			}
+		}
+
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+func geterrmsg(errstr string) (msgstr string) {
+	var hzRegexp = regexp.MustCompile("^[\u4e00-\u9fa5]$") // 判断是否为汉字
+	rs := []rune(errstr)
+	if len(rs) == 0 {
+		msgstr = errstr
+		return
+	}
+	if hzRegexp.MatchString(string(rs[0])) {
+		msgstr = errstr
+		return
+	}
+
+	if strings.Contains(errstr, "Duplicate entry") {
+		strs := strings.Split(errstr, ` key '`)
+		if len(strs) > 1 {
+			if len(strs[len(strs)-1]) > 1 {
+				errstr = "Duplicate entry :" + strs[len(strs)-1]
+			}
+		}
+	}
+
+	msg, err := restful.MapStrList("SELECT msg FROM err_msg where err = ? ", errstr)
+	if err != nil {
+		msgstr = errstr
+		return
+	}
+	if msg == nil || len(msg) == 0 {
+		var param []interface{}
+		param = append(param, errstr, errstr)
+		go func() {
+			tx, err := restful.Dbs.Beginx()
+			defer func() {
+				switch {
+				case err != nil:
+					logging.Error("tx.Begin 事务启动失败__error:", err)
+					if tx != nil {
+						tx.Rollback()
+					}
+				default:
+					if tx != nil {
+						err = tx.Commit()
+					}
+				}
+				if tx != nil {
+
+				}
+			}()
+			_, err = restful.ExecQueryT("insert into err_msg(err,msg) VALUES(?,?) ON DUPLICATE KEY UPDATE err=err", param, tx)
+			if err != nil {
+				logging.Error("insert into err_msg(err,msg) err", err)
+			}
+
+		}()
+		msgstr = errstr
+	} else {
+		msgstr = msg[0]["msg"]
+	}
+	return
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags GetDataByNameForm
+// @Accept json
+// @Produce  json
+// @Param  sqlname  body   json true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Param  s formData   json true "ss"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/GetDataByNameForm  [POST]
+func GetDataByNameForm(c *gin.Context) {
+	appG := app.Gin{C: c}
+	//sqlnamestr := c.PostForm("measureNumber")
+	//dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	//fsion := gofasion.NewFasion(string(dataByte))
+	//sqlnamestr := fsion.Get("name").ValueStr()
+	//offset := fsion.Get("offset").ValueInt()
+	//pagecount := fsion.Get("pagecount").ValueInt()
+	//returntype := fsion.Get("returntype").ValueStr()
+	//params := fsion.Get("params").Array()
+
+	c.Request.ParseForm()
+	params := c.Request.Form
+	offset := 0
+	pageSize_ := 0
+	returntype := params.Get("page")
+	if returntype == "" {
+		returntype = "0"
+	}
+	if tempv, exists := c.Get("jwt_username"); exists {
+		params.Set("JwtUserName", tempv.(string))
+	} else {
+		params.Set("JwtUserName", "")
+	}
+	sqlnamestr := params.Get("name")
+	logging.Info("GetDataByNameForm ", c.Keys, sqlnamestr)
+	s_params := make([]interface{}, 0)
+	if returntype == "1" {
+		pageNum, error := strconv.Atoi(params.Get("pageNum"))
+		if error != nil {
+			appG.ResponseEq(http.StatusOK, e.ERROR, 0, "页码不是整数")
+		}
+		pageSize, error := strconv.Atoi(params.Get("pageSize"))
+		if error != nil {
+			appG.ResponseEq(http.StatusOK, e.ERROR, 0, "每页行数不是整数")
+		}
+		pageSize_ = pageSize
+		offset = pageNum
+	}
+
+	sql, p := restful.GetSqlByNameDB(sqlnamestr)
+
+	paramslist := strings.Split(p, ",")
+	if len(paramslist) > 0 && p != "" {
+		for _, value := range paramslist {
+			s_params = append(s_params, params.Get(strings.Trim(value, " ")))
+		}
+	}
+
+	if sql != "" {
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			c.Header("Content-Type", "application/octet-stream")
+			c.Header("Content-Disposition", "attachment; filename="+sqlnamestr+".xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+		} else {
+			queryData, err := getDataBySql(sql, offset, pageSize_, returntype, s_params)
+
+			if err != nil {
+				appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
+			} else {
+				appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
+			}
+		}
+
+	} else {
+		appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
+	}
+}
+
+// @Summary   递归获取所有
+// @Tags menu
+// @Accept json
+// @Produce  json
+// @Param  Ton  query  string true "Ton"
+// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Router /authdata/GetRoleMenus  [GET]
+func GetRecuDataByName(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	parentidname := fsion.Get("idname").ValueStr()
+	sql, p := restful.GetSqlByNameDB(sqlnamestr)
+	params := make(map[string]interface{})
+	s_params := make([]interface{}, 0)
+	if fsion.HasKey("params") {
+
+		for _, v_params := range fsion.Get("params").Array() {
+			s_params = append(s_params, v_params.ValueStr())
+		}
+		params["params"] = s_params
+
+	} else {
+		jparams := fsion.Get("parammaps")
+		paramslist := strings.Split(p, ",")
+		if len(paramslist) > 0 && p != "" {
+			for _, value := range paramslist {
+				if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+					if tempv, exists := c.Get("jwt_username"); exists {
+						params[value] = tempv.(string)
+					} else {
+						params[value] = ""
+					}
+				} else {
+					params[value] = jparams.Get(strings.Trim(value, " ")).ValueStr()
+				}
+			}
+
+		}
+	}
+	queryData, err := GetRecuData_BySql(sql, p, parentidname, params, fsion.HasKey("params"))
+	logging.Info("sqlname parammaps", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+	if err != nil {
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, queryData)
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags GetDataByNames
+// @Accept json
+// @Produce  json
+// @RequestBody  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/GetDataByNames  [POST]
+func GetDataByNames(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlParams := fsion.Array()
+	queryData := make(map[string]interface{})
+	for _, v := range sqlParams {
+		fsion2 := gofasion.NewFasion(v.Json())
+		logging.Info("GetDataByNames", c.Keys, fsion2.Get("name").ValueStr(), c.Request.RemoteAddr)
+		// p是sql表中的sql语句中的变量差数格式
+		sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
+		if sql == "" {
+			errorm := make(map[string]interface{})
+			errorm["code"] = e.ERROR
+			errorm["message"] = "sql没找到"
+			queryData[fsion2.Get("name").ValueStr()] = errorm
+			continue
+		} else if sql != "" {
+			offset := fsion2.Get("offset").ValueInt()
+			pagecount := fsion2.Get("pagecount").ValueInt()
+			returntype := fsion2.Get("returntype").ValueStr()
+			// s_params 是用来存储sql中需要的参数
+			s_params := make([]interface{}, 0)
+			// 这边是判断是传过来的是参数格式如果是map格式的是需要在apisql表中查询params字段
+			if fsion2.HasKey("parammaps") {
+				parammaps := fsion2.Get("parammaps")
+				paramslist := strings.Split(p, ",")
+				if len(paramslist) > 0 && p != "" {
+					for _, value := range paramslist {
+						if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+							if tempv, exists := c.Get("jwt_username"); exists {
+								s_params = append(s_params, tempv.(string))
+							} else {
+								s_params = append(s_params, "")
+							}
+						} else {
+							s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+						}
+					}
+				}
+			} else if fsion2.HasKey("params") {
+				params := fsion2.Get("params").Array()
+				for _, v_params := range params {
+					s_params = append(s_params, v_params.ValueStr())
+				}
+			}
+
+			queryData1, err := getDataBySql(sql, offset, pagecount, returntype, s_params)
+
+			if err != nil {
+				errorm := make(map[string]interface{})
+				errorm["code"] = e.ERROR
+				errorm["message"] = err.Error()
+				queryData[fsion2.Get("name").ValueStr()] = errorm
+				logging.Error("GetDataByNames  err: ", err)
+				continue
+			} else {
+				queryData[fsion2.Get("name").ValueStr()] = queryData1
+			}
+		}
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, queryData)
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags PostDataByNameForm
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误朱红彬彬"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByNameForm  [POST]
+func PostDataByNameForm(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	c.Request.ParseForm()
+	params := c.Request.Form
+	sqlnamestr := params.Get("name")
+	logging.Info("PostDataByNameForm ", c.Keys, sqlnamestr)
+
+	s_params := make([]interface{}, 0)
+
+	sql, p := restful.GetSqlByNameDB(sqlnamestr)
+	paramslist := strings.Split(p, ",")
+
+	if len(paramslist) > 0 {
+		for _, value := range paramslist {
+			s_params = append(s_params, params.Get(strings.Trim(value, " ")))
+		}
+	}
+
+	if sql != "" {
+		queryData, err := execDataBySql(sql, s_params)
+
+		if err != nil {
+			appG.ResponseEq(http.StatusOK, e.ERROR, 1, err.Error())
+		} else {
+			appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, queryData)
+		}
+	} else {
+		appG.ResponseEq(http.StatusOK, e.SUCCESS, 0, "后台没有数据接口")
+	}
+}
+func GetReportform(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	parammaps := fsion.Get("parammaps")
+	logging.Info("GetReportform ", c.Keys, sqlnamestr, parammaps)
+	queryData, _ := praseReportform(sqlnamestr, parammaps)
+
+	appG.Response(http.StatusOK, e.SUCCESS, queryData)
+}
+func praseReportform(sqlnamestr string, parammaps *gofasion.Fasion) (queryData map[string]interface{}, err error) {
+	switch sqlnamestr {
+	case "getpSumNow", "getpSumNowWater", "getpSumNowElec", "getpSumNowDiesel":
+		queryData, err = getpSumNow(sqlnamestr, parammaps)
+	case "getPastureSumMonth", "getPastureSumMonthWater", "getPastureSumMonthElec", "getPastureSumMonthDiesel":
+		queryData, err = getPastureSumMonth(sqlnamestr, parammaps)
+	case "getPastureSumDayWater", "getPastureSumDayElec", "getPastureSumDayDiesel":
+		queryData, err = getPastureSumDay(sqlnamestr, parammaps)
+	case "getPastureSumDay":
+		queryData, err = getPastureSumDay1(sqlnamestr, parammaps)
+	case "geteqclassSumMonth", "geteqclassSumMonthWater", "geteqclassSumMonthElec", "geteqclassSumMonthDiesel":
+		queryData, err = geteqclassSumMonth(sqlnamestr, parammaps)
+	case "geteCowWaterList", "geteCowElecList", "geteCowDieselList", "geteCowMaintainList", "geteCowAllList":
+		queryData, err = geteCow(sqlnamestr, parammaps)
+	case "geteCowWaterMonthList", "geteCowElecMonthList", "geteCowDieselMonthList", "geteCowMaintainMonthList", "geteCowAllMonthList":
+		queryData, err = geteCowMonth(sqlnamestr, parammaps)
+	case "getEqRunSurveyListPasture":
+		queryData, err = getEqRunSurveyListPasture(sqlnamestr, parammaps)
+	case "geteqclassFeeSum", "geteqclassFeeSumPasture":
+		queryData, err = geteqclassFeeSum(sqlnamestr, parammaps)
+	case "getEqRunSurveyListDay":
+		queryData, err = getEqRunSurveyListDay(sqlnamestr, parammaps)
+	case "getReportEqCostYear":
+		queryData, err = geteqCostYear(sqlnamestr, parammaps)
+	case "getReportEqCostMonth":
+		queryData, err = geteqCostMonth(sqlnamestr, parammaps)
+	case "homepagePastureInfor":
+		queryData, err = homepagePastureInfor(sqlnamestr, parammaps)
+	case "homepageEqstatus":
+		queryData, err = homepageEqstatus(sqlnamestr, parammaps)
+	case "homepageEqRunstatueListPasture", "homepageEqRunstatueListEqclass":
+		queryData, err = homepageEqRunstatue(sqlnamestr, parammaps)
+	case "homepageFeeWX", "homepageFeeWater", "homepageFeeElec", "homepageFeeDiesel":
+		queryData, err = homepageFee(sqlnamestr, parammaps)
+	default:
+		queryData, err = nil, nil
+	}
+	return
+}
+func homepageFee(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	pSumNow, err := restful.MapStrList(sqlNow, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName, pastureName)
+	if err != nil {
+		log.Default().Printf("homepageFee queryx: %v", err)
+	}
+	typeStr := parammaps.Get(strings.Trim("type", " ")).ValueStr()
+	list1s := make([]string, 1)
+	list2s := make([]string, 1)
+	list3s := make([]string, 1)
+	list4s := make([]string, 1)
+	list5s := make([]string, 1)
+	list6s := make([]string, 1)
+	list7s := make([]string, 1)
+	list8s := make([]string, 1)
+	list1s[0] = typeStr
+
+	for _, value := range pSumNow {
+		list2s[0] = value["monthBudget"]
+		list3s[0] = value["sumPrice"]
+		list4s[0] = value["monthBudgetL"]
+		list5s[0] = value["sumPriceL"]
+		list6s[0] = value["monthBudget"]
+		list7s[0] = value["sumPrice"]
+		list8s[0] = value["cowS"]
+	}
+	queryData["data1"] = list1s
+	queryData["data2"] = list2s
+	queryData["data3"] = list3s
+	queryData["data4"] = list4s
+	queryData["data5"] = list5s
+	queryData["data6"] = list6s
+	queryData["data7"] = list7s
+	queryData["data8"] = list8s
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func homepageEqRunstatue(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	typeStr := parammaps.Get(strings.Trim("type", " ")).ValueStr()
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureName)
+
+	list1s := make([]string, 0)
+	list2s := make([]string, 0)
+	list3s := make([]string, 1)
+	list3s[0] = typeStr
+
+	for _, value := range pSumNow {
+		list1s = append(list1s, value["name"])
+		list2s = append(list2s, value["rate"])
+	}
+	queryData["data1"] = list1s
+	queryData["data2"] = list2s
+	queryData["data3"] = list3s
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func homepageEqstatus(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pastureName := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureName, pastureName)
+
+	list1s := make([]string, 0)
+	list2s := make([]string, 0)
+
+	for _, value := range pSumNow {
+		list1s = append(list1s, value["status"])
+		list2s = append(list2s, value["cou"])
+	}
+	queryData["data1"] = list1s
+	queryData["data2"] = list2s
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func homepagePastureInfor(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow)
+
+	lolalists := make([]map[string]interface{}, 0)
+	pasturelists := make([]map[string]interface{}, 0)
+
+	lolalist := make(map[string]interface{}, 1)
+
+	for _, value := range pSumNow {
+		lola := make([]string, 0)
+		pasturelist := make(map[string]interface{}, 1)
+		lola = append(lola, value["longitude"])
+		lola = append(lola, value["latitude"])
+		lolalist[value["name"]] = lola
+		pasturelist["name"] = value["name"]
+		pasturelist["value"] = value["name"]
+		pasturelists = append(pasturelists, pasturelist)
+	}
+	lolalists = append(lolalists, lolalist)
+	queryData["data1"] = lolalists
+	queryData["data2"] = pasturelists
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func geteqCostMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	eqId := parammaps.Get(strings.Trim("eqId", " ")).ValueStr()
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, receiveTime, eqId, receiveTime, receiveTime, eqId, receiveTime, receiveTime)
+
+	chartData := make(map[string]interface{})
+	months := []string{}
+	upkeepCost := []string{}
+	repireCost := []string{}
+	//lastTotal,nowTotal := 0,0
+	a := true
+	month := ""
+	for i := 1; i <= 12; i++ {
+		if i < 10 {
+			month = receiveTime + "-0" + strconv.Itoa(i)
+		} else {
+			month = receiveTime + "-" + strconv.Itoa(i)
+		}
+		months = append(months, month)
+		for _, va := range pSumNow {
+			if va["yearR"][5:] == month[5:] {
+				upkeepCost = append(upkeepCost, va["Ucost"])
+				repireCost = append(repireCost, va["Rcost"])
+				a = false
+			}
+		}
+
+		if a {
+			upkeepCost = append(upkeepCost, "0")
+			repireCost = append(repireCost, "0")
+		}
+		a = true
+	}
+	chartData["months"] = months
+	chartData["upkeepCost"] = upkeepCost
+	chartData["repireCost"] = repireCost
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+func geteqCostYear(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+
+	//receiveTime :=parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	eqId := parammaps.Get(strings.Trim("eqId", " ")).ValueStr()
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, eqId, eqId, eqId)
+
+	chartData := make(map[string]interface{})
+	year := []string{}
+	upkeepCost := []string{}
+	repireCost := []string{}
+
+	for _, va := range pSumNow {
+		year = append(year, va["yearR"])
+		upkeepCost = append(upkeepCost, va["Ucost"])
+		repireCost = append(repireCost, va["Rcost"])
+	}
+
+	chartData["year"] = year
+	chartData["upkeepCost"] = upkeepCost
+	chartData["repireCost"] = repireCost
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func geteCowMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("year", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	var pSumNow, pSumLast []map[string]string
+	if sqlnamestr == "geteCowAllMonthList" {
+		sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+		pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, receiveTime, receiveTime, receiveTime, receiveTime, receiveTime, pastureNames)
+		tempTime, _ := strconv.Atoi(receiveTime)
+		receiveTimetemp := strconv.Itoa(tempTime - 1)
+		pSumLast, _ = restful.MapStrList(sqlNow, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, receiveTimetemp, pastureNames)
+	} else {
+		sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+		pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, receiveTime, receiveTime, pastureNames)
+		tempTime, _ := strconv.Atoi(receiveTime)
+		receiveTimetemp := strconv.Itoa(tempTime - 1)
+		pSumLast, _ = restful.MapStrList(sqlNow, receiveTimetemp, receiveTimetemp, receiveTimetemp, pastureNames)
+	}
+
+	chartData := make(map[string]interface{})
+	months := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+	budgetYear := []string{}
+	//lastTotal,nowTotal := 0,0
+	a, b := true, true
+	month := ""
+
+	for i := 1; i <= 12; i++ {
+		if i < 10 {
+			month = receiveTime + "-0" + strconv.Itoa(i)
+		} else {
+			month = receiveTime + "-" + strconv.Itoa(i)
+		}
+		months = append(months, month)
+		for _, va := range pSumNow {
+			if va["month"][5:] == month[5:] {
+				nowYear = append(nowYear, va["psum"])
+				budgetYear = append(budgetYear, va["lsum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["month"][5:] == month[5:] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			nowYear = append(nowYear, "0")
+			budgetYear = append(budgetYear, "0")
+		}
+		if b {
+			lastYear = append(lastYear, "0")
+		}
+		a = true
+		b = true
+	}
+	chartData["months"] = months
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	chartData["budgetYear"] = budgetYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+func getEqRunSurveyListDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("praseTime", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime)
+	if pSumNow == nil {
+		return nil, nil
+	}
+	typeName := make([]map[string]interface{}, 4)
+	ma := make(map[string]interface{})
+	ma1 := make(map[string]interface{})
+	ma2 := make(map[string]interface{})
+	ma3 := make(map[string]interface{})
+	ma["name"] = "在用"
+	ma["value"] = pSumNow[0]["eqUse"]
+	typeName[0] = ma
+	ma1["name"] = "闲置"
+	ma1["value"] = pSumNow[0]["eqXZ"]
+	typeName[1] = ma1
+	ma2["name"] = "报废"
+	ma2["value"] = pSumNow[0]["eqBF"]
+	typeName[2] = ma2
+	ma3["name"] = "封存"
+	ma3["value"] = pSumNow[0]["eqFC"]
+	typeName[3] = ma3
+
+	queryData["psm"] = typeName
+	queryData["code"] = 0
+	queryData["total"] = pSumNow[0]["eqSum"]
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+func getEqRunSurveyListPasture(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+
+	receiveTime := parammaps.Get(strings.Trim("praseTime", " ")).ValueStr()
+	pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture order by sort")
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, receiveTime)
+	chartData := make(map[string]interface{})
+	pasture := []string{}
+	eqUse := []string{}
+	eqXZ := []string{}
+	eqBF := []string{}
+	eqFC := []string{}
+
+	//lastTotal,nowTotal := 0,0
+	a := true
+	for _, value := range pastureNames {
+		pasture = append(pasture, value["name"])
+		for _, va := range pSumNow {
+			if va["pastureName"] == value["name"] {
+				eqUset, _ := strconv.Atoi(va["eqUse"])
+				eqSumt, _ := strconv.Atoi(va["eqSum"])
+				eqXZt, _ := strconv.Atoi(va["eqXZ"])
+				eqBFt, _ := strconv.Atoi(va["eqBF"])
+				eqFCt, _ := strconv.Atoi(va["eqFC"])
+				eqUsetem := float64(eqUset) / float64(eqSumt) * 100
+				eqXZtem := float64(eqXZt) / float64(eqSumt) * 100
+				eqBFtem := float64(eqBFt) / float64(eqSumt) * 100
+				eqFCtem := float64(eqFCt) / float64(eqSumt) * 100
+				eqUse = append(eqUse, strconv.FormatFloat(eqUsetem, 'f', 2, 64))
+				//eqSum = append(eqSum, va["eqSum"])
+				eqXZ = append(eqXZ, strconv.FormatFloat(eqXZtem, 'f', 2, 64))
+				eqBF = append(eqBF, strconv.FormatFloat(eqBFtem, 'f', 2, 64))
+				eqFC = append(eqFC, strconv.FormatFloat(eqFCtem, 'f', 2, 64))
+				a = false
+			}
+		}
+
+		if a {
+			eqUse = append(eqUse, "0")
+			//eqSum = append(eqSum, "0")
+			eqXZ = append(eqXZ, "0")
+			eqBF = append(eqBF, "0")
+			eqFC = append(eqFC, "0")
+		}
+
+		a = true
+	}
+
+	chartData["pastureName"] = pasture
+	chartData["eqUseRate"] = eqUse
+	//chartData["eqSum"] = eqSum
+	chartData["eqXZRate"] = eqXZ
+	chartData["eqBFRate"] = eqBF
+	chartData["eqFCRate"] = eqFC
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func geteqclassFeeSum(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+
+	year := parammaps.Get(strings.Trim("year", " ")).ValueStr()
+	month := parammaps.Get(strings.Trim("month", " ")).ValueStr()
+	eqClassName := parammaps.Get(strings.Trim("eqClassName", " ")).ValueStr()
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+
+	pSumNow, _ := restful.MapStrList(sqlNow, year, month, eqClassName, eqClassName)
+	if len(pSumNow) == 0 {
+		log.Default().Printf("geteqclassFeeSum  result is empty")
+	}
+	chartData := make(map[string]interface{})
+	eqUse := []string{}
+	eqXZ := []string{}
+
+	for _, va := range pSumNow {
+		eqUse = append(eqUse, va["psum"])
+		eqXZ = append(eqXZ, va["typeName"])
+
+	}
+
+	chartData["data1"] = eqUse
+	chartData["data2"] = eqXZ
+
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func geteqclassSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	deptName := parammaps.Get(strings.Trim("deptName", " ")).ValueStr()
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime, deptName)
+	if len(pSumNow) == 0 {
+		log.Default().Printf("geteqclassSumMonth  result is empty")
+	}
+	chartData := make(map[string]interface{})
+	typeName := []string{}
+	eqCost := []string{}
+	for _, va := range pSumNow {
+		typeName = append(typeName, va["typeName"])
+		eqCost = append(eqCost, va["psum"])
+	}
+	chartData["typeName"] = typeName
+	chartData["eqCost"] = eqCost
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+func getPastureSumDay(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime)
+	if len(pSumNow) == 0 {
+		log.Default().Printf("getPastureSumDay  result is empty")
+	}
+	tempTime, _ := strconv.Atoi(receiveTime[:4])
+	receiveTimetemp := strconv.Itoa(tempTime-1) + receiveTime[4:]
+	pSumLast, _ := restful.MapStrList(sqlNow, pastureNames, receiveTimetemp)
+	chartData := make(map[string]interface{})
+	months := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+	//lastTotal,nowTotal := 0,0
+	a, b := true, true
+	month := ""
+	dayCount := GetMonthCount(receiveTime)
+	for i := 1; i <= dayCount; i++ {
+		if i < 10 {
+			month = receiveTime + "-0" + strconv.Itoa(i)
+		} else {
+			month = receiveTime + "-" + strconv.Itoa(i)
+		}
+		months = append(months, strconv.Itoa(i))
+		for _, va := range pSumNow {
+			if va["month"][8:] == month[8:] {
+				nowYear = append(nowYear, va["psum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["month"][8:] == month[8:] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			if month[:] > time.Now().Format("2006-01-02") {
+				nowYear = append(nowYear, "")
+			} else {
+				nowYear = append(nowYear, "0")
+			}
+
+		}
+		if b {
+			lastYear = append(lastYear, "0")
+		}
+		a = true
+		b = true
+	}
+	chartData["day"] = months
+
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+
+func getPastureSumDay1(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr()
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	pSumNow, _ := restful.MapStrList(sqlNow, pastureNames, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	if len(pSumNow) == 0 {
+		log.Default().Printf("getPastureSumDay1query is empty")
+	}
+	tempTime, _ := strconv.Atoi(receiveTime[:4])
+	receiveTimetemp := strconv.Itoa(tempTime-1) + receiveTime[4:]
+	pSumLast, _ := restful.MapStrList(sqlNow, pastureNames, receiveTimetemp, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	if len(pSumLast) == 0 {
+		log.Default().Printf("getPastureSumDay1 query is empty")
+	}
+	chartData := make(map[string]interface{})
+	months := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+	a, b := true, true
+	month := ""
+	for i := 1; i <= 12; i++ {
+		if i < 10 {
+			month = receiveTime[:4] + "-0" + strconv.Itoa(i)
+		} else {
+			month = receiveTime[:4] + "-" + strconv.Itoa(i)
+		}
+		months = append(months, month)
+		for _, va := range pSumNow {
+			if va["month"][5:7] == month[5:] {
+				nowYear = append(nowYear, va["psum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["month"][5:7] == month[5:] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			if month[:] > time.Now().Format("2006-01") {
+				nowYear = append(nowYear, "")
+			} else {
+				nowYear = append(nowYear, "0")
+			}
+
+		}
+		if b {
+			lastYear = append(lastYear, "0")
+		}
+		a = true
+		b = true
+	}
+	chartData["months"] = months
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+
+func GetMonthCount(receiveTime string) (days int) {
+	year, _ := strconv.Atoi(receiveTime[:4])
+	month, _ := strconv.Atoi(receiveTime[5:])
+	if month != 2 {
+		if month == 4 || month == 6 || month == 9 || month == 11 {
+			days = 30
+		} else {
+			days = 31
+		}
+	} else {
+		if ((year%4) == 0 && (year%100) != 0) || (year%400) == 0 {
+			days = 29
+		} else {
+			days = 28
+		}
+	}
+	return
+}
+func getPastureSumMonth(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	pastureNames := parammaps.Get(strings.Trim("pastureName", " ")).ValueStr()
+	departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr()
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	var pSumNow []map[string]string
+	if sqlnamestr == "getPastureSumMonth" {
+		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	} else {
+		pSumNow, _ = restful.MapStrList(sqlNow, pastureNames, receiveTime)
+	}
+	tempTime, _ := strconv.Atoi(receiveTime)
+	receiveTimetemp := strconv.Itoa(tempTime - 1)
+	var pSumLast []map[string]string
+	if sqlnamestr == "getPastureSumMonth" {
+		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	} else {
+		pSumLast, _ = restful.MapStrList(sqlNow, pastureNames, receiveTimetemp)
+	}
+
+	chartData := make(map[string]interface{})
+	months := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+	//lastTotal,nowTotal := 0,0
+	a, b := true, true
+	month := ""
+	for i := 1; i <= 12; i++ {
+		if i < 10 {
+			month = receiveTime + "-0" + strconv.Itoa(i)
+		} else {
+			month = receiveTime + "-" + strconv.Itoa(i)
+		}
+		months = append(months, month)
+		for _, va := range pSumNow {
+			if va["month"][5:] == month[5:] {
+				nowYear = append(nowYear, va["psum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["month"][5:] == month[5:] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			if month[:] > time.Now().Format("2006-01") {
+				nowYear = append(nowYear, "")
+			} else {
+				nowYear = append(nowYear, "0")
+			}
+
+		}
+		if b {
+			lastYear = append(lastYear, "0")
+		}
+		a = true
+		b = true
+	}
+	chartData["months"] = months
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+
+}
+func geteCow(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+
+	receiveTime := parammaps.Get(strings.Trim("year", " ")).ValueStr()
+	pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture where `name` <> '现代牧业' order by sort")
+	var pSumNow, pSumLast []map[string]string
+	rTime := ""
+	if sqlnamestr == "geteCowAllList" {
+		sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+		if receiveTime == time.Now().Format("2006") {
+			rTime = time.Now().Format("2006-01-02")
+		} else {
+			rTime = receiveTime + "-12-31"
+		}
+		pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime)
+		if receiveTime == time.Now().Format("2006") {
+			rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02")
+		} else {
+			rTime = receiveTime + "-12-31"
+		}
+		receiveTimei, _ := strconv.Atoi(receiveTime)
+		receiveTime = strconv.Itoa(receiveTimei - 1)
+		pSumLast, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime)
+	} else {
+		sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+		if receiveTime == time.Now().Format("2006") {
+			rTime = time.Now().Format("2006-01-02")
+		} else {
+			rTime = receiveTime + "-12-31"
+		}
+		pSumNow, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime)
+		if receiveTime == time.Now().Format("2006") {
+			rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02")
+		} else {
+			rTime = receiveTime + "-12-31"
+		}
+		receiveTimei, _ := strconv.Atoi(receiveTime)
+		receiveTime = strconv.Itoa(receiveTimei - 1)
+		pSumLast, _ = restful.MapStrList(sqlNow, receiveTime, rTime, receiveTime, rTime, receiveTime, rTime)
+	}
+	chartData := make(map[string]interface{})
+	pasture := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+	budgetYear := []string{}
+
+	//lastTotal,nowTotal := 0,0
+	a, b := true, true
+	for _, value := range pastureNames {
+		pasture = append(pasture, value["name"])
+		for _, va := range pSumNow {
+			if va["name"] == value["name"] {
+				nowYear = append(nowYear, va["psum"])
+				budgetYear = append(budgetYear, va["lsum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["name"] == value["name"] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			nowYear = append(nowYear, "0.0000")
+			budgetYear = append(budgetYear, "0.0000")
+		}
+		if b {
+			lastYear = append(lastYear, "0.0000")
+		}
+		a = true
+		b = true
+	}
+
+	chartData["pasture"] = pasture
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	chartData["budgetYear"] = budgetYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+
+func getpSumNow(sqlnamestr string, parammaps *gofasion.Fasion) (map[string]interface{}, error) {
+	queryData := make(map[string]interface{})
+
+	receiveTime := parammaps.Get(strings.Trim("receiveTime", " ")).ValueStr()
+	departmentName := parammaps.Get(strings.Trim("departmentName", " ")).ValueStr()
+	pastureNames, _ := restful.MapStrList("SELECT `name` FROM pasture where `name` <> '现代牧业' order by sort")
+	rTime := ""
+	sqlNow, _ := restful.GetSqlByNameDB(sqlnamestr)
+	var pSumNow []map[string]string
+	if sqlnamestr == "getpSumNow" {
+		pSumNow, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	} else {
+		pSumNow, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime)
+	}
+	//pSumNow, _ := restful.MapStrList(sqlNow, rTime, rTime, receiveTime,departmentName,departmentName,departmentName,departmentName,departmentName,departmentName)
+	receiveTimei, _ := strconv.Atoi(receiveTime)
+	if receiveTime == time.Now().Format("2006") {
+		rTime = time.Now().AddDate(-1, 0, 0).Format("2006-01-02")
+	} else {
+		rTime = receiveTime + "-12-31"
+	}
+	receiveTime = strconv.Itoa(receiveTimei - 1)
+	var pSumLast []map[string]string
+	if sqlnamestr == "getpSumNow" {
+		pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime, departmentName, departmentName, departmentName, departmentName, departmentName, departmentName)
+	} else {
+		pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime)
+	}
+	//pSumLast, _ = restful.MapStrList(sqlNow, rTime, rTime, receiveTime,departmentName,departmentName,departmentName,departmentName,departmentName,departmentName)
+	chartData := make(map[string]interface{})
+	pasture := []string{}
+	lastYear := []string{}
+	nowYear := []string{}
+
+	//lastTotal,nowTotal := 0,0
+	a, b := true, true
+	for _, value := range pastureNames {
+		pasture = append(pasture, value["name"])
+		for _, va := range pSumNow {
+			if va["name"] == value["name"] {
+				nowYear = append(nowYear, va["psum"])
+				a = false
+			}
+		}
+		for _, va := range pSumLast {
+			if va["name"] == value["name"] {
+				lastYear = append(lastYear, va["psum"])
+				b = false
+			}
+		}
+		if a {
+			nowYear = append(nowYear, "0")
+		}
+		if b {
+			lastYear = append(lastYear, "0")
+		}
+		a = true
+		b = true
+	}
+
+	chartData["pasture"] = pasture
+	chartData["lastYear"] = lastYear
+	chartData["nowYear"] = nowYear
+	queryData["chart_data"] = chartData
+	queryData["code"] = 0
+	queryData["message"] = "ok"
+	return queryData, nil
+}
+func GetUpkeepPlan(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+	month := fsion.Get("month").ValueDefaultStr("map")
+	logging.Info("GetUpkeepPlan ", c.Keys, sqlnamestr, month)
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			//c.File("c:/dd.xlsx")
+			c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+			c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+
+		} else {
+			// queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params)
+
+			if err != nil {
+				appG.Response(http.StatusOK, e.ERROR, err.Error())
+			} else {
+				for index, value := range queryData.(map[string]interface{})["list"].([]map[string]string) {
+					if v, ok := value["id"]; ok {
+						//month = "2020-03"
+						seviceplans, _ := restful.MapStrList("SELECT seviceplan.* FROM seviceplan WHERE seviceplan.eqId = ? AND (seviceplan.month=? OR (SELECT COUNT(*) FROM bigupkeep WHERE seviceplanId = seviceplan.`id` AND plantime BETWEEN CONCAT(?,'-01') AND CONCAT(?,'-31'))>0) ", v, month, month, month) //获取保养计划
+						if seviceplans != nil {
+							for _, va := range seviceplans { //根据保养计划获取保养单
+								//day,_ :=strconv.Atoi(va["day"])
+								bigupkeeps, _ := restful.MapStrList("SELECT * FROM bigupkeep where seviceplanId = ? and plantime between concat(?,'-01') and concat(?,'-31') ", va["id"], month, month) //获取保养计划中的保养单
+								//buk := make(map[string]map[string]string)
+								for _, bu := range bigupkeeps { //日期为key ,保养单为value 存到map中
+									jstr := ""
+									if bu["plantime"][8:9] == "0" {
+										jstr = "m" + bu["plantime"][9:]
+									} else {
+										jstr = "m" + bu["plantime"][8:]
+									}
+
+									if bu["flowCompeleted"] < "2" && bu["plantime"] < time.Now().Add(-24*time.Hour).Format("2006-01-02") { //如果保养状态是0并且小于当前日期 则状态已延期2
+										queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#2" + "#" + bu["id"] + "#" + bu["pushbackId"]
+									} else {
+										if bu["flowCompeleted"] >= "2" {
+											queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#1" + "#" + bu["id"] + "#" + bu["pushbackId"]
+										} else {
+											queryData.(map[string]interface{})["list"].([]map[string]interface{})[index][jstr] = va["upkeepName"] + "#" + va["id"] + "#0" + "#" + bu["id"] + "#" + bu["pushbackId"]
+										}
+									}
+								}
+
+							}
+
+						}
+					}
+				}
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+
+			}
+		}
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+func GetAccount(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	returntype := fsion.Get("returntype").ValueDefaultStr("map")
+
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, nil)
+	//fmt.Println("sql========\n",sqlnamestr,sql)
+	if sql != "" {
+		s_params := make([]interface{}, 0)
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			if sqlnamestr != "getNoMesList" && sqlnamestr != "getNoMesCount" {
+				logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			}
+
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+				fmt.Println("params parse end")
+			}
+
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("GetDataByName", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		if returntype == "xlsx" {
+			var xlsxfile *xlsx.File
+			xlsxfile, _ = restful.QueryByXlsx(sql, s_params)
+			//c.File("c:/dd.xlsx")
+			c.Header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
+			c.Header("Content-Disposition", "attachment; filename="+"Workbook.xlsx")
+			c.Header("Content-Transfer-Encoding", "binary")
+			_ = xlsxfile.Write(c.Writer)
+
+		} else {
+			// queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params, tx)
+			queryData, err := getDataBySqlT(sql, offset, pagecount, returntype, s_params)
+
+			if err != nil {
+				logging.Error("GetDataByName  err: ", err)
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg)
+				//appG.Response(http.StatusOK, e.ERROR, err.Error())
+			} else {
+				appG.Response(http.StatusOK, e.SUCCESS, queryData)
+			}
+		}
+
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags PostDataByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByName  [POST]
+func PostDataByName(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	parammaps := fsion.Get("parammaps")
+	if sqlnamestr == "partsCharge" && parammaps.Get("statue").ValueInt() == 1 {
+		//fmt.Println("jinlaile")
+		defer func() {
+			go util.EASBillSync(5, fsion.Get("parammaps").Get("id").ValueStr(), fsion.Get("parammaps").Get("statue").ValueStr())
+		}()
+		//go CheckEASWebServiceParts(fsion.Get("parammaps").Get("statue").ValueStr(),fsion.Get("parammaps").Get("id").ValueStr())
+	}
+
+	s_params := make([]interface{}, 0)
+	tx, err := restful.Dbs.Beginx()
+
+	defer func() {
+		switch {
+		case err != nil:
+			fmt.Println("__error:", err)
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+
+	}()
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
+	if sql != "" {
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		queryData, err := execDataBySqlT(sql, s_params, tx)
+		if err != nil {
+			logging.Error("PostDataByName  err: ", err)
+			//appG.Response(http.StatusOK, e.ERROR, err.Error())
+			msg := geterrmsg(err.Error())
+			appG.Response(http.StatusOK, e.ERROR, msg)
+		} else {
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+func PostThirdPartyData(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	tempval_ := make(map[string]interface{})
+	tempval := make([]map[string]interface{}, 0)
+	err := json.Unmarshal(dataByte, &tempval_)
+	logging.Info("PostThirdPartyData ", c.Keys, c.Request.RemoteAddr, tempval_["name"])
+	//logging.Info("PostThirdPartyData ", c.Keys, c.Request.RemoteAddr, tempval_["name"],tempval_)
+	if err != nil {
+		logging.Error("PostThirdPartyData Unmarshal error:", err)
+	} else {
+		if v, ok := tempval_["list"].([]interface{}); ok {
+			for _, Tvalue := range v {
+				if v1, ok := Tvalue.(map[string]interface{}); ok {
+					tempval = append(tempval, v1)
+				}
+			}
+		}
+		tx, err := restful.Dbs.Beginx()
+
+		if err != nil {
+			logging.Error("tx.Begin 事务启动失败__error:", err)
+		}
+		defer func() {
+			switch {
+			case err != nil:
+				fmt.Println("__error:", err)
+				if tx != nil {
+					tx.Rollback()
+				}
+			default:
+				if tx != nil {
+					err = tx.Commit()
+				}
+			}
+			if tx != nil {
+
+			}
+		}()
+
+		if err == nil {
+			sqlname, ok := tempval_["name"]
+			if ok {
+
+			}
+			sql, p := restful.GetSqlByNameDBT(sqlname.(string), tx)
+			if sql == "" {
+				appG.Response(http.StatusOK, e.ERROR, "调用接口不存在")
+			}
+			//s_params := make([]interface{}, 0)
+			paramslist := strings.Split(p, ",")
+			resname := ""
+
+			for _, paramvalue := range tempval {
+				s_params := make([]interface{}, 0)
+				if len(paramslist) > 0 && p != "" {
+					for _, value := range paramslist {
+						s_params = append(s_params, paramvalue[value])
+						//fmt.Println(value,paramvalue[value])
+
+					}
+				}
+				var res []map[string]string
+				res, err = restful.MapStrList("select id from measure where meterNumber = ? and meterType = '电表' and isdel = 0", paramvalue["meterNumber"])
+				if len(res) == 0 || err != nil {
+					switch paramvalue["meterNumber"].(type) {
+					case string:
+						resname = paramvalue["meterNumber"].(string)
+					}
+					err = errors.New("电表不存在")
+					break
+				}
+
+				_, err = execDataBySqlT(sql, s_params, tx)
+				if err != nil {
+					switch paramvalue["meterNumber"].(type) {
+					case string:
+						resname = paramvalue["meterNumber"].(string)
+					}
+					break
+				}
+			}
+			if err == nil {
+				appG.Response(http.StatusOK, e.SUCCESS, "ok")
+			} else {
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg+"  "+resname)
+				//appG.Response(http.StatusOK, e.ERROR, err.Error())
+			}
+		}
+	}
+	if err != nil {
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		//appG.Response(http.StatusOK, e.ERROR, err.Error())
+	}
+}
+func PostDataByNameOPEN(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	sqlnamestr = sqlnamestr + "OPEN"
+	s_params := make([]interface{}, 0)
+	tx, err := restful.Dbs.Beginx()
+
+	defer func() {
+		switch {
+		case err != nil:
+			fmt.Println("__error:", err)
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+
+	}()
+	sql, p := restful.GetSqlByNameDBT(sqlnamestr, tx)
+	if sql != "" {
+		if fsion.HasKey("parammaps") {
+			parammaps := fsion.Get("parammaps")
+			logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, parammaps.ValueStr())
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+					}
+				}
+			}
+		} else if fsion.HasKey("params") {
+			params := fsion.Get("params").Array()
+			logging.Info("PostDataByName ", c.Keys, c.Request.RemoteAddr, sqlnamestr, params)
+			for _, v_params := range params {
+				s_params = append(s_params, v_params.ValueStr())
+			}
+		}
+		queryData, err := execDataBySqlT(sql, s_params, tx)
+		if err != nil {
+			logging.Error("PostDataByName  err: ", err)
+			//appG.Response(http.StatusOK, e.ERROR, err.Error())
+			msg := geterrmsg(err.Error())
+			appG.Response(http.StatusOK, e.ERROR, msg)
+		} else {
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags ExecDataByConfig
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByName  [POST]
+//
+func ExecDataByConfig(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	tempval_ := make(map[string]interface{})
+	tempCommon := make(map[string]interface{})
+	tempval := make([]map[string]interface{}, 0)
+	err := json.Unmarshal(dataByte, &tempval_)
+	logging.Info("ExecDataByConfig ", c.Keys, c.Request.RemoteAddr, tempval_["common"], tempval_["data"])
+	if err != nil {
+		fmt.Println("error:", err)
+	} else {
+		if v, ok := tempval_["common"].(map[string]interface{}); ok {
+			tempCommon = v
+		}
+
+		if v, ok := tempval_["data"].([]interface{}); ok {
+			for _, Tvalue := range v {
+				if v1, ok := Tvalue.(map[string]interface{}); ok {
+					tempval = append(tempval, v1)
+				}
+			}
+		}
+		tx, err := restful.Dbs.Beginx()
+
+		if err != nil {
+			logging.Error("tx.Begin 事务启动失败__error:", err)
+		}
+		defer func() {
+			switch {
+			case err != nil:
+				fmt.Println("__error:", err)
+				if tx != nil {
+					tx.Rollback()
+				}
+			default:
+				if tx != nil {
+					err = tx.Commit()
+				}
+			}
+			if tx != nil {
+
+			}
+		}()
+
+		if err == nil {
+			if tempv, exists := c.Get("jwt_username"); exists {
+				tempCommon["jwt_username"] = tempv.(string)
+			}
+
+			for _, paramvalue := range tempval {
+				if _, ok := paramvalue["resultname"]; !ok {
+					paramvalue["resultname"] = paramvalue["name"]
+				}
+				_, err = ExecDataParam(paramvalue, tempCommon, tempval, nil, nil, tx)
+				if err != nil {
+					logging.Error("ExecDataParam error:", err)
+					break
+				}
+			}
+			if err == nil {
+				if tempCommon["returnmap"] != nil && tempCommon["returnmap"] != "" {
+					appG.Response(http.StatusOK, e.SUCCESS, tempval)
+				} else {
+					appG.Response(http.StatusOK, e.SUCCESS, "成功执行!")
+				}
+				go NextService(tempval)
+			} else {
+				msg := geterrmsg(err.Error())
+				appG.Response(http.StatusOK, e.ERROR, msg)
+			}
+		}
+	}
+
+	if err != nil {
+		msg := geterrmsg(err.Error())
+		appG.Response(http.StatusOK, e.ERROR, msg)
+		//appG.Response(http.StatusOK, e.ERROR, err.Error())
+	}
+	// 开协程
+	defer func() {
+		go BillType(tempval_)
+	}()
+}
+func BillType(tempval_ map[string]interface{}) {
+	var typein int
+	switch tempval_["data"].(type) {
+	case []interface{}:
+		if len(tempval_["data"].([]interface{})) > 0 {
+			name := tempval_["data"].([]interface{})[0].(map[string]interface{})["name"]
+			switch name {
+			case "insertBigPartlaid":
+				billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["laidCode"]
+				laidType := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["laidType"])
+
+				if laidType != "2" {
+					typein = 1
+				} else {
+					typein = 6
+				}
+				_ = util.EASBillSync(typein, billcode, "")
+			case "insertBigPartUse":
+				billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useForm"]
+				usetypev := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useType"])
+				if usetypev != "4" {
+					typein = 2
+				} else {
+					typein = 7
+				}
+				_ = util.EASBillSync(typein, billcode, "")
+			case "insertBigPartquit":
+				billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["useForm"]
+				_ = util.EASBillSync(3, billcode, "")
+			case "PartRefundCharge1":
+				billcode := tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["id"]
+				statue := interfacetostringv2(tempval_["data"].([]interface{})[0].(map[string]interface{})["parammaps"].(map[string]interface{})["statue"])
+				if statue == "5" {
+					_ = util.EASBillSync(4, billcode, "")
+				}
+			}
+		}
+	}
+}
+func interfacetostring(val interface{}) string {
+	switch val.(type) {
+	case string:
+		ss := val.(string)
+		return ss
+	case int:
+		ss := val.(int)
+		return strconv.Itoa(ss)
+	case int64:
+		ss := val.(int64)
+		return strconv.FormatInt(ss, 10)
+	case float64:
+		ss := val.(float64)
+		return strconv.FormatFloat(ss, 'E', -1, 32)
+	}
+	return ""
+}
+func interfacetostringv2(val interface{}) string {
+	switch val.(type) {
+	case string:
+		ss := val.(string)
+		return ss
+	case int:
+		ss := val.(int)
+		return strconv.Itoa(ss)
+	case int64:
+		ss := val.(int64)
+		return strconv.FormatInt(ss, 10)
+	case float64:
+		ss := int(val.(float64))
+		return strconv.Itoa(ss)
+	}
+	return ""
+}
+func getParamValue(parammaps map[string]interface{}, value string, ParamMap []map[string]interface{}) string {
+	if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
+
+		tempstrb := strings.IndexAny(valuestring, "@")
+		tempstre := strings.IndexAny(valuestring, ".")
+		if tempstrb > -1 && tempstre > -1 {
+			for _, ParamMapList := range ParamMap {
+				if v, ok := ParamMapList["resultname"]; ok {
+					if v == valuestring[tempstrb+1:tempstre] {
+						if v1, ok := ParamMapList["resultmaps"]; ok {
+							if newA, ok := v1.([]map[string]interface{}); ok {
+								return interfacetostring(newA[0][valuestring[tempstre+1:]])
+							} else if newA, ok := v1.(map[string]interface{}); ok {
+								return interfacetostring(newA[valuestring[tempstre+1:]])
+							}
+
+						}
+					}
+				}
+			}
+		} else {
+			return valuestring
+		}
+	} else if valuestring, ok := parammaps[strings.Trim(value, " ")].(float64); ok {
+		return strconv.FormatInt(int64(valuestring), 10)
+	}
+	return ""
+}
+func getParamValue_(parammaps map[string]interface{}, value string, ParamMap map[string]interface{}) string {
+	if valuestring, ok := parammaps[strings.Trim(value, " ")].(string); ok {
+		tempstrb := strings.IndexAny(valuestring, "@")
+		tempstre := strings.IndexAny(valuestring, ".")
+		if tempstrb > -1 && tempstre > -1 {
+			if v, ok := ParamMap[valuestring[tempstre+1:]]; ok {
+				if s, ok := v.(string); ok {
+					return s
+				} else if s, ok := v.(float64); ok {
+					return strconv.FormatInt(int64(s), 10)
+				}
+			}
+		}
+	}
+
+	return ""
+}
+func ExecDataParam(fasion map[string]interface{}, CommonParamMap map[string]interface{}, ParamMap []map[string]interface{}, ParentParamMap map[string]interface{}, sameParamMap []map[string]interface{}, tx *sqlx.Tx) ([]map[string]interface{}, error) {
+	sqlname := fasion["name"].(string)
+	sqltype := "" //v  校验/s1 查询/sm 查询/e  执行
+	defer func() {
+		if sqlname == "batchPartsSH" {
+			id := ""
+			switch ParentParamMap["id"].(type) {
+			case float64:
+				id = strconv.Itoa(int(ParentParamMap["id"].(float64)))
+			case string:
+				id = ParentParamMap["id"].(string)
+			case int:
+				id = strconv.Itoa(ParentParamMap["id"].(int))
+			}
+			go util.EASBillSync(5, id, "1")
+			//go CheckEASWebServiceParts("1",id)
+		}
+	}()
+	if v, ok := fasion["type"]; ok {
+		sqltype = v.(string)
+	}
+	sql := ""
+	p := ""
+	s_params := make([]interface{}, 0)
+	if sqltype != "" {
+		sql, p = restful.GetSqlByName(sqlname, nil)
+		//sqlApi, _ := model.GetApisqlByName(sqlname)
+		if v, ok := fasion["parammaps"].(map[string]interface{}); ok {
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					ss := ""
+
+					if ss == "" && CommonParamMap != nil {
+						if valuestring, ok := v[strings.Trim(value, " ")].(string); ok {
+							ss = valuestring
+							tempstrb := strings.IndexAny(valuestring, "@")
+							tempstre := strings.IndexAny(valuestring, ".")
+							if (tempstre > tempstrb) && (strings.ToLower(valuestring[tempstrb+1:tempstre]) == "common") {
+								if CommonParamMap[valuestring[tempstre+1:]] != nil {
+									ss = CommonParamMap[valuestring[tempstre+1:]].(string)
+								}
+							} else {
+								ss = ""
+							}
+						}
+
+					}
+					if ss == "" && ParentParamMap != nil {
+						ss = getParamValue_(v, value, ParentParamMap)
+					}
+
+					if ss == "" && sameParamMap != nil {
+						ss = getParamValue(v, value, sameParamMap)
+					}
+
+					if ss == "" && ParamMap != nil {
+						ss = getParamValue(v, value, ParamMap)
+					}
+					s_params = append(s_params, ss)
+				}
+			}
+
+		}
+	}
+	if sql == "" {
+		sqltype = ""
+	}
+	if sqltype == "s1" {
+		tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
+		if v, ok := tempValParam.(map[string]interface{}); ok {
+			fasion["resultmaps"] = v["list"].([]map[string]interface{})
+		}
+		if err != nil {
+			return nil, err
+		}
+		err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
+		if err != nil {
+			return nil, err
+		}
+		return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
+	} else if sqltype == "sm" {
+		tempValParam, err := restful.QueryByMap(sql, 0, 0, s_params)
+		if v, ok := tempValParam.(map[string]interface{}); ok {
+			fasion["resultmaps"] = v["list"].([]map[string]interface{})
+		} else {
+			fmt.Println("sm", tempValParam)
+		}
+
+		if err != nil {
+			return nil, err
+		}
+		err = ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
+		if err != nil {
+			return nil, err
+		}
+		return tempValParam.(map[string]interface{})["list"].([]map[string]interface{}), err
+
+	} else if sqltype == "v" {
+		tempValParam, err := restful.QueryByMap(sql, 0, 1, s_params)
+		if v, ok := tempValParam.(map[string]interface{}); ok {
+			fasion["resultmaps"] = v["list"].([]map[string]interface{})
+		} else {
+			fmt.Println("v", tempValParam)
+		}
+		if err != nil {
+			return nil, err
+		}
+		if tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"] != "" {
+			return nil, errors.New(tempValParam.(map[string]interface{})["list"].([]map[string]interface{})[0]["vmsg"].(string))
+		}
+	} else if sqltype == "e" {
+		tempVal_arrary := make([]map[string]interface{}, 0)
+		tempVal_map := make(map[string]interface{})
+		tempValParam, err := restful.ExecQueryT(sql, s_params, tx)
+		if err == nil {
+			fasion["resultmaps"] = tempValParam.(map[string]interface{})
+			tempVal_map["result"] = tempValParam.(map[string]interface{})["result"]
+			tempVal_map["LastInsertId"] = tempValParam.(map[string]interface{})["LastInsertId"]
+			tempVal_arrary = append(tempVal_arrary, tempVal_map)
+			return tempVal_arrary, err
+		}
+		return nil, err
+	} else {
+		if tempValParam, ok := fasion["resultmaps"].(map[string]interface{}); ok {
+			err := ExitsChildrenParam(fasion, tempValParam, ParamMap, CommonParamMap, tx)
+			if err != nil {
+				return nil, err
+			}
+			return nil, err
+		}
+	}
+	return nil, nil
+}
+func ExitsChildrenParam(fasion map[string]interface{}, tempValParam interface{}, ParamMap []map[string]interface{}, commonParam map[string]interface{}, tx *sqlx.Tx) error {
+	var err error
+	subarray, ok := fasion["children"]
+
+	if ok {
+		for _, v := range tempValParam.(map[string]interface{})["list"].([]interface{}) { //遍历父集有多少行数据
+			tempVal_arrary := make([]map[string]interface{}, 0)
+			for _, subarrayvalue := range subarray.([]interface{}) { //遍历所有执行命令
+				tempVal_ := make(map[string]interface{})
+				if _, ok := subarrayvalue.(map[string]interface{})["resultname"]; !ok {
+					tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["name"]
+				} else {
+					tempVal_["resultname"] = subarrayvalue.(map[string]interface{})["resultname"]
+				}
+				tempVal_["resultmaps"], err = ExecDataParam(subarrayvalue.(map[string]interface{}), commonParam, ParamMap, v.(map[string]interface{}), tempVal_arrary, tx) //递归调用执行
+
+				if err != nil {
+					return err
+				}
+				tempVal_arrary = append(tempVal_arrary, tempVal_)
+			}
+			v.(map[string]interface{})["children"] = tempVal_arrary
+		}
+	}
+	return nil
+}
+
+// @Summary   删除图片
+// @Tags RemovePicByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByName  [POST]
+func RemovePicByName(c *gin.Context) {
+	logging.Info("RemovePicByName ", c.Keys)
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlnamestr := fsion.Get("name").ValueStr()
+	picname := fsion.Get("picname").ValueStr()
+	sql, _ := restful.GetSqlByNameDB(sqlnamestr)
+	params := fsion.Get("params").Array()
+	s_params := make([]interface{}, 0)
+	for _, v_params := range params {
+		s_params = append(s_params, v_params.ValueStr())
+	}
+	if sql != "" {
+		queryData, err := execDataBySql(sql, s_params)
+
+		if picname != "" {
+			// Destination
+			distPath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picname)
+
+			err := os.Remove(distPath) //删除文件test.txt
+			if err != nil {
+				//如果删除失败则输出 file remove Error!
+				fmt.Println("file remove Error!")
+				//输出错误详细信息
+				fmt.Printf("%s", err)
+			} else {
+				//如果删除成功则输出 file remove OK!
+				fmt.Print("file remove OK!")
+			}
+			distPath = path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picname)
+
+			err = os.Remove(distPath) //删除文件test.txt
+			if err != nil {
+				//如果删除失败则输出 file remove Error!
+				fmt.Println("file remove Error!")
+				//输出错误详细信息
+				fmt.Printf("%s", err)
+			} else {
+				//如果删除成功则输出 file remove OK!
+				fmt.Print("file remove OK!")
+			}
+		}
+
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR, err.Error())
+		} else {
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	} else {
+		appG.Response(http.StatusOK, e.SUCCESS, nil)
+	}
+}
+
+// @Summary   删除文件
+// @Tags RemoveFileByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByName  [POST]
+func RemoveFileByName(c *gin.Context) {
+	appG := app.Gin{C: c}
+	id := c.Param("id")
+	logging.Info("DownloadFile ", c.Keys, id)
+	eqdoc, err := restful.MapStrList("SELECT * FROM eq_doc where id = ? ", id)
+	if eqdoc == nil {
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+		return
+	}
+	distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, eqdoc[0]["docpath"], eqdoc[0]["newdocname"])
+
+	err = os.Remove(distPath) //删除文件test.txt
+	if err != nil {
+		//如果删除失败则输出 file remove Error!
+		fmt.Println("file remove Error!")
+		//输出错误详细信息
+		fmt.Printf("%s", err)
+		appG.Response(http.StatusOK, e.ERROR, err.Error())
+		return
+	}
+	fmt.Print("file remove OK!")
+	_, err = restful.MapStrList("delete FROM eq_doc where id = ? ", id)
+	if err != nil {
+		log.Default().Printf("RemoveFileByName:%v", err)
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, "OK")
+
+	//dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	//fsion := gofasion.NewFasion(string(dataByte))
+	//sqlnamestr := fsion.Get("name").ValueStr()
+	//filename := fsion.Get("filename").ValueStr()
+	//sql, _ := restful.GetSqlByNameDB(sqlnamestr)
+	//params := fsion.Get("params").Array()
+	//s_params := make([]interface{}, 0)
+	//for _, v_params := range params {
+	//	s_params = append(s_params, v_params.ValueStr())
+	//}
+	//if sql != "" {
+	//	queryData, err := execDataBySql(sql, s_params)
+	//
+	//	if filename != "" {
+	//		// Destination
+	//		distPath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
+	//
+	//		err := os.Remove(distPath) //删除文件test.txt
+	//		if err != nil {
+	//			//如果删除失败则输出 file remove Error!
+	//			fmt.Println("file remove Error!")
+	//			//输出错误详细信息
+	//			fmt.Printf("%s", err)
+	//		} else {
+	//			//如果删除成功则输出 file remove OK!
+	//			fmt.Print("file remove OK!")
+	//		}
+	//	}
+
+	//	if err != nil {
+	//		appG.Response(http.StatusOK, e.ERROR, err.Error())
+	//	} else {
+	//		appG.Response(http.StatusOK, e.SUCCESS, "OK")
+	//	}
+	//} else {
+	//	appG.Response(http.StatusOK, e.SUCCESS, nil)
+	//}
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags PostDataByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDataByName  [POST]
+func UpdateDataRelation(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	tablename := fsion.Get("name").ValueStr()
+	dataname := fsion.Get("dataname").ValueStr()
+	datavalue := fsion.Get("datavalue").ValueStr()
+	valuename := fsion.Get("valuename").ValueStr()
+	logging.Info("UpdateDataRelation ", c.Keys, c.Request.RemoteAddr, tablename, dataname, datavalue, valuename)
+	values := fsion.Get("values").Array()
+	tx, err := restful.Dbs.Beginx()
+
+	defer func() {
+		switch {
+		case err != nil:
+			fmt.Println("__error:", err)
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+
+	}()
+	insertSqlstr := "insert into " + tablename + "( " + dataname + "," + valuename + ") select DISTINCT  ?, ? from DUAL " +
+		" where NOT EXISTS (select " + valuename + " from " + tablename + " where " + valuename + " = ? and " + dataname + " = ?)"
+
+	d_params := make([]interface{}, 4)
+	d_params[0] = datavalue
+	s_params := ""
+
+	for _, v_values := range values {
+		d_params[1] = v_values.ValueStr()
+		if s_params == "" {
+			s_params = v_values.ValueStr()
+		} else {
+			s_params = s_params + "," + v_values.ValueStr()
+		}
+		d_params[2] = d_params[1]
+		d_params[3] = d_params[0]
+		_, err := execDataBySqlT(insertSqlstr, d_params, tx)
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR, err.Error())
+			break
+		}
+	}
+
+	if s_params != "" {
+
+		deleteSqlstr := "delete from " + tablename + " " +
+			"           where " + dataname + " = " + datavalue + " and " + valuename + " not in (" + s_params + ")"
+		queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR, err.Error())
+		} else if err == nil {
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	} else {
+		deleteSqlstr := "delete from " + tablename + " " +
+			"           where " + dataname + " = " + datavalue
+		queryData, err := execDataBySqlT(deleteSqlstr, nil, tx)
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR, err.Error())
+		} else if err == nil {
+			appG.Response(http.StatusOK, e.SUCCESS, queryData)
+		}
+	}
+}
+
+// @Summary   根据APISQL表中SQL执行得到数据集
+// @Tags PostDatasByName
+// @Accept json
+// @Produce  json
+// @Param  sqlname  query   string true "sqlname"
+// @Param  offset  query   int true "offset"
+// @Param  pagecount  query   int true "pagecount"
+// @Param  returntype  query   string true "returntype"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/PostDatasByName  [POST]
+func PostDataByNames(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	sqlParams := fsion.Get("array").Array()
+	queryData := make(map[string]interface{})
+	for _, v := range sqlParams {
+		fsion2 := gofasion.NewFasion(v.Json())
+		logging.Info("PostDataByNames ", c.Keys, fsion2.Get("name").ValueStr())
+		sql, p := restful.GetSqlByNameDB(fsion2.Get("name").ValueStr())
+		if sql == "" {
+			errorm := make(map[string]interface{})
+			errorm["code"] = e.ERROR
+			errorm["message"] = "sql没有找到"
+			errorm["param"] = ""
+			queryData[fsion2.Get("name").ValueStr()] = errorm
+			continue
+		} else if sql != "" {
+			s_params := make([]interface{}, 0)
+			if fsion2.HasKey("parammaps") {
+				parammaps := fsion2.Get("parammaps")
+
+				paramslist := strings.Split(p, ",")
+				if len(paramslist) > 0 && p != "" {
+					for _, value := range paramslist {
+						if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+							if tempv, exists := c.Get("jwt_username"); exists {
+								s_params = append(s_params, tempv.(string))
+							} else {
+								s_params = append(s_params, "")
+							}
+						} else {
+							s_params = append(s_params, parammaps.Get(strings.Trim(value, " ")).ValueStr())
+						}
+					}
+				}
+			} else if fsion2.HasKey("params") {
+				params := fsion2.Get("params").Array()
+				for _, v_params := range params {
+					s_params = append(s_params, v_params.ValueStr())
+				}
+			}
+			_, err := execDataBySql(sql, s_params)
+
+			if err != nil {
+				logging.Error("PostDataByName  err: ", err)
+				errorm := make(map[string]interface{})
+				errorm["code"] = e.ERROR
+				errorm["message"] = err.Error()
+				errorm["msg"] = "fail"
+				errorm["param"] = s_params
+				queryData[fsion2.Get("name").ValueStr()] = errorm
+				continue
+			} else {
+				errorm := make(map[string]interface{})
+				errorm["code"] = e.SUCCESS
+				errorm["message"] = "success"
+				errorm["msg"] = "ok"
+				queryData[fsion2.Get("name").ValueStr()] = errorm
+				continue
+			}
+		} else {
+			errorm := make(map[string]interface{})
+			errorm["code"] = e.ERROR
+			errorm["message"] = "NO SQL"
+			errorm["param"] = ""
+			queryData[fsion2.Get("name").ValueStr()] = errorm
+		}
+	}
+	//appG.Response(http.StatusOK, e.SUCCESS, msg)
+	appG.Response(http.StatusOK, e.SUCCESS, queryData)
+}
+func getDataBySql(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
+	if offset > 0 {
+		offset = offset - 1
+	}
+
+	if returntype == "list" {
+		queryData, err := restful.QueryByList(sqlstr, offset, pagecount, params)
+		return queryData, err
+	} else if returntype == "listlist" {
+		queryData, err := restful.QueryByListList(sqlstr, offset, pagecount, params)
+		return queryData, err
+	} else {
+		queryData, err := restful.QueryByMap(sqlstr, offset, pagecount, params)
+		return queryData, err
+	}
+}
+
+// func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+func getDataBySqlT(sqlstr string, offset, pagecount int, returntype string, params []interface{}) (interface{}, error) {
+	if offset > 0 {
+		offset = offset - 1
+	}
+
+	if returntype == "list" {
+		// queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params, tx)
+		queryData, err := restful.QueryByListT(sqlstr, offset, pagecount, params)
+		return queryData, err
+	} else if returntype == "listlist" {
+		// queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params, tx)
+		queryData, err := restful.QueryByListListT(sqlstr, offset, pagecount, params)
+		return queryData, err
+	} else {
+		// queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params, tx)
+		queryData, err := restful.QueryByMapT(sqlstr, offset, pagecount, params)
+		return queryData, err
+	}
+}
+func GetRecuData_BySql(sql string, Params string, idname string, thisParams map[string]interface{}, isList bool) (interface{}, error) {
+	paramslist := strings.Split(Params, ",")
+	s_params := make([]interface{}, 0)
+	if isList {
+		for _, v_params := range thisParams["params"].([]interface{}) {
+			s_params = append(s_params, v_params)
+		}
+	} else {
+		paramslist := strings.Split(Params, ",")
+		if len(paramslist) > 0 && Params != "" {
+			for _, value := range paramslist {
+				s_params = append(s_params, thisParams[strings.Trim(value, " ")])
+			}
+		}
+	}
+	queryData, err := restful.QueryByMapMenu(sql, 0, 0, s_params)
+	for _, queryData_ := range queryData {
+		if v, ok := queryData_["haschildren"]; (ok && v.(int64) > 0) || !ok {
+			if isList {
+				//fmt.Println(idname, "--------------             -queryData_[idname]", queryData_)
+				if queryData_[idname] != nil {
+					thisParams["params"].([]interface{})[len(thisParams["params"].([]interface{}))-1] = queryData_[idname].(interface{})
+				}
+
+			} else {
+				if queryData_[idname] != nil {
+					thisParams[idname] = queryData_[idname].(interface{})
+				}
+				if len(paramslist) > 0 && Params != "" {
+					s_params = make([]interface{}, 0)
+					for _, value := range paramslist {
+						s_params = append(s_params, thisParams[strings.Trim(value, " ")])
+					}
+				}
+			}
+			queryData_["children"], _ = GetRecuData_BySql(sql, Params, idname, thisParams, isList)
+		} else {
+
+		}
+	}
+	return queryData, err
+}
+func execDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
+	queryData, err := restful.ExecQuery(sqlstr, params)
+	return queryData, err
+}
+func execDataBySqlT(sqlstr string, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+	queryData, err := restful.ExecQueryT(sqlstr, params, tx)
+	return queryData, err
+}
+func ExecDataBySql(sqlstr string, params []interface{}) (interface{}, error) {
+	queryData, err := restful.ExecQuery(sqlstr, params)
+	return queryData, err
+}
+
+// @Summary   导入excel文件到数据库,excel第一行作为参数
+// @Tags ImportExcel
+// @Accept json
+// @Produce  json
+// @Param  file  query   string true "文件名"
+// @Param  name  header   string  true "执行sql的名字"
+// @Success 200 {string} json  "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /data/ImportExcel  [POST]
+// @param 备件编号,备件名称,规格型号,计量单位,品牌,计划量,单价,备注,jwt_username
+// func ImportExcel(c *gin.Context) {
+// 	log.Default().Println("Importing Excel================================")
+// 	appG := app.Gin{C: c}
+// 	file, _, err := c.Request.FormFile("file")
+// 	if err != nil {
+// 		logrus.Errorf("request.FormFile: %v", err)
+// 		appG.Response(http.StatusOK, e.ERROR, err)
+// 		return
+// 	}
+// 	xlsx1, err := excelize.OpenReader(file)
+// 	if err != nil {
+// 		logrus.Errorf("excelize.OpenReader: %v", err)
+// 		appG.Response(http.StatusOK, e.ERROR, err)
+// 		return
+// 	}
+// 	c.Request.ParseForm()
+// 	params := c.Request.Form
+// 	sheetname := params.Get("sheetname")
+// 	rows := xlsx1.GetRows(sheetname)
+// 	importParams := params.Get("importParams")
+// 	paramslist := strings.Split(importParams, ",")
+// 	sqlnamestr := params.Get("name")
+// 	sql, _ := restful.GetSqlByNameDB(sqlnamestr)
+// 	inputdata := ""
+// 	ok := 0
+// 	error := 0
+// 	queryData := make([]interface{}, 0)
+// 	data := make(map[string]interface{})
+// 	if len(rows) > 10000 {
+// 		rows = rows[:10000]
+// 	}
+// 	if len(rows) <= 1 {
+// 		logrus.Errorln("表格为空")
+// 		appG.Response(http.StatusOK, e.ERROR, errors.New("表格为空"))
+// 		return
+// 	}
+// 	if len(rows[0]) < len(paramslist) {
+// 		logrus.Errorln("表格缺少数据列")
+// 		appG.Response(http.StatusOK, e.ERROR, errors.New("表格缺少数据列"))
+// 		return
+// 	}
+// 	for i, v := range paramslist {
+// 		if strings.Trim(rows[0][i], " ") != v {
+// 			logrus.Errorln("表格数据列顺序不符合标准,或标题名称错误")
+// 			appG.Response(http.StatusOK, e.ERROR, errors.New("表格数据列顺序不符合标准,或标题名称错误"))
+// 			return
+// 		}
+// 	}
+// 	for _, row := range rows[1:] {
+// 		s_params := make([]interface{}, 0)
+// 		outentry := make(map[string]interface{})
+// 		for i := range row {
+// 			row[i] = strings.TrimSpace(row[i])
+// 			s_params = append(s_params, row[i])
+// 		}
+// 		uname := ""
+// 		if tempv, b := c.Get("jwt_username"); b {
+// 			uname = tempv.(string)
+// 		}
+// 		s_params = append(s_params, uname)
+// 		outentry["input"] = inputdata
+// 		log.Default().Printf("params=%v", s_params...)
+// 		returnmsg, err := getDataBySql(sql, 0, 0, "4", s_params)
+
+// 		returnmsgmap, _ := returnmsg.(map[string]interface{})
+// 		returnmsgmap1, _ := returnmsgmap["list"].([]map[string]interface{})
+// 		if err != nil {
+// 			outentry["error_msg"] = err.Error()
+// 			error++
+// 			queryData = append(queryData, outentry)
+// 		} else if (len(returnmsgmap1) > 0) && (returnmsgmap1[0]["msg"] == "success") {
+// 			ok++
+// 		} else {
+// 			msg := geterrmsg(returnmsgmap1[0]["msg"].(string))
+// 			outentry["error_msg"] = msg
+// 			error++
+// 			queryData = append(queryData, outentry)
+// 		}
+// 	}
+// 	data["result"] = queryData
+// 	data["success"] = ok
+// 	data["err_count"] = error
+// 	appG.Response(http.StatusOK, e.SUCCESS, data)
+// }
+func ImportExcel(c *gin.Context) {
+	appG := app.Gin{C: c}
+
+	inputdata := ""
+	if err := c.Request.ParseForm(); err != nil {
+		log.Default().Printf("request.parseform:%v", err)
+		appG.Response(http.StatusOK, e.ERROR, err)
+		return
+	}
+	params := c.Request.Form
+	// file, _, err := c.Request.FormFile("file")
+	fileHeader, err := c.FormFile("file")
+	file, err := fileHeader.Open()
+	if err != nil {
+		log.Default().Printf("multipart.FileHeader.open:%v", err)
+		appG.Response(http.StatusOK, e.ERROR, err)
+		return
+	}
+	if err != nil {
+		log.Default().Printf("request.FormFile: %v", err)
+		appG.Response(http.StatusOK, e.ERROR, err)
+		return
+	}
+	sqlnamestr := params.Get("name")
+	sheetname := params.Get("sheetname")
+	importParams := params.Get("importParams")
+	sql, _ := restful.GetSqlByNameDB(sqlnamestr)
+	// 备件编号,备件名称,规格型号,计量单位,品牌,计划量,单价,备注,jwt_username
+	paramslist := strings.Split(importParams, ",")
+	paramslist = append(paramslist, "jwt_username")
+	queryData := make([]interface{}, 0)
+
+	xlsx1, err := excelize.OpenReader(file)
+
+	if err != nil {
+		log.Default().Printf("excelize.OpenReader:%v", err)
+		return
+	}
+	ok := 0
+	error := 0
+
+	rows := xlsx1.GetRows(sheetname)
+	if len(rows) > 10000 {
+		rows = rows[:10000]
+	}
+	for i, row := range rows {
+		if i > 0 {
+			if len(paramslist) > 0 {
+				s_params := make([]interface{}, 0)
+				entry := make(map[string]interface{})
+				outentry := make(map[string]interface{})
+				inputdata = ""
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
+						if tempv, exists := c.Get("jwt_username"); exists {
+							s_params = append(s_params, tempv.(string))
+						} else {
+							s_params = append(s_params, "")
+						}
+					} else {
+						for j, colCell := range rows[0] {
+							if strings.Trim(value, " ") == colCell {
+								for k, colCell1 := range row {
+									if j == k {
+										outentry[colCell] = colCell1
+										entry[colCell] = colCell1
+										//inputdata = inputdata + colCell + ":" + colCell1 + ";"
+									}
+								}
+							}
+						}
+						s_params = append(s_params, entry[strings.Trim(value, " ")])
+					}
+				}
+				outentry["input"] = inputdata
+				returnmsg, err := getDataBySql(sql, 0, 0, "4", s_params)
+
+				returnmsgmap, _ := returnmsg.(map[string]interface{})
+				returnmsgmap1, _ := returnmsgmap["list"].([]map[string]interface{})
+				log.Default().Printf("return:%v", returnmsgmap)
+				if err != nil {
+					outentry["error_msg"] = err.Error()
+					error++
+					queryData = append(queryData, outentry)
+				} else if (len(returnmsgmap1) > 0) && (returnmsgmap1[0]["msg"] == "success") {
+					ok++
+				} else {
+					error++
+					msg := ""
+					if len(returnmsgmap1) > 0 && returnmsgmap1[0]["msg"] != nil {
+						msg = geterrmsg(returnmsgmap1[0]["msg"].(string))
+					}
+					outentry["error_msg"] = msg
+					queryData = append(queryData, outentry)
+				}
+			}
+		}
+	}
+	data := make(map[string]interface{})
+	data["result"] = queryData
+	data["success"] = ok
+	data["err_count"] = error
+	appG.Response(http.StatusOK, e.SUCCESS, data)
+}
+func DownloadMailReport(context *gin.Context) {
+	dataByte, _ := ioutil.ReadAll(context.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	//filename := context.Param("filename")
+	sqlnamestr := fsion.Get("name").ValueStr()
+	pastureId := fsion.Get("pastureId").ValueStr()
+	pastureName := fsion.Get("pastureName").ValueStr()
+	date := fsion.Get("date").ValueStr()
+	logging.Info("DownloadMailReport ", context.Keys, sqlnamestr, pastureName)
+	filepath := ""
+
+	if sqlnamestr == "DownloadMailReportJY" {
+		filepath, _ = util.DownloadDataJT(date)
+	} else if sqlnamestr == "DownloadMailReportMC" {
+		filepath, _ = util.DownloadDataMC(pastureName, date, pastureId)
+	} else if sqlnamestr == "sssss" { // 平时用来拉数据的
+		util.Sssss()
+	} else if sqlnamestr == "DownloadEquipment" { // 设备指标导出方法
+		parammaps := fsion.Get("parammaps").ValueStr()
+		filepath, _ = util.DownloadEquipment(parammaps)
+
+	}
+
+	if filepath == "" {
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	originFilePath := filepath
+	//println("originFilePath==========",originFilePath)
+	if fs.PathExists(originFilePath) == false {
+		// if the path not found
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	http.ServeFile(context.Writer, context.Request, originFilePath)
+
+}
+
+// 资产标准管理判断牧场是否有选择的该部门
+func PastureDepartment(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+
+	paramMap := fsion.Get("param")
+	ids := paramMap.Get("ids").ValueStr()
+	deptName := paramMap.Get("deptName").ValueStr()
+	idList := strings.Split(ids, ",")
+	checkDeptList := make([]map[string]interface{}, 0)
+	for _, v := range idList {
+		aa, _ := strconv.Atoi(v)
+		data, err := restful.MapStrList("select * from department where pastureId=? and name=? and enable=1 and isDel=0 and isPasture=0", aa, deptName)
+		if err != nil {
+			fmt.Println(err)
+		} else {
+			list := make(map[string]interface{}, 1)
+			if len(data) == 0 {
+				list["id"] = v
+				list["enable"] = 0
+			} else {
+				list["id"] = v
+				list["enable"] = 1
+			}
+			checkDeptList = append(checkDeptList, list)
+		}
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, checkDeptList)
+}
+
+//{ 'label': '汶上', 'property': 'm1' }
+// 资产标准管理
+func Equipment(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	deptName := fsion.Get("deptName").ValueStr()
+	eqClassId := fsion.Get("eqClassId").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	dataList := make([]interface{}, 0)
+	pastureData, err := restful.MapStrList("select p.`name`,p.id from pasture p group by p.`name`")
+	str := "select eqS.id,eqS.deapartmentName deptName, eqS.`use`,eqclass.`typeName`,p.`name`,p.id pastureId ,eqS.eqClassId " +
+		" from equipment_standard eqS" +
+		" left join pasture p on p.id= eqS.pastureId" +
+		" left join eqclass  on eqclass.id=eqS.eqClassId " +
+		" where (eqS.deapartmentName = :deptName or :deptName ='') and " +
+		" (eqS.eqClassId = :eqClassId or :eqClassId ='') " +
+		" group by deptName,eqClassId " +
+		" ORDER BY eqS.id DESC"
+	offset = offset - 1
+	if pagecount > 0 && offset > 0 {
+		offset = offset * pagecount
+	}
+	paramMap_3_6 := map[string]interface{}{"deptName": deptName, "eqClassId": eqClassId}
+	str += fmt.Sprintf("limit %d  offset %d", pagecount, offset)
+	equipmentStandardData1, err := restful.MapStrList(str, paramMap_3_6)
+	//数据
+	equipmentStandardData2, err := restful.MapStrList("select eqS.deapartmentName deptName, eqS.id eqSId,eqS.equipmentNumber,p.`name`,p.id pastureId,eqS.eqClassId"+
+		" from equipment_standard eqS"+
+		" left join pasture p on p.id= eqS.pastureId "+
+		" left join eqclass eqc on eqc.id=eqS.eqClassId "+
+		"where (eqS.deapartmentName =? or ?='') and"+
+		" (eqS.eqClassId = ? or ?='') ", deptName, deptName, eqClassId, eqClassId)
+
+	sqlstr := str
+
+	params := make([]interface{}, 0)
+	for i := 0; i < 2; i++ {
+		param := make(map[string]interface{}, 0)
+		param["deptName"] = deptName
+		param["eqClassId"] = eqClassId
+		params = append(params, param)
+	}
+	label := make([]map[string]interface{}, 0)
+	if err != nil {
+		fmt.Println(err)
+	} else {
+		for i, v := range pastureData {
+			pasturelist := make(map[string]interface{}, 1)
+			pasturelist["label"] = v["name"]
+			pasturelist["id"] = v["id"]
+			pasturelist["property"] = "m" + strconv.Itoa(i+1)
+			label = append(label, pasturelist)
+		}
+		label2 := make([]map[string]interface{}, 0)
+		for _, s := range equipmentStandardData1 {
+			equipmentStandardList := make(map[string]interface{}, 1)
+			for i := 1; i <= len(label); i++ {
+				equipmentStandardList["m"+strconv.Itoa(i)] = ""
+			}
+			equipmentStandardList["deptName"] = s["deptName"]
+			equipmentStandardList["use"] = s["use"]
+			equipmentStandardList["typeName"] = s["typeName"]
+			equipmentStandardList["eqClassId"] = s["eqClassId"]
+			for _, z := range equipmentStandardData2 {
+				for e, x := range label {
+					if s["deptName"] == z["deptName"] && x["label"] == z["name"] && s["eqClassId"] == z["eqClassId"] {
+						equipmentStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"]
+						equipmentStandardList[x["property"].(string)] = z["equipmentNumber"]
+					} else {
+						equipmentStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"]
+					}
+				}
+			}
+			label2 = append(label2, equipmentStandardList)
+		}
+		if err != nil {
+			msg := geterrmsg(err.Error())
+			appG.Response(http.StatusOK, e.ERROR, msg)
+		} else {
+			dataList = append(dataList, label)
+			dataList = append(dataList, label2)
+			data := make(map[string]interface{})
+			recordcount := int64(0)
+			if pagecount > 1 {
+				sqlstr := fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr)
+				params := []interface{}{deptName, deptName, eqClassId, eqClassId}
+				err := restful.BasicList(sqlstr, params, &recordcount)
+				if err != nil {
+					log.Default().Printf("Equipment query error: %v", err)
+				}
+			}
+			if err != nil {
+				fmt.Println(err)
+			}
+			if recordcount == 0 {
+				recordcount = int64(len(equipmentStandardData1))
+			}
+
+			data["list"] = dataList
+			//data := make(map[string]interface{})
+			data["total"] = recordcount
+			data["code"] = 0
+			data["message"] = "ok"
+			if pagecount > 0 {
+				data["pages"] = math.Ceil(float64(recordcount) / float64(pagecount))
+				data["pageNum"] = math.Ceil(float64(offset+1) / float64(pagecount))
+			}
+			data["pageSize"] = pagecount
+			appG.Response(http.StatusOK, e.SUCCESS, data)
+		}
+	}
+}
+
+// 资产标准管理插入修改写在一起
+func UpdateAndInsert(c *gin.Context) {
+	appG := app.Gin{C: c}
+	data := make(map[string]interface{}, 0)
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	param := fsion.Get("param")
+	check := fsion.Get("check").ValueStr()
+	tx, err := restful.Dbs.Beginx()
+
+	deptName := param.Get("deptName").ValueStr()
+	eqCode := param.Get("eqCode").ValueStr()
+	eqClassId, err := strconv.Atoi(param.Get("eqClassId").ValueStr())
+	use := param.Get("use").ValueStr()
+	paramStr := fsion.Get("param").ValueStr()
+	paramMap := make(map[string]interface{}, 0)
+	err = json.Unmarshal([]byte(paramStr), &paramMap)
+	fmt.Println(len(paramMap))
+	fmt.Println(paramMap)
+	// 标准库存
+	name := fsion.Get("name").ValueStr()
+	partClassId, err := strconv.Atoi(param.Get("partClassId").ValueStr())
+	ff := 0
+	if check == "insert" {
+		querydata := make([]map[string]string, 0)
+		if name == "partStandard" {
+			ff = 2
+			querydata, err = restful.MapStrList(" select * from part_standard where partClassId2 =? ", partClassId)
+			if querydata != nil {
+				//data["msg"]="请不输入重复数据"
+				msg := geterrmsg("请不输入重复数据")
+				appG.Response(http.StatusOK, e.ERROR, msg)
+				return
+			}
+		} else {
+			ff = 4
+			querydata, err = restful.MapStrList(" select * from equipment_standard where eqClassId =? and deapartmentName = ?", eqClassId, deptName)
+			if querydata != nil {
+				//data["msg"]="请不输入重复数据"
+				msg := geterrmsg("请不输入重复数据")
+				appG.Response(http.StatusOK, e.ERROR, msg)
+				return
+			}
+		}
+
+		for i := 1; i <= (len(paramMap)-ff)/2; i++ {
+			pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr())
+			if err != nil {
+			}
+			if name == "partStandard" {
+				if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" {
+					tx.Exec("call add_part_standard(?,?,?)", partClassId, pastureId, param.Get("m"+strconv.Itoa(i)))
+				}
+			} else {
+				if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" {
+					tx.Exec("call add_equipment_standard(?,?,?,?,?,?)", deptName, use, eqClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr(), eqCode)
+				}
+			}
+
+		}
+		if err != nil {
+		}
+	}
+	if check == "update" {
+		if name == "partStandard" {
+			ff = 2
+			tx.Exec("delete from part_standard where partClassId2 =?", partClassId)
+			for i := 1; i <= (len(paramMap)-ff)/2; i++ {
+				pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr())
+				if err != nil {
+				}
+				if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" {
+					tx.Exec("call add_part_standard(?,?,?)", partClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr())
+				}
+			}
+		} else {
+			ff = 4
+			tx.Exec("delete from equipment_standard   where deapartmentName=? and eqClassId=?", deptName, eqClassId)
+			for i := 1; i <= (len(paramMap)-ff)/2; i++ {
+				pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr())
+				if err != nil {
+				}
+				if param.Get("m"+strconv.Itoa(i)).ValueStr() != "" {
+					tx.Exec("call add_equipment_standard(?,?,?,?,?,?)", deptName, use, eqClassId, pastureId, param.Get("m"+strconv.Itoa(i)).ValueStr(), eqCode)
+					//	" WHERE deapartmentName=? and pastureId = ? and eqClassId=?", use, param.Get("m"+strconv.Itoa(i)).ValueStr(), deptName, pastureId,eqClassId).Execute()
+				}
+			}
+		}
+		if err != nil {
+			data["msg"] = "error"
+			data["error"] = err.Error()
+			appG.Response(http.StatusOK, e.SUCCESS, data)
+		}
+	}
+	if check == "delete" {
+		if name == "partStandard" {
+			for i := 1; i <= (len(paramMap)-ff)/2; i++ {
+				pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr())
+				if err != nil {
+				}
+				tx.Exec("delete from part_standard   where  pastureId=? and partClassId2=?", pastureId, partClassId)
+			}
+		} else {
+			ff = 4
+			for i := 1; i <= (len(paramMap)-ff)/2; i++ {
+				pastureId, err := strconv.Atoi(param.Get("pastureId" + strconv.Itoa(i)).ValueStr())
+				if err != nil {
+				}
+				tx.Exec("delete from equipment_standard   where deapartmentName=? and pastureId=? and eqClassId=?", deptName, pastureId, eqClassId)
+			}
+		}
+	}
+
+	data["msg"] = "ok"
+	appG.Response(http.StatusOK, e.SUCCESS, data)
+	defer func() {
+		switch {
+		case err != nil:
+			logging.Error("tx.Begin 事务启动失败__error:", err)
+			if tx != nil {
+				tx.Rollback()
+			}
+		default:
+			if tx != nil {
+				err = tx.Commit()
+			}
+		}
+
+	}()
+}
+
+func StandardPart(c *gin.Context) {
+	appG := app.Gin{C: c}
+	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+	fsion := gofasion.NewFasion(string(dataByte))
+	partClassId := fsion.Get("partClassId").ValueStr()
+	offset := fsion.Get("offset").ValueDefaultInt(0)
+	pagecount := fsion.Get("pagecount").ValueDefaultInt(0)
+	pastureData, err := restful.MapStrList("select p.`name`,p.id from pasture p group by p.`name`")
+
+	//s_params := make([]interface{}, 0)
+	offset = offset - 1
+	if pagecount > 0 && offset > 0 {
+		offset = offset * pagecount
+	}
+	dataList := make([]interface{}, 0)
+	label := make([]map[string]interface{}, 0)
+	str := "select p_c.partName,p.`name`,p_s.pastureId,p_s.partClassId2 from part_standard p_s left join part_class p_c on p_c.id= p_s.partClassId2 " +
+		" left join pasture p on p.id = p_s.pastureId where p_s.partClassId2 = ? or ?='' " +
+		" GROUP BY p_s.partClassId2  ORDER BY p_s.id DESC"
+	str1 := "select  p_s.standardMoney,p_s.partClassId2,p_s.pastureId,p.`name` from part_standard p_s left join pasture p on p.id=p_s.pastureId  where p_s.partClassId2 = ? or ?=''"
+	str += fmt.Sprintf(" limit %d  offset %d", pagecount, offset)
+	partStandardData1, err := restful.MapStrList(str, partClassId, partClassId)
+	//数据
+	partStandardData2, err := restful.MapStrList(str1, partClassId, partClassId)
+
+	if err != nil {
+		fmt.Println(err)
+	} else {
+		for i, v := range pastureData {
+			pasturelist := make(map[string]interface{}, 1)
+			pasturelist["label"] = v["name"]
+			pasturelist["id"] = v["id"]
+			pasturelist["property"] = "m" + strconv.Itoa(i+1)
+			label = append(label, pasturelist)
+		}
+		label2 := make([]map[string]interface{}, 0)
+		//equipmentStandardList := make(map[string]interface{}, 1)
+		for _, s := range partStandardData1 {
+			partStandardList := make(map[string]interface{}, 1)
+			for i := 1; i <= len(label); i++ {
+				partStandardList["m"+strconv.Itoa(i)] = ""
+			}
+			partStandardList["partClassId"] = s["partClassId2"]
+			partStandardList["partName"] = s["partName"]
+			for _, z := range partStandardData2 {
+				for e, x := range label {
+					if x["label"] == z["name"] && s["partClassId2"] == z["partClassId2"] {
+						partStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"]
+						//equipmentStandardList["eqSId"+strconv.Itoa(e+1)] = z["eqSId"]
+						partStandardList[x["property"].(string)] = z["standardMoney"]
+					} else {
+						partStandardList["pastureId"+strconv.Itoa(e+1)] = x["id"]
+					}
+				}
+			}
+			label2 = append(label2, partStandardList)
+		}
+		if err != nil {
+			//logging.Error("GetDataByName  err: ", err)
+			msg := geterrmsg(err.Error())
+			appG.Response(http.StatusOK, e.ERROR, msg)
+		} else {
+			dataList = append(dataList, label)
+			dataList = append(dataList, label2)
+			fmt.Println(label2)
+			data := make(map[string]interface{})
+			recordcount := int64(0)
+			if pagecount > 1 {
+				sqlstr := fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", str)
+				params := []interface{}{partClassId, partClassId}
+				restful.BasicList(sqlstr, params, &recordcount)
+				if err != nil {
+					fmt.Println("s1", err)
+				}
+			}
+			if err != nil {
+				fmt.Println(err)
+			}
+			if recordcount == 0 {
+				recordcount = int64(len(partStandardData1))
+			}
+
+			data["list"] = dataList
+			//data := make(map[string]interface{})
+			data["total"] = recordcount
+			data["code"] = 0
+			data["message"] = "ok"
+			if pagecount > 0 {
+				data["pages"] = math.Ceil(float64(recordcount) / float64(pagecount))
+				data["pageNum"] = math.Ceil(float64(offset+1) / float64(pagecount))
+			}
+			data["pageSize"] = pagecount
+
+			//pageNum: 1  pageSize: 10  pages: 202  total: 2019
+			//data["pageNum"]=queryData
+			//data["pageNum"]=queryData["pageNum"]
+			appG.Response(http.StatusOK, e.SUCCESS, data)
+		}
+	}
+}

+ 553 - 0
apiserver/routers/api/upload.go

@@ -0,0 +1,553 @@
+package api
+
+import (
+	"crypto/md5"
+	"encoding/hex"
+	"fmt"
+	"image"
+	"image/gif"
+	"image/jpeg"
+	"image/png"
+	"io"
+	"log"
+	"mime/multipart"
+	"net/http"
+	"os"
+	"path"
+	"strconv"
+	"strings"
+
+	"github.com/pkg/errors"
+
+	fs "github.com/axetroy/go-fs"
+	"github.com/gin-gonic/gin"
+	"github.com/nfnt/resize"
+	"kpt.xdmy/apiserver/routers/restful"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+	"kpt.xdmy/pkg/logging"
+	"kpt.xdmy/pkg/setting"
+)
+
+// 支持的图片后缀名
+var supportImageExtNames = []string{".jpg", ".jpeg", ".png", ".ico", ".svg", ".bmp", ".gif"}
+
+/**
+check a file is a image or not
+*/
+func isImage(extName string) bool {
+	for i := 0; i < len(supportImageExtNames); i++ {
+		if supportImageExtNames[i] == extName {
+			return true
+		}
+	}
+	return false
+}
+
+/**
+Handler the parse error
+*/
+func parseFormFail(context *gin.Context) {
+	context.JSON(http.StatusBadRequest, gin.H{
+		"message": "Can not parse form",
+	})
+}
+
+/**
+Upload file handler
+*/
+func UploadFile(context *gin.Context) {
+	appG := app.Gin{C: context}
+	dictId := context.Param("id")
+	dictName := context.Param("name")
+	logging.Info("UploadFile ", context.Keys, dictId, dictName)
+	var (
+		isSupportFile bool
+		maxUploadSize = setting.AppSetting.FileMaxSize   // 最大上传大小
+		allowTypes    = setting.AppSetting.FileAllowType // 可上传的文件类型
+		distPath      string                             // 最终的输出目录
+		err           error
+		file          *multipart.FileHeader
+		src           multipart.File
+		dist          *os.File
+	)
+	// Source
+	if file, err = context.FormFile("file"); err != nil {
+		parseFormFail(context)
+		return
+	}
+	sqlname := context.GetHeader("optname")
+	extname := path.Ext(file.Filename)
+	if len(allowTypes) != 0 {
+		for i := 0; i < len(allowTypes); i++ {
+			if allowTypes[i] == extname {
+				isSupportFile = true
+				break
+			}
+		}
+
+		if isSupportFile == false {
+			context.JSON(http.StatusBadRequest, gin.H{
+				"message": "不支持的文件类型: " + extname,
+			})
+			return
+		}
+	}
+
+	if file.Size > int64(maxUploadSize) {
+		context.JSON(http.StatusBadRequest, gin.H{
+			"message": "上传文件太大, 最大限制为" + strconv.Itoa(int(maxUploadSize)/1048576) + "(M): ",
+		})
+		return
+	}
+
+	if src, err = file.Open(); err != nil {
+		// open the file fail...
+	}
+	defer src.Close()
+
+	hash := md5.New()
+
+	io.Copy(hash, src)
+
+	md5string := hex.EncodeToString(hash.Sum([]byte("")))
+
+	fileName := md5string + extname
+	// Destination
+
+	filePath := setting.CurrentPath + setting.AppSetting.FileSavePath + dictName + "/"
+	err = PathCheck(filePath) //检查路径并创建
+	if err != nil {
+		fmt.Println("PathCheck err", err)
+	}
+	distPath = path.Join(filePath, fileName)
+	if dist, err = os.Create(distPath); err != nil {
+		fmt.Println("Create err", err)
+	}
+	defer dist.Close()
+	//distPath = setting.CurrentPath + setting.AppSetting.FileSavePath +"/"+ fileName
+
+	if dist, err = os.Create(distPath); err != nil {
+		// create dist file fail...
+	}
+	defer dist.Close()
+
+	// FIXME: open 2 times
+	if src, err = file.Open(); err != nil {
+		//
+	}
+
+	// Copy
+	io.Copy(dist, src)
+	var execresult interface{}
+
+	params := context.Request.Form
+
+	if sqlname != "" {
+		sql, p := restful.GetSqlByNameDB(sqlname) //todo insertcustomdoc
+		if sql != "" {
+			s_params := make([]interface{}, 0)
+			paramslist := strings.Split(p, ",")
+
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					fmt.Println("s_params value", s_params, value)
+					if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
+						tempv := params.Get("jwt_username")
+						s_params = append(s_params, tempv)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "docname" {
+						s_params = append(s_params, file.Filename)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "newdocname" {
+						s_params = append(s_params, fileName)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "docpath" {
+						s_params = append(s_params, dictName) //
+					} else if strings.ToLower(strings.Trim(value, " ")) == "dictid" {
+						s_params = append(s_params, dictId) //
+						fmt.Println("s_params", s_params, dictId)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "filesize" {
+						s_params = append(s_params, file.Size) //
+					} else {
+						s_params = append(s_params, params.Get(strings.Trim(value, " ")))
+					}
+				}
+			}
+			execresult, err = execDataBySql(sql, s_params)
+			if err != nil {
+				fmt.Println("execDataBySql err", err)
+				appG.Response(http.StatusOK, e.ERROR, err.Error())
+			}
+		}
+	}
+	context.JSON(http.StatusOK, gin.H{
+		"hash":       md5string,
+		"filename":   fileName,
+		"origin":     file.Filename,
+		"size":       file.Size,
+		"execresult": execresult,
+	})
+
+}
+
+/**
+Upload image handler
+*/
+func UploaderImage(context *gin.Context) {
+	logging.Info("UploaderImage ", context.Keys)
+	var (
+		maxUploadSize = setting.AppSetting.ImageMaxSize // 最大上传大小
+		distPath      string                            // 最终的输出目录
+		err           error
+		file          *multipart.FileHeader
+		src           multipart.File
+		dist          *os.File
+	)
+	// Source
+	if file, err = context.FormFile("file"); err != nil {
+		parseFormFail(context)
+		return
+	}
+
+	sqlname := context.GetHeader("optname")
+
+	extname := strings.ToLower(path.Ext(file.Filename))
+
+	if isImage(extname) == false {
+		context.JSON(http.StatusBadRequest, gin.H{
+			"message": "不支持的上传文件类型: " + extname,
+		})
+		return
+	}
+	if file.Size > int64(maxUploadSize) {
+		context.JSON(http.StatusBadRequest, gin.H{
+			"message": "上传文件太大, 最大文件大小限制为(byte): " + strconv.Itoa(int(maxUploadSize)),
+		})
+		return
+	}
+
+	if src, err = file.Open(); err != nil {
+
+	}
+	defer src.Close()
+
+	hash := md5.New()
+
+	io.Copy(hash, src)
+
+	md5string := hex.EncodeToString(hash.Sum([]byte("")))
+
+	fileName := md5string + extname
+
+	picPath := setting.CurrentPath + setting.AppSetting.ImageSavePath + sqlname + "/"
+	err = PathCheck(picPath) //检查路径并创建
+	if err != nil {
+		fmt.Println("PathCheck err", err)
+	}
+	distPath = path.Join(picPath, fileName)
+	if dist, err = os.Create(distPath); err != nil {
+		fmt.Println("Create err", err)
+	}
+	defer dist.Close()
+
+	// FIXME: open 2 times
+	if src, err = file.Open(); err != nil {
+		//
+	}
+	defer src.Close()
+
+	// Copy
+	io.Copy(dist, src)
+
+	// 压缩缩略图
+	// 不管成功与否,都会进行下一步的返回
+	if _, err := thumbnailify(distPath, sqlname); err != nil {
+		logging.Error("thumbnailify_err", err)
+		picThumbnailPath := setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + sqlname + "/"
+		println(picThumbnailPath)
+		err = PathCheck(picThumbnailPath) //检查路径并创建
+		distThumbnailPath := path.Join(picThumbnailPath, fileName)
+		println(distThumbnailPath)
+		distThumbnail, err := os.Create(distThumbnailPath)
+		if err != nil {
+			fmt.Println("CreateThumbnail err", err)
+		}
+		srcThumbnail, err := file.Open()
+		if err != nil {
+			//
+		}
+		io.Copy(distThumbnail, srcThumbnail)
+		distThumbnail.Close()
+		src.Close()
+	}
+	var execresult interface{}
+
+	params := context.Request.Form
+
+	if sqlname != "" {
+		sql, p := restful.GetSqlByNameDB(sqlname)
+		if sql != "" {
+			s_params := make([]interface{}, 0)
+			paramslist := strings.Split(p, ",")
+			if len(paramslist) > 0 && p != "" {
+				for _, value := range paramslist {
+					if strings.ToLower(strings.Trim(value, " ")) == "username" { //picpath, picname, username, newpicname
+						tempv := params.Get("jwt_username")
+						s_params = append(s_params, tempv)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "picname" {
+						s_params = append(s_params, file.Filename)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "newpicname" {
+						s_params = append(s_params, fileName)
+					} else if strings.ToLower(strings.Trim(value, " ")) == "picpath" {
+						s_params = append(s_params, sqlname) //全路径加文件名
+					} else {
+						s_params = append(s_params, params.Get(strings.Trim(value, " ")))
+					}
+				}
+			}
+			execresult, err = execDataBySql(sql, s_params)
+			if err != nil {
+				fmt.Println("execDataBySql err", err)
+			}
+		}
+	}
+	context.JSON(http.StatusOK, gin.H{
+		"hash":       md5string,
+		"filename":   fileName,
+		"origin":     file.Filename,
+		"size":       file.Size,
+		"execresult": execresult,
+	})
+}
+
+/**
+Get file raw
+*/
+func GetFileRaw(context *gin.Context) {
+	filename := context.Param("filename")
+	logging.Info("GetFileRaw ", context.Keys, filename)
+
+	filePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, filename)
+	if isExistFile := fs.PathExists(filePath); isExistFile == false {
+		// if the path not found
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	http.ServeFile(context.Writer, context.Request, filePath)
+}
+
+/**
+Download a file
+*/
+func DownloadFile(context *gin.Context) {
+	filename := context.Param("filename")
+	logging.Info("DownloadFile ", context.Keys, filename)
+	sqlstr := fmt.Sprintf("SELECT docpath ,newdocname FROM eq_doc where id = %s ", filename)
+	var docpath, newdocname string
+	err := restful.BasicList(sqlstr, nil, &docpath, &newdocname)
+	if err != nil {
+		log.Default().Printf("DownloadFile queryx:%v", err)
+	}
+	originFilePath := path.Join(setting.CurrentPath, setting.AppSetting.FileSavePath, docpath, newdocname)
+	if fs.PathExists(originFilePath) == false {
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	http.ServeFile(context.Writer, context.Request, originFilePath)
+
+}
+
+/**
+Get Origin image
+*/
+func GetOriginImage(context *gin.Context) {
+	//appG := app.Gin{C: context}
+	filename := context.Param("filename")
+	logging.Info("GetOriginImage ", context.Keys, filename)
+	sqlstr := fmt.Sprintf("SELECT picpath,newpicname FROM eq_pic where id = %s ", filename)
+	var picpath, newpicname string
+	err := restful.BasicList(sqlstr, nil, &picpath, &newpicname)
+
+	if err != nil {
+		log.Default().Printf("GetOriginImage queryx eq_pic: %v", err)
+	}
+	if picpath == "" && newpicname == "" {
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, picpath, newpicname)
+	if fs.PathExists(originImagePath) == false {
+		// if the path not found
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	http.ServeFile(context.Writer, context.Request, originImagePath)
+	//appG.Response(http.StatusOK, e.SUCCESS, eqpic[0]["picname"])
+}
+
+/**
+Get thumbnail image
+*/
+func GetThumbnailImage(context *gin.Context) {
+	filename := context.Param("filename")
+	logging.Info("GetThumbnailImage ", context.Keys, filename)
+	sqlstr := fmt.Sprintf("SELECT picpath,newpicname FROM eq_pic where id = %s ", filename)
+	var picpath, newpicname string
+	err := restful.BasicList(sqlstr, nil, &picpath, &newpicname)
+	if err != nil {
+		log.Default().Printf("GetOriginImage queryx eq_pic: %v", err)
+	}
+	if newpicname == "" {
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	thumbnailImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ThumbnailSavePath, picpath, newpicname)
+	originImagePath := path.Join(setting.CurrentPath, setting.AppSetting.ImageSavePath, filename)
+
+	if fs.PathExists(thumbnailImagePath) == false {
+		// if thumbnail image not exist, try to get origin image
+		if fs.PathExists(originImagePath) == true {
+			http.ServeFile(context.Writer, context.Request, originImagePath)
+			return
+		}
+		// if the path not found
+		http.NotFound(context.Writer, context.Request)
+		return
+	}
+	http.ServeFile(context.Writer, context.Request, thumbnailImagePath)
+}
+
+/**
+Generate thumbnail
+*/
+func thumbnailify(imagePath, subdirectory string) (outputPath string, err error) {
+	var (
+		file *os.File
+		img  image.Image
+	)
+	Filename := strings.ToLower(path.Base(imagePath))
+	extname := strings.ToLower(path.Ext(imagePath))
+	outputPath = setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory + "/" + Filename
+	err = PathCheck(setting.CurrentPath + setting.AppSetting.ThumbnailSavePath + subdirectory)
+	if err != nil {
+		fmt.Println("thumbnailify PathCheck err", err)
+	}
+	// 读取文件
+	if file, err = os.Open(imagePath); err != nil {
+		return
+	}
+
+	defer file.Close()
+
+	// decode jpeg into image.Image
+	switch extname {
+	case ".jpg", ".jpeg":
+		img, err = jpeg.Decode(file)
+		break
+	case ".png":
+		img, err = png.Decode(file)
+		break
+	case ".gif":
+		img, err = gif.Decode(file)
+		break
+	default:
+		err = errors.New("Unsupport file type" + extname)
+		return
+	}
+
+	if img == nil {
+		err = errors.New("Generate thumbnail fail...")
+		return
+	}
+
+	m := resize.Thumbnail(uint(setting.AppSetting.ThumbnailMaxWidth), uint(setting.AppSetting.ThumbnailMaxHeight), img, resize.Lanczos3)
+
+	out, err := os.Create(outputPath)
+	if err != nil {
+		return
+	}
+	defer out.Close()
+
+	// write new image to file
+
+	//decode jpeg/png/gif into image.Image
+	switch extname {
+	case ".jpg", ".jpeg":
+		jpeg.Encode(out, m, nil)
+		break
+	case ".png":
+		png.Encode(out, m)
+		break
+	case ".gif":
+		gif.Encode(out, m, nil)
+		break
+	default:
+		err = errors.New("Unsupport file type" + extname)
+		return
+	}
+
+	return
+}
+
+func UploadFiles(c *gin.Context) {
+	logging.Info("UploadFiles ", c.Keys)
+	appG := app.Gin{C: c}
+	err := c.Request.ParseMultipartForm(200000)
+	if err != nil {
+		appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
+		return
+	}
+	// 获取表单
+	form := c.Request.MultipartForm
+	// 获取参数upload后面的多个文件名,存放到数组files里面,
+	files := form.File["upload"]
+	// 遍历数组,每取出一个file就拷贝一次
+	for i := range files {
+		file, err := files[i].Open()
+		defer file.Close()
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
+			return
+		}
+
+		fileName := files[i].Filename
+		fmt.Println(fileName)
+
+		out, err := os.Create(fileName)
+		defer out.Close()
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
+			return
+		}
+
+		_, err = io.Copy(out, file)
+		if err != nil {
+			appG.Response(http.StatusOK, e.ERROR_IMPORT_FAIL, err)
+			return
+		}
+
+		appG.Response(http.StatusOK, e.SUCCESS, "upload successful \n")
+	}
+}
+func PathCheck(path string) (err error) {
+	b, err := PathExists(path)
+	if err != nil {
+		fmt.Println("exist err", err)
+	}
+	if !b {
+		fmt.Println(path, "  目录不存在,重新创建")
+		err = os.Mkdir(path, 0777)
+		if err != nil {
+			fmt.Println("Mkdir err", err)
+		}
+	}
+	return
+}
+func PathExists(path string) (bool, error) {
+	_, err := os.Stat(path)
+	if err == nil {
+		return true, nil
+	}
+	if os.IsNotExist(err) {
+		return false, nil
+	}
+	return false, err
+}

+ 119 - 0
apiserver/routers/api/user.go

@@ -0,0 +1,119 @@
+package api
+
+import (
+	"net/http"
+
+	"github.com/astaxie/beego/validation"
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/routers/restful"
+	"kpt.xdmy/apiserver/service/user_service"
+	"kpt.xdmy/pkg/app"
+	"kpt.xdmy/pkg/e"
+	"kpt.xdmy/pkg/util"
+)
+
+type auth struct {
+	Id         int    `json:"id"`
+	Username   string `json:"username"`
+	Password   string `json:"password"`
+	CaptchaKey string `json:"CaptchaKey"`
+	Role       int    `json:"role_id"`
+}
+
+// @Summary   获取登录token 信息
+// @Tags auth
+// @Accept json
+// @Produce  json
+// @Param username formData string true  "admin"
+// @Param password formData string true  "123456"
+// @Success 200 {string} json "{ "code": 200e, "data": { "token": "xxx" }, "msg": "ok" }"
+// @Failure 400 {string} json "{"code":400,  "data":null,"msg":"请求参数错误"}"
+// @Failure 404 {string} json "{ "code": 404, "data":null,"msg":"请求参数错误"}"
+// @Router /auth  [POST]
+func Auth(c *gin.Context) {
+
+	appG := app.Gin{C: c}
+	var reqInfo auth
+	err := c.BindJSON(&reqInfo)
+	//c.Request.ParseForm()
+	//reqInfo.Username = c.PostForm("username")
+	//reqInfo.Password = c.PostForm("pwd")
+
+	valid := validation.Validation{}
+	valid.MaxSize(reqInfo.Username, 100, "username").Message("最长为100字符")
+	valid.MaxSize(reqInfo.Password, 100, "password").Message("最长为100字符")
+
+	if valid.HasErrors() {
+		app.MarkErrors(valid.Errors)
+		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, valid.Errors)
+		return
+	}
+
+	authService := user_service.User{Username: reqInfo.Username, Password: reqInfo.Password}
+	isExist, err := authService.Check()
+
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_CHECK_TOKEN_FAIL, err)
+		return
+	}
+
+	if !isExist {
+		//appG.Response(http.StatusUnauthorized, e.ERROR_AUTH, nil)
+		appG.Response(http.StatusOK, e.ERROR_AUTH, "用户名或密码错误")
+		return
+	}
+
+	token, err := util.GenerateToken(reqInfo.Username, reqInfo.Password)
+	if err != nil {
+		appG.Response(http.StatusInternalServerError, e.ERROR_AUTH_TOKEN, err)
+		return
+	}
+
+	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
+		"token": token,
+	})
+}
+
+// @Summary   获取单个用户信息
+// @Tags  users
+// @Accept json
+// @Produce  json
+// @Param  id  body  int true "id"
+// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Router /authdata/userinfo  [GET]
+func UserLogout(c *gin.Context) {
+	appG := app.Gin{C: c}
+	data := make(map[string]interface{})
+	data["name"] = ""
+	data["avatar"] = ""
+	data["introduction"] = ""
+	appG.Response(http.StatusOK, e.SUCCESS, data)
+}
+
+// @Summary   获取单个用户信息
+// @Tags  users
+// @Accept json
+// @Produce  json
+// @Param  id  path  int true "iddd"
+// @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// @Router /authdata/userinfo  [GET]
+func GetUserinfo(c *gin.Context) {
+	appG := app.Gin{C: c}
+	data := restful.GetUserInfo(c.MustGet("jwt_username").(string))
+	appG.Response(http.StatusOK, e.SUCCESS, data)
+}
+
+func GetOpenID(c *gin.Context) {
+	code := c.Param("code")
+	appG := app.Gin{C: c}
+	openid, err := util.SendWxAuthAPI(code)
+	if err != nil {
+		appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
+			"err": "openid 获取失败 :" + err.Error(),
+		})
+		return
+	}
+	appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
+		"openid": openid,
+	})
+}

+ 223 - 0
apiserver/routers/api/v1/menu.go

@@ -0,0 +1,223 @@
+package v1
+
+// "kpt.xdmy/service/menu_service"
+
+// // @Summary   获取单个菜单
+// // @Tags menu
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/menus/:id  [GET]
+// func GetMenu(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	valid := validation.Validation{}
+// 	valid.Min(id, 1, "id").Message("ID必须大于0")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	menuService := menu_service.Menu{ID: id}
+// 	exists, err := menuService.ExistByID()
+
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+
+// 	article, err := menuService.Get()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, article)
+// }
+
+// // @Summary   获取所有菜单
+// // @Tags menu
+// // @Accept json
+// // @Produce  json
+// // @Param  Ton  query  string true "Ton"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/menus  [GET]
+// func GetMenus(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	valid := validation.Validation{}
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	menuService := menu_service.Menu{
+// 		PageNum:  util.GetPage(c),
+// 		PageSize: setting.AppSetting.PageSize,
+// 	}
+
+// 	total, err := menuService.Count()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_COUNT_FAIL, nil)
+// 		return
+// 	}
+
+// 	articles, err := menuService.GetAll()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_GET_S_FAIL, nil)
+// 		return
+// 	}
+
+// 	data := make(map[string]interface{})
+// 	data["lists"] = articles
+// 	data["total"] = total
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, data)
+// }
+
+// // @Summary   增加菜单
+// // @Tags menu
+// // @Accept json
+// // @Produce  json
+// // @Param  name  query  string true "name"
+// // @Param  path  query  string true "path"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/menus  [POST]
+// func AddMenu(c *gin.Context) {
+// 	var (
+// 		appG = app.Gin{C: c}
+// 	)
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	name := fsion.Get("name").ValueStr()
+// 	path := fsion.Get("path").ValueStr()
+// 	method := fsion.Get("method").ValueStr()
+
+// 	valid := validation.Validation{}
+// 	valid.MaxSize(name, 100, "name").Message("最长为100字符")
+// 	valid.MaxSize(path, 100, "path").Message("最长为100字符")
+// 	valid.MaxSize(method, 100, "method").Message("最长为100字符")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+
+// 	menuService := menu_service.Menu{
+// 		Name:   name,
+// 		Path:   path,
+// 		Method: method,
+// 	}
+// 	if err := menuService.Add(); err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+
+// }
+
+// // @Summary   更新菜单
+// // @Tags menu
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Param  name  query  string true "name"
+// // @Param  path  query  string true "path"
+// // @Param  method  query  string true "method"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/menus/:id  [PUT]
+// func EditMenu(c *gin.Context) {
+// 	var (
+// 		appG = app.Gin{C: c}
+// 	)
+
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	name := fsion.Get("name").ValueStr()
+// 	path := fsion.Get("path").ValueStr()
+// 	method := fsion.Get("method").ValueStr()
+
+// 	valid := validation.Validation{}
+// 	valid.MaxSize(name, 100, "name").Message("最长为100字符")
+// 	valid.MaxSize(path, 100, "path").Message("最长为100字符")
+// 	valid.MaxSize(method, 100, "method").Message("最长为100字符")
+// 	valid.Min(id, 1, "id").Message("ID必须大于0")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+// 	menuService := menu_service.Menu{
+// 		Name:   name,
+// 		Path:   path,
+// 		Method: method,
+// 	}
+// 	exists, err := menuService.ExistByID()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+
+// 	err = menuService.Edit()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_FAIL, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+// }
+
+// // @Summary   删除菜单
+// // @Tags menu
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/menus/:id  [DELETE]
+// func DeleteMenu(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	valid := validation.Validation{}
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	valid.Min(id, 1, "id").Message("ID必须大于0")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	menuService := menu_service.Menu{ID: id}
+// 	exists, err := menuService.ExistByID()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+
+// 	err = menuService.Delete()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_DELETE_FAIL, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+// }

+ 228 - 0
apiserver/routers/api/v1/role.go

@@ -0,0 +1,228 @@
+package v1
+
+// // @Summary   获取单个角色
+// // @Tags role
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/roles/:id  [GET]
+// func GetRole(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	valid := validation.Validation{}
+// 	valid.Min(id, 1, "id").Message("ID必须大于0")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	RoleService := Role_service.Role{ID: id}
+// 	exists, err := RoleService.ExistByID()
+
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+
+// 	article, err := RoleService.Get()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_NOT_EXIST, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, article)
+// }
+
+// // @Summary   获取所有角色
+// // @Tags role
+// // @Accept json
+// // @Produce  json
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/roles  [GET]
+// func GetRoles(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	name := c.Query("name")
+// 	valid := validation.Validation{}
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	RoleService := Role_service.Role{
+// 		Name:     name,
+// 		PageNum:  util.GetPage(c),
+// 		PageSize: setting.AppSetting.PageSize,
+// 	}
+
+// 	total, err := RoleService.Count()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_COUNT_FAIL, nil)
+// 		return
+// 	}
+
+// 	articles, err := RoleService.GetAll()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_GET_S_FAIL, nil)
+// 		return
+// 	}
+
+// 	data := make(map[string]interface{})
+// 	data["lists"] = articles
+// 	data["total"] = total
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, data)
+// }
+
+// // @Summary   增加角色
+// // @Tags role
+// // @Accept json
+// // @Produce  json
+// // @Param  name  query  string true "name"
+// // @Param  menu_id  query  string true "menu_id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/roles  [POST]
+// func AddRole(c *gin.Context) {
+// 	var (
+// 		appG = app.Gin{C: c}
+// 	)
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	name := fsion.Get("username").ValueStr()
+// 	menuId := com.StrTo(fsion.Get("menu_id").ValueInt()).MustInt()
+
+// 	valid := validation.Validation{}
+// 	valid.MaxSize(name, 100, "path").Message("名称最长为100字符")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+
+// 	RoleService := Role_service.Role{
+// 		Name: name,
+// 		Menu: menuId,
+// 	}
+
+// 	if id, err := RoleService.Add(); err != nil {
+
+// 		err = inject.Obj.Common.RoleAPI.LoadPolicy(id)
+// 		if err != nil {
+// 			appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_FAIL, nil)
+// 			return
+// 		}
+// 		appG.Response(http.StatusOK, e.SUCCESS, nil)
+// 	} else {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+
+// }
+
+// // @Summary   更新角色
+// // @Tags role
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Param  name  query  string true "name"
+// // @Param  menu_id  query  string true "menu_id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/roles/:id  [PUT]
+// func EditRole(c *gin.Context) {
+// 	var (
+// 		appG = app.Gin{C: c}
+// 	)
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	dataByte, _ := ioutil.ReadAll(c.Request.Body)
+// 	fsion := gofasion.NewFasion(string(dataByte))
+// 	name := fsion.Get("username").ValueStr()
+// 	menuId := com.StrTo(fsion.Get("menu_id").ValueInt()).MustInt()
+
+// 	valid := validation.Validation{}
+// 	valid.MaxSize(name, 100, "path").Message("名称最长为100字符")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_ADD_FAIL, nil)
+// 		return
+// 	}
+// 	RoleService := Role_service.Role{
+// 		ID:   id,
+// 		Name: name,
+// 		Menu: menuId,
+// 	}
+// 	exists, err := RoleService.ExistByID()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+
+// 	err = RoleService.Edit()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_FAIL, nil)
+// 		return
+// 	}
+
+// 	err = inject.Obj.Common.RoleAPI.LoadPolicy(id)
+
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_FAIL, nil)
+// 		return
+// 	}
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+// }
+
+// // @Summary   删除角色
+// // @Tags role
+// // @Accept json
+// // @Produce  json
+// // @Param  id  path  string true "id"
+// // @Success 200 {string} json "{ "code": 200, "data": {}, "msg": "ok" }"
+// // @Router /authdata/roles/:id  [DELETE]
+// func DeleteRole(c *gin.Context) {
+// 	appG := app.Gin{C: c}
+// 	valid := validation.Validation{}
+// 	id := com.StrTo(c.Param("id")).MustInt()
+// 	valid.Min(id, 1, "id").Message("ID必须大于0")
+
+// 	if valid.HasErrors() {
+// 		app.MarkErrors(valid.Errors)
+// 		appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
+// 		return
+// 	}
+
+// 	RoleService := Role_service.Role{ID: id}
+// 	exists, err := RoleService.ExistByID()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+// 	if !exists {
+// 		appG.Response(http.StatusOK, e.ERROR_EXIST_FAIL, nil)
+// 		return
+// 	}
+// 	role, err := RoleService.Get()
+// 	err = RoleService.Delete()
+// 	if err != nil {
+// 		appG.Response(http.StatusInternalServerError, e.ERROR_DELETE_FAIL, nil)
+// 		return
+// 	}
+
+// 	inject.Obj.Enforcer.DeleteUser(role.Name)
+
+// 	appG.Response(http.StatusOK, e.SUCCESS, nil)
+// }

+ 34 - 0
apiserver/routers/job.go

@@ -0,0 +1,34 @@
+package routers
+
+import (
+	// "github.com/robfig/cron"
+
+	"time"
+
+	"github.com/robfig/cron/v3"
+	"kpt.xdmy/apiserver/service"
+	"kpt.xdmy/pkg/log"
+)
+
+func SapJobInit(s *service.Service) {
+	svc = s
+	c := cron.New()
+	// 02:00
+	if _, e := c.AddFunc("00 00 02 * * *", jobMaterial); e != nil {
+		log.Error("jobMaterial", e)
+	}
+	if _, e := c.AddFunc("00 00 02 * * *", jobTransfer); e != nil {
+		log.Error("transfer", e)
+	}
+	c.Start()
+
+}
+
+func jobMaterial() {
+	t := time.Now()
+	var code string
+	svc.SapMaterial(t, code)
+}
+func jobTransfer() {
+	
+}

+ 31 - 0
apiserver/routers/mcs.go

@@ -0,0 +1,31 @@
+package routers
+
+import (
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+)
+
+func McsControl(c *gin.Context) {
+	mpd := new(model.McsPostDataReq)
+	if !Bind(c, mpd) {
+		return
+	}
+	resp, err := svc.McsPostHttp(mpd)
+	eJSON(c, resp, err)
+}
+
+func McsAccounts(c *gin.Context) {
+	sa := []model.McsAccount{
+		{
+			DeviceId: "apptest2",
+			UserID:   "PC",
+			Password: "mcs8",
+		},
+	}
+	resp := &http.Response{
+		Code: 200,
+		Data: sa,
+	}
+	eJSON(c, resp, nil)
+}

+ 15 - 0
apiserver/routers/part.go

@@ -0,0 +1,15 @@
+package routers
+
+import (
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/service"
+)
+
+func EasBatch(c *gin.Context) {
+	n, e := service.PartBatch()
+	if n == 0 {
+		c.JSON(500, e.Error())
+	} else {
+		c.JSON(200, n)
+	}
+}

二進制
apiserver/routers/restful/.DS_Store


+ 1322 - 0
apiserver/routers/restful/sql_utils.go

@@ -0,0 +1,1322 @@
+package restful
+
+import (
+	"database/sql"
+	"fmt"
+	"log"
+	"math"
+	"reflect"
+	"strconv"
+	"strings"
+	"time"
+	"unsafe"
+
+	"github.com/pkg/errors"
+
+	_ "github.com/go-sql-driver/mysql"
+	"github.com/jmoiron/sqlx"
+	"github.com/patrickmn/go-cache"
+	"github.com/tealeg/xlsx"
+	"github.com/xormplus/xorm/schemas"
+	"kpt.xdmy/pkg/setting"
+)
+
+var (
+	Dbs          *sqlx.DB
+	Apisql_cache *cache.Cache
+)
+
+// SQLInit 初始化数据库操作句柄,这里要提供:
+// driverName string: 数据库类型,例如mysql、sqlite等,参考github.com/go-sql-driver/mysql官方介绍
+// dataSourceName string: 数据库地址,参考github.com/go-sql-driver/mysql官方介绍
+// MaxOpenConns int: 最大缓存连接数,这个数值包含了MaxIdleConns
+// MaxIdleConns int:预备的最大空闲连接数
+func SQLInit(driverName, dataSourceName string, maxOpenConns, maxIdleConns int, showlog bool) error {
+
+	if Dbs == nil {
+		var err error
+		if Dbs, err = sqlx.Open(driverName, dataSourceName); err != nil {
+			return err
+		}
+		Dbs.SetMaxOpenConns(maxOpenConns)
+		Dbs.SetMaxIdleConns(maxIdleConns)
+		Dbs.SetConnMaxLifetime(300 * time.Second)
+	}
+	if Apisql_cache == nil {
+		Apisql_cache = cache.New(600*time.Second, 10*time.Second)
+	}
+	// SetCacheSql()
+	return nil
+}
+
+func SetCacheSql() {
+	rows, err := Dbs.Queryx("SELECT sqlname, CONCAT(sqlstr,'|',IFNULL(params,'')) AS sqlstr FROM apisql WHERE ENABLE>0 ")
+	if err != nil {
+		return
+	}
+	valuesMap, err := Rows2Strings(rows)
+
+	if err == nil && len(valuesMap) > 0 {
+		for _, v := range valuesMap {
+			Apisql_cache.Set(v["sqlname"], v["sqlstr"], cache.DefaultExpiration)
+		}
+	}
+}
+func sqlCheckParam(param string) error {
+
+	if strings.Contains(param, ";") {
+		return errors.New("can not have ;")
+	}
+
+	return nil
+}
+
+func GetSqlByName(name string, tx *sqlx.Tx) (string, string) {
+	sqls := ""
+	param := ""
+	if sql, ok := Apisql_cache.Get(name); ok {
+		tempstrb := strings.IndexAny(sql.(string), "|")
+		sqls = sql.(string)[0:tempstrb]
+		param = sql.(string)[tempstrb+1:]
+	} else {
+		valuesMap, err := MapStr("SELECT sqlstr, params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
+		if err != nil {
+			return err.Error(), "err"
+		}
+		if len(valuesMap) > 0 {
+			sqls = valuesMap["sqlstr"]
+			param = valuesMap["params"]
+			// Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
+		}
+	}
+	if setting.DatabaseSetting.ShowGetSqllog {
+
+		fmt.Println("==============")
+		fmt.Println("apisql:" + sqls)
+		fmt.Println("--------------")
+		fmt.Println("param:" + param)
+		fmt.Println("==============")
+	}
+	return sqls, param
+}
+func GetSqlByNameDB(name string) (string, string) {
+
+	var sqls, param string
+	if sql, ok := Apisql_cache.Get(name); ok {
+		tempstrb := strings.IndexAny(sql.(string), "|")
+		sqls = sql.(string)[0:tempstrb]
+		param = sql.(string)[tempstrb+1:]
+	} else {
+		rows, err := Dbs.Queryx("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
+		if err != nil {
+			return err.Error(), "err"
+		}
+		valuesMap, err := Rows2Strings(rows)
+		if err == nil && len(valuesMap) > 0 {
+			sqls = valuesMap[0]["sqlstr"]
+			param = valuesMap[0]["params"]
+			// Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
+		}
+	}
+
+	if setting.DatabaseSetting.ShowGetSqllog {
+
+		fmt.Println("==============")
+		fmt.Println("apisql:" + sqls)
+		fmt.Println("--------------")
+		fmt.Println("param:" + param)
+		fmt.Println("==============")
+	}
+	return sqls, param
+}
+
+func GetSqlByNameDBT(name string, tx *sqlx.Tx) (string, string) {
+	var sqls, param string
+	if sql, ok := Apisql_cache.Get(name); ok {
+		tempstrb := strings.IndexAny(sql.(string), "|")
+		sqls = sql.(string)[0:tempstrb]
+		param = sql.(string)[tempstrb+1:]
+	} else {
+
+		rows, err := Dbs.Queryx("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", name)
+		if err != nil {
+			log.Default().Printf("GetSqlByNameDBT :%v", err)
+			return "", ""
+		}
+		if rows.Next() {
+			rows.Scan(&sqls, &param)
+		}
+		if sqls != "" {
+			// Apisql_cache.Set(name, (sqls + "|" + param), cache.DefaultExpiration)
+		}
+	}
+	if setting.DatabaseSetting.ShowGetSqllog {
+
+		fmt.Println("==============")
+		fmt.Println("apisql:" + sqls)
+		fmt.Println("--------------")
+		fmt.Println("param:" + param)
+		fmt.Println("==============")
+	}
+	return sqls, param
+}
+
+// sqlGetValues 根据结构体中指向实际数据的指针获取出数据,并存储到另一张表中返回
+func sqlGetValues(pvs []interface{}, columnsType []*sql.ColumnType, columnsLen int) map[string]interface{} {
+
+	result := make(map[string]interface{}, columnsLen)
+
+	for a := 0; a < columnsLen; a++ {
+		switch s := pvs[a].(type) {
+		case *int8:
+			result[columnsType[a].Name()] = *s
+		case *int16:
+			result[columnsType[a].Name()] = *s
+		case *int32:
+			result[columnsType[a].Name()] = *s
+		case *int64:
+			result[columnsType[a].Name()] = *s
+		case *float32:
+			result[columnsType[a].Name()] = *s
+		case *float64:
+			result[columnsType[a].Name()] = *s
+		case *string:
+			result[columnsType[a].Name()] = *s
+		case *sql.NullInt64:
+			result[columnsType[a].Name()] = *s
+		case *sql.NullString:
+			result[columnsType[a].Name()] = *s
+		}
+	}
+	return result
+}
+
+// 这里返回的是原始数组的基础上加上了字段名标识
+func sqlQuery(columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) ([]map[string]interface{}, error) {
+
+	jsondata := make([]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		jsondata[k1] = sqlGetValues(v1, columnsType, columnsLen)
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByTinyIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int8]map[string]interface{}, error) {
+
+	jsondata := make(map[int8]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*int8); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryBySmallIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int16]map[string]interface{}, error) {
+
+	jsondata := make(map[int16]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*int16); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int32]map[string]interface{}, error) {
+
+	jsondata := make(map[int32]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*int32); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByBigIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[int64]map[string]interface{}, error) {
+
+	jsondata := make(map[int64]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*int64); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByFloatIntMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float32]map[string]interface{}, error) {
+
+	jsondata := make(map[float32]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*float32); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByDoubleMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[float64]map[string]interface{}, error) {
+
+	jsondata := make(map[float64]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*float64); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlQueryByStringMap(columnName string, columnsType []*sql.ColumnType, columnsLen int, queryData [][]interface{}, queryCount int) (map[string]map[string]interface{}, error) {
+
+	jsondata := make(map[string]map[string]interface{}, queryCount)
+	for k1, v1 := range queryData {
+		if k1 >= queryCount {
+			break
+		}
+
+		for a := 0; a < columnsLen; a++ {
+			if columnsType[a].Name() == columnName {
+				if value, ok := v1[a].(*string); ok {
+					jsondata[*value] = sqlGetValues(v1, columnsType, columnsLen)
+				}
+				break
+			}
+		}
+	}
+
+	return jsondata, nil
+}
+
+func sqlGetColumnType(columnsType []*sql.ColumnType, columnsLen int, valueName string) string {
+
+	for a := 0; a < columnsLen; a++ {
+		if columnsType[a].Name() == valueName {
+			return columnsType[a].DatabaseTypeName()
+		}
+	}
+
+	return ""
+}
+
+func round(num float64) int {
+	return int(num + math.Copysign(0.5, num))
+}
+
+func toFixed(num float64, precision int) float64 {
+	output := math.Pow(10, float64(precision))
+	return float64(round(num*output)) / output
+}
+
+// QueryByMap 将查询到的数据,按照指定字段的值做为索引构建map并返回
+// columnName string: 作为索引的字段名称
+// sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
+// where string: 过滤条件,就是where后面跟着的部分
+// order string: 排序条件,就是order by后面跟着的部分。默认是ASC排序,除非"-"开头则DESC排序
+// offset string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
+// count string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
+func QueryByMap(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	recordcount := int64(0)
+
+	if count > 1 {
+		sqlstr = fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr)
+		err := BasicList(sqlstr, params, &recordcount)
+		if err != nil {
+			fmt.Println("s1", err)
+			return nil, err
+		}
+	}
+	queryData := make([]map[string]interface{}, 1)
+	var err error
+	if count == 0 {
+		rows, err := Dbs.Queryx(sqlstr, params...)
+		if err != nil {
+			return err.Error(), err
+		}
+		queryData, err = rows2mapObjects(rows)
+	} else {
+		if count > 0 && offset > 0 {
+			offset = offset * count
+		}
+		rows, err := Dbs.Queryx(fmt.Sprintf(sqlstr+" limit %d , %d", offset, count), params...)
+		if err != nil {
+			return err.Error(), err
+		}
+		queryData, err = rows2mapObjects(rows)
+	}
+
+	if err != nil {
+		return nil, err
+	}
+	if recordcount == 0 {
+		recordcount = int64(len(queryData))
+	}
+
+	data := make(map[string]interface{})
+	data["list"] = queryData
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+// func QueryByMapT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+func QueryByMapT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	recordcount := int64(0)
+
+	if count > 1 {
+		sql := "SELECT COUNT(*) as count FROM (" + sqlstr + ") a"
+		err := BasicList(sql, params, &recordcount)
+		if err != nil {
+			fmt.Println("s1", err)
+			return nil, err
+		}
+	}
+	queryData := make([]map[string]interface{}, 1)
+	// queryData := make([]map[string]string, 1)
+	var err error
+	if count == 0 {
+		// queryData, err = MapStrList(sqlstr, params...)
+		queryData, err = MapInterList(sqlstr, params...)
+	} else {
+		// if count > 0 && offset > 0 {
+		// 	offset = offset * count
+		// }
+		sqllist := sqlstr + fmt.Sprintf("  limit %d  offset %d", count, offset*count)
+		// queryData, err = MapStrList(sqllist, params...)
+		queryData, err = MapInterList(sqllist, params...)
+	}
+	if err != nil {
+		return nil, err
+	}
+	if recordcount == 0 {
+		recordcount = int64(len(queryData))
+	}
+
+	data := make(map[string]interface{})
+	data["list"] = queryData
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+// QueryByXlsx 将查询到的数据,按照指定字段的值做为索引构建map并返回
+// sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
+// params string: 过滤条件,就是where后面跟着的部分
+
+func QueryByXlsx(sqlstr string, params []interface{}) (*xlsx.File, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return nil, err
+	}
+
+	rows, err := Dbs.Queryx(sqlstr, params...)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	columnsType, _ := rows.ColumnTypes()
+	columnsLen := len(columnsType)
+	columns, _ := rows.Columns()
+	values := make([]interface{}, columnsLen)
+	valuePtrs := make([]interface{}, columnsLen)
+
+	var sheet *xlsx.Sheet
+	var row *xlsx.Row
+	var cell *xlsx.Cell
+
+	file := xlsx.NewFile()
+	sheet, err = file.AddSheet("Sheet1")
+
+	if err != nil {
+		fmt.Printf(err.Error())
+	}
+	row = sheet.AddRow()
+	for _, columnname := range columns {
+		cell = row.AddCell()
+		cell.Value = columnname
+	}
+	for rows.Next() {
+		for a := 0; a < columnsLen; a++ {
+			valuePtrs[a] = &values[a]
+		}
+		rows.Scan(valuePtrs...)
+		row = sheet.AddRow()
+		for i := range columns {
+			var v interface{}
+			val := values[i]
+			b, ok := val.([]byte)
+			cell = row.AddCell()
+			if ok {
+				v1 := string(b)
+				switch columnsType[i].DatabaseTypeName() {
+				case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
+					{
+						v, _ = strconv.ParseInt(v1, 10, 32)
+						cell.Value = fmt.Sprintf("%v", v)
+					}
+				case "FLOAT", "DOUBLE", "DECIMAL":
+					{
+						cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
+						v2, _ := strconv.ParseFloat(v1, 32)
+						v = toFixed(v2, cindex)
+						cell.Value = fmt.Sprintf("%v", v)
+					}
+				case "BOOL":
+					{
+						v, _ = strconv.ParseBool(v1)
+						cell.Value = fmt.Sprintf("%v", v)
+					}
+				default:
+					{
+						v = v1
+						cell.Value = fmt.Sprintf("%v", v)
+					}
+				}
+
+			} else {
+				v = val
+				cell.Value = fmt.Sprintf("%v", v)
+			}
+			if cell.Value == "<nil>" {
+				cell.Value = ""
+			}
+		}
+	}
+
+	return file, nil
+}
+
+// QueryByMap 将查询到的数据,按照指定字段的值做为索引构建map并返回
+// columnName string: 作为索引的字段名称
+// sql string: 查询需要获取哪些字段的值,就是select后面跟着的部分,一般用"*"
+// where string: 过滤条件,就是where后面跟着的部分
+// order string: 排序条件,就是order by后面跟着的部分。默认是ASC排序,除非"-"开头则DESC排序
+// offset string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
+// count string: limit后面逗号相隔的两个数值,前者就是offset,后者就是count
+
+func QueryByMapMenu(sqlstr string, offset, count int, params []interface{}) ([]map[string]interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return nil, err
+	}
+
+	if offset < 0 {
+		offset = 0
+	}
+	if count <= 0 {
+		count = 0
+	}
+	if count > 0 {
+		sqlstr += " limit " + strconv.Itoa(offset) + "," + strconv.Itoa(count)
+	}
+
+	rows, err := Dbs.Query(sqlstr, params...)
+	if err != nil {
+		return nil, err
+	}
+	defer rows.Close()
+	columnsType, _ := rows.ColumnTypes()
+	columnsLen := len(columnsType)
+	columns, _ := rows.Columns()
+	queryData := make([]map[string]interface{}, 0)
+	values := make([]interface{}, columnsLen)
+	valuePtrs := make([]interface{}, columnsLen)
+
+	for rows.Next() {
+		for a := 0; a < columnsLen; a++ {
+			valuePtrs[a] = &values[a]
+		}
+		rows.Scan(valuePtrs...)
+		entry := make(map[string]interface{})
+		for i, col := range columns {
+			entry[col] = getValue(values[i], columnsType[i].DatabaseTypeName())
+		}
+		queryData = append(queryData, entry)
+	}
+
+	data := queryData
+	return data, nil
+}
+
+func QueryByList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	if count == 0 {
+		count = 1000
+	}
+	recordcount := int64(0)
+	if count > 1 {
+		trow, err := Dbs.Queryx("SELECT COUNT(1) as count FROM ("+sqlstr+") a", params...)
+		if err != nil {
+			return nil, err
+		}
+		tt, err := rows2mapObjects(trow)
+		if err != nil {
+			return nil, err
+		}
+		recordcount = tt[0]["count"].(int64)
+	}
+	queryData := make([]map[string]interface{}, 1)
+	var err error
+	if count == 0 {
+		tqueryData, err := Dbs.Queryx(sqlstr, params...)
+		if err != nil {
+			return nil, err
+		}
+		queryData, err = rows2mapObjects(tqueryData)
+	} else {
+		// if count > 0 && offset > 0 {
+		// 	offset = offset * count
+		// }
+		sqlstr += fmt.Sprintf(" limit %d offset %d", count, offset*count)
+		tqueryData, err := Dbs.Queryx(sqlstr, params...)
+		if err != nil {
+			return nil, err
+		}
+		queryData, err = rows2mapObjects(tqueryData)
+	}
+	if err != nil {
+		return nil, err
+	}
+	columnsname := make([]string, 0)
+	listdata := make(map[string][]interface{})
+	if len(queryData) > 0 {
+		for i := range queryData {
+			if i == 0 {
+				for i := range queryData[0] {
+					columnsname = append(columnsname, i)
+				}
+			}
+
+			for _, v := range columnsname {
+				listdata[v] = append(listdata[v], queryData[i][v])
+			}
+
+		}
+		recordcount = int64(len(queryData))
+	}
+
+	data := make(map[string]interface{})
+	data["list"] = listdata
+	//data["columnsname"] = columnsname
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+func QueryByListList(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	if count == 0 {
+		count = 1000
+	}
+	recordcount := int64(0)
+	if count > 1 {
+		trow, err := Dbs.Queryx("SELECT COUNT(1) as count FROM ("+sqlstr+") a", params...)
+		if err != nil {
+			return nil, err
+		}
+		tt, err := rows2mapObjects(trow)
+		if err != nil {
+			return nil, err
+		}
+		recordcount = tt[0]["count"].(int64)
+	}
+
+	queryData := make([]map[string]interface{}, 1)
+	var err error
+	if count == 0 {
+		tqueryData, err := Dbs.Queryx(sqlstr, params...)
+		if err != nil {
+			return nil, err
+		}
+		queryData, err = rows2mapObjects(tqueryData)
+	} else {
+		if count > 0 && offset > 0 {
+			offset = offset * count
+		}
+		tqueryData, err := Dbs.Queryx(fmt.Sprintf(sqlstr+" limit %d , %d", offset, count), params...)
+		if err != nil {
+			return nil, err
+		}
+		queryData, err = rows2mapObjects(tqueryData)
+	}
+
+	if err != nil {
+		return nil, err
+	}
+	columnsname := make([]string, 0)
+	listdata := make([]interface{}, 0)
+	if len(queryData) > 0 {
+		for i := range queryData {
+			if i == 0 {
+				for i := range queryData[0] {
+					columnsname = append(columnsname, i)
+				}
+			}
+			listdatarow := make([]interface{}, 0)
+
+			for _, v := range columnsname {
+				listdatarow = append(listdatarow, queryData[i][v])
+			}
+			listdata = append(listdata, listdatarow)
+		}
+		recordcount = int64(len(queryData))
+	}
+	data := make(map[string]interface{})
+	data["list"] = listdata
+	data["columnsname"] = columnsname
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+// func QueryByListT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+func QueryByListT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	if count == 0 {
+		count = 1000
+	}
+	recordcount := int64(0)
+	if count > 1 {
+		tt, err := Dbs.Queryx("SELECT COUNT(*) as count FROM ("+sqlstr+") a", params...)
+		if err != nil {
+			return nil, err
+		}
+		tt.Next()
+		tt.Scan(&recordcount)
+	}
+	var err error
+	var sqllist string
+	if count > 0 {
+		sqllist = sqlstr + fmt.Sprintf(" limit %d offset %d", count, offset*count)
+	}
+	listdata, err := MapInterList(sqllist, params...)
+	if err != nil {
+		log.Default().Printf("QueryByListT MapInterList : %v", err)
+	}
+
+	data := make(map[string]interface{})
+	data["lists"] = listdata
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+// func QueryByListListT(sqlstr string, offset, count int, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+func QueryByListListT(sqlstr string, offset, count int, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	if count == 0 {
+		count = 1000
+	}
+	recordcount := int64(0)
+	if count > 1 {
+		sqlstr = fmt.Sprintf("SELECT COUNT(*) as count FROM (%s) a", sqlstr)
+		err := BasicList(sqlstr, params, &recordcount)
+		if err != nil {
+			return nil, err
+		}
+	}
+
+	queryData := make([]map[string]string, 1)
+	var err error
+	if count == 0 {
+		queryData, err = MapStrList(sqlstr, params...)
+	} else {
+		// if count > 0 && offset > 0 {
+		// 	offset = offset * count
+		// }
+		sqllist := sqlstr + fmt.Sprintf(" limit %d offset %d", count, offset*count)
+		queryData, err = MapStrList(sqllist, params...)
+	}
+
+	if err != nil {
+		return nil, err
+	}
+	columnsname := make([]string, 0)
+	listdata := make([]interface{}, 0)
+	if len(queryData) > 0 {
+		for i := range queryData {
+			if i == 0 {
+				for i := range queryData[0] {
+					columnsname = append(columnsname, i)
+				}
+			}
+			listdatarow := make([]interface{}, 0)
+
+			for _, v := range columnsname {
+				listdatarow = append(listdatarow, queryData[i][v])
+			}
+			listdata = append(listdata, listdatarow)
+		}
+		recordcount = int64(len(queryData))
+	}
+	data := make(map[string]interface{})
+	data["list"] = listdata
+	data["columnsname"] = columnsname
+	data["total"] = recordcount
+	data["code"] = 0
+	data["message"] = "ok"
+	if count > 0 {
+		data["pages"] = math.Ceil(float64(recordcount) / float64(count))
+		data["pageNum"] = math.Ceil(float64(offset+1) / float64(count))
+	}
+	data["pageSize"] = count
+	return data, nil
+}
+
+func ExecQuery(sqlstr string, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+
+	rows, err := Dbs.Exec(sqlstr, params...)
+	if err != nil {
+		return nil, err
+	}
+	data := make(map[string]interface{})
+	LastInsertId, _ := rows.LastInsertId()
+	idPointer := (*int)(unsafe.Pointer(&LastInsertId))
+	idd16 := *idPointer
+	RowsAffected, _ := rows.RowsAffected()
+	_idPointer := (*int)(unsafe.Pointer(&RowsAffected))
+	_idd16 := *_idPointer
+	data["result"] = rows
+	data["LastInsertId"] = idd16
+
+	data["RowsAffected"] = _idd16
+	return data, nil
+}
+
+func ExecQueryT(sqlstr string, params []interface{}, tx *sqlx.Tx) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+
+	rows, err := tx.Exec(sqlstr, params...)
+	if err != nil {
+
+		fmt.Println("exe", err)
+		return nil, err
+	}
+
+	LastInsertId, _ := rows.LastInsertId()
+	idPointer := (*int)(unsafe.Pointer(&LastInsertId))
+	idd16 := *idPointer
+	data := make(map[string]interface{})
+
+	RowsAffected, _ := rows.RowsAffected()
+	_idPointer := (*int)(unsafe.Pointer(&RowsAffected))
+	_idd16 := *_idPointer
+	data["LastInsertId"] = idd16
+	data["RowsAffected"] = _idd16
+	data["result"] = rows
+	return data, nil
+}
+
+func ExecQuerys(sqlstr string, params []interface{}) (interface{}, error) {
+	if err := sqlCheckParam(sqlstr); err != nil {
+		return 0, err
+	}
+	var res sql.Result
+	var e error
+	res, e = Dbs.Exec(sqlstr, params...)
+	if e != nil {
+		return nil, e
+	}
+	fmt.Printf("%#v\n", res)
+	data := make(map[string]interface{})
+	data["result"] = nil
+	return data, nil
+}
+
+func getValue(value interface{}, CT string) interface{} {
+	var v interface{}
+	val := value
+	b, ok := val.([]byte)
+	if ok {
+		v1 := string(b)
+		switch CT {
+		case "TINYINT", "SMALLINT", "MEDIUMINT", "INT", "INTEGER", "BIGINT":
+			{
+				v, _ = strconv.ParseInt(v1, 10, 32)
+			}
+		case "FLOAT", "DOUBLE", "DECIMAL":
+			{
+				cindex := len(val.([]byte)) - strings.Index(v1, ".") - 1
+				v2, _ := strconv.ParseFloat(v1, 32)
+				v = toFixed(v2, cindex)
+			}
+		case "BOOL":
+			{
+				v, _ = strconv.ParseBool(v1)
+			}
+		default:
+			{
+				v = v1
+			}
+		}
+	} else {
+		v = val
+	}
+	return v
+}
+func reflect2object(rawValue *reflect.Value) (value interface{}, err error) {
+	aa := reflect.TypeOf((*rawValue).Interface())
+	vv := reflect.ValueOf((*rawValue).Interface())
+	switch aa.Kind() {
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		value = vv.Int()
+	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+		value = vv.Uint()
+	case reflect.Float32, reflect.Float64:
+		value = vv.Float()
+	case reflect.String:
+		value = vv.String()
+	case reflect.Array, reflect.Slice:
+		switch aa.Elem().Kind() {
+		case reflect.Uint8:
+			data := rawValue.Interface().([]byte)
+			value = string(data)
+		default:
+			err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+		}
+	// time type
+	case reflect.Struct:
+		if aa.ConvertibleTo(schemas.TimeType) {
+			value = vv.Convert(schemas.TimeType).Interface().(time.Time)
+		} else {
+			err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+		}
+	case reflect.Bool:
+		value = vv.Bool()
+	case reflect.Complex128, reflect.Complex64:
+		value = vv.Complex()
+	/* TODO: unsupported types below
+	   case reflect.Map:
+	   case reflect.Ptr:
+	   case reflect.Uintptr:
+	   case reflect.UnsafePointer:
+	   case reflect.Chan, reflect.Func, reflect.Interface:
+	*/
+	default:
+		err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+	}
+	return
+}
+func value2Object(rawValue *reflect.Value) (data interface{}, err error) {
+	data, err = reflect2object(rawValue)
+	if err != nil {
+		return
+	}
+	return
+}
+
+func rows2mapObjects(rows *sqlx.Rows) (resultsSlice []map[string]interface{}, err error) {
+	fields, err := rows.Columns()
+	if err != nil {
+		return nil, err
+	}
+	for rows.Next() {
+		result, err := rows2mapObject(rows, fields)
+		if err != nil {
+			return nil, err
+		}
+		resultsSlice = append(resultsSlice, result)
+	}
+
+	return resultsSlice, nil
+}
+
+func rows2mapObject(rows *sqlx.Rows, fields []string) (resultsMap map[string]interface{}, err error) {
+	result := make(map[string]interface{})
+	scanResultContainers := make([]interface{}, len(fields))
+	for i := 0; i < len(fields); i++ {
+		var scanResultContainer interface{}
+		scanResultContainers[i] = &scanResultContainer
+	}
+	if err := rows.Scan(scanResultContainers...); err != nil {
+		return nil, err
+	}
+
+	for ii, key := range fields {
+		rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
+		//if row is null then ignore
+		if rawValue.Interface() == nil {
+			continue
+		}
+
+		if data, err := value2Object(&rawValue); err == nil {
+			result[key] = data
+		} else {
+			return nil, err // !nashtsai! REVIEW, should return err or just error log?
+		}
+
+	}
+	return result, nil
+}
+
+func row2mapStr(rows *sqlx.Rows, fields []string) (resultsMap map[string]string, err error) {
+	result := make(map[string]string)
+	scanResultContainers := make([]interface{}, len(fields))
+	for i := 0; i < len(fields); i++ {
+		var scanResultContainer interface{}
+		scanResultContainers[i] = &scanResultContainer
+	}
+	if err := rows.Scan(scanResultContainers...); err != nil {
+		return nil, err
+	}
+
+	for ii, key := range fields {
+		rawValue := reflect.Indirect(reflect.ValueOf(scanResultContainers[ii]))
+		// if row is null then as empty string
+		if rawValue.Interface() == nil {
+			result[key] = ""
+			continue
+		}
+
+		if data, err := value2String(&rawValue); err == nil {
+			result[key] = data
+		} else {
+			return nil, err
+		}
+	}
+	return result, nil
+}
+
+func Rows2Strings(rows *sqlx.Rows) (resultsSlice []map[string]string, err error) {
+	fields, err := rows.Columns()
+	if err != nil {
+		return nil, err
+	}
+	for rows.Next() {
+		result, err := row2mapStr(rows, fields)
+		if err != nil {
+			return nil, err
+		}
+		resultsSlice = append(resultsSlice, result)
+	}
+
+	return resultsSlice, nil
+}
+func value2String(rawValue *reflect.Value) (str string, err error) {
+	aa := reflect.TypeOf((*rawValue).Interface())
+	vv := reflect.ValueOf((*rawValue).Interface())
+	switch aa.Kind() {
+	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
+		str = strconv.FormatInt(vv.Int(), 10)
+	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
+		str = strconv.FormatUint(vv.Uint(), 10)
+	case reflect.Float32, reflect.Float64:
+		str = strconv.FormatFloat(vv.Float(), 'f', -1, 64)
+	case reflect.String:
+		str = vv.String()
+	case reflect.Array, reflect.Slice:
+		switch aa.Elem().Kind() {
+		case reflect.Uint8:
+			data := rawValue.Interface().([]byte)
+			str = string(data)
+			if str == "\x00" {
+				str = "0"
+			}
+		default:
+			err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+		}
+	// time type
+	case reflect.Struct:
+		if aa.ConvertibleTo(schemas.TimeType) {
+			str = vv.Convert(schemas.TimeType).Interface().(time.Time).Format(time.RFC3339Nano)
+		} else {
+			err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+		}
+	case reflect.Bool:
+		str = strconv.FormatBool(vv.Bool())
+	case reflect.Complex128, reflect.Complex64:
+		str = fmt.Sprintf("%v", vv.Complex())
+	/* TODO: unsupported types below
+	   case reflect.Map:
+	   case reflect.Ptr:
+	   case reflect.Uintptr:
+	   case reflect.UnsafePointer:
+	   case reflect.Chan, reflect.Func, reflect.Interface:
+	*/
+	default:
+		err = fmt.Errorf("Unsupported struct type %v", vv.Type().Name())
+	}
+	return
+}
+
+func MapStrList(sql string, param ...interface{}) ([]map[string]string, error) {
+	ress := make([]map[string]string, 0, 0)
+	rows, err := Dbs.Queryx(sql, param...)
+	if err != nil {
+		log.Default().Printf("MapStrList Queryx: %v", err)
+		return ress, err
+	}
+	col, err := rows.Columns()
+	if err != nil {
+		log.Default().Printf("BigpartUse clolumns: %v", err)
+		return ress, err
+	}
+	for rows.Next() {
+		m := make(map[string]string)
+		rs, err := rows.SliceScan()
+		if err != nil {
+			log.Default().Printf("BigpartUse SliceScan: %v", err)
+			return ress, err
+		}
+		for i, r := range rs {
+			switch r.(type) {
+			case []uint8:
+				m[col[i]] = string(r.([]uint8))
+			case int64:
+				m[col[i]] = strconv.FormatInt(r.(int64), 10)
+			}
+		}
+		ress = append(ress, m)
+	}
+	defer func() {
+		if err := rows.Close(); err != nil {
+			log.Default().Printf("sqlx row  close:%v", err)
+		}
+	}()
+	return ress, nil
+}
+func MapInterList(sql string, param ...interface{}) ([]map[string]interface{}, error) {
+	ress := make([]map[string]interface{}, 0, 0)
+	rows, err := Dbs.Queryx(sql, param...)
+	if err != nil {
+		log.Default().Printf("MapInterList Queryx: %v", err)
+		return ress, err
+	}
+	col, err := rows.Columns()
+	if err != nil {
+		log.Default().Printf("BigpartUse clolumns: %v", err)
+		return ress, err
+	}
+	for rows.Next() {
+		m := make(map[string]interface{})
+		rs, err := rows.SliceScan()
+		if err != nil {
+			log.Default().Printf("BigpartUse SliceScan: %v", err)
+			return ress, err
+		}
+		for i, r := range rs {
+			switch r.(type) {
+			case []uint8:
+				m[col[i]] = string(r.([]uint8))
+			case int64:
+				m[col[i]] = r.(int64)
+			}
+		}
+		ress = append(ress, m)
+	}
+	defer func() {
+		if err := rows.Close(); err != nil {
+			log.Default().Printf("sqlx row  close:%v", err)
+		}
+	}()
+	return ress, nil
+}
+
+func BasicList(sql string, params []interface{}, res ...interface{}) error {
+	// fmt.Printf("%s\n", sql)
+	if params == nil {
+		params = make([]interface{}, 0)
+	}
+	// var count int
+	tt, err := Dbs.Queryx(sql, params...)
+
+	if err != nil {
+		fmt.Println("s1", err)
+		return err
+	}
+	if tt.Next() {
+		tt.Scan(res...)
+		// tt.Scan(&count)
+	}
+	defer func() {
+		if err := tt.Close(); err != nil {
+			log.Default().Printf("sqlx row  close:%v", err)
+		}
+	}()
+	return nil
+}
+
+func MapStr(sql string, param ...interface{}) (map[string]string, error) {
+	m := make(map[string]string)
+	rows, err := Dbs.Queryx(sql, param...)
+	if err != nil {
+		log.Default().Printf("MapStr Queryx: %v", err)
+		return m, err
+	}
+	col, err := rows.Columns()
+	if err != nil {
+		log.Default().Printf("BigpartUse clolumns: %v", err)
+		return m, err
+	}
+	if rows.Next() {
+
+		rs, err := rows.SliceScan()
+		if err != nil {
+			log.Default().Printf("BigpartUse SliceScan: %v", err)
+			return m, err
+		}
+		for i, r := range rs {
+			switch r.(type) {
+			case []uint8:
+				m[col[i]] = string(r.([]uint8))
+			case int64:
+				m[col[i]] = strconv.FormatInt(r.(int64), 10)
+			}
+		}
+	}
+	defer func() {
+		if err := rows.Close(); err != nil {
+			log.Default().Printf("sqlx row  close:%v", err)
+		}
+	}()
+	return m, nil
+}
+
+func MapStrListTx(tx *sqlx.Tx, sql string, param ...interface{}) ([]map[string]string, error) {
+	ress := make([]map[string]string, 0, 0)
+	rows, err := tx.Queryx(sql, param...)
+	if err != nil {
+		log.Default().Printf("MapStrListTx Queryx: %v", err)
+		return ress, err
+	}
+	col, err := rows.Columns()
+	if err != nil {
+		log.Default().Printf("BigpartUse clolumns: %v", err)
+		return ress, err
+	}
+	for rows.Next() {
+		m := make(map[string]string)
+		rs, err := rows.SliceScan()
+		if err != nil {
+			log.Default().Printf("BigpartUse SliceScan: %v", err)
+			return ress, err
+		}
+		for i, r := range rs {
+			switch r.(type) {
+			case []uint8:
+				m[col[i]] = string(r.([]uint8))
+			case int64:
+				m[col[i]] = strconv.FormatInt(r.(int64), 10)
+			}
+		}
+		ress = append(ress, m)
+	}
+	defer func() {
+		if err := rows.Close(); err != nil {
+			log.Default().Printf("sqlx row  close:%v", err)
+		}
+	}()
+	return ress, nil
+}

+ 91 - 0
apiserver/routers/restful/test.go

@@ -0,0 +1,91 @@
+package restful
+
+import (
+	"fmt"
+
+	log "github.com/sirupsen/logrus"
+	// "kpt.xdmy/apiserver/dao"
+)
+
+func Sqlx() {
+	// st := time.Now()
+	// rows, e := Dbs.Queryx("SELECT id,partcode FROM parts limit 3000")
+	// rows, e := Dbs.Queryx("SELECT * FROM parts limit 3000")
+	// rows, e := Dbs.Queryx("SELECT * FROM parts limit 3000")
+	// dao.D.DB.Raw("SELECT id,partcode FROM parts limit 1000")
+	// s.d.DB.Raw()
+	// log.Printf("%d", time.Now().Sub(st).Milliseconds())
+	// sql, e := Dbs.Beginx()
+	// if e != nil {
+	// 	log.Error(e)
+	// }
+	// _, e = sql.Exec("update pasture  set name =33 where name  ='22'")
+	// if e != nil {
+	// 	log.Error(e)
+	// }
+	// sql.Commit()
+	// var name string
+	var sqls, param string
+	tx, e := Dbs.Beginx()
+	if e != nil {
+		log.Error(e)
+	}
+	rows, e := tx.Queryx("SELECT sqlstr,params FROM apisql WHERE sqlname = ? AND ENABLE>0 ", "getBigPartTransferList")
+	// rows, e := Dbs.Queryx("select id from parts where createTime is not null   limit 10 ")
+	// rows, e := Dbs.NamedQuery("select name  from  pasture  where  name=:name", map[string]interface{}{"name": "33"})
+	if e != nil {
+		fmt.Print(e)
+	}
+	if rows.Next() {
+		rows.Scan(&sqls, &param)
+	}
+	// tx.Commit()
+	fmt.Println(sqls, param)
+	// for rows.Next() {
+	// 	var value string
+	// 	rs, err := rows.SliceScan()
+	// 	if err != nil {
+	// 		fmt.Printf("BigpartUse SliceScan: %v", err)
+	// 	}
+	// 	for _, r := range rs {
+
+	// 		switch r.(type) {
+	// 		case []uint8:
+	// 			value = string(r.([]uint8))
+	// 		case int64:
+	// 			value = strconv.FormatInt(r.(int64), 10)
+	// 		case time.Time:
+	// 			value = r.(time.Time).Format("2006-01-02 15:04:05")
+	// 		}
+	// 		fmt.Println(value)
+	// 	}
+	// }
+
+	// rows.Scan(&name)
+	// fmt.Printf("name = %s  \n", name)
+	// var ids int
+	// var partcode string
+	// p := make(map[string]interface{})
+	// in := make([]string, 0)
+
+	// rows.Next()
+	// rows.Scan(&ids, &partcode)
+
+	// fmt.Printf("id: %d, code: %s\n", ids, partcode)
+
+	// rows.Next()
+	// rows.MapScan(p)
+	// fmt.Printf("map: %s\n", p)
+
+	// rows.Next()
+	// rows.Scan(&in)
+	// fmt.Printf("interface: %s\n", in)
+
+	// rows.Next()
+	// sl, e := rows.SliceScan()
+	// if e != nil {
+	// 	fmt.Println(e)
+	// }
+	// fmt.Printf("slice: %s\n", sl)
+	defer rows.Close()
+}

+ 61 - 0
apiserver/routers/restful/user.go

@@ -0,0 +1,61 @@
+package restful
+
+type User struct {
+	Id         int    `xorm:"not null pk autoincr INT(10)"`
+	Username   string `xorm:"default '''' comment('账号') VARCHAR(50)"`
+	Password   string `xorm:"default '''' comment('密码') VARCHAR(50)"`
+	Empid      int    `xorm:"default -1 INT(11)"`
+	Sort       int    `xorm:"default 0 INT(11)"`
+	Enable     int    `xorm:"default 1 TINYINT(4)"`
+	CreatedOn  int    `xorm:"default NULL comment('创建时间') INT(11)"`
+	ModifiedOn int    `xorm:"default NULL comment('更新时间') INT(11)"`
+	DeletedOn  int    `xorm:"default 0 comment('删除时间戳') INT(11)"`
+}
+
+/*
+type UserRole struct {
+	Id        int `xorm:"not null pk autoincr INT(10)"`
+	UserId    int `xorm:"default NULL comment('用户ID') INT(11)"`
+	RoleId    int `xorm:"default NULL comment('角色ID') INT(11)"`
+	DeletedOn int `xorm:"default 0 comment('删除时间戳') INT(11)"`
+}
+
+type Role struct {
+	Id         int    `xorm:"not null pk autoincr INT(10)"`
+	Name       string `xorm:"default '''' comment('名字') VARCHAR(50)"`
+	Sort       int    `xorm:"default 0 INT(11)"`
+	Enable     int    `xorm:"default 1 TINYINT(4)"`
+	CreatedOn  int    `xorm:"default NULL comment('创建时间') INT(11)"`
+	ModifiedOn int    `xorm:"default NULL comment('更新时间') INT(11)"`
+	DeletedOn  int    `xorm:"default 0 comment('删除时间戳') INT(11)"`
+}
+*/
+func CheckUser(username, password string) (bool, error) {
+
+	return true, nil
+}
+func GetUserInfo(username string) map[string]interface{} {
+	valuesMap := make([]map[string]interface{}, 1)
+	valuesMap2 := make([]map[string]interface{}, 1)
+
+	tqueryData, err := Dbs.Queryx("SELECT * FROM  `user` WHERE `username` = ? and `enable` >0 ", username)
+	if err != nil {
+		return nil
+	}
+	valuesMap, err = rows2mapObjects(tqueryData)
+
+	if err != nil {
+		return nil
+	}
+	if len(valuesMap) > 0 {
+		tqueryData2, err := Dbs.Queryx("SELECT r.`name`,r.`id` FROM `user` u JOIN `user_role` ur ON u.`id`=ur.`user_id` JOIN `role` r ON r.id=ur.`role_id` WHERE r.`enable`>0 AND u.username=?", username)
+		if err == nil {
+			valuesMap2, err = rows2mapObjects(tqueryData2)
+			if err == nil {
+				valuesMap[0]["role"] = valuesMap2
+			}
+		}
+		return valuesMap[0]
+	}
+	return nil
+}

+ 198 - 0
apiserver/routers/router.go

@@ -0,0 +1,198 @@
+package routers
+
+import (
+	"fmt"
+
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/middleware/comm"
+	"kpt.xdmy/middleware/jwt"
+
+	//	"kpt.xdmy/middleware/permission"
+	"net/http"
+	"strings"
+
+	swaggerFiles "github.com/swaggo/files"
+	ginSwagger "github.com/swaggo/gin-swagger"
+
+	// "github.com/swaggo/gin-swagger/swaggerFiles"
+
+	"kpt.xdmy/apiserver/routers/api"
+	"kpt.xdmy/pkg/setting"
+)
+
+func InitRouter() *gin.Engine {
+
+	r := gin.New()
+
+	r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
+		// 你的自定义格式
+		return fmt.Sprintf("   %+v \n",
+			param.Keys,
+		)
+	}))
+	r.Use(gin.Logger()) // 日志
+	// r.Use(gzip.Gzip(gzip.DefaultCompression))
+	r.Use(Cors()) // 跨域请求rolemenus
+	r.Use(gin.Recovery())
+	gin.SetMode(setting.ServerSetting.RunMode)
+	r.MaxMultipartMemory = 1
+
+	r.Static("/static", setting.CurrentPath+"/dist/static")               // 添加资源路径
+	r.Static("/datas", setting.CurrentPath+"/dist/datas")                 // 添加资源路径
+	r.StaticFile("/", setting.CurrentPath+"/dist/index.html")             //前端接口
+	r.StaticFile("/favicon.ico", setting.CurrentPath+"/dist/favicon.ico") //前端接口
+	r.StaticFile("/myMap.json", setting.CurrentPath+"/data/myMap.json")   //前端接口
+	r.Static("/file", setting.CurrentPath+"/uploads/file")
+	r.Static("/uploads", setting.CurrentPath+"/uploads")
+	r.POST("/auth", api.Auth) // 获取登录token
+
+	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) // API 注释
+
+	if setting.CommSetting.PortName != "" {
+		r.GET("/comm/:id/:x/:y/", comm.ProcessHttp)
+		r.GET("/cps/:id/:limit", comm.ProcessHttpCPS)
+		r.POST("/comm/:id/:x/:y/", comm.ProcessHttp)
+		r.POST("/cps/:id/:limit", comm.ProcessHttpCPS)
+	}
+	eqm := r.Group("/manage/api")
+	eqm.POST("/login", api.Auth)
+
+	apiV1 := r.Group("/authdata")
+
+	apiV1.Use(jwt.JWT()) // token 验证
+
+	{
+
+		apiV1.POST("sap/transfer/send", ManualTransfer)
+		apiV1.POST("part/eas/batch", EasBatch)
+		apiV1.POST("/sap/proof/off/list", ProofOffList)
+		apiV1.POST("/sap/proof/off", ProofOff)
+		apiV1.POST("/sap/proof/detail", ProofList)
+		apiV1.GET("/mcs/accounts", McsAccounts)
+		apiV1.POST("/mcs/record", McsControl)
+		apiV1.POST("/rolemenus", api.GetRecuDataByName)
+		apiV1.GET("/userinfo", api.GetUserinfo)
+		apiV1.POST("/logout", api.UserLogout)
+		apiV1.POST("/GetRecuDataByName", api.GetRecuDataByName) ////
+		apiV1.POST("/GetDataByName", api.GetDataByName)
+		apiV1.POST("/GetDataByNames", api.GetDataByNames)
+		apiV1.POST("/PostDataByName", api.PostDataByName)
+		apiV1.POST("/PostThirdPartyData", api.PostThirdPartyData)
+		apiV1.POST("/PostDataByNames", api.PostDataByNames)
+		apiV1.POST("/UpdateDataRelation", api.UpdateDataRelation) //log.error
+		apiV1.POST("/GetDataByNameForm", api.GetDataByNameForm)
+		apiV1.POST("/PostDataByNameForm", api.PostDataByNameForm)
+		apiV1.POST("/GetUpkeepPlan", api.GetUpkeepPlan)
+		apiV1.POST("/GetReportform", api.GetReportform)
+		apiV1.POST("/GetAccount", api.GetAccount)
+		apiV1.POST("/ExecDataByConfig", api.ExecDataByConfig)
+		apiV1.POST("/ImportExcel", api.ImportExcel)
+		apiV1.POST("/upload/:id/:name", api.UploadFile)
+		apiV1.POST("/uploads", api.UploadFiles)
+		apiV1.POST("/uploaderimage", api.UploaderImage)
+		apiV1.POST("/removeimage", api.RemovePicByName)
+		apiV1.GET("/getthumbnailimage/:filename", api.GetThumbnailImage)
+		apiV1.POST("/getoriginimage/:filename", api.GetOriginImage)
+		apiV1.GET("/getfileraw/:filename", api.GetFileRaw)
+		apiV1.GET("/downloadfile/:filename", api.DownloadFile)
+		apiV1.POST("/downloadmailreport", api.DownloadMailReport)
+		apiV1.POST("/removefile/:id", api.RemoveFileByName)
+
+		apiV1.POST("/testdata", api.TestData)
+		apiV1.POST("/Testpartitions", api.Testpartitions)
+		// eas 对接
+		apiV1.POST("/EasSync", api.EasSync)
+	}
+	if setting.ServerSetting.NoAuth > 0 {
+		apiV2 := r.Group("/data") // restful  接口 tablename 是 表名字
+		{
+			apiV2.POST("sap/transfer/send", ManualTransfer)
+			apiV2.POST("/getdata", api.GetData)
+
+			apiV2.POST("/GetDataByName", api.GetDataByName)
+			apiV2.POST("/GetDataByNames", api.GetDataByNames)
+			apiV2.POST("/PostDataByName", api.PostDataByName)
+			apiV2.POST("/PostDataByNames", api.PostDataByNames)
+
+			apiV2.POST("/ExecDataByConfig", api.ExecDataByConfig)
+
+			apiV2.POST("/GetDataByNameForm", api.GetDataByNameForm)
+			apiV2.POST("/PostDataByNameForm", api.PostDataByNameForm)
+
+			apiV2.POST("/ImportExcel", api.ImportExcel)
+			//调用资产标准管理
+			apiV2.POST("/Equipment", api.Equipment)
+			apiV2.POST("/PastureDepartment", api.PastureDepartment)
+			//插入和修改标准管理
+			apiV2.POST("/updateAndInster", api.UpdateAndInsert)
+			// 标准库存管理
+			apiV2.POST("/StandardPart", api.StandardPart)
+			apiV2.POST("/upload", api.UploadFile)
+			apiV2.POST("/uploads", api.UploadFiles)
+			apiV2.POST("/uploaderimage", api.UploaderImage)
+			apiV2.POST("/removeimage", api.RemovePicByName)
+			apiV2.GET("/getthumbnailimage/:filename", api.GetThumbnailImage)
+			apiV2.GET("/getoriginimage/:filename", api.GetOriginImage)
+			apiV2.GET("/getfileraw/:filename", api.GetFileRaw)
+			apiV2.GET("/downloadfile/:filename", api.DownloadFile)
+			apiV2.POST("/removefile", api.RemoveFileByName)
+
+			apiV2.POST("/testdata", api.TestData)
+
+			//apiV2.POST("/DingShi",api.DingShi)
+			//apiV2.POST("/Ceshi",api.Ceshi)
+		}
+	}
+	r.POST("/getopenid/:code", api.GetOpenID)
+	apiV3 := r.Group("/thi") // restful  接口 tablename 是 表名字
+	{
+		apiV3.POST("/GetDataByName", api.GetDataByName)
+		apiV3.POST("/PostDataByName", api.PostDataByName)
+	}
+
+	apiV4 := r.Group("/openapi")
+	//apiV4.Use(jwt.JWT())
+	{
+		apiV4.POST("/GetDataByName", api.GetDataByNameOPEN)
+		apiV4.POST("/PostDataByName", api.PostDataByNameOPEN)
+	}
+
+	return r
+}
+
+// 跨域
+func Cors() gin.HandlerFunc {
+	return func(c *gin.Context) {
+		method := c.Request.Method               //请求方法
+		origin := c.Request.Header.Get("Origin") //请求头部
+		var headerKeys []string                  // 声明请求头keys
+		for k := range c.Request.Header {
+			headerKeys = append(headerKeys, k)
+		}
+		headerStr := strings.Join(headerKeys, ", ")
+		if headerStr != "" {
+			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
+		} else {
+			headerStr = "access-control-allow-origin, access-control-allow-headers"
+		}
+		if origin != "" {
+			c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
+			c.Header("Access-Control-Allow-Origin", "*")                                        // 这是允许访问所有域
+			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE") //服务器支持的所有跨域请求的方法,为了避免浏览次请求的多次'预检'请求
+			//  header的类型
+			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, id,  Token, name, optname, thumbnail, session, X_Requested_With, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
+			//              允许跨域设置                                                                                                      可以返回其他子段
+			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, FooBar") // 跨域关键设置 让浏览器可以解析
+			c.Header("Access-Control-Max-Age", "172800")                                                                                                                                                                  // 缓存请求信息 单位为秒
+			c.Header("Access-Control-Allow-Credentials", "false")                                                                                                                                                         //  跨域请求是否需要带cookie信息 默认设置为true
+			c.Set("content-type", "application/json")                                                                                                                                                                     // 设置返回格式是json
+		}
+
+		//放行所有OPTIONS方法
+		if method == "OPTIONS" {
+			c.JSON(http.StatusOK, "Options Request!")
+		}
+		// 处理请求
+		c.Next() //  处理请求
+	}
+}

+ 40 - 0
apiserver/routers/sap.go

@@ -0,0 +1,40 @@
+package routers
+
+import (
+	"github.com/gin-gonic/gin"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/service"
+)
+
+func ProofList(c *gin.Context) {
+	p := new(model.ProofReq)
+	if !Bind(c, p) {
+		return
+	}
+	rp := service.ProofList(p)
+	c.JSON(200, &rp)
+}
+
+func ProofOff(c *gin.Context) {
+	p := new(model.ProofReq)
+	if !Bind(c, p) {
+		return
+	}
+	rp := svc.ProofOff(p)
+	c.JSON(200, &rp)
+}
+
+func ProofOffList(c *gin.Context) {
+	p := new(model.ProofReq)
+	if !Bind(c, p) {
+		return
+	}
+	rp := service.ProofList(p)
+	c.JSON(rp.Code, &rp)
+}
+
+func ManualTransfer(c *gin.Context) {
+	code := c.PostForm("code")
+	count, e := service.ManualTransfer(code)
+	c.JSON(200, map[string]interface{}{"count": count, "error": e})
+}

+ 47 - 0
apiserver/routers/server.go

@@ -0,0 +1,47 @@
+package routers
+
+import (
+	"github.com/gin-gonic/gin"
+
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/apiserver/service"
+)
+
+var (
+	svc *service.Service
+)
+
+func Init(s *service.Service) {
+	svc = s
+}
+func eJSON(c *gin.Context, rp *http.Response, e error) {
+	if rp == nil {
+		rp = &http.Response{}
+	}
+	if e != nil {
+		rp.Message = e.Error()
+		rp.Success = false
+		if rp.Code == 0 {
+			rp.Code = 400
+		}
+	}
+	if e == nil {
+		rp.Success = true
+		rp.Code = 200
+	}
+	c.JSON(rp.Code, &rp)
+	return
+}
+
+func Bind(c *gin.Context, req model.Request) bool {
+	if err := c.ShouldBind(req); err != nil {
+		rp := &http.Response{
+			Code:    500,
+			Message: err.Error(),
+		}
+		eJSON(c, rp, nil)
+		return false
+	}
+	return true
+}

二進制
apiserver/service/.DS_Store


+ 104 - 0
apiserver/service/apisql_service/apisql_service.go

@@ -0,0 +1,104 @@
+package apisql_service
+
+// type Apisql struct {
+// 	ID         int
+// 	Sqlstr     string
+// 	Sqlname    string
+// 	Returetype string
+// 	Method     string
+// 	CreatedBy  string
+// 	ModifiedBy string
+
+// 	PageNum  int
+// 	PageSize int
+// }
+
+// func (a *Apisql) Add() (id int, err error) {
+// 	data := map[string]interface{}{
+// 		"Sqlstr":     a.Sqlstr,
+// 		"Sqlname":    a.Sqlname,
+// 		"Returetype": a.Returetype,
+// 		"Method":     a.Method,
+// 	}
+// 	Sqlname, _ := model.CheckSqlname(a.Sqlname)
+
+// 	if Sqlname {
+// 		return 0, errors.New("名字重复,请更改!")
+// 	}
+
+// 	if id, err := model.AddApisql(data); err == nil {
+// 		return id, err
+// 	} else {
+// 		return 0, err
+// 	}
+// }
+
+// func (a *Apisql) Edit() error {
+// 	data := map[string]interface{}{
+// 		"Sqlstr":     a.Sqlstr,
+// 		"Sqlname":    a.Sqlname,
+// 		"Returetype": a.Returetype,
+// 		"Method":     a.Method,
+// 	}
+
+// 	Sqlname, _ := model.CheckSqlname(a.Sqlname)
+
+// 	if Sqlname {
+// 		return errors.New("名字重复,请更改!")
+// 	}
+// 	err := model.EditApisql(a.ID, data)
+// 	if err != nil {
+// 		return err
+// 	}
+
+// 	return nil
+// }
+
+// func (a *Apisql) GetByName() (*model.Apisql, error) {
+// 	apisql, err := model.GetApisqlByName(a.Sqlname)
+// 	if err != nil {
+// 		return nil, err
+// 	}
+// 	return apisql, nil
+// }
+
+// func (a *Apisql) GetAll() ([]*model.Apisql, error) {
+// 	if a.Sqlname != "" {
+// 		maps := make(map[string]interface{})
+// 		maps["deleted_on"] = 0
+// 		maps["sqlname"] = a.Sqlname
+// 		apisql, err := model.GetApisqls(a.PageNum, a.PageSize, maps)
+// 		if err != nil {
+// 			return nil, err
+// 		}
+// 		return apisql, nil
+// 	} else {
+// 		apisql, err := model.GetApisqls(a.PageNum, a.PageSize, a.getMaps())
+// 		if err != nil {
+// 			return nil, err
+// 		}
+// 		return apisql, nil
+// 	}
+// }
+
+// func (a *Apisql) Delete() error {
+// 	err := model.DeleteApisqlByName(a.Sqlname)
+// 	if err != nil {
+// 		return err
+// 	}
+// 	return nil
+// }
+
+// func (a *Apisql) ExistByID() (bool, error) {
+// 	return model.ExistApisqlByID(a.ID)
+// }
+
+// func (a *Apisql) Count() (int, error) {
+// 	return model.GetApisqlTotal(a.getMaps())
+// }
+
+// func (a *Apisql) getMaps() map[string]interface{} {
+// 	maps := make(map[string]interface{})
+// 	maps["deleted_on"] = 0
+// 	return maps
+// }

+ 130 - 0
apiserver/service/asset.go

@@ -0,0 +1,130 @@
+package service
+
+import (
+	"fmt"
+	"time"
+
+	"github.com/k0kubun/pp/v3"
+	"github.com/pkg/errors"
+
+	_ "github.com/go-sql-driver/mysql"
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+)
+
+var assetChan chan error
+
+func (s *Service) SapAsset(t time.Time, code string) {
+	assetChan = make(chan error, 10)
+	r := new(http.AssetReq)
+	rp := new(http.AssetResp)
+	var e error
+
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "FI004"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/EAM/FI004/QueryAsset"
+
+	if t.IsZero() {
+		t = time.Now()
+	}
+	r.Data.BudatB = t.Format("20060102")
+	r.Data.BudatE = t.Format("20060102")
+	r.Data.CompanyCode = []http.Company{
+		// {Code: "9099"}, {Code: "1006"}
+		{Code: "1002"},
+	}
+	if code != "" {
+		r.Data.Codes = []http.TANLN1{{Code: code}}
+	}
+	if e = s.SyncSap(r, rp); e == nil {
+		if rp.Dest.Status == "S" {
+			log.Infof("sap  asset  success sum=%d", len(rp.Data.Master))
+		} else {
+			log.Infof("sap asset fail", rp.Dest.MessText)
+			pp.Print(r)
+		}
+	} else {
+		log.Error(e)
+	}
+	var update error
+	var count int
+	for _, v := range rp.Data.Master {
+		update = nil
+		go updateEQ(&v)
+		update = <-assetChan
+		if update != nil {
+			log.Error(update)
+			count++
+			l := model.SapDetailLog{Name: "asset", Code: fmt.Sprintf("%s-%s", v.AssetCode, v.SonCode), ErrorText: update.Error()}
+			if e := s.d.DB.Create(&l); e != nil {
+				log.Errorf("add sapdetail log: %v", e)
+			}
+		}
+	}
+	if e != nil {
+		log.Error(e)
+	} else if update != nil {
+		e = errors.Errorf("asset update fail sum:%d", count)
+	} else {
+		log.Infof("asset update success sum:%d", len(rp.Data.Master)-count)
+	}
+	s.AddSapLog(r, e)
+	return
+}
+func updateEQ(p *http.Asset) {
+	eq := new(model.Equipment)
+	pa := new(model.Pasture)
+	pv := new(model.Provider)
+	if e := s.d.DB.First(pa, model.Pasture{CompanyCode: p.CompanyCode}).Error; e != nil {
+		assetChan <- errors.Wrapf(e, "pasture companycode:%s", p.CompanyCode)
+	}
+	if e := s.d.DB.First(pa, model.Provider{ProviderNumber: p.Supplier}).Error; e != nil {
+		assetChan <- errors.Wrapf(e, "Provider ProviderNumber:%s", p.Supplier)
+	}
+	if len(p.Udate) == 8 {
+		p.Udate = p.Udate[:4] + "-" + p.Udate[4:6] + "-" + p.Udate[6:]
+	}
+	if len(p.Utime) == 6 {
+		p.Utime = p.Utime[:2] + ":" + p.Utime[2:4] + ":" + p.Utime[4:]
+	}
+	if p.Utime != "" {
+		p.Udate = p.Udate + " " + p.Utime
+	}
+	if t, e := time.Parse("2006-01-02 15:04:05", p.Udate); e != nil {
+		assetChan <- errors.Errorf("util ParseDateAndTime  : %s, %s", p.Udate)
+	} else {
+		eq.ModifyTime = t
+	}
+
+	eq.PastureId = pa.ID
+	eq.SHStatus = 1
+	eq.Status = 17
+	eq.EqName = p.Name
+	eq.AssetCode = p.AssetCode
+	eq.FinanceCode = p.AssetCode
+	eq.SonCode = p.SonCode
+	eq.EqCode = fmt.Sprintf("%s-%s", p.AssetCode, p.SonCode)
+	eq.EqClassName = p.Type
+	eq.Specification = p.Model
+	eq.EntranceDate = p.BuyDate
+	eq.Yuanzhi = p.BuyValue
+	eq.CompanyCode = p.CompanyCode
+	eq.Quantity = p.Quantity
+	eq.CostCenter = p.CostCenter
+	eq.Unit = p.Unit
+	eq.ProfitCenter = p.ProfitCenter
+	eq.EqCode = p.AssetCode
+	eq.ProId = pv.ID
+	if p.Dflag == "" && p.TransferFlag != "X" {
+		eq.Enable = 1
+	}
+	// pp.Print(eq)
+
+	if e := s.d.DB.Where(model.Equipment{EqCode: eq.EqCode}).Assign(eq).FirstOrCreate(&eq).Error; e != nil {
+		assetChan <- errors.Wrapf(e, "equipment update : %s, %s,%s,%s", p.AssetCode, p.SonCode, p.Name, p.CompanyCode)
+	} else {
+		log.Infof("equipment update sucess :%s, %s,%s,%s", p.AssetCode, p.SonCode, p.Name, p.CompanyCode)
+		assetChan <- nil
+	}
+}

+ 332 - 0
apiserver/service/charge_off.go

@@ -0,0 +1,332 @@
+package service
+
+import (
+	"fmt"
+
+	_ "github.com/go-sql-driver/mysql"
+	"github.com/k0kubun/pp/v3"
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/util"
+)
+
+func (s *Service) ProofOff(p *model.ProofReq) (hrp *http.Response) {
+	r := new(http.ChargeOffReq)
+	rp := new(http.SapResp)
+	hrp = new(http.Response)
+	hrp.Code = 200
+	hrp.Msg = "fail"
+
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "MM015"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM015/CancelMblnr"
+
+	r.Data.ProofCode = p.ProofCode
+	r.Data.ProofYear = p.ProofYear
+	r.Data.ChargeDate = p.ChargeDate
+	r.Data.OrderNumber = p.OrderNumber
+	r.Data.HasTicket = util.ZeroStr(p.HasTicket == 1, "X")
+	log.Infof("proofcode: %s", r.Data.ProofCode)
+	sl := r.Data.RowsNumber
+	for i := range p.RowsNumber {
+		sl = append(sl, http.ChargeOffDetail{RowNumber: p.RowsNumber[i]})
+	}
+	r.Data.RowsNumber = sl
+	e := s.SyncSap(r, rp)
+	pp.Print(r)
+	if e == nil {
+		if rp.Data.Status == "S" {
+			hrp.Message = fmt.Sprintf("sap物料冲销成功:%d %s %s", p.NumberType, rp.Data.ProofNumber, rp.Data.EqNumber)
+			log.Info(hrp.Message)
+		} else {
+			hrp.Message = fmt.Sprintf("sap凭证冲销失败:%s", rp.Dest.MessText)
+			log.Infoln(hrp.Message, r, p)
+			return
+		}
+	} else {
+		hrp.Message = fmt.Sprintf("sap冲销接口报错:error:%s", e)
+		log.Infoln(hrp.Message, r, p)
+		return
+	}
+
+	hrp.Msg = "ok"
+	e = UpdateProof(p)
+	if e != nil {
+		hrp.Message += fmt.Sprintf("%s . bigid = %d ,rows=%v", e.Error(), p.OrderNumberId, p.RowsNumber)
+	}
+	return
+}
+
+func UpdateProof(p *model.ProofReq) (e error) {
+	var tname string
+	switch p.NumberType {
+	case 1: // 入库
+		tname = "partlaid"
+	case 2: // 退货
+
+		tname = "PartRefund"
+	case 3: // 出库
+		tname = "PartUse"
+	case 4: // 退库
+		tname = "Partquit"
+	}
+	if e = s.d.DB.Table(tname).Where("bigid=? and rownumber  in (?)", p.OrderNumberId, p.RowsNumber).Update("dflag", 1).Error; e != nil {
+		log.Errorln(e, p.OrderNumberId, p.RowsNumber)
+	}
+	return e
+}
+
+// 查询 单据 对应备件
+func ProofList(p *model.ProofReq) (hrp *http.Response) {
+	switch p.NumberType {
+	case 1: // 入库
+		return s.laidProofList(p)
+	case 2: // 退货
+		return s.returnProofList(p)
+	case 3: // 出库
+		return s.useProofList(p)
+	case 4: // 退库
+		return s.quitProofList(p)
+	}
+	return
+}
+func (s *Service) laidProofList(p *model.ProofReq) (hrp *http.Response) {
+	bp := new(model.BigPartLaid)
+	proofs := make([]model.ProofPart, 0)
+	var e error
+	hrp = new(http.Response)
+	hrp.Code = 200
+	hrp.Msg = "fail"
+	if e = s.d.DB.First(bp, model.BigPartLaid{LaidCode: p.OrderNumber}).Error; e != nil {
+		hrp.Message = fmt.Sprintf("%s ,error=%v,", p.OrderNumber, e)
+		return
+	}
+	p.OrderNumberId = bp.ID
+	p.ProofCode = bp.ProofCode
+	p.ChargeDate = bp.CreatDate.Format("2006-01-02")
+	p.ProofYear = bp.CreatDate.Format("2006")
+
+	parts := make([]model.PartLaid, 0)
+	if e = s.d.DB.Order("id asc ").Find(&parts, model.PartLaid{BigID: bp.ID}).Error; e != nil || len(parts) == 0 {
+		hrp.Message = fmt.Sprintf("入库单明细查询报错或结果为空:bigid=%v error=%v,", bp.ID, e)
+		hrp.Msg = "fail"
+		return
+	}
+	for i, v := range parts {
+		mp := new(model.ProofPart)
+		br := new(model.Brand)
+		w := new(model.Warehouse)
+		pv := new(model.Provider)
+		if e := s.d.DB.First(&pv, model.Provider{ID: v.ProviderID}).Error; e != nil {
+			log.Errorln(v.ProviderID, e)
+			continue
+		}
+		if e := s.d.DB.First(&br, model.Brand{ID: v.BrandID}).Error; e != nil {
+			log.Errorln(e, v.BrandID)
+			continue
+		}
+		if e := s.d.DB.First(&w, model.Warehouse{ID: v.LocationID}).Error; e != nil {
+			log.Errorln(v.LocationID, e)
+			continue
+		}
+		mp.RowNumber = i + 1
+		mp.PartCode = v.PartCode
+		mp.PartName = v.PartName
+		mp.Specification = v.Specification
+		mp.ChangeCount = v.StorageAmount
+		mp.UnitPrice = v.Price
+		mp.TotalPrice = v.SumPrice
+		mp.PartBrand = br.BrandName
+		mp.Supplier = pv.ProviderName
+		mp.Warehouse = w.WarehoseCode
+		if v.Dflag == 0 {
+			proofs = append(proofs, *mp)
+		}
+	}
+	p.ProofPart = proofs
+	hrp.Msg = "ok"
+	hrp.Data = p
+	hrp.Message = fmt.Sprintf("success  :type = %v OrderNumber = %s", p.NumberType, p.OrderNumber)
+	return
+}
+
+func (s *Service) returnProofList(p *model.ProofReq) (hrp *http.Response) {
+	hrp = new(http.Response)
+	bp := new(model.BigPartRefund)
+	proofs := make([]model.ProofPart, 0)
+	hrp.Code = 200
+	var e error
+
+	if e = s.d.DB.First(bp, model.BigPartRefund{UseForm: p.OrderNumber}).Error; e != nil {
+		hrp.Message = fmt.Sprintf("bigpartrefund : %d,%s", p.NumberType, p.OrderNumber)
+		hrp.Msg = "fail"
+		return
+	}
+	p.OrderNumberId = bp.ID
+	p.ProofCode = bp.ProofCode
+	p.ChargeDate = bp.CreateTime.Format("2006-01-02")
+	p.ProofYear = bp.CreateTime.Format("2006")
+
+	funds := []model.PartRefund{}
+	if e = s.d.DB.Find(&funds, model.PartRefund{BigID: bp.ID}).Error; e != nil || len(funds) == 0 {
+		hrp.Message = fmt.Sprintf("PartRefund  query error  . bigid=%v error=%v,", bp.ID, e)
+		hrp.Msg = "fail"
+		return
+	}
+	for i, v := range funds {
+		mp := new(model.ProofPart)
+		pv := new(model.Provider)
+		if e := s.d.DB.First(&pv, model.Provider{ID: bp.ProviderID}).Error; e != nil {
+			log.Errorln(bp.ProviderID, e)
+			continue
+		}
+
+		mp.Supplier = pv.ProviderName
+		mp.RowNumber = i
+		mp.PartBrand = v.Brand
+		mp.Warehouse = v.Location
+		mp.PartCode = v.PartCode
+		mp.PartName = v.PartName
+		mp.Specification = v.Specification
+		mp.ChangeCount = v.RefundNumber
+		mp.UnitPrice = v.Price
+		mp.TotalPrice = v.SumPrice
+		proofs = append(proofs, *mp)
+	}
+	p.ProofPart = proofs
+
+	hrp.Msg = "ok"
+	hrp.Data = p
+	hrp.Message = fmt.Sprintf("success  :type = %v OrderNumber = %s", p.NumberType, p.OrderNumber)
+	return
+}
+
+// 查询 单据 对应备件
+func (s *Service) useProofList(p *model.ProofReq) (hrp *http.Response) {
+	hrp = new(http.Response)
+	bp := new(model.BigPartUse)
+	proofs := make([]model.ProofPart, 0)
+
+	hrp.Code = 200
+	hrp.Msg = "fail"
+	var e error
+
+	if e = s.d.DB.First(bp, model.BigPartUse{UseForm: p.OrderNumber}).Error; e != nil {
+		log.Error(e)
+		hrp.Message = fmt.Sprintf("bigpartuse useform=%s", p.OrderNumber)
+		return
+	}
+
+	p.OrderNumberId = bp.ID
+	p.ProofCode = bp.ProofCode
+	p.ChargeDate = bp.ReceiveTime.Format("2006-01-02")
+	p.ProofYear = bp.ReceiveTime.Format("2006")
+	uses := make([]model.PartUse, 0)
+	if e = s.d.DB.Find(&uses, model.PartUse{BigID: bp.ID}).Error; e != nil || len(uses) == 0 {
+		log.Error(e)
+		hrp.Message = fmt.Sprintf("PartUse bigid = %v ", bp.ID)
+		return
+	}
+	for i, v := range uses {
+		mp := new(model.ProofPart)
+		br := new(model.Brand)
+		w := new(model.Warehouse)
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Error(e)
+			hrp.Message = fmt.Sprintf("contract id =%d", v.ContractID)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Error(e)
+			hrp.Message = fmt.Sprintf("bigcontract id =%d", v.BigID)
+			return
+		}
+		if e := s.d.DB.First(&br, model.Brand{ID: v.BrandID}).Error; e != nil {
+			log.Error(e)
+			hrp.Message = fmt.Sprintf("brand id =%d", v.BrandID)
+			return
+		}
+		if e := s.d.DB.First(&w, model.Warehouse{ID: v.LocationID}).Error; e != nil {
+			log.Errorln(v.LocationID, e)
+			return
+		}
+		mp.PartBrand = br.BrandName
+		mp.Warehouse = w.WarehoseCode
+		mp.Supplier = bc.ProviderName
+		mp.RowNumber = i + 1
+		mp.PartCode = v.PartCode
+		mp.PartName = v.PartName
+		mp.Specification = v.Specification
+		mp.ChangeCount = v.CheckoutNumber
+		mp.UnitPrice = v.Price
+		mp.TotalPrice = v.SumPrice
+		proofs = append(proofs, *mp)
+	}
+	p.ProofPart = proofs
+	hrp.Msg = "ok"
+	hrp.Data = p
+	hrp.Message = fmt.Sprintf("success  :type = %v OrderNumber = %s", p.NumberType, p.OrderNumber)
+	return
+}
+
+// 查询 单据 对应备件
+func (s *Service) quitProofList(p *model.ProofReq) (hrp *http.Response) {
+	hrp = new(http.Response)
+	bp := new(model.BigPartquit)
+	proofs := make([]model.ProofPart, 0)
+	hrp.Code = 200
+	var e error
+
+	if e = s.d.DB.First(bp, model.BigPartquit{UseForm: p.OrderNumber}).Error; e != nil {
+		log.Error(e)
+		hrp.Message = fmt.Sprintf("bigpartquit %d,%s", p.NumberType, p.OrderNumber)
+		hrp.Msg = "fail"
+		return
+	}
+	p.OrderNumberId = bp.ID
+	p.ProofCode = bp.ProofCode
+	p.ChargeDate = bp.QuitDate.Format("2006-01-02")
+	p.ProofYear = bp.QuitDate.Format("2006")
+	parts := make([]model.Partquit, 0)
+	if e = s.d.DB.Find(&parts, model.Partquit{BigID: bp.ID}).Error; e != nil || len(parts) == 0 {
+		hrp.Message = fmt.Sprintf("partquit  bigid = %d ", bp.ID)
+		hrp.Msg = "fail"
+		return
+	}
+	for i, v := range parts {
+		mp := new(model.ProofPart)
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Error(e)
+			hrp.Message = fmt.Sprintf("contract id =%d", v.ContractID)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Error(e)
+			hrp.Message = fmt.Sprintf("bigcontract id =%d", v.BigID)
+			return
+		}
+
+		mp.Supplier = bc.ProviderName
+		mp.PartBrand = v.Brand
+		mp.Warehouse = v.Location
+		mp.RowNumber = i
+		mp.PartCode = v.PartCode
+		mp.PartName = v.PartName
+		mp.Specification = v.Specification
+		mp.ChangeCount = v.QuitNumber
+		mp.UnitPrice = v.Price
+		mp.TotalPrice = v.SumPrice
+		proofs = append(proofs, *mp)
+	}
+	p.ProofPart = proofs
+
+	hrp.Msg = "ok"
+	hrp.Data = p
+	hrp.Message = fmt.Sprintf("success  :type = %v OrderNumber = %s", p.NumberType, p.OrderNumber)
+	return
+}

+ 43 - 0
apiserver/service/eas.go

@@ -0,0 +1,43 @@
+package service
+
+import (
+	"fmt"
+	"strconv"
+
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/util"
+)
+
+func Eas() {
+	sid, err := util.EASWebServiceLogin("http://192.168.61.23:6888")
+	if err != nil {
+		panic(err)
+	}
+	fmt.Println(sid)
+}
+func (s *Service) EasBatch() {
+
+	// log.Infof("%v", setting.ServerSetting)
+
+	nch = make(chan error, 10)
+	p := make([]model.Parts, 0, 0)
+	if e := s.d.DB.Where("msg <>''").Find(&p, &model.Parts{Statue: 1, Issync: 0}).Error; e != nil {
+		panic(e)
+	}
+	for _, v := range p {
+		if v.Unit == "" {
+			continue
+		}
+		go GoEas(strconv.Itoa(v.ID))
+		if e := <-nch; e != nil {
+			log.Errorf("EasBatch() :%v", e)
+		}
+	}
+	
+}
+func GoEas(id string) {
+	e := util.EASBillSync(5, id, "1")
+	nch <- e
+}
+

+ 30 - 0
apiserver/service/job.go

@@ -0,0 +1,30 @@
+package service
+
+import (
+	"time"
+
+	"github.com/robfig/cron/v3"
+	log "github.com/sirupsen/logrus"
+)
+
+func SapJobInit() {
+	c := cron.New()
+	// 02:00
+	// if _, e := c.AddFunc("00 00 02 * * *", jobMaterial); e != nil {
+	// 	log.Error("jobMaterial", e)
+	// }
+	if _, e := c.AddFunc("30 0/1 6-23 * * ? ", jobTransfer); e != nil {
+		log.Error("transfer", e)
+	}
+	c.Start()
+
+}
+
+func jobMaterial() {
+	t := time.Now()
+	var code string
+	s.SapMaterial(t, code)
+}
+func jobTransfer() {
+	autoTransfer()
+}

+ 105 - 0
apiserver/service/material.go

@@ -0,0 +1,105 @@
+package service
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+
+	_ "github.com/go-sql-driver/mysql"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	// "kpt.xdmy/pkg/log"
+)
+
+var partChan chan error
+
+func (s *Service) SapMaterial(t time.Time, code string) {
+	partChan = make(chan error, 10)
+	r := new(http.MaterialReq)
+	rp := new(http.MaterialResp)
+	var e error
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "MM002"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM002/QueryMaterial/"
+
+	if t.IsZero() {
+		t = time.Now()
+	}
+	r.Data.BudatB = t.Format("20060102")
+	r.Data.BudatE = t.Format("20060102")
+	r.Data.BudatB = "20220920"
+	r.Data.BudatE = "20220922"
+
+	r.Data.Type = http.MTART{MTART: "XD08"}
+	// r.Data.Group = []http.MATKL{{MATKL: "14010101"}}
+	// r.Data.Group = []http.MATKL{{MATKL: "14"}}
+	if code != "" {
+		// r.Data.Codes = []http.MATNR{{Code: "14.01.06.02.000216"}}
+	}
+
+	if e = s.SyncSap(r, rp); e == nil {
+		if rp.Dest.Status == "S" {
+			log.Infof("sap material success:len=%d", len(rp.Data.Master))
+		} else {
+			e = errors.Errorf("sap material fail", rp.Dest.MessText)
+		}
+	} else {
+		e = errors.Wrapf(e, "sap material error")
+	}
+	var update error
+	var count int
+	for _, v := range rp.Data.Master {
+		update = nil
+		go s.UpdatePart(&v)
+		update = <-partChan
+		if update != nil {
+			log.Error(update)
+			count++
+			l := model.SapDetailLog{Name: "part", Code: v.Code, ErrorText: update.Error()}
+			if e := s.d.DB.Create(&l); e != nil {
+				log.Errorf("add sapdetail log: %v", e)
+			}
+		}
+	}
+	if e != nil {
+		log.Error(e)
+	} else if update != nil {
+		e = errors.Errorf("material update fail sum:%d", count)
+	} else {
+		log.Infof("material update success sum:%d", len(rp.Data.Master)-count)
+	}
+	s.AddSapLog(r, e)
+	return
+}
+
+func (s *Service) UpdatePart(p *http.MaterialDetail) {
+	part := new(model.Parts)
+
+	if len(p.ModifyTime) >= 8 {
+		p.ModifyTime = p.ModifyTime[:4] + "-" + p.ModifyTime[4:6] + "-" + p.ModifyTime[6:8]
+	} else {
+		partChan <- errors.New("ModifyTime is  invalid:" + p.ModifyTime)
+	}
+	if t, e := time.ParseInLocation("2006-01-02", p.ModifyTime, time.Local); e != nil {
+		partChan <- errors.Wrapf(e, "time:%s", p.ModifyTime)
+	} else {
+		part.ModifyTime = t
+	}
+	if p.Dflag == "" {
+		part.Enable = 1
+		part.Statue = 1
+	}
+	part.PartCode = p.Code
+	part.Note = p.Description
+	part.Category = p.Type
+	part.Unit = p.Unit
+	part.Name = p.Name
+	part.Specification = p.Model
+	if e := s.d.DB.Where(model.Parts{PartCode: p.Code}).Assign(*part).FirstOrCreate(part).Error; e != nil {
+		partChan <- errors.Wrapf(e, "code:%s", p.Code)
+	} else {
+		log.Infof("sap part update success:%s", p.Code)
+		partChan <- nil
+	}
+}

+ 190 - 0
apiserver/service/mcs.go

@@ -0,0 +1,190 @@
+package service
+
+import (
+	"time"
+
+	"github.com/gin-gonic/gin"
+	"github.com/pkg/errors"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/log"
+	"kpt.xdmy/pkg/util"
+)
+
+var McsChan = make(chan string, 0)
+
+// start  or stop mcs eq
+func (s *Service) McsPostHttp(mpd *model.McsPostDataReq) (res *http.Response, err error) {
+	url := "http://8.130.17.8:7711/api/postData"
+	req, e := s.http.NewRequest("POST", url, mpd)
+	if e != nil {
+		return nil, e
+	}
+
+	var r struct {
+		Code    int    `json:"error"`
+		Message string `json:"message"`
+	}
+	e = s.http.Do(req, &r)
+	if e != nil {
+		return nil, e
+	}
+	//add respone
+	res = &http.Response{
+		Message: r.Message,
+		Code:    r.Code,
+		Success: false,
+	}
+	if res.Code == 200 {
+		if mpd.Method == "startRecord" {
+			mv := &model.McsVideo{
+				EmpId:        mpd.Data.PeopleNo,
+				UpkeepId:     mpd.Data.WorkNo,
+				DeviceId:     mpd.Data.DevID,
+				NewCreatedAt: time.Now(),
+				EndRecord:    2,
+			}
+			go s.UpdateOrAddVideo(mv)
+		}
+		if mpd.Method == "stopRecord" {
+			mv := &model.McsVideo{
+				EmpId:    mpd.Data.PeopleNo,
+				UpkeepId: mpd.Data.WorkNo,
+				DeviceId: mpd.Data.DevID,
+			}
+			mv2 := &model.McsVideo{
+				UpkeepId:  mpd.Data.WorkNo,
+				EndRecord: 1,
+			}
+			go s.UpdateOrAddVideo(mv2)
+			go s.McsGetFiles(mv)
+		}
+	}
+
+	return
+}
+
+// param has value empid, deviceid   use  to query mcs server
+// use param upkeepid   to  query  video  from s.d.DB
+func (s *Service) McsGetFiles(mv *model.McsVideo) (err error) {
+	url := "https://www.51cow.cn:7715/api/GetRecordFileList"
+	st := time.Now().Local().AddDate(0, 0, -1).Format("2006-01-02")
+	et := time.Now().Local().AddDate(0, 0, 1).Format("2006-01-02")
+	sid := "7eea4610d4f1dcc572b7351f5a5fdef131571842484b03f05fa8e5a90486f227680272d2e47d7a98738b32473e0dffb348bd1b0273079c67d5ee3d90050d78c9"
+	mfr := &model.McsFilesRequest{
+		SessionId: sid,
+		Did:       mv.DeviceId,
+		Wno:       mv.UpkeepId,
+		St:        st,
+		Et:        et,
+		Ft:        "3",
+		Lt:        "-1",
+		Pagesize:  "10",
+	}
+	//query the video record file from s.d.DB
+	cont := &model.McsVideo{
+		UpkeepId: mv.UpkeepId,
+	}
+	mvs, e := s.QueryVideo(cont)
+	if e != nil {
+		return e
+	}
+	if len(mvs) == 0 {
+		return errors.New("no video start record")
+	}
+	ntime := mvs[0].NewCreatedAt
+	t := time.NewTicker(time.Second * 2)
+	defer t.Stop()
+	flag := false
+	for !flag {
+		select {
+		case <-t.C:
+			resp, e := s.http.NewRequest("GET", url+"?"+mfr.Encode(), nil)
+			if e != nil {
+				return e
+			}
+			mf := new(model.McsFilesResponse)
+			e = s.http.Do(resp, mf)
+			if e != nil {
+				return e
+			}
+			//get the last record file
+			f := LastMCsFile(mf)
+			if f == nil {
+				continue
+			}
+			// compare  the time
+			st, e := util.ParseDate(f.StartTime)
+			if e != nil {
+				log.Path("service McsGetFiles")
+				continue
+			}
+			if st.Sub(ntime) < 10*time.Second && st.Sub(ntime) >= 0 {
+				mv.CreatedAt = ntime
+				mv.Location = "https://www.51cow.cn:7715/files" + f.Path
+				e := s.UpdateOrAddVideo(mv)
+				if e != nil {
+					return e
+				}
+				flag = true
+				t.Stop()
+				<-McsChan
+			} else {
+				continue
+			}
+		}
+	}
+	return nil
+}
+
+// get the last record file from mcs server
+func LastMCsFile(mfr *model.McsFilesResponse) (pmf *model.McsFile) {
+	if len(mfr.Data) == 0 {
+		return
+	}
+	mf := mfr.Data[0]
+	for _, v := range mfr.Data {
+		if v.StartTime > mf.StartTime {
+			mf = v
+		}
+	}
+	return &mf
+}
+
+// param has value empid, upkeepid, deviceid,createdAt
+func (s *Service) UpdateOrAddVideo(m *model.McsVideo) (err error) {
+	//new  condition
+	cton := map[string]interface{}{
+		"upkeepId": m.UpkeepId,
+	}
+	rt := s.d.DB.Table("video").Where(cton).Updates(m)
+	if rt.Error != nil {
+		err = log.Error("UpdateOrAddVideo update ", rt.Error, m)
+		return
+	}
+	if rt.RowsAffected > 0 {
+		return
+	}
+	//add vedio
+	if err = s.d.DB.Table("video").Create(&m).Error; err != nil {
+		err = log.Error("UpdateOrAddVideo create ", err, m)
+	}
+	return
+}
+func (s *Service) QueryVideo(m *model.McsVideo) (res []model.McsVideo, err error) {
+	if err = s.d.DB.Table("video").Where(m).Find(&res).Error; err != nil {
+		err = log.Error("QueryVideo query ", err, m)
+	}
+	return
+}
+
+func (s *Service) mcsAccounts(c *gin.Context) {
+	ma := []model.McsAccount{
+		{
+			DeviceId: "apptest2",
+			UserID:   "PC",
+			Password: "mcs8",
+		},
+	}
+	c.JSON(200, ma)
+}

+ 145 - 0
apiserver/service/order.go

@@ -0,0 +1,145 @@
+package service
+
+import (
+	"fmt"
+	"strconv"
+	"time"
+
+	"github.com/k0kubun/pp/v3"
+
+	_ "github.com/go-sql-driver/mysql"
+
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/util"
+)
+
+// sap采购订单接口
+func (s *Service) PurchaseOrder(p interface{}) {
+	r := new(model.BigBuyDetailReq)
+	if e := util.Unmarshal(p, r); e != nil {
+		log.Errorf("purchaseorder param :%v ", e)
+		log.Info(p)
+		return
+	}
+	if r.ID == "" && r.Code == "" {
+		log.Error("buy order request param is empty")
+		return
+	}
+	bdetails := []model.BigBuyDetail{}
+	bpp := new(model.Bigpartpurchase)
+
+	if r.ID != "" {
+		pid, err := strconv.ParseInt(r.ID, 10, 32)
+		if err != nil {
+			log.Errorf("parseInt  purchase id  :%v", err)
+		}
+		id := int(pid)
+		if e := s.d.DB.First(bpp, model.Bigpartpurchase{ID: id}).Error; e != nil {
+			log.Error("Bigpartpurchase query error", e)
+			return
+		}
+		if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: bpp.OrderNumber}).Error; e != nil || len(bdetails) == 0 {
+			log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e)
+			return
+		}
+	} else if r.Code != "" {
+		if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: r.Code}).Error; e != nil || len(bdetails) == 0 {
+			log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e)
+			return
+		}
+	}
+	for _, v := range bdetails {
+		s.SapOrder(&v)
+	}
+}
+
+func (s *Service) SapOrder(p *model.BigBuyDetail) {
+	r := new(http.OrderReq)
+	rp := new(http.OrderResp)
+	parts := []model.BuyDetail{}
+	pa := new(model.Pasture)
+	pv := new(model.Provider)
+	// dp := new(model.Department)
+
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "MM007"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM007/PurchaseOrder"
+
+	if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil {
+		log.Errorf("pasture query :id=%d,%v", p.PastureID, e)
+		return
+	}
+	if e := s.d.DB.Where("amount>0").Find(&parts, model.BuyDetail{BigID: p.ID}).Error; e != nil || len(parts) == 0 {
+		log.Errorf("buydetail query :bigid=%d,%v", p.ID, e)
+		return
+	}
+	r.Data.IsCancle = ""
+	r.Data.CompanyCode = pa.CompanyCode
+	r.Data.SupplierCode = pv.ProviderNumber
+	r.Data.OrderDate = p.BuyerDate.Format("20060102")
+	r.Data.PayCondition = ""
+	r.Data.CurrencyCode = "CNY"
+	r.Data.ProofType = "ZNB4"
+	r.Data.EqSysCode = p.BuyeCode[4:]
+	// r.Data.Organization = pa.ParchaseOrganization
+	r.Data.Organization = pa.CompanyCode
+	r.Data.Group = "A02"
+
+	for i, v := range parts {
+		detail := http.OrderDetail{}
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Errorf("order detail error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Errorf("order detail error:%v", e)
+			return
+		}
+
+		detail.RowNumber = fmt.Sprintf("%d", i+1)
+		detail.Factory = pa.FactoryCode
+		detail.Quantity = fmt.Sprintf("%d", v.Amount)
+		detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
+		detail.TaxCode = "J0"
+		detail.Per = "1"
+		detail.NetPrice = c.Price
+		detail.Unit = c.Unit
+		detail.MaterialCode = c.PartCode
+		detail.IsOwn = util.ZeroStr(bc.IsZeroStock == 1, "K")
+
+		r.Data.Detail = append(r.Data.Detail, detail)
+
+		if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil {
+			log.Errorln(e, v.ID)
+		}
+	}
+
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Errorf("sap buy order error: %v", e)
+		p.SapStatus = 3
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber)
+			p.SapStatus = 1
+			p.SapNumber = rp.Data.SapNumber
+		} else {
+			log.Warnf("buy order fail :msg=%s,r=%v", rp.Data.MsgText, r)
+			p.SapStatus = 2
+			pp.Print(r)
+		}
+	}
+	if p.SapStatus == 1 {
+		if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigBuyDetail{SapStatus: p.SapStatus, SapNumber: p.SapNumber}).Error; e != nil {
+			log.Errorf("update big buy detail error: %v", e)
+		}
+	}
+}

+ 185 - 0
apiserver/service/part.go

@@ -0,0 +1,185 @@
+package service
+
+import (
+	"fmt"
+	"strconv"
+	"time"
+
+	"gorm.io/gorm"
+	"kpt.xdmy/pkg/util"
+
+	log "github.com/sirupsen/logrus"
+	"github.com/xuri/excelize/v2"
+)
+
+func PartBatch() (count int, e error) {
+	nch = make(chan error, 10)
+	r, e := s.d.DB.Raw(`select id FROM parts WHERE issync = 0 and statue = 1 `).Rows()
+	defer r.Close()
+	if e != nil {
+		fmt.Print(e)
+		return 0, e
+	}
+	var id string
+	for r.Next() {
+		r.Scan(&id)
+		easBillSync(id)
+		if e = <-nch; e != nil {
+			fmt.Print(e)
+		} else {
+			count++
+		}
+	}
+	return count, nil
+}
+func easBillSync(id string) {
+	e := util.EASBillSync(5, id, "1")
+	nch <- e
+}
+
+var parchan chan *gorm.DB
+
+func (s *Service) PartUpdate() {
+	parchan = make(chan *gorm.DB, 10)
+	// f, e := excelize.OpenFile("/Users/desire/Documents/partcode.xlsx")
+	f, e := excelize.OpenFile("partcode.xlsx")
+	if e != nil {
+		log.Error("excle open  :%d", e)
+	}
+	defer func() {
+		// Close the spreadsheet.
+		if err := f.Close(); err != nil {
+			fmt.Println(err)
+		}
+	}()
+	sheet := []string{"Sheet1", "Sheet2"}
+	// var s []string
+	for _, name := range sheet {
+
+		rows, err := f.GetRows(name)
+		if err != nil {
+			fmt.Println(err)
+			return
+		}
+		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
+		value := ""
+		for i, row := range rows {
+			if i == 0 {
+				value += fmt.Sprintf("('%s', '%s','%s',%s)", row[0], row[1], row[2], row[3])
+			} else {
+				value += fmt.Sprintf(",('%s', '%s','%s',%s)", row[0], row[1], row[2], row[3])
+			}
+		}
+		iusql := fmt.Sprintf(`insert  into  parts (partcode ,new_partcode,unit,issave) values %s
+	on DUPLICATE KEY UPDATE  new_partcode=values(new_partcode) ,unit=values(unit),issave=values(issave) `, value)
+
+		if r := s.d.DB.Exec(iusql); r.Error != nil {
+			fmt.Printf("insert part_Data: %v\n", r.Error)
+			return
+		} else {
+			fmt.Printf("insert part_Data success!:%d\n", r.RowsAffected)
+		}
+		fmt.Println(time.Now().Format("2006-01-02 15:04:05"))
+	}
+
+}
+
+func (s *Service) PartInsert() {
+	// f, e := excelize.OpenFile("/Users/desire/Downloads/part_insert.xlsx")
+	f, e := excelize.OpenFile("part_insert.xlsx")
+	if e != nil {
+		log.Error("excle open  :%d", e)
+	}
+	defer func() {
+		if err := f.Close(); err != nil {
+			fmt.Println(err)
+		}
+	}()
+	slist := f.GetSheetList()
+	log.Infof("%v", slist)
+	// sheet := "Sheet1"
+	rows, err := f.GetRows(slist[0])
+	if err != nil {
+		fmt.Println(err)
+		return
+	}
+	value := ""
+	for i, row := range rows {
+		// if i > 3550 {
+		// 	continue
+		// }
+		if i == 0 {
+			value += fmt.Sprintf("('%s', '%s','%s','%s')", row[0], row[1], row[2], row[3])
+		} else {
+			value += fmt.Sprintf(",('%s', '%s','%s','%s')", row[0], row[1], row[2], row[3])
+		}
+	}
+	iusql := fmt.Sprintf(`insert  into  parts (partcode ,name,specification,unit) values %s
+	on DUPLICATE KEY UPDATE  partcode=values(partcode) ,name=values(name),specification=values(specification),
+	unit=values(unit)`, value)
+
+	if r := s.d.DB.Exec(iusql); r.Error != nil {
+		fmt.Printf("insert parts: %v\n", r.Error)
+		return
+	} else {
+		fmt.Printf("insert parts success!:%d\n", r.RowsAffected)
+	}
+
+}
+func (s *Service) RepertoryUpdate() {
+	f, e := excelize.OpenFile("repertory.xlsx")
+	// f, e := excelize.OpenFile("/Users/desire/Documents/repertory.xlsx")
+	if e != nil {
+		log.Errorf("excle open  :%d", e)
+	}
+	defer func() {
+		if err := f.Close(); err != nil {
+			fmt.Println(err)
+		}
+	}()
+	rows, e := f.GetRows("SheetJS")
+	if e != nil {
+		fmt.Println(e)
+		return
+	}
+	sql := "call insertRepertory(?,?,?,?,?,?,?,?,?,?,?)"
+	var sum, count, suc int
+	for _, row := range rows[1:2] {
+		sum++
+		var e error
+		// var msg, msg2 string
+		// scan := new(sqlScan)
+		var res interface{}
+		var storage, price float64
+		if storage, e = strconv.ParseFloat(row[6], 64); e != nil {
+			log.Errorf("failed to parse storage:%s , e:%v", row[6], e)
+			continue
+		}
+		if price, e = strconv.ParseFloat(row[7], 64); e != nil {
+			log.Errorf("failed to parse price:%s , e:%v", row[7], e)
+			continue
+		}
+
+		if r := s.d.DB.Raw(sql, row[0], row[1], row[2], row[3], row[4], storage, price, row[7], row[8], row[9], "00611"); r.Error != nil {
+			log.Errorf("exec :%v", r.Error)
+		} else {
+			count++
+			// r.Row().Scan(&msg, &msg2)
+			r.Row().Scan(&res)
+			// r.Row().Scan(scan)
+			log.Infof("res:%s", res)
+			// if msg == "success" {
+			// 	suc++
+			// } else {
+			// 	log.Infoln(msg)
+			// }
+		}
+	}
+	log.Infoln(suc, count, sum)
+}
+
+type sqlScan struct {
+	msg        string
+	id         string
+	contractid string
+}

+ 439 - 0
apiserver/service/proof.go

@@ -0,0 +1,439 @@
+package service
+
+import (
+	"fmt"
+	"strconv"
+	"strings"
+	"time"
+
+	_ "github.com/go-sql-driver/mysql"
+	"github.com/k0kubun/pp/v3"
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+	"kpt.xdmy/pkg/util"
+)
+
+func (s *Service) LaidProof(p interface{}) {
+	pr := new(http.ProofPartReq)
+	r := new(http.ProofReq)
+	rp := new(http.ProofResp)
+	parts := []model.PartLaid{}
+	bp := new(model.BigPartLaid)
+	bbd := new(model.BigBuyDetail)
+	pa := new(model.Pasture)
+
+	if e := util.Unmarshal(p, pr); e != nil {
+		log.Error(e, p)
+		return
+	}
+	if e := s.d.DB.First(bp, model.BigPartLaid{LaidCode: pr.LaidCode}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.Find(&parts, model.PartLaid{BigID: bp.ID}).Error; e != nil || len(parts) == 0 {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(bbd, model.BigBuyDetail{BuyeCode: bp.PurchaseID}).Error; e != nil {
+		log.Error(e)
+
+	}
+	if e := s.d.DB.First(pa, model.Pasture{ID: bp.PastureID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+
+	proofDest(r)
+	r.Data.EqNumber = pr.LaidCode
+	r.Data.CreateTime = time.Now().Format("20060102")
+	if t, e := util.ParseDate(pr.StorageTime); e != nil {
+		log.Errorf("parse time error:err=%v,param=%v", e, pr.StorageTime)
+	} else {
+		r.Data.PostDate = t.Format("20060102")
+	}
+	for i, v := range parts {
+
+		sdetail := http.ProofDetail{MoveType: "101"}
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+		bd := new(model.BuyDetail)
+
+		w := new(model.Warehouse)
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Errorf("contract query error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Errorf("bigcontract query error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(bd, model.BuyDetail{BigID: bbd.ID, ContractID: v.ContractID}).Error; e != nil {
+			log.Error(e)
+			return
+		}
+
+		if e := s.d.DB.First(w, model.Warehouse{ID: v.LocationID}).Error; e != nil {
+			log.Error(e)
+			return
+		}
+
+		sdetail.RowNumber = fmt.Sprintf("%d", i+1)
+		sdetail.Quantity = fmt.Sprintf("%f", v.StorageAmount)
+		sdetail.Unit = c.Unit
+		sdetail.Code = c.PartCode
+		sdetail.SaveType = util.ZeroStr(bc.IsZeroStock == 1, "K")
+		sdetail.Factory = pa.FactoryCode
+		sdetail.Location = w.WarehoseCode
+		sdetail.OrderNumber = bbd.SapNumber
+		sdetail.OrderRowNum = fmt.Sprintf("%d", bd.RowNumber)
+		r.Data.Detail = append(r.Data.Detail, sdetail)
+	}
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Error(e)
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Printf("laid proof success:%s,%s", rp.Data.EqNumber, rp.Data.SapNumber)
+			if e := s.d.DB.Model(&model.BigPartLaid{}).Where("laidcode = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
+				log.Errorln(e)
+			}
+		} else {
+			log.Warnf("%s laid proof failed:causetext=%s", rp.Dest.MessText)
+			pp.Print(r)
+			// if b, e := json.MarshalIndent(r, "", " "); e != nil {
+			// 	log.Error("json.MarshalIndent error")
+			// } else {
+			// 	fmt.Println(string(b))
+			// }
+		}
+	}
+
+}
+
+func (s *Service) UseProof(p interface{}) {
+	pr := new(http.ProofPartReq)
+	r := new(http.ProofReq)
+	rp := new(http.ProofResp)
+	parts := []model.PartUse{}
+	bp := new(model.BigPartUse)
+	pa := new(model.Pasture)
+	dp := new(model.Department)
+
+	if e := util.Unmarshal(p, pr); e != nil {
+		log.Error(e)
+		return
+	}
+
+	if e := s.d.DB.First(bp, model.BigPartUse{UseForm: pr.UseForm}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.Find(&parts, model.PartUse{BigID: bp.ID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	// pp.Print(bp)
+	if e := s.d.DB.First(pa, model.Pasture{ID: bp.PastureID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(dp, model.Department{ID: bp.DepartmentID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	// pp.Println(bp, d)
+	proofDest(r)
+	r.Data.EqNumber = pr.UseForm
+	r.Data.CreateTime = time.Now().Format("20060102")
+	if t, e := util.ParseDate(pr.ReceiveTime); e != nil {
+		log.Error(e, pr.ReceiveTime)
+	} else {
+		r.Data.PostDate = t.Format("20060102")
+	}
+	for i, v := range parts {
+		bc := new(model.BigContract)
+		c := new(model.Contract)
+		w := new(model.Warehouse)
+		pv := new(model.Provider)
+		eq := new(model.Equipment)
+		storage := new(model.PartRepertory)
+		if v.ContractID < 0 {
+			if e := s.d.DB.First(storage, model.PartRepertory{ContractID: v.ContractID}).Error; e != nil {
+				log.Errorln(e, v.ContractID)
+				return
+			}
+			if e := s.d.DB.First(pv, model.Provider{ID: storage.ProviderID}).Error; e != nil {
+				log.Errorln(e, storage.ProviderID)
+				return
+			}
+
+		} else {
+
+			if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+				log.Errorf("contract query error:%v", e)
+				return
+			}
+			if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+				log.Errorf("bigcontract query error:%v", e)
+				return
+			}
+			if e := s.d.DB.First(pv, model.Provider{ID: bc.ProviderID}).Error; e != nil {
+				log.Errorln(e, bc.ProviderID)
+				return
+			}
+		}
+
+		if e := s.d.DB.First(w, model.Warehouse{ID: v.LocationID}).Error; e != nil {
+			log.Errorln(e, v.LocationID)
+			return
+		}
+		if e := s.d.DB.First(eq, model.Equipment{Id: v.EqID}).Error; e != nil {
+			log.Errorln(e, v.EqID)
+			return
+		}
+		sdetail := http.ProofDetail{}
+
+		// 报废出库
+		if pr.UseType == 5 {
+			sdetail.MoveType = "Z19"
+			if v.ContractID > 0 && bc.IsZeroStock != 0 {
+				log.Info("寄售不能报废=======")
+				return
+			}
+		}
+		// 领用出库、手动出库
+		if pr.UseType == 0 || pr.UseType == 1 {
+			sdetail.MoveType = "201"
+			sdetail.CostCenter = dp.CostCenterCode
+		}
+		sdetail.Factory = pa.FactoryCode
+		if pa.FactoryCode == "M005" && strings.Contains(dp.Name, "二期") {
+			sdetail.Factory = "M017"
+		}
+		sdetail.RowNumber = fmt.Sprintf("%d", i+1)
+		sdetail.Quantity = fmt.Sprintf("%f", v.CheckoutNumber)
+		// sdetail.Unit = c.Unit
+		sdetail.Unit = v.Unit
+		// sdetail.Code = c.PartCode
+		sdetail.Code = v.PartCode
+		sdetail.AssetCode = eq.FinanceCode
+		sdetail.Location = w.WarehoseCode
+		if v.ContractID > 0 && bc.IsZeroStock == 1 {
+			sdetail.SaveType = "K"
+		}
+
+		if sdetail.SaveType == "K" {
+			sdetail.Provider = pv.ProviderNumber
+		}
+		r.Data.Detail = append(r.Data.Detail, sdetail)
+	}
+	pp.Print(r)
+	log.Infof("bp.pastureId:%d,pa.name:%s,pa.companycode:%s", bp.PastureID, pa.Name, pa.CompanyCode)
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Errorf("laid proof error:%v", e)
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Printf("use proof  success:eqcode=%s,sapcode=%s", rp.Data.EqNumber, rp.Data.SapNumber)
+			if e := s.d.DB.Model(&model.BigPartUse{}).Where("useform = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
+				log.Errorln(e)
+			}
+		} else {
+			log.Warnf(" use proof :%s", rp.Dest.MessText)
+		}
+	}
+
+}
+
+// 退库
+func (s *Service) QuitProof(p interface{}) {
+	pr := new(http.ProofPartReq)
+	r := new(http.ProofReq)
+	rp := new(http.ProofResp)
+	parts := []model.Partquit{}
+	bp := new(model.BigPartquit)
+	pa := new(model.Pasture)
+	d := new(model.Department)
+
+	if e := util.Unmarshal(p, pr); e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(bp, model.BigPartquit{UseForm: pr.UseForm}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.Find(&parts, model.Partquit{BigID: bp.ID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(pa, model.Pasture{ID: bp.PastureID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(d, model.Department{ID: bp.DeptID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	proofDest(r)
+	r.Data.EqNumber = pr.UseForm
+	r.Data.CreateTime = time.Now().Format("20060102")
+	if t, e := util.ParseDate(pr.QuitDate); e != nil {
+		log.Error(e, pr.QuitDate)
+	} else {
+		r.Data.PostDate = t.Format("20060102")
+	}
+	for i, v := range parts {
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+		pv := new(model.Provider)
+		// w := new(model.Warehouse)
+
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Errorf("contract query error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Errorf("bigcontract query error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(pv, model.Provider{ID: bc.ProviderID}).Error; e != nil {
+			log.Errorln(e, bc.ProviderID)
+			return
+		}
+
+		sdetail := http.ProofDetail{MoveType: "202"}
+		sdetail.RowNumber = fmt.Sprintf("%d", i+1)
+		sdetail.Quantity = fmt.Sprintf("%f", v.QuitNumber)
+		sdetail.Unit = c.Unit
+		sdetail.Code = c.PartCode
+		sdetail.Factory = pa.FactoryCode
+		sdetail.CostCenter = d.CostCenterCode
+		sdetail.Location = v.Location
+		sdetail.Provider = pv.ProviderNumber
+		sdetail.SaveType = util.ZeroStr(bc.IsZeroStock == 1, "K")
+		r.Data.Detail = append(r.Data.Detail, sdetail)
+	}
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Errorf("laid proof error:%v", e)
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Printf("quit proof  success:eqcode=%s,sapcode=%s", rp.Data.EqNumber, rp.Data.SapNumber)
+			if e := s.d.DB.Model(&model.BigPartquit{}).Where("useform = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
+				log.Errorln(e)
+			}
+		} else {
+			log.Warnf("%s quit proof failed:causetext=%s", rp.Dest.MessText)
+			pp.Print(r)
+		}
+	}
+
+}
+
+func (s *Service) RefundProof(p interface{}) {
+	pr := new(model.RefundParam)
+	r := new(http.ProofReq)
+	rp := new(http.ProofResp)
+	parts := []model.PartRefund{}
+	bp := new(model.BigPartRefund)
+	pa := new(model.Pasture)
+
+	if e := util.Unmarshal(p, pr); e != nil {
+		log.Error(e)
+		log.Info("%v", pr)
+		return
+	}
+	pid, err := strconv.ParseInt(pr.ID, 10, 32)
+	if err != nil {
+		log.Errorf("parseInt  purchase id  :%v", err)
+	}
+	if e := s.d.DB.First(bp, model.BigPartRefund{ID: int(pid)}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.Find(&parts, model.PartRefund{BigID: bp.ID}).Error; e != nil || len(parts) == 0 {
+		log.Error(e)
+		return
+	}
+	if e := s.d.DB.First(pa, model.Pasture{ID: bp.PastureID}).Error; e != nil {
+		log.Error(e)
+		return
+	}
+
+	proofDest(r)
+	r.Data.EqNumber = bp.UseForm
+	r.Data.PostDate = bp.CreateTime.Format("20060102")
+	r.Data.CreateTime = time.Now().Format("20060102")
+
+	for i, v := range parts {
+
+		sdetail := http.ProofDetail{}
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+		bd := new(model.BuyDetail)
+		bbd := new(model.BigBuyDetail)
+		pv := new(model.Provider)
+
+		if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
+			log.Errorf("contract query error:%v", e)
+			return
+		}
+		if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+			log.Errorf("bigcontract query error:%v", e)
+			return
+		}
+
+		if e := s.d.DB.Order("id desc").First(bd, model.BuyDetail{ContractID: v.ContractID}).Error; e != nil {
+			log.Error(e)
+			return
+		}
+		if e := s.d.DB.First(bbd, model.BigBuyDetail{ID: bd.BigID}).Error; e != nil {
+			log.Errorf("refund proof bigbuydetail:id=%d,%v", bd.BigID, e)
+			return
+		}
+		if e := s.d.DB.First(pv, model.Provider{ID: bc.ProviderID}).Error; e != nil {
+			log.Errorf("refund proof provider:id=%d,%v", bc.ProviderID, e)
+			return
+		}
+
+		if bc.IsZeroStock == 0 {
+			sdetail.MoveType = "161"
+		} else {
+			sdetail.MoveType = "502"
+		}
+		sdetail.RowNumber = fmt.Sprintf("%d", i+1)
+		sdetail.Quantity = fmt.Sprintf("%f", v.RefundNumber)
+		sdetail.Unit = c.Unit
+		sdetail.Code = c.PartCode
+		sdetail.SaveType = util.ZeroStr(bc.IsZeroStock == 1, "K")
+		sdetail.Factory = pa.FactoryCode
+		sdetail.Location = v.Location
+		sdetail.OrderNumber = bbd.SapNumber
+		sdetail.OrderRowNum = fmt.Sprintf("%d", bd.RowNumber)
+		sdetail.Provider = pv.ProviderNumber
+
+		r.Data.Detail = append(r.Data.Detail, sdetail)
+	}
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Error(e)
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Printf("refund proof success:%s,%s", rp.Data.EqNumber, rp.Data.SapNumber)
+			if e := s.d.DB.Model(&model.BigPartRefund{}).Where("useform = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
+				log.Errorln(e)
+			}
+		} else {
+			log.Warnf("return good fail: %s", rp.Dest.MessText)
+			// if b, e := json.MarshalIndent(r, "", " "); e != nil {
+			// 	log.Error("json.MarshalIndent error")
+			// } else {
+			// 	fmt.Println(string(b))
+			// }
+		}
+	}
+
+}
+func proofDest(p *http.ProofReq) {
+	p.Dest.DestID = "EQMAN"
+	p.Dest.BussTp = "MM001"
+	p.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM001/ModifyMblnr"
+}

+ 50 - 0
apiserver/service/sap.go

@@ -0,0 +1,50 @@
+package service
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+
+	"kpt.xdmy/pkg/util"
+)
+
+func (s *Service) AddSapLog(p http.SapDest, err error) {
+	b, e := util.Marshal(p)
+	if e != nil {
+		log.Error(e)
+		return
+	}
+	d := p.GetDest()
+	l := model.SapLog{
+		Url:       d.Url,
+		Name:      d.BussTp,
+		Status:    d.Status,
+		MsgText:   d.MessText,
+		Param:     string(b),
+		CreatedAt: time.Now(),
+	}
+	if err != nil {
+		l.Flag = 1
+	}
+	if e := s.d.DB.Create(&l).Error; e != nil {
+		log.Error(e)
+	} else {
+		log.Infof("create sap log:%s ", p.GetUrl())
+	}
+}
+
+func (s *Service) SyncSap(r http.SapDest, rp interface{}) (err error) {
+	req, e := s.http.NewRequest("POST", r.GetUrl(), r)
+	if e != nil {
+		return errors.Wrapf(e, "SyncSap")
+	}
+	s.http.SetBasicAuth(req)
+
+	if err = s.http.Do(req, rp); err != nil {
+		err = errors.Wrapf(err, "SyncSap")
+	}
+	return
+}

+ 72 - 0
apiserver/service/service.go

@@ -0,0 +1,72 @@
+package service
+
+import (
+	"fmt"
+	"time"
+
+	"kpt.xdmy/apiserver/config"
+	"kpt.xdmy/apiserver/dao"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/pkg/http"
+	"kpt.xdmy/pkg/log"
+)
+
+var s *Service
+
+var nch chan error
+
+type Service struct {
+	c    *config.Config
+	d    *dao.Dao
+	http *http.Client
+}
+
+func New(conf *config.Config) *Service {
+	c := http.NewClient(conf)
+	d := dao.New(conf)
+	model.ModelInit(d)
+	SapJobInit()
+
+	s = &Service{
+		d:    d,
+		http: c,
+	}
+	return s
+}
+
+func (s *Service) queryDB(tname string, c interface{}, r interface{}) (err error) {
+	if err := s.d.DB.Table(tname).Where(c).Find(r).Error; err != nil {
+		err = log.Error("queryDB", err, c)
+	}
+	return
+}
+func (s *Service) insertDB(tname string, p interface{}) (err error) {
+	if err = s.d.DB.Table(tname).Create(p).Error; err != nil {
+		err = log.Error("insertDB "+tname, err, p)
+	}
+	return
+}
+func (s *Service) updateDB(tname string, c interface{}, r interface{}) (err error) {
+	if err = s.d.DB.Table(tname).Where(c).Updates(r).Error; err != nil {
+		err = log.Error("updateDB", err, r)
+	}
+	return
+}
+func (s *Service) RawDB(sql string, dest interface{}, c ...interface{}) (err error) {
+	err = s.d.DB.Raw(sql, c).Scan(&dest).Error
+	if err != nil {
+		err = log.Error("service RawDB", err, sql, c)
+	}
+	return
+}
+
+func (s *Service) Xorm() {
+	st := time.Now()
+	if r, e := s.d.DB.Raw("SELECT * FROM parts limit 3000").Rows(); e != nil {
+		fmt.Print(e)
+	} else {
+		r.Close()
+	}
+	log.Printf("xorm:%d", time.Now().Sub(st).Milliseconds())
+
+}

+ 106 - 0
apiserver/service/supplier.go

@@ -0,0 +1,106 @@
+package service
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+	log "github.com/sirupsen/logrus"
+
+	_ "github.com/go-sql-driver/mysql"
+
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+)
+
+var supplierChan chan error
+
+func (s *Service) SapSupplier(t time.Time, code string) {
+	supplierChan = make(chan error, 10)
+	r := new(http.SupplierReq)
+	rp := new(http.SupplierResp)
+	var e error
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "MM004"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM004/QuerySupplier/"
+	if t.IsZero() {
+		t = time.Now()
+	}
+	r.Data.BudatB = t.Format("20060102")
+	r.Data.BudatE = t.Format("20060102")
+	r.Data.BudatB = "20220920"
+	r.Data.BudatE = "20220922"
+	// r.Data.CompanyCode = "1004"
+	r.Data.CompanyCode = "9099"
+	r.Data.Types = []http.ZSORT{{Type: "设备"}}
+
+	if e = s.SyncSap(r, rp); e == nil {
+		if rp.Dest.Status == "S" {
+			log.Infof("sap  supplier success :  mlen=%d", len(rp.Data.Master))
+		} else {
+			e = errors.Errorf("sap  supplier fail: %s", rp.Dest.MessText)
+		}
+	} else {
+		e = errors.Wrap(e, "sap supplier error:")
+	}
+	var update error
+	var count int
+	for _, v := range rp.Data.Master {
+		update = nil
+		go s.updateProvider(&v)
+		update = <-supplierChan
+		if update != nil {
+			log.Error(update)
+			count++
+			l := model.SapDetailLog{Name: "supplier", Code: v.Code, ErrorText: update.Error()}
+			if e := s.d.DB.Create(&l); e != nil {
+				log.Errorf("add sapdetail log: %v", e)
+			}
+		}
+		break
+	}
+	if e != nil {
+		log.Error(e)
+	} else if update != nil {
+		e = errors.Errorf("supplier update fail sum:%d", count)
+	} else {
+		log.Infof("supplier update success sum:%d", len(rp.Data.Master)-count)
+	}
+	s.AddSapLog(r, e)
+	return
+}
+
+func (s *Service) updateProvider(sup *http.Supplier) {
+	pv := new(model.Provider)
+
+	if len(sup.UpDate) == 8 {
+		sup.UpDate = sup.UpDate[:4] + "-" + sup.UpDate[4:6] + "-" + sup.UpDate[6:]
+	}
+	if len(sup.UpTime) == 6 {
+		sup.UpTime = sup.UpTime[:2] + ":" + sup.UpTime[2:4] + ":" + sup.UpTime[4:]
+	}
+	if sup.UpTime != "" {
+		sup.UpDate = sup.UpDate + " " + sup.UpTime
+	}
+	if t, e := time.Parse("2006-01-02 15:04:05", sup.UpDate); e != nil {
+		supplierChan <- errors.Errorf("time parse  : %s, %s", sup.UpDate)
+	} else {
+		pv.ModifyTime = t
+	}
+	pv.ProviderIntro = sup.Name
+	pv.ProviderName = sup.ShortName
+	pv.ProviderNumber = sup.Code
+	pv.CompanyCode = sup.CompanyCode
+	pv.SortName = sup.ZSORT
+	pv.Linkman = sup.Contact
+	pv.Email = sup.Mail
+	pv.Telphone = sup.Phone
+	if sup.Dflag == "" {
+		pv.Enable = 1
+	}
+	if e := s.d.DB.Where(model.Provider{ProviderNumber: sup.Code}).Assign(pv).FirstOrCreate(&pv).Error; e != nil {
+		supplierChan <- errors.Wrapf(e, "provider update  failed:code =%s", sup.Code)
+	} else {
+		log.Infof("provider update succeeded:%s,%s,%s", sup.Code, sup.ShortName, sup.CompanyCode)
+		supplierChan <- nil
+	}
+}

+ 160 - 0
apiserver/service/transfer.go

@@ -0,0 +1,160 @@
+package service
+
+import (
+	"fmt"
+
+	_ "github.com/go-sql-driver/mysql"
+	log "github.com/sirupsen/logrus"
+
+	"github.com/pkg/errors"
+	"kpt.xdmy/apiserver/model"
+	"kpt.xdmy/apiserver/model/http"
+)
+
+func autoTransfer() {
+	bp := []model.BigPartTransfer{}
+	if e := s.d.DB.Where(" CreatDate > '2022-09-28' and sapStatus =0  ").Find(&bp, model.BigPartTransfer{Statue: 1}).Error; e != nil {
+		log.Errorf("autoTransfer find :%v", e)
+		return
+	}
+	log.Infof("sap  transfer len=%d", len(bp))
+	for _, v := range bp {
+		err := SapTransfer(&v)
+		TransferLog("auto", v.ApplyCode, err)
+	}
+}
+func ManualTransfer(code string) (int, map[string]interface{}) {
+	bp := []model.BigPartTransfer{}
+	re := make(map[string]interface{})
+	r := s.d.DB.Where("CreatDate >'2022-09-28'  ")
+	if code != "" {
+		r = r.Where("applycode", code)
+	}
+	r = r.Find(&bp, model.BigPartTransfer{Statue: 1, SapStatus: 2})
+	if r.Error != nil {
+		log.Errorf("ManualTransfers find :%v", r.Error)
+		re["find"] = r.Error
+		return 0, re
+	}
+	var count int
+	for _, v := range bp {
+		err := SapTransfer(&v)
+		TransferLog("manual", v.ApplyCode, err)
+		if err == nil {
+			count++
+		} else {
+			re[v.ApplyCode] = err.Error()
+		}
+	}
+	return count, re
+}
+
+func TransferLog(c, code string, err error) {
+	m := make(map[string]interface{})
+	if err != nil {
+		err = errors.Wrap(err, code)
+		m["sapText"] = err.Error()
+		if c == "auto" {
+			m["sapStatus"] = 2
+		}
+	} else {
+		m["sapStatus"] = 1
+	}
+	if e := s.d.DB.Model(&model.BigPartTransfer{}).Where("applycode =?", code).Updates(m).Error; e != nil {
+		log.Errorf("BigPartTransfer update :%v", e)
+	}
+}
+func SapTransfer(bp *model.BigPartTransfer) error {
+	// 寄售无调拨
+	//非寄售
+	r := new(http.TransferReq)
+
+	parts := []model.PartTransfer{}
+	blaid := new(model.BigPartLaid)
+	inpa := new(model.Pasture)
+	outpa := new(model.Pasture)
+	dp := new(model.Department)
+
+	if e := s.d.DB.Find(&parts, model.PartTransfer{BigID: bp.ID}).Error; e != nil || len(parts) == 0 {
+		return errors.Wrapf(e, "parttarnsfer query bigid: %d", bp.ID)
+	}
+	if e := s.d.DB.First(blaid, model.BigPartLaid{LaidCode: bp.LaidCode}).Error; e != nil {
+		return errors.Wrapf(e, "bigpartlaid query laidcode: %s", bp.LaidCode)
+	}
+	if e := s.d.DB.First(inpa, model.Pasture{ID: bp.InPastureID}).Error; e != nil {
+		return errors.Wrapf(e, "pasture :id=%d", bp.InPastureID)
+	}
+	if e := s.d.DB.First(outpa, model.Pasture{ID: bp.PastureID}).Error; e != nil {
+		return errors.Wrapf(e, "pasture :id=%d", bp.PastureID)
+	}
+	if e := s.d.DB.First(dp, model.Department{ID: bp.DeptId}).Error; e != nil {
+		return errors.Wrapf(e, "pasture :id=%d", bp.DeptId)
+	}
+
+	r.Dest.DestID = "EQMAN"
+	r.Dest.BussTp = "MM012"
+	r.Dest.Url = "https://app.modernfarming.cn:7443/sap/Common/MM012/TransferStock"
+
+	r.Data.OrderDate = bp.CreatDate.Format("20060102")
+	r.Data.PostDate = bp.ApplyDate.Format("20060102")
+	r.Data.TransferCode = bp.ApplyCode
+	r.Data.Group = "B11"
+
+	for i, v := range parts {
+		detail := new(http.TransferDetail)
+		outStock := new(model.PartRepertory)
+		pslaid := new(model.PartLaid)
+		inw := new(model.Warehouse)
+		c := new(model.Contract)
+		bc := new(model.BigContract)
+
+		if e := s.d.DB.First(outStock, model.PartRepertory{ID: v.PartRepID}).Error; e != nil {
+			return errors.Wrapf(e, "partrepertory query :id=%d", v.PartRepID)
+		}
+		if e := s.d.DB.First(pslaid, model.PartLaid{BigID: blaid.ID, PartID: v.PartID}).Error; e != nil {
+			return errors.Wrapf(e, "partlaid query :bigid=%d", blaid.ID)
+		}
+		if e := s.d.DB.First(inw, model.Warehouse{ID: pslaid.LocationID}).Error; e != nil {
+			return errors.Wrapf(e, "warehouse query :id=%d", pslaid.LocationID)
+		}
+		if outStock.ContractID > 0 {
+			// if e := s.d.DB.Table("BigContract").Select("BigContract.IsZeroStock ").Joins("join Contract c on c.bigid =BigContract.id").
+			// 	Where("c.id  =?", outStock.ContractID).First(bc).Error; e != nil {
+			// 	return errors.Wrapf(e, "BigContract IsZeroStock  :id=%d", outStock.ContractID)
+			// }
+			if e := s.d.DB.First(c, model.Contract{ID: outStock.ContractID}).Error; e != nil {
+			}
+			if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
+				return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID)
+			}
+			if bc.IsZeroStock == 1 {
+				return errors.New("寄售无调拨")
+			}
+		}
+		detail.RowNumber = fmt.Sprintf("%d", i+1)
+		detail.MaterialCode = v.PartCode
+		detail.Quantity = v.Amount
+		detail.Unit = v.Unit
+		detail.Per = "1"
+		detail.DeliverDate = blaid.StorageTime.Format("20060102")
+		detail.OutFactory = outpa.FactoryCode
+		detail.InFactory = inpa.FactoryCode
+		detail.OutLocation = inw.WarehoseCode
+		detail.InLocation = outStock.Location
+		// detail.TaxCode = "J0"
+		// detail.NetPrice = "2"
+		r.Data.Detail = append(r.Data.Detail, *detail)
+	}
+	rp := new(http.TransferResp)
+	if e := s.SyncSap(r, rp); e != nil {
+		log.Info(r)
+		return errors.Wrapf(e, "transfer error:%v")
+	} else {
+		if rp.Dest.Status == "S" {
+			log.Printf("transfer success:%s,%s", rp.Data.Proof.EqTransferCode, rp.Data.Proof.ProofCode)
+			return nil
+		} else {
+			return errors.Wrapf(e, "tranfer fail: %s", rp.Dest.MessText)
+		}
+	}
+}

+ 29 - 0
apiserver/service/user_service/user.go

@@ -0,0 +1,29 @@
+package user_service
+
+import (
+	"github.com/casbin/casbin"
+	"kpt.xdmy/apiserver/routers/restful"
+	"kpt.xdmy/pkg/util"
+)
+
+type User struct {
+	ID       int
+	Username string
+	Password string
+	Fullname string
+	Deptid   int
+	Role     int
+
+	CreatedBy  string
+	ModifiedBy string
+
+	PageNum  int
+	PageSize int
+
+	Enforcer *casbin.Enforcer `inject:""`
+}
+
+func (a *User) Check() (bool, error) {
+	return restful.CheckUser(a.Username, util.EncodeMD5(a.Password))
+
+}

+ 3 - 0
bk/bat/arm.bat

@@ -0,0 +1,3 @@
+set GOARCH=arm
+set GOOS=linux
+go build -o KPTAdminARM

+ 1 - 0
bk/bat/doc.bat

@@ -0,0 +1 @@
+swag init

+ 3 - 0
bk/bat/linux64.bat

@@ -0,0 +1,3 @@
+set GOARCH=amd64
+set GOOS=linux
+go build -o KPTAdmin

+ 3 - 0
bk/bat/win32.bat

@@ -0,0 +1,3 @@
+set GOARCH=386
+set GOOS=windows
+go build -o KPTAdmin32.exe

+ 4 - 0
bk/bat/win64.bat

@@ -0,0 +1,4 @@
+set GOARCH=amd64
+set GOOS=windows
+go clean
+go build -o KPTAdmin64.exe

二進制
bk/browse/dist0624/.DS_Store


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/datas/myMap.json


二進制
bk/browse/dist0624/favicon.ico


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/index.html


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/css/app.1c97fb9d.css


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/css/chunk-elementUI.45ab9bc1.css


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/css/chunk-libs.2e418612.css


二進制
bk/browse/dist0624/static/fonts/element-icons.535877f5.woff


二進制
bk/browse/dist0624/static/fonts/element-icons.732389de.ttf


二進制
bk/browse/dist0624/static/img/1.1ddf085a.png


二進制
bk/browse/dist0624/static/img/404.a57b6f31.png


二進制
bk/browse/dist0624/static/img/404_cloud.0f4bc32b.png


二進制
bk/browse/dist0624/static/img/cow.3495de2a.jpg


二進制
bk/browse/dist0624/static/img/login-bg.dfe7c90f.jpg


二進制
bk/browse/dist0624/static/img/login-bg1.1f1602f0.jpg


二進制
bk/browse/dist0624/static/img/login-bujian.8695940d.png


二進制
bk/browse/dist0624/static/img/logo.4a74cb8a.png


二進制
bk/browse/dist0624/static/img/logo1.d2343c0f.png


二進制
bk/browse/dist0624/static/img/logo_u3.34a9ffae.png


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/js/app.1f5f7ce2.js


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/js/chunk-581b2547.35f5db31.js


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/js/chunk-d17f893e.ab3f161f.js


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/js/chunk-elementUI.e7d11236.js


文件差異過大導致無法顯示
+ 0 - 0
bk/browse/dist0624/static/js/chunk-fb16bab8.723f5a84.js


部分文件因文件數量過多而無法顯示