diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6898445 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/logs/*.log diff --git a/ModulePath/ModulePath.go b/ModulePath/ModulePath.go new file mode 100644 index 0000000..5840a20 --- /dev/null +++ b/ModulePath/ModulePath.go @@ -0,0 +1,39 @@ +package ModulePath + +import ( + // "errors" + // "fmt" + "os" + // "os/exec" + "path/filepath" + // "strings" +) + +func GetModuleCurrentPath() (string, error) { + + file, err := os.Executable() + if err != nil { + return "", err + } + + exPath := filepath.Dir(file) + return exPath, nil + + /*file, err := exec.LookPath(os.Args[0]) + if err != nil { + fmt.Println("lookpath err:", err.Error()) + return "", err + } + path, err := filepath.Abs(file) + if err != nil { + return "", err + } + i := strings.LastIndex(path, "/") + if i < 0 { + i = strings.LastIndex(path, "\\") + } + if i < 0 { + return "", errors.New(`error: Can't find "/" or "\".`) + } + return string(path[0 : i+1]), nil*/ +} diff --git a/conf/app.conf b/conf/app.conf new file mode 100644 index 0000000..89c70cc --- /dev/null +++ b/conf/app.conf @@ -0,0 +1,5 @@ +server = 119.3.242.17 +port = 1433 +user = sa +password = lh123456? +database = ma \ No newline at end of file diff --git a/data.go b/data.go new file mode 100644 index 0000000..c153c8b --- /dev/null +++ b/data.go @@ -0,0 +1,102 @@ +package main + +type ma_temp_plan struct { + ID int `json:"id"` //序号 + Recv_date string `json:"recv_date"` //接收日期 + Dispath_date string `json:"dispath_date"` //下发日期 + + Return_task string `json:"return_task"` //退货任务 + Head string `json:"head"` //负责人 + P_id string `json:"p_id"` //产品编号 + P_name string `json:"p_name"` //产品名称 + P_serial string `json:"p_serial"` //产品序列号 + + Repairer string `json:"repairer"` //维修人员 + Repair_type string `json:"rt"` //维修类型 + + Work string `json:"work"` //工作内容 + Work_h string `json:"work_h"` //天工时长 + Inspection_analysis string `json:"ia"` //初检分析 + Repair_plan string `json:"rp"` //维修方案 + Actual_completed_date string `json:"acd"` //实际完成 + Link string `json:"link"` //自检记录链接 + + Material_status string `json:"ms"` //缺料情况 + Material_task string `json:"mt"` //物料任务 + + Total_work_time string `json:"total_work_time"` + Total_cost string `json:"total_cost"` + + Plan_data []plan_info `json:"plan_data"` + + State string `json:"state"` //已审核 未审核 + + If_do int `json:"if_do"` // 1-已处理 + + If_e1 bool `json:"if_e1"` //是否转入E1库 true-转入 + If_e1_str string `json:"if_e1_str"` //是否转入E1库 true-转入 + Odd_num string `json:"odd_num"` +} + +type ma_plan struct { + ID int `json:"id"` //序号 + Recv_date string `json:"recv_date"` //接收日期 + Dispath_date string `json:"dispath_date"` //下发日期 + Repair_id string `json:"repair_id"` //维修订单号 + Repair_report_id string `json:"repair_report_id"` //维修报告编号 + Customer string `json:"customer"` //客户名称 + Regional_head string `json:"regional_head"` //区域负责人 + P_id string `json:"p_id"` //产品编号 + P_name string `json:"p_name"` //产品名称 + P_serial string `json:"p_serial"` //产品序列号 + + Repairer string `json:"repairer"` //维修人员 + Repair_plan string `json:"rp"` //维修方案 + Material_status string `json:"ms"` //缺料情况 + Repair_cycle string `json:"rc"` //承诺维修周期 + Repair_quotation_date string `json:"rqd"` //维修报价日期 + Repair_status string `json:"rs"` //维修状态 + Repair_OK_date string `json:"rod"` //确认维修日期 + If_repair string `json:"if_repair"` //是否维修 + Committed_completed_date string `json:"ccd"` //承诺完成 + Actual_completed_date string `json:"acd"` //实际完成 + Overdue string `json:"overdue"` //超期 + Quotation string `json:"quotation"` //报价花费时间 + Material_committed_date string `json:"mcd"` //承诺到料日期 + Material_task string `json:"mt"` //物料任务 + + Inventory string `json:"inventory"` //库存量 + + Location string `json:"Location"` + + Date_of_issuance string `json:"doi"` //发料日期 + Link string `json:"link"` //自检记录链接 + + Mcn string `json:"mcn"` //维修合同号 + + If_warn int `json:"if_warn"` + + Total_work_time string `json:"total_work_time"` + + Total_cost string `json:"total_cost"` + + Plan_data []plan_info `json:"plan_data"` + + Station string `json:"station"` //维保站 + + State string `json:"state"` //已审核 未审核 +} + +type plan_info struct { + ID int `json:"id"` + + Process_name string `json:"produce_plan"` + Process_t string `json:"produce_plan_use_t"` + Produce_user string `json:"produce_user"` + + Actual_finished_t string `json:"p_actual_finished_t"` + + State string `json:"state"` //已审核 未审核 + + Times int `json:"times"` +} diff --git a/file/导入临时计划.csv b/file/导入临时计划.csv new file mode 100644 index 0000000..3c28d6f --- /dev/null +++ b/file/导入临时计划.csv @@ -0,0 +1,2 @@ +,˿,,Ʒ,Ʒ,к,άԱ,ά,(칤),칤ʱ,תE1 +2022-11-4,,,2,1,AA,Ա1,,,, diff --git a/file/导入维保计划.csv b/file/导入维保计划.csv new file mode 100644 index 0000000..ff28dca --- /dev/null +++ b/file/导入维保计划.csv @@ -0,0 +1,2 @@ +,·,ά޶,άޱ,ͬ,ͻ,,Ʒ,Ʒ,к,άԱ,ά״̬,Ƿά,άվ +2022-11-4,2022-11-4,219457,219457,219457,4,3,2,1,AA,Ա1,,, diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3a4a085 --- /dev/null +++ b/go.mod @@ -0,0 +1,22 @@ +module ma + +go 1.16 + +require ( + github.com/LukeMauldin/lodbc v0.0.0-20130219161755-59316a7de9d4 + github.com/OwnLocal/goes v1.0.0 // indirect + github.com/alexbrainman/odbc v0.0.0-20210605012845-39f8520b0d5f // indirect + github.com/astaxie/beego v1.12.3 + github.com/denisenkom/go-mssqldb v0.11.0 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/mattn/go-adodb v0.0.1 + github.com/mattn/go-sqlite3 v2.0.3+incompatible + github.com/satori/go.uuid v1.2.0 + github.com/shopspring/decimal v1.3.1 // indirect + github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726 // indirect + github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373 // indirect + github.com/tealeg/xlsx v1.0.5 + github.com/weigj/go-odbc v0.0.0-20120414035027-f09eefba7e19 // indirect + gitlab.com/stone.code/odbc3-go v0.0.0-20140130212748-f9bdfa0350f2 // indirect + golang.org/x/net v0.0.0-20211020060615-d418f374d309 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..cc246b0 --- /dev/null +++ b/go.sum @@ -0,0 +1,206 @@ +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/LukeMauldin/lodbc v0.0.0-20130219161755-59316a7de9d4 h1:MNptLl+J1e/11fmvv5sC47Kc6pJh336HGhEa4ga81IQ= +github.com/LukeMauldin/lodbc v0.0.0-20130219161755-59316a7de9d4/go.mod h1:wVRoKWzJl1ZecJg0GW+iCvOyWUHSE87uCCxWaF9WMzw= +github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alexbrainman/odbc v0.0.0-20210605012845-39f8520b0d5f h1:qJp6jWdG+PBNCDtIwRpspahMaZ3hlfde/25ExBORKso= +github.com/alexbrainman/odbc v0.0.0-20210605012845-39f8520b0d5f/go.mod h1:c5eyz5amZqTKvY3ipqerFO/74a/8CYmXOahSr40c+Ww= +github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGnFV6hVsYE877CKEZ6tDNTjaSXYUk6QqoIK6PrAtcc= +github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= +github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= +github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= +github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= +github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= +github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60= +github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= +github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= +github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= +github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= +github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisenkom/go-mssqldb v0.11.0 h1:9rHa233rhdOyrz2GcP9NM+gi2psgJZ4GWDpL/7ND8HI= +github.com/denisenkom/go-mssqldb v0.11.0/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU= +github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= +github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/ledisdb/ledisdb v0.0.0-20200510135210-d35789ec47e6/go.mod h1:n931TsDuKuq+uX4v1fulaMbA/7ZLLhjc85h7chZGBCQ= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-adodb v0.0.1 h1:g/pk3V8m/WFX2IQRI58wAC24OQUFFXEiNsvs7dQ1WKg= +github.com/mattn/go-adodb v0.0.1/go.mod h1:jaSTRde4bohMuQgYQPxW3xRTPtX/cZKyxPrFVseJULo= +github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/KYA= +github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= +github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R9JX0FuA/U= +github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= +github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.10.0 h1:RyRA7RzGXQZiW+tGMr7sxa85G1z0yOpM1qq5c8lNawc= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= +github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= +github.com/shopspring/decimal v1.3.1 h1:2Usl1nmF/WZucqkFZhnfFYxxxu8LG21F6nPQBE5gKV8= +github.com/shopspring/decimal v1.3.1/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= +github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= +github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg= +github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= +github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE= +github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM= +github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/weigj/go-odbc v0.0.0-20120414035027-f09eefba7e19 h1:0n3XLY0QrWER887wlRh9pzd0dmfsYak/WYwXYMEwVso= +github.com/weigj/go-odbc v0.0.0-20120414035027-f09eefba7e19/go.mod h1:I2IXPqsCTidAXyoiDDMxw9dTlFyFvpv25SiZl2Xhbnw= +github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= +github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= +gitlab.com/stone.code/odbc3-go v0.0.0-20140130212748-f9bdfa0350f2 h1:euSt1+U+70sxHwOIiKaUthbzkuSWYDwDBO2FzK+6qec= +gitlab.com/stone.code/odbc3-go v0.0.0-20140130212748-f9bdfa0350f2/go.mod h1:susDFwJTAkX5t89LhGIcv/+3ZXIPZCkpAg0s5QkoPw4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20211020060615-d418f374d309 h1:A0lJIi+hcTR6aajJH4YqKWwohY4aW9RO7oRMcdv+HKI= +golang.org/x/net v0.0.0-20211020060615-d418f374d309/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da h1:b3NXsE2LusjYGGjL5bxEVZZORm/YEFFrWFjR8eFrw/c= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyzM= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/ma-server.debug.exe b/ma-server.debug.exe new file mode 100644 index 0000000..0c2789c Binary files /dev/null and b/ma-server.debug.exe differ diff --git a/ma.debug.exe b/ma.debug.exe new file mode 100644 index 0000000..ea0a741 Binary files /dev/null and b/ma.debug.exe differ diff --git a/main.go b/main.go new file mode 100644 index 0000000..dbcaf0e --- /dev/null +++ b/main.go @@ -0,0 +1,7341 @@ +package main + +import ( + "fmt" + "sort" + + // "io" + "net/http" + + "encoding/json" + + "strconv" + + "io/ioutil" + + "time" + + "database/sql" + + "strings" + + _ "github.com/LukeMauldin/lodbc" + _ "github.com/denisenkom/go-mssqldb" + _ "github.com/mattn/go-adodb" + + "ma/ModulePath" + + "os" + + "sync" + + "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" + + _ "github.com/mattn/go-sqlite3" + uuid "github.com/satori/go.uuid" + + "encoding/csv" + //_ "net/http/pprof" + // "runtime" + // "github.com/shopspring/decimal" + "github.com/tealeg/xlsx" +) + +/* +go-adodb ---cache leak + +github.com/weigj/go-odbc ---查询处理特殊字符有问题 + +github.com/alexbrainman/odbc ---sqlserver读取汉字乱码(编码格式没有转换) + + +*/ + +func testAdo() { + var conf []string + var db *sql.DB + var err error + conf = append(conf, "Provider=SQLOLEDB") + conf = append(conf, "Data Source=127.0.0.1,1433") // sqlserver IP 和 服务器名称 + conf = append(conf, "Initial Catalog=WellNameInformation") // 数据库名 + conf = append(conf, "user id=sa") // 登陆用户名 + conf = append(conf, "password=lh123456") // 登陆密码 + fmt.Println(strings.Join(conf, ";")) + db, err = sql.Open("adodb", strings.Join(conf, ";")) + if err != nil { + fmt.Println("sql open:", err) + return + } else { + + } + defer db.Close() + + beginTime := time.Now() + // 执行SQL语句 + rows, err := db.Query("select [6506] from [AUTHINFO] order by ID") + if err != nil { + fmt.Println("query: ", err) + return + } + for rows.Next() { + var id float32 + + rows.Scan(&id) + fmt.Println("id: ", id) + } + + defer rows.Close() + + fmt.Println(fmt.Sprintf("use time:%v", (time.Now().UnixNano()-beginTime.UnixNano())/1e6)) +} + +// 2008是要升级sqlserver数据库的补丁的,不建议使用。 +func testMssqldb() { + var server = "127.0.0.1" + port := 1433 + var user = "sa" + var password = "lh123456" + var database = "WellNameInformation" + + //连接字符串 + connString := fmt.Sprintf("server=%s;port%d;database=%s;user id=%s;password=%s", server, port, database, user, password) + fmt.Println(connString) + + //建立连接 + db, err := sql.Open("mssql", connString) + if err != nil { + fmt.Println("Open Connection failed:", err.Error()) + } + defer db.Close() + + //通过连接对象执行查询 + rows, err := db.Query(`select ID from WellInformation order by ID`) + if err != nil { + fmt.Println("Query failed:", err.Error()) + return + } + defer rows.Close() + + for rows.Next() { + var id int64 + + rows.Scan(&id) + fmt.Printf("id: %d \n", id) + } + +} + +func testOdbc() { + conn, err := sql.Open("odbc", "driver={SQL Server};SERVER=127.0.0.1;UID=sa;PWD=lh123456?;DATABASE=WellNameInformation") + if err != nil { + fmt.Println("Connecting Error", err.Error()) + return + } else { + fmt.Println("connect success!") + } + + defer conn.Close() + + beginTime := time.Now() + stmt, err := conn.Prepare("select ID from [WellNameInformation].[dbo].[WellInformation] order by ID") + if err != nil { + fmt.Println("Query Error", err) + return + } + defer stmt.Close() + row, err := stmt.Query() + if err != nil { + fmt.Println("Query Error", err) + return + } + defer row.Close() + + cnt := 0 + for row.Next() { + var id int + if err := row.Scan(&id); err == nil { + //fmt.Println(id) + + cnt++ + } + } + + fmt.Println("record len:", cnt) + + fmt.Println(fmt.Sprintf("use time:%v", (time.Now().UnixNano()-beginTime.UnixNano())/1e6)) + + fmt.Printf("%s\n", "finish") + return +} + +var ( + server string + port int + user string + password string + database string + + sqlConn *sql.DB + //odbcConn *sql.DB + + //user + refreshSpan int64 + ExpireTimeSpan time.Duration + + modelePath string + + mu sync.Mutex + + p_lock sync.Mutex + p_import_f int + + process_lock sync.Mutex + process_lock_n int + + ma_plan_lock sync.Mutex + ma_plan_lock_n int + + ma_temp_plan_lock sync.Mutex + ma_temp_plan_lock_n int + + g_time_format string = "2006-01-02 15:04:05" +) + +func initLog() { + + beego.BeeLogger.DelLogger("console") + + var err error + modelePath, err = ModulePath.GetModuleCurrentPath() + if err != nil { + fmt.Println("ModulePath.GetModuleCurrentPath() failed err:", err.Error()) + return + } + + fmt.Println("modelePath:", modelePath) + + config := make(map[string]interface{}) + config["filename"] = modelePath + string("/logs/ma.log") + config["level"] = 7 + config["maxlines"] = 0 + config["maxsize"] = 50 * 1024 * 1024 //50M + config["daily"] = true + config["maxdays"] = 10 + + configJsonStr, err := json.Marshal(config) + if err != nil { + fmt.Println("package main init json.Marshal(config) failed,err:", err.Error()) + os.Exit(-1) + } + + logs.SetLogger(logs.AdapterFile, string(configJsonStr)) +} + +func initSqlPool(driverType string) { + + if driverType == "ado" { + var conf []string + var err error + conf = append(conf, "Provider=SQLOLEDB") + conf = append(conf, fmt.Sprintf("Data Source=%s,%d", server, port)) // sqlserver IP 和 服务器名称 + conf = append(conf, fmt.Sprintf("Initial Catalog=%s", database)) // 数据库名 + conf = append(conf, fmt.Sprintf("user id=%s", user)) // 登陆用户名 + conf = append(conf, fmt.Sprintf("password=%s", password)) // 登陆密码 + fmt.Println(strings.Join(conf, ";")) + sqlConn, err = sql.Open("adodb", strings.Join(conf, ";")) + if err != nil { + fmt.Println("sql open:", err.Error()) + os.Exit(0) + } else { + fmt.Println("connect success!") + } + + } else { + // dataSource := fmt.Sprintf("driver={SQL Server};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s", server, user, password, database) + // fmt.Println(dataSource) + + // var err error + // sqlConn, err = sql.Open("lodbc", dataSource) + // if err != nil { + // fmt.Println("sql open:", err.Error()) + // os.Exit(0) + // } else { + // logs.Info("connect success!") + // } + dataSource := fmt.Sprintf( + "server=%s;user id=%s;password=%s;database=%s;port=%d;encrypt=disable;TrustServerCertificate=true", + server, // 仅服务器 IP 或域名(不包含端口) + user, + password, + database, + port, // 端口通过 port 参数单独指定 + ) + + fmt.Println("lalalalala", dataSource) + + var err error + // sqlConn, err = sql.Open("lodbc", dataSource) + // sqlConn, err = sql.Open("odbc", dataSource) + sqlConn, err = sql.Open("sqlserver", dataSource) + if err = sqlConn.Ping(); err != nil { + fmt.Println("sql open:", err.Error()) + os.Exit(0) + } else { + fmt.Println("连接成功") + } + } + + sqlConn.SetMaxOpenConns(10) + sqlConn.SetMaxIdleConns(3) +} + +func getConn(db string) (conn *sql.DB, err error) { + var conf []string + conf = append(conf, "Provider=SQLOLEDB") + conf = append(conf, fmt.Sprintf("Data Source=%s,%d", server, port)) // sqlserver IP 和 服务器名称 + conf = append(conf, fmt.Sprintf("Initial Catalog=%s", db)) // 数据库名 + conf = append(conf, fmt.Sprintf("user id=%s", user)) // 登陆用户名 + conf = append(conf, fmt.Sprintf("password=%s", password)) // 登陆密码 + //fmt.Println(strings.Join(conf, ";")) + conn, err = sql.Open("adodb", strings.Join(conf, ";")) + if err != nil { + fmt.Println("sql open:", err.Error()) + logs.Error("sql open:", err.Error()) + return + } + + conn.SetMaxIdleConns(1) + conn.SetMaxOpenConns(2) + + return +} + +func getOdbcConn(db string) (conn *sql.DB, err error) { + + dataSource := fmt.Sprintf("driver={SQL Server};SERVER=%s;UID=%s;PWD=%s;DATABASE=%s", server, user, password, db) + fmt.Println(dataSource) + + conn, err = sql.Open("lodbc", dataSource) + if err != nil { + logs.Error("sql open:", err.Error()) + return + } + + conn.SetMaxOpenConns(2) + conn.SetMaxIdleConns(1) + + return +} + +func init() { + + refreshSpan = 5 //5s + + ExpireTimeSpan = time.Second * 25 + + initLog() + + server = beego.AppConfig.String("server") + port, _ = beego.AppConfig.Int("port") + user = beego.AppConfig.String("user") + password = beego.AppConfig.String("password") + database = beego.AppConfig.String("database") + + initSqlPool("odbc") + +} + +func main() { + + go checkFileExpired() + + go check_ma_plan_warn_g() + + http.HandleFunc("/test", test) + + http.HandleFunc("/u_ma/login", Login) + http.HandleFunc("/u_ma/loginOut", LoginOut) + http.HandleFunc("/u_ma/refreshUser", refreshUser) + + http.HandleFunc("/u_ma/getMenu", getMenu) + + http.HandleFunc("/u_ma/getUsers", getUsers) + http.HandleFunc("/u_ma/postUser", postUser) + + http.HandleFunc("/u_ma/get_p", get_p) + http.HandleFunc("/u_ma/post_p", post_p) + http.HandleFunc("/u_ma/del_p", del_p) + http.HandleFunc("/u_ma/import_p", import_p) + http.HandleFunc("/u_ma/export_sap", export_sap) + http.HandleFunc("/u_ma/download_file", download_file) + + http.HandleFunc("/u_ma/get_process", get_process) + http.HandleFunc("/u_ma/import_process", import_process) + http.HandleFunc("/u_ma/update_process", update_process) + http.HandleFunc("/u_ma/del_process", del_process) + + http.HandleFunc("/u_ma/import_ma_plan", import_ma_plan) + http.HandleFunc("/u_ma/get_ma_plan", get_ma_plan) + http.HandleFunc("/u_ma/update_ma_plan_ex", update_ma_plan_ex) + http.HandleFunc("/u_ma/update_ma_plan_ex1", update_ma_plan_ex1) + http.HandleFunc("/u_ma/remove_ma_plan", remove_ma_plan) + http.HandleFunc("/u_ma/export_ma_plan", export_ma_plan) + + http.HandleFunc("/u_ma/get_p_id_options", get_p_id_options) + http.HandleFunc("/u_ma/get_p_name", get_p_name) + http.HandleFunc("/u_ma/get_ma_username", get_ma_username) + + http.HandleFunc("/u_ma/cal_completion_date", cal_completion_date) + + http.HandleFunc("/u_ma/get_rs", get_rs) + http.HandleFunc("/u_ma/postRs", post_rs) + + http.HandleFunc("/u_ma/get_p_process_options", get_p_process_options) + + http.HandleFunc("/u_ma/export_plan_process", export_plan_process) + + http.HandleFunc("/u_ma/get_processes", get_processes) + + http.HandleFunc("/u_ma/export_processes", export_processes) + + http.HandleFunc("/u_ma/approval_provesses", approval_provesses) + + http.HandleFunc("/u_ma/export_base_processes", export_base_processes) + + http.HandleFunc("/u_ma/import_ma_temp_plan", import_ma_temp_plan) + http.HandleFunc("/u_ma/get_ma_temp_plan", get_ma_temp_plan) + http.HandleFunc("/u_ma/update_ma_temp_plan", update_ma_temp_plan) + http.HandleFunc("/u_ma/remove_ma_temp_plan", remove_ma_temp_plan) + http.HandleFunc("/u_ma/export_ma_temp_plan", export_ma_temp_plan) + + http.HandleFunc("/u_ma/get_ma_temp_plan_fin", get_ma_temp_plan_fin) + http.HandleFunc("/u_ma/update_ma_temp_ex", update_ma_temp_ex) + + http.HandleFunc("/u_ma/export_ma_plan_processes", export_ma_plan_processes) + + //监听服务 + fmt.Println("listen server ...") + err := http.ListenAndServe("0.0.0.0:8876", nil) + if err != nil { + fmt.Println("服务器错误") + } + +} + +func export_ma_plan_processes(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_ma_plan_processes recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var filename string + var file *xlsx.File + + var err error + var req get_ma_plan_req + var resp download_file_Resp + var data []get_processes_resp_data + var data1 []get_processes_resp_data + + var sqlstr string + var rdRow *sql.Rows + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [return_task] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[return_task] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.Bt != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] >= '%s'`, req.Bt) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] >= '%s'`, req.Bt) + if_where = true + } + } + + if req.Et != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] <= '%s'`, req.Et) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] <= '%s'`, req.Et) + if_where = true + } + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[data] from [ma_temp_plan] where [state]='已审核' order by ID desc") + } else { + sqlstr = fmt.Sprintf("select [ID],[data] from [ma_temp_plan] where [state]='已审核' and %s order by ID desc", where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_ma_plan Query err:%v", err.Error())) + return + } + + for rdRow.Next() { + var s string + var v ma_temp_plan + var id int + if err := rdRow.Scan(&id, &s); err == nil { + + json.Unmarshal([]byte(s), &v) + v.ID = id + + if v.Repair_type == "退库" { + for i := 0; i < len(v.Plan_data); i++ { + tv := v.Plan_data[i] + var d get_processes_resp_data + d.Actual_finished_t = tv.Actual_finished_t + d.ID = tv.ID + d.Process_name = tv.Process_name + d.Process_t = tv.Process_t + d.Produce_user = tv.Produce_user + d.P_id = v.P_id + d.P_serial = v.P_serial + d.Repair_id = v.Return_task + d.Repair_plan = v.Repair_plan + d.Serial_id = tv.ID + d.State = tv.State + d.Times = tv.Times + + data = append(data, d) + } + } else if v.Repair_type == "天工" { + var d get_processes_resp_data + d.Actual_finished_t = v.Actual_completed_date + d.ID = v.ID + d.P_id = v.P_id + d.P_serial = v.P_serial + d.Repair_id = v.Return_task + d.Work = v.Work + d.Work_h = v.Work_h + d.State = v.State + d.Produce_user = v.Repairer + d.Head = v.Head + + data1 = append(data1, d) + } + + } else { + logs.Error("export_ma_plan scan Error", err.Error()) + } + } + rdRow.Close() + + file = xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "退货任务" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修方案" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工序" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "次数" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时费" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维保人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "审核状态" + + cost_map := make(map[string]float64) + for i := 0; i < len(data); i++ { + v := data[i] + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_plan + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = strconv.Itoa(v.Times) + + cell1 = row.AddCell() + cell1.SetStyle(style) + + pt, _ := strconv.ParseFloat(v.Process_t, 64) + cell1.Value = fmt.Sprintf(`%.2f`, pt*float64(v.Times)*25) + + if _, ok := cost_map[v.Produce_user]; ok { + cost_map[v.Produce_user] += pt * float64(v.Times) * 25 + } else { + cost_map[v.Produce_user] = pt * float64(v.Times) * 25 + } + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Produce_user + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Actual_finished_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.State + } + + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时费" + + for key, value := range cost_map { + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = key + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = fmt.Sprintf(`%.2f`, value) + } + + /*row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow()*/ + + sheet, err = file.AddSheet("sheet2") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + row = sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "负责人" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "天工内容" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "天工工时" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工费" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维保人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "审核状态" + + cost_map = make(map[string]float64) + for i := 0; i < len(data1); i++ { + v := data1[i] + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Head + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Work + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Work_h + + cell1 = row.AddCell() + cell1.SetStyle(style) + pt, _ := strconv.ParseFloat(v.Work_h, 64) + cell1.Value = fmt.Sprintf(`%.2f`, pt*25) + if _, ok := cost_map[v.Produce_user]; ok { + cost_map[v.Produce_user] += pt * 25 + } else { + cost_map[v.Produce_user] = pt * 25 + } + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Produce_user + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Actual_finished_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.State + } + + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时费" + + for key, value := range cost_map { + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = key + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = fmt.Sprintf(`%.2f`, value) + } + + filename = fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + resp.FileId = filename + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_ma_plan_processes recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_ma_temp_plan_fin_data(req get_ma_temp_plan_req) (resp get_ma_temp_plan_resp) { + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [return_task] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[return_task] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and [if_do]=1 and [state]='已审核'`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [if_do]=1 and [state]='已审核'`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and [if_do]=1 and [state]!='已审核'`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [if_do]=1 and [state]!='已审核'`) + if_where = true + } + } + + if req.Head != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [head] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_id != "" { + + if if_where { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_serial != "" { + + if if_where { + likeStr := "%" + req.P_serial + "%" + where_sql += fmt.Sprintf(` and [p_serial] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_serial + "%" + where_sql += fmt.Sprintf(` [p_serial] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_type != "" { + + if if_where { + likeStr := "%" + req.Repair_type + "%" + where_sql += fmt.Sprintf(` and [rt] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_type + "%" + where_sql += fmt.Sprintf(` [rt] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_temp_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_temp_plan] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data] from [ma_temp_plan] where ID not in (select top %v ID from [ma_temp_plan] order by acd desc) order by acd desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data] from [ma_temp_plan] where %s and ID not in (select top %v ID from [ma_temp_plan] where %s order by acd desc) order by acd desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_temp_plan + var id int + var s string + if err := rdRow.Scan(&id, &s); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + } + + if d.State == "" { + d.State = "未审核" + } + + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_ma_temp_plan scan Error", err.Error()) + } + } + +exit: + return +} + +func get_ma_temp_plan_fin(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_ma_temp_plan_fin recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_ma_temp_plan_req + var resp get_ma_temp_plan_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + resp = get_ma_temp_plan_fin_data(req) + +exit: + + jdata, _ := json.Marshal(resp) + str := string(jdata) + str = strings.ReplaceAll(str, "%", "%%") + fmt.Fprintf(response, str) + //fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_ma_temp_plan_fin recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func export_ma_temp_plan(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_ma_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var filename string + var file *xlsx.File + + var req get_ma_temp_plan_req + var resp download_file_Resp + var data get_ma_temp_plan_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + req.Index = 1 + req.Count = 100000 + data = get_ma_temp_plan_data(req) + fmt.Println(data) + + file = xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "接收日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "退库任务" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "负责人" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品名称" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修类型" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工作内容" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "初检分析" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修方案" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "自检记录" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "缺料情况" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "物料任务" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "转入E1库" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "转储单号" + + for i := 0; i < len(data.Data); i++ { + v := data.Data[i] + + var return_task string + if v.Return_task != "" { + return_task = "http://123.54.1.214:10010/redmine/issues/" + v.Return_task + } + + var link string + if v.Link != "" { + link = "http://123.54.1.214:10010/redmine/issues/" + v.Link + } + + var mt string + if v.Material_task != "" { + mt = "http://123.54.1.214:10010/redmine/issues/" + v.Material_task + } + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Recv_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = return_task + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Head + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repairer + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_type + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Work + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Inspection_analysis + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_plan + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Actual_completed_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = link + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Material_status + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = mt + + cell1 = row.AddCell() + cell1.SetStyle(style) + if v.If_e1 { + cell1.Value = "是" + } else { + cell1.Value = "否" + } + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Odd_num + } + + filename = fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + resp.FileId = filename + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_ma_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func remove_ma_temp_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("remove_ma_temp_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var userinfo useInfo + + reqdata, _ := ioutil.ReadAll(request.Body) + var req remove_ma_plan_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + userinfo, err = getUserInfo(req.OpUser) + if userinfo.RoleId != 1 { + resp.Ret = 1 + goto exit + } + + if req.ID == 0 { + logs.Info("remove_ma_temp_plan req id ==0") + resp.Ret = -1 + goto exit + } + + sqlstr = fmt.Sprintf(`DELETE FROM [ma_temp_plan] where ID=%d`, req.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("remove_ma_temp_plan err:", err.Error()) + resp.Ret = -1 + goto exit + } + + resp.Ret = 0 + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("remove_ma_temp_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func update_ma_temp_ex(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("update_ma_temp_ex recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var rows *sql.Rows + var old_data ma_temp_plan + var if_exist bool + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req update_ma_temp_plan_req + json.Unmarshal(reqdata, &req) + + // var user_info useInfo + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.Plan.ID == 0 { + logs.Info("update_ma_temp_plan sap req id ==0") + resp.Ret = -1 + goto exit + } + + /*user_info, _ = getUserInfo(req.OpUser) + if user_info.RoleId > 1 { + + names := make(map[string]bool) + names[req.Plan.Repairer] = true + + for i := 0; i < len(req.Plan.Plan_data); i++ { + names[req.Plan.Plan_data[i].Produce_user] = true + } + + if _, ok := names[req.OpUser]; !ok { + logs.Info("普通用户不可修改不是自己的计划") + resp.Ret = 1 + goto exit + } + }*/ + + sqlstr = fmt.Sprintf(`select data from [ma_temp_plan] where ID=%d`, req.Plan.ID) + rows, err = sqlConn.Query(sqlstr) + if err == nil { + for rows.Next() { + var s string + if err = rows.Scan(&s); err == nil { + json.Unmarshal([]byte(s), &old_data) + if_exist = true + } + } + } + + if if_exist { + old_data.Plan_data = req.Plan.Plan_data + + if true || old_data.Total_work_time == "" { + var wt float64 + for i := 0; i < len(old_data.Plan_data); i++ { + old_data.Plan_data[i].State = "已审核" + + t, _ := strconv.ParseFloat(old_data.Plan_data[i].Process_t, 64) + + t = t * float64(old_data.Plan_data[i].Times) + + wt += t + } + old_data.Total_work_time = fmt.Sprintf("%.2f", wt) + } + + old_data.State = "已审核" + + s, _ := json.Marshal(old_data) + sqlstr = fmt.Sprintf(`UPDATE [dbo].[ma_temp_plan] + SET [data] = '%s' + ,[return_task] = '%s' + ,[head] = '%s' + ,[p_id] = '%s' + ,[p_name] = '%s' + ,[p_serial] = '%s' + ,[repairer] = '%s' + ,[rt] = '%s' + ,[if_do] = %d + ,[state]='%s' + WHERE ID=%d`, + string(s), old_data.Return_task, old_data.Head, old_data.P_id, old_data.P_name, old_data.P_serial, + old_data.Repairer, old_data.Repair_type, old_data.If_do, old_data.State, + req.Plan.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_temp_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("update_ma_temp_ex recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func update_ma_temp_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("update_ma_temp_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var rows *sql.Rows + var old_data ma_temp_plan + var if_exist bool + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req update_ma_temp_plan_req + json.Unmarshal(reqdata, &req) + + var user_info useInfo + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.Plan.ID == 0 { + logs.Info("update_ma_temp_plan sap req id ==0") + resp.Ret = -1 + goto exit + } + + sqlstr = fmt.Sprintf(`select data from [ma_temp_plan] where ID=%d`, req.Plan.ID) + rows, err = sqlConn.Query(sqlstr) + if err == nil { + for rows.Next() { + var s string + if err = rows.Scan(&s); err == nil { + json.Unmarshal([]byte(s), &old_data) + if_exist = true + } + } + } + + if if_exist { + user_info, _ = getUserInfo(req.OpUser) + if user_info.RoleId > 1 { + + names := make(map[string]bool) + names[old_data.Repairer] = true + + for i := 0; i < len(old_data.Plan_data); i++ { + names[old_data.Plan_data[i].Produce_user] = true + } + + if _, ok := names[req.OpUser]; !ok { + logs.Info("普通用户不可修改不是自己的计划") + resp.Ret = 1 + goto exit + } + + if old_data.State == "已审核" { + resp.Ret = 1 + goto exit + } + } + + old_data = req.Plan + + if true || old_data.Total_work_time == "" { + var wt float64 + for i := 0; i < len(old_data.Plan_data); i++ { + t, _ := strconv.ParseFloat(old_data.Plan_data[i].Process_t, 64) + + t = t * float64(old_data.Plan_data[i].Times) + + wt += t + } + old_data.Total_work_time = fmt.Sprintf("%.2f", wt) + } + + if old_data.Actual_completed_date != "" { + old_data.If_do = 1 + + if old_data.Repair_type == "天工" { + old_data.State = "已审核" + } + } + + var if_e1 int + if old_data.If_e1 { + if_e1 = 1 + } + + s, _ := json.Marshal(old_data) + sqlstr = fmt.Sprintf(`UPDATE [dbo].[ma_temp_plan] + SET [data] = '%s' + ,[return_task] = '%s' + ,[head] = '%s' + ,[p_id] = '%s' + ,[p_name] = '%s' + ,[p_serial] = '%s' + ,[repairer] = '%s' + ,[rt] = '%s' + ,[if_do] = %d + ,[if_e1]= %d + ,[state]='%s',[acd]='%s' + WHERE ID=%d`, + string(s), old_data.Return_task, old_data.Head, old_data.P_id, old_data.P_name, old_data.P_serial, + old_data.Repairer, old_data.Repair_type, old_data.If_do, if_e1, old_data.State, old_data.Actual_completed_date, + req.Plan.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("update_ma_temp_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_ma_temp_plan_data(req get_ma_temp_plan_req) (resp get_ma_temp_plan_resp) { + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [return_task] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[return_task] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and [if_do]=1`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [if_do]=1`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and [if_do]!=1`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [if_do]!=1`) + if_where = true + } + } + + if req.If_e1 { + + if if_where { + where_sql += fmt.Sprintf(` and [if_e1]=1`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [if_e1]=1`) + if_where = true + } + } + + if req.Head != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [head] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_id != "" { + + if if_where { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_serial != "" { + + if if_where { + likeStr := "%" + req.P_serial + "%" + where_sql += fmt.Sprintf(` and [p_serial] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_serial + "%" + where_sql += fmt.Sprintf(` [p_serial] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repairer != "" { + + if req.Repairer == "空" { + if if_where { + where_sql += fmt.Sprintf(` and ([repairer] ='' or [repairer] is null)`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([repairer] ='' or [repairer] is null)`) + if_where = true + } + } else { + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + } + + if req.Repair_type != "" { + + if if_where { + likeStr := "%" + req.Repair_type + "%" + where_sql += fmt.Sprintf(` and [rt] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_type + "%" + where_sql += fmt.Sprintf(` [rt] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_temp_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_temp_plan] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data] from [ma_temp_plan] where ID not in (select top %v ID from [ma_temp_plan] order by [acd] desc) order by [acd] desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data] from [ma_temp_plan] where %s and ID not in (select top %v ID from [ma_temp_plan] where %s order by [acd] desc) order by [acd] desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_temp_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_temp_plan + var id int + var s string + if err := rdRow.Scan(&id, &s); err == nil { + + json.Unmarshal([]byte(s), &d) + d.ID = id + + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + } + + if d.If_e1 { + d.If_e1_str = "是" + } else { + d.If_e1_str = "否" + } + + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_ma_temp_plan scan Error", err.Error()) + } + } + +exit: + return +} + +func get_ma_temp_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_ma_temp_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_ma_temp_plan_req + var resp get_ma_temp_plan_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + resp = get_ma_temp_plan_data(req) + +exit: + + jdata, _ := json.Marshal(resp) + + str := string(jdata) + str = strings.ReplaceAll(str, "%", "%%") + fmt.Fprintf(response, str) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_ma_temp_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func export_base_processes(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_base_processes recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_process_req + var resp get_process_resp + + var file_resp download_file_Resp + + var sqlstr string + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + if req.P_id != "" { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(`[p_id] like '%s'`, likeStr) + if_where = true + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(`[p_name] like '%s'`, likeStr) + if_where = true + } + } + + if req.Process_name != "" { + + if if_where { + likeStr := "%" + req.Process_name + "%" + where_sql += fmt.Sprintf(` and [process_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Process_name + "%" + where_sql += fmt.Sprintf(`[process_name] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name],[process_name],[process_t] from [process] order by ID desc") + } else { + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name],[process_name],[process_t] from [process] where %s order by ID desc", where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_base_processes Query err:%v", err.Error())) + return + } + defer rdRow.Close() + + for rdRow.Next() { + var d process_info + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name, &d.Process_name, &d.Process_t); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("export_base_processes scan Error", err.Error()) + } + } + + file := xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品名称" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工序" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时" + + for i := 0; i < len(resp.Data); i++ { + v := resp.Data[i] + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_t + + } + + filename := fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + file_resp.FileId = filename + + jdata, _ := json.Marshal(file_resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_plan_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func approval_provesses(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("approval_provesses recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var rows *sql.Rows + var old_data ma_plan + var if_exist bool + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req approval_provesses_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.ID == 0 { + logs.Info("update_ma_plan_ex sap req id ==0") + resp.Ret = -1 + goto exit + } + + sqlstr = fmt.Sprintf(`select data from [ma_plan] where [repair_id]='%s'`, req.Rid) + rows, err = sqlConn.Query(sqlstr) + if err == nil { + for rows.Next() { + var s string + if err = rows.Scan(&s); err == nil { + json.Unmarshal([]byte(s), &old_data) + if_exist = true + } + } + } + + if if_exist { + for i := 0; i < len(old_data.Plan_data); i++ { + if old_data.Plan_data[i].ID == req.Serial_id { + if req.Undo { + old_data.Plan_data[i].State = "" + } else { + old_data.Plan_data[i].State = "已审核" + } + + } + } + s, _ := json.Marshal(old_data) + sqlstr = fmt.Sprintf(`UPDATE [ma_plan] SET [data] = '%s' WHERE [repair_id]='%s' `, + string(s), req.Rid) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + + if req.Undo { + sqlstr = fmt.Sprintf(`UPDATE [dbo].[processes] + SET [state] = '%s' WHERE ID=%d`, "未审核", req.ID) + } else { + sqlstr = fmt.Sprintf(`UPDATE [dbo].[processes] + SET [state] = '%s' WHERE ID=%d`, "已审核", req.ID) + } + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("approval_provesses recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +// 导出商丘维保已审核 +func export_processes(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_processes recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var filename string + var file *xlsx.File + + var err error + var req get_ma_plan_req + var resp download_file_Resp + var data []get_processes_resp_data + + var sqlstr string + var rdRow *sql.Rows + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + // user_data, _ := getUserInfo(req.OpUser) + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [produce_user] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [produce_user] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.Bt != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] >= '%s'`, req.Bt) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] >= '%s'`, req.Bt) + if_where = true + } + } + + if req.Et != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] <= '%s'`, req.Et) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] <= '%s'`, req.Et) + if_where = true + } + } + + if if_where { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[data] from [ma_plan] where [state]='已审核' order by ID desc") + } else { + sqlstr = fmt.Sprintf("select [ID],[data] from [ma_plan] where [state]='已审核' and %s order by ID desc", where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_ma_plan Query err:%v", err.Error())) + return + } + + for rdRow.Next() { + var s string + var v ma_plan + var id int + if err := rdRow.Scan(&id, &s); err == nil { + + json.Unmarshal([]byte(s), &v) + v.ID = id + + for i := 0; i < len(v.Plan_data); i++ { + tv := v.Plan_data[i] + var d get_processes_resp_data + d.Actual_finished_t = tv.Actual_finished_t + d.ID = tv.ID + d.Process_name = tv.Process_name + d.Process_t = tv.Process_t + d.Produce_user = tv.Produce_user + d.P_id = v.P_id + d.P_serial = v.P_serial + d.Repair_id = v.Repair_id + d.Repair_plan = v.Repair_plan + d.Serial_id = tv.ID + d.State = tv.State + d.Times = tv.Times + data = append(data, d) + } + + } else { + logs.Error("export_ma_plan scan Error", err.Error()) + } + } + rdRow.Close() + + file = xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修单号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修方案" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工序" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "次数" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时费" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维保人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "审核状态" + + cost_map := make(map[string]float64) + for i := 0; i < len(data); i++ { + v := data[i] + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_plan + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Process_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = strconv.Itoa(v.Times) + + cell1 = row.AddCell() + cell1.SetStyle(style) + + pt, _ := strconv.ParseFloat(v.Process_t, 64) + cell1.Value = fmt.Sprintf(`%.2f`, pt*float64(v.Times)*25) + + if _, ok := cost_map[v.Produce_user]; ok { + cost_map[v.Produce_user] += pt * float64(v.Times) * 25 + } else { + cost_map[v.Produce_user] = pt * float64(v.Times) * 25 + } + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Produce_user + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Actual_finished_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.State + } + + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + row = sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时费" + + for key, value := range cost_map { + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = key + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = fmt.Sprintf(`%.2f`, value) + } + + filename = fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + resp.FileId = filename + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_plan_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_done_processes(req get_ma_plan_req) (resp get_ma_plan_resp) { + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var t_data []ma_plan + + var where_sql string + var if_where bool + + // user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and [state] ='已审核' and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [state] ='已审核' and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([state] !='已审核' or [state] is null) and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([state] !='已审核' or [state] is null) and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if if_where { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + + if req.Station != "" { + + if if_where { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` and [station] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` [station] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_plan] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[mcn],[state] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by [acd] desc) order by [acd] desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[mcn],[state] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by [acd] desc) order by [acd] desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var mcn string + var state string + if err := rdRow.Scan(&id, &s, &mcn, &state); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + d.If_warn = 0 + d.Mcn = mcn + + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + } + if len(d.Dispath_date) > 2 { + d.Dispath_date = d.Dispath_date[2:] + } + + if len(d.Repair_quotation_date) > 2 { + d.Repair_quotation_date = d.Repair_quotation_date[2:] + } + + if len(d.Repair_OK_date) > 2 { + d.Repair_OK_date = d.Repair_OK_date[2:] + } + + if len(d.Committed_completed_date) > 2 { + d.Committed_completed_date = d.Committed_completed_date[2:10] + d.Committed_completed_date = strings.ReplaceAll(d.Committed_completed_date, "-", "/") + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + } + + if len(d.Material_committed_date) > 2 { + d.Material_committed_date = d.Material_committed_date[2:] + } + + if len(d.Date_of_issuance) > 2 { + d.Date_of_issuance = d.Date_of_issuance[2:] + } + + if d.Actual_completed_date != "" && d.Committed_completed_date != "" { + if d.Actual_completed_date <= d.Committed_completed_date { + d.Overdue = "否" + } else { + d.Overdue = "是" + } + } else { + d.Overdue = "" + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + } + + if state != "" && d.State == "" { + d.State = state + } + + t_data = append(t_data, d) + + /* + if len(t_data) == 0 { + t_data = append(t_data, d) + } else { + if d.Repairer == t_data[len(t_data)-1].Repairer { + t_data = append(t_data, d) + } else { + //排序 + sort.Slice(t_data, func(i, j int) bool { + return t_data[i].Committed_completed_date > t_data[j].Committed_completed_date + }) + resp.Data = append(resp.Data, t_data...) + + t_data = []ma_plan{} + t_data = append(t_data, d) + } + }*/ + + } else { + logs.Error("get_ma_plan scan Error", err.Error()) + } + } + +exit: + //fmt.Println(t_data) + if len(t_data) > 0 { + sort.Slice(t_data, func(i, j int) bool { + return t_data[i].Actual_completed_date > t_data[j].Actual_completed_date + }) + resp.Data = append(resp.Data, t_data...) + } + return +} + +func get_not_done_processes(req get_ma_plan_req) (resp get_ma_plan_resp) { + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + // user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + //计划必须已处理 + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and [state] ='已审核' and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` [state] ='已审核' and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([state] !='已审核' or [state] is null) and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([state] !='已审核' or [state] is null) and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if if_where { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + "睿控维保" + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + + if req.Station != "" { + + if if_where { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` and [station] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` [station] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_plan] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if req.Sort_field == "" { + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by acd desc) order by acd desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by acd desc) order by acd desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + } else { + var field string + if req.Sort_field == "客户名称" { + field = "[customer]" + } else if req.Sort_field == "负责人" { + field = "[regional_head]" + } else if req.Sort_field == "维修人员" { + field = "[repairer]" + } else if req.Sort_field == "维修状态" { + field = "[rs]" + } else if req.Sort_field == "承诺完成日期" { + field = "[ccd]" + } else { + field = "ID" + } + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by %s desc) order by %s desc", req.Count, (req.Index-1)*req.Count, field, field) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by %s desc) order by %s desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql, field, field) + } + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var if_warn int + var mcn string + if err := rdRow.Scan(&id, &s, &if_warn, &mcn); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + d.Mcn = mcn + + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + } + if len(d.Dispath_date) > 2 { + d.Dispath_date = d.Dispath_date[2:] + } + + if len(d.Repair_quotation_date) > 2 { + d.Repair_quotation_date = d.Repair_quotation_date[2:] + } + + if len(d.Repair_OK_date) > 2 { + d.Repair_OK_date = d.Repair_OK_date[2:] + } + + if len(d.Committed_completed_date) > 2 { + d.Committed_completed_date = d.Committed_completed_date[2:10] + d.Committed_completed_date = strings.ReplaceAll(d.Committed_completed_date, "-", "/") + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + } + + if len(d.Material_committed_date) > 2 { + d.Material_committed_date = d.Material_committed_date[2:] + } + + if len(d.Date_of_issuance) > 2 { + d.Date_of_issuance = d.Date_of_issuance[2:] + } + + if d.Actual_completed_date != "" && d.Committed_completed_date != "" { + if d.Actual_completed_date <= d.Committed_completed_date { + d.Overdue = "否" + } else { + d.Overdue = "是" + } + } else { + d.Overdue = "" + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + } + + if d.State == "" { + d.State = "未审核" + } + + d.If_warn = if_warn + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_ma_plan scan Error", err.Error()) + } + } + +exit: + return +} + +func get_processes(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_processes recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_ma_plan_req + var resp get_ma_plan_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if !req.If_done { //未处理 + resp = get_not_done_processes(req) + } else { + resp = get_done_processes(req) + } + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_processes recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func export_plan_process(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_plan_process recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var filename string + var file *xlsx.File + + var err error + var req get_ma_plan_req + var resp download_file_Resp + var data []ma_plan + + var sqlstr string + var rdRow *sql.Rows + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if user_data.RoleId != 1 { + if if_where { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } else { + if req.Location != "" { + + if if_where { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } + + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[data],[location] from [ma_plan] order by ID desc") + } else { + sqlstr = fmt.Sprintf("select [ID],[data],[location] from [ma_plan] where %s order by ID desc", where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_ma_plan Query err:%v", err.Error())) + return + } + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var location string + if err := rdRow.Scan(&id, &s, &location); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + d.Location = location + data = append(data, d) + } else { + logs.Error("export_ma_plan scan Error", err.Error()) + } + } + rdRow.Close() + + file = xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修单号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工序" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "工时" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维保人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "审核状态" + + for i := 0; i < len(data); i++ { + v := data[i] + + for j := 0; j < len(v.Plan_data); j++ { + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Plan_data[j].Process_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Plan_data[j].Process_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Plan_data[j].Produce_user + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Plan_data[j].Actual_finished_t + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Plan_data[j].State + } + } + + filename = fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + resp.FileId = filename + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_plan_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_p_process_options(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("get_p_process_options recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var sqlstr string + var rdRow *sql.Rows + var err error + + var req get_p_process_options_req + var resp get_p_process_options_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_id == "" { + goto exit + } + + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name],[process_name],[process_t] from [process] where [p_id] ='%s' order by ID desc", req.P_id) + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_p_process_options Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d process_info + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name, &d.Process_name, &d.Process_t); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_p_process_options scan Error", err.Error()) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("get_p_process_options recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func post_rs(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("post_rs recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + + var req post_rs_req + var resp CommonResp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.Oper_type == 1 { + insert_sql := fmt.Sprintf(`INSERT INTO [rs] ([rs]) VALUES ('%s')`, req.State) + _, err = sqlConn.Exec(insert_sql) + if err != nil { + logs.Error(fmt.Sprintf(`post_rs insert err:%s`, err.Error())) + } + } else if req.Oper_type == 2 { + if req.ID == 0 { + goto exit + } + + update_sql := fmt.Sprintf(`UPDATE [rs] SET [rs] = '%s' WHERE ID=%d`, req.State, req.ID) + _, err = sqlConn.Exec(update_sql) + if err != nil { + logs.Error(fmt.Sprintf(`post_rs update err:%s`, err.Error())) + } + } else if req.Oper_type == 3 { + del_sql := fmt.Sprintf(`DELETE FROM [rs] WHERE ID=%d `, req.ID) + _, err = sqlConn.Exec(del_sql) + if err != nil { + logs.Error(fmt.Sprintf(`post_rs del err:%s`, err.Error())) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("post_rs recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_rs(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("get_rs recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var sqlstr string + var rows *sql.Rows + var err error + + var req get_rs_req + var resp get_rs_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.State == "" { + sqlstr = fmt.Sprintf(`SELECT [ID],[rs] FROM [rs] order by ID desc`) + } else { + + likestr := "%" + req.State + "%" + sqlstr = fmt.Sprintf(`SELECT [ID],[rs] FROM [rs] where rs like '%s' order by ID desc`, likestr) + } + + rows, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf(`get_rs query err:%s`, err.Error())) + goto exit + } + + for rows.Next() { + var d Repair_state + if err = rows.Scan(&d.ID, &d.Rs); err == nil { + resp.Data = append(resp.Data, d) + } + + } + rows.Close() + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("get_rs recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func cal_completion_date(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("cal_completion_date recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var sqlstr string + var resp cal_completion_date_resp + var days int + + reqdata, _ := ioutil.ReadAll(request.Body) + var req cal_completion_date_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.Bt == "" { + logs.Info("cal_completion_date req bt 为空") + goto exit + } + + req.Bt = strings.ReplaceAll(req.Bt, "/", "-") + " 00:00:00" + days, _ = strconv.Atoi(req.Days) + if days > 0 { + m := make(map[int]int) + var cnt int + + loc, _ := time.LoadLocation("Local") + bt, _ := time.ParseInLocation(g_time_format, req.Bt, loc) + + fmt.Println(bt.Month()) + id := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + sqlstr = fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, id) + fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("cal_completion_date err:", err.Error()) + goto exit + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + fmt.Println(m) + + for { + + if cnt >= days { + resp.Completion_date = bt.Format(g_time_format) + if len(resp.Completion_date) >= 19 { + resp.Completion_date = resp.Completion_date[:10] + } + break + } + + bt = bt.Add(time.Hour * 24) + key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + + } else if m[key] == 2 { + cnt++ + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + + } else { + cnt++ + } + } + + } + } else { + resp.Completion_date = req.Bt + goto exit + } + +exit: + + if len(resp.Completion_date) >= 19 { + resp.Completion_date = resp.Completion_date[:10] + } + resp.Completion_date = strings.ReplaceAll(resp.Completion_date, "-", "/") + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("cal_completion_date recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func export_ma_plan(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_ma_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var filename string + var file *xlsx.File + + var err error + var req get_ma_plan_req + var resp download_file_Resp + var data []ma_plan + + var sqlstr string + var rdRow *sql.Rows + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + return + } + + user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if req.Bt != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] >= '%s'`, req.Bt) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] >= '%s'`, req.Bt) + if_where = true + } + } + + if req.Et != "" { + + if if_where { + where_sql += fmt.Sprintf(` and [acd] <= '%s'`, req.Et) + if_where = true + } else { + where_sql += fmt.Sprintf(` [acd] <= '%s'`, req.Et) + if_where = true + } + } + + if user_data.RoleId != 1 { + if if_where { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } else { + if req.Location != "" { + + if if_where { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } + + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[data],[location],[mcn] from [ma_plan] order by ID desc") + } else { + sqlstr = fmt.Sprintf("select [ID],[data],[location],[mcn] from [ma_plan] where %s order by ID desc", where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_ma_plan Query err:%v", err.Error())) + return + } + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var location, mcn string + if err := rdRow.Scan(&id, &s, &location, &mcn); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + d.Location = location + d.Mcn = mcn + data = append(data, d) + } else { + logs.Error("export_ma_plan scan Error", err.Error()) + } + } + rdRow.Close() + + file = xlsx.NewFile() + sheet, err := file.AddSheet("sheet1") + if err != nil { + logs.Error("file add sheet err:", err.Error()) + } + + style := xlsx.NewStyle() + font := *xlsx.NewFont(11, "宋体") + style.Font = font + alignment := xlsx.Alignment{ + Horizontal: "center", + Vertical: "center", + } + style.Alignment = alignment + style.ApplyAlignment = true + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维保位置" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "接收日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "下发日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修单号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修合同号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "报告编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "客户名称" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "负责人" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品编号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "产品名称" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "序列号" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修人员" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修方案" + + /*cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "库存"*/ + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "承诺维修日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修报价日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "维修状态" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "确认维修日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "是否维修" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "承诺完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "实际完成日期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "超期" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "报价耗时(天)" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "缺料情况" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "承诺到料" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "物料任务" + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = "总工时" + + for i := 0; i < len(data); i++ { + v := data[i] + + var task string + if v.Material_task != "" { + task = "http://123.54.1.214:10010/redmine/issues/" + v.Material_task + } + + row := sheet.AddRow() + //row.SetHeightCM(1) //设置每行的高度 + cell1 := row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Location + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Recv_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Dispath_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Mcn + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_report_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Customer + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Regional_head + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_id + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_name + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.P_serial + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repairer + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_plan + + /*cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Inventory*/ + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_cycle + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_quotation_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_status + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Repair_OK_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.If_repair + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Committed_completed_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Actual_completed_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Overdue + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Quotation + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Material_status + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Material_committed_date + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = task + + cell1 = row.AddCell() + cell1.SetStyle(style) + cell1.Value = v.Total_work_time + + } + + filename = fmt.Sprintf(`%v.xlsx`, beginTime) + err = file.Save("./file/" + filename) + if err != nil { + logs.Error("xlsx save err:", err.Error()) + } + + resp.FileId = filename + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_ma_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func remove_ma_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("remove_ma_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var userinfo useInfo + + reqdata, _ := ioutil.ReadAll(request.Body) + var req remove_ma_plan_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + userinfo, err = getUserInfo(req.OpUser) + if userinfo.RoleId != 1 { + resp.Ret = 1 + goto exit + } + + if req.ID == 0 { + logs.Info("remove_ma_plan req id ==0") + resp.Ret = -1 + goto exit + } + + sqlstr = fmt.Sprintf(`DELETE FROM [ma_plan] where ID=%d`, req.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("remove_ma_plan err:", err.Error()) + resp.Ret = -1 + goto exit + } + + resp.Ret = 0 + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("remove_ma_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_ma_username(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("get_ma_username recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_ma_username_req + var resp get_ma_username_resp + + var users []useInfo + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + //user_data, _ := getUserInfo(req.OpUser) + + users, _ = get_all_user() + for i := 0; i < len(users); i++ { + if users[i].Username != "孙青山" && users[i].Username != "武杏丽" && users[i].Username != "霍涛" && + users[i].Username != "王真" && users[i].Username != "李俊杉" && users[i].Username != "马纺霞" && + users[i].Username != "温亚辉" && users[i].Username != "尚永强" && users[i].Username != "叶修令" && + users[i].RoleId != 3 { + + if req.Location != "" { + if req.Location == "现场维保" && users[i].Location == "现场维保" { + resp.Data = append(resp.Data, users[i].Username) + } else if req.Location == "睿控维保" && (users[i].Location == "睿控维保" || users[i].Location == "") { + resp.Data = append(resp.Data, users[i].Username) + } + + } else { + resp.Data = append(resp.Data, users[i].Username) + } + } + + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("get_ma_username recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_p_name(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("get_p_name recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_p_name_req + var resp get_p_name_resp + + var sqlstr string + var rdRow *sql.Rows + var err error + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_id != "" { + sqlstr = fmt.Sprintf("select distinct [p_name] from [process] where p_id = '%s' ", req.P_id) + } else { + goto exit + } + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_p_name Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d string + if err := rdRow.Scan(&d); err == nil { + resp.P_name = d + } else { + logs.Error("get_p_name scan Error", err.Error()) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("get_p_name recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_p_id_options(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("get_p_id_options recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_p_id_options_req + var resp get_p_id_options_resp + + var sqlstr string + var rdRow *sql.Rows + var err error + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_like_id != "" { + like_id := "%" + req.P_like_id + "%" + sqlstr = fmt.Sprintf("select distinct [p_id] from [process] where p_id like '%s' ", like_id) + } else { + sqlstr = fmt.Sprintf("select distinct [p_id] from [process] ") + } + + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_p_id_options Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d string + + if err := rdRow.Scan(&d); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_p_id_options scan Error", err.Error()) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("get_p_id_options recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func update_ma_plan_ex1(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("update_ma_plan_ex recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp CommonResp + var rows *sql.Rows + var old_data ma_plan + var location string + var if_exist bool + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req update_ma_plan_req + json.Unmarshal(reqdata, &req) + + var user_info useInfo + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.Plan.ID == 0 { + logs.Info("update_ma_plan_ex sap req id ==0") + resp.Ret = -1 + goto exit + } + + user_info, _ = getUserInfo(req.OpUser) + if req.OpUser != "霍涛" && user_info.RoleId > 1 { + + names := make(map[string]bool) + names[req.Plan.Repairer] = true + + for i := 0; i < len(req.Plan.Plan_data); i++ { + names[req.Plan.Plan_data[i].Produce_user] = true + } + + if _, ok := names[req.OpUser]; !ok { + logs.Info("普通用户不可修改不是自己的计划") + resp.Ret = 1 + goto exit + } + } + + sqlstr = fmt.Sprintf(`select data,[location] from [ma_plan] where ID=%d`, req.Plan.ID) + rows, err = sqlConn.Query(sqlstr) + if err == nil { + for rows.Next() { + var s string + if err = rows.Scan(&s, &location); err == nil { + json.Unmarshal([]byte(s), &old_data) + if_exist = true + } + } + } + + if if_exist { + old_data.Plan_data = []plan_info{} + var wt float64 + for i := 0; i < len(req.Plan.Plan_data); i++ { + v := req.Plan.Plan_data[i] + var d plan_info + d.Actual_finished_t = v.Actual_finished_t + d.ID = v.ID + d.Process_name = v.Process_name + d.Process_t = v.Process_t + d.Produce_user = v.Produce_user + d.State = "已审核" + d.Times = v.Times + + t, _ := strconv.ParseFloat(v.Process_t, 64) + t = t * float64(v.Times) + wt += t + + old_data.Plan_data = append(old_data.Plan_data, d) + } + old_data.Total_work_time = fmt.Sprintf("%.2f", wt) + + //old_data.Total_work_time = req.Plan.Total_work_time + old_data.State = "已审核" + + s, _ := json.Marshal(old_data) + sqlstr = fmt.Sprintf(`UPDATE [ma_plan] SET [data] = '%s',[state] = '%s' WHERE ID=%d`, + string(s), "已审核", + req.Plan.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("update_ma_plan_ex recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func update_ma_plan_ex(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("update_ma_plan_ex recv req begin", time.Now().Format("2006-01-02 15:04:05")) + fmt.Println("123123") + var err error + var sqlstr string + var resp CommonResp + var rows *sql.Rows + var old_data ma_plan + var location string + var if_exist bool + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req update_ma_plan_req + json.Unmarshal(reqdata, &req) + + var user_info useInfo + + // b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + // if !b { + // resp.Ret = -1 + // goto exit + // } + + if req.Plan.ID == 0 { + logs.Info("update_ma_plan_ex sap req id ==0") + resp.Ret = -1 + goto exit + } + + user_info, _ = getUserInfo(req.OpUser) + + sqlstr = fmt.Sprintf(`select data,[location] from [ma_plan] where ID=%d`, req.Plan.ID) + rows, err = sqlConn.Query(sqlstr) + if err == nil { + for rows.Next() { + var s string + if err = rows.Scan(&s, &location); err == nil { + json.Unmarshal([]byte(s), &old_data) + if_exist = true + } + } + } + + if if_exist { + + if user_info.RoleId > 1 { + + names := make(map[string]bool) + names[old_data.Repairer] = true + + for i := 0; i < len(old_data.Plan_data); i++ { + names[old_data.Plan_data[i].Produce_user] = true + } + + if _, ok := names[req.OpUser]; !ok { + logs.Info("普通用户不可修改不是自己的计划") + resp.Ret = 1 + goto exit + } + + if old_data.State == "已审核" { + resp.Ret = 1 + goto exit + } + } + + old_data = req.Plan + + if old_data.Actual_completed_date != "" && old_data.Committed_completed_date != "" { + if old_data.Actual_completed_date <= old_data.Committed_completed_date { + old_data.Overdue = "否" + } else { + old_data.Overdue = "是" + } + } else { + old_data.Overdue = "" + } + + //报价花费时间(天) + if old_data.Repair_quotation_date != "" { + loc, _ := time.LoadLocation("Local") + et, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(old_data.Repair_quotation_date, "/", "-")+" 00:00:00", loc) + bt, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(old_data.Dispath_date, "/", "-")+" 00:00:00", loc) + fmt.Println(et, bt) + + var cnt int + var key int + b_key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + e_key := et.Year()*10000 + int(et.Month())*100 + et.Day() + key = b_key + + m := make(map[int]int) + sqlstr = fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, b_key) + fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex err:", err.Error()) + resp.Ret = -1 + goto exit + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + + if e_key > b_key { + for { + + if key >= e_key { + break + } + + bt = bt.Add(time.Hour * 24) + key = bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + } else if m[key] == 2 { + cnt++ + //fmt.Println(key) + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + } else { + cnt++ + //fmt.Println(key) + } + } + + } + old_data.Quotation = strconv.Itoa(cnt) + } else { + old_data.Quotation = strconv.Itoa(0) + } + + } else { + old_data.Quotation = "未报价" + } + + old_data.If_warn = warn_ma_plan(old_data) + + if true || old_data.Total_work_time == "" { + var wt float64 + for i := 0; i < len(old_data.Plan_data); i++ { + t, _ := strconv.ParseFloat(old_data.Plan_data[i].Process_t, 64) + + t = t * float64(old_data.Plan_data[i].Times) + + wt += t + } + old_data.Total_work_time = fmt.Sprintf("%.2f", wt) + } + + s, _ := json.Marshal(old_data) + fmt.Println("555555") + fmt.Println(string(s)) + sqlstr = fmt.Sprintf(`UPDATE [ma_plan] SET [data] = '%s',[repair_id] = '%s',[p_id] = '%s',[p_name]= '%s',[if_repair]='%s',[rs]='%s',[repairer]='%s',[regional_head]='%s',[ms]='%s',[customer]='%s',[ccd]='%s',[if_warn]=%d,[mcn]='%s',[acd]='%s' WHERE ID=%d`, + string(s), old_data.Repair_id, old_data.P_id, old_data.P_name, + req.Plan.If_repair, req.Plan.Repair_status, + req.Plan.Repairer, req.Plan.Regional_head, req.Plan.Material_status, + req.Plan.Customer, req.Plan.Committed_completed_date, old_data.If_warn, + req.Plan.Mcn, req.Plan.Actual_completed_date, + req.Plan.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + + if location == "睿控维保" { + sqlstr = fmt.Sprintf(`DELETE FROM [dbo].[processes] where [repair_id]='%s'`, old_data.Repair_id) + sqlConn.Exec(sqlstr) + + for i := 0; i < len(old_data.Plan_data); i++ { + v := old_data.Plan_data[i] + sqlstr = fmt.Sprintf(`INSERT INTO [dbo].[processes] + ([repair_id] + ,[p_id] + ,[p_serial] + ,[rp] + ,[serial_id] + ,[produce_plan] + ,[produce_plan_use_t] + ,[produce_user] + ,[p_actual_finished_t] + ,[state] + ,[times]) + VALUES + ('%s' + ,'%s' + ,'%s' + ,'%s' + ,%d + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,%d)`, old_data.Repair_id, old_data.P_id, old_data.P_serial, old_data.Repair_plan, + v.ID, v.Process_name, v.Process_t, v.Produce_user, v.Actual_finished_t, v.State, v.Times) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_ma_plan_ex Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + } + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("update_ma_plan_ex recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func check_ma_plan_warn() { + + sqlstr := fmt.Sprintf("select [ID],[data],[if_warn] from [ma_plan] ") + + rdRow, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("check_ma_plan_warn Query err:%v", err.Error())) + return + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var if_warn int + if err := rdRow.Scan(&id, &s, &if_warn); err == nil { + json.Unmarshal([]byte(s), &d) + if_warn = warn_ma_plan(d) + + sqlstr = fmt.Sprintf(`UPDATE [ma_plan] SET [if_warn]=%d WHERE ID=%d`, + if_warn, id) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("check_ma_plan_warn Exec Error:", err.Error()) + } + + } else { + logs.Error("check_ma_plan_warn scan Error", err.Error()) + } + } +} + +func check_ma_plan_warn_g() { + + tick := time.NewTicker(time.Hour * 1) + check_ma_plan_warn() + + for { + select { + case <-tick.C: + check_ma_plan_warn() + default: + time.Sleep(time.Second * 3) + } + } +} + +func warn_ma_plan(data ma_plan) (if_warn int) { + loc, _ := time.LoadLocation("Local") + //维修报价日期为空 + if data.Repair_quotation_date == "" { + et := time.Now() + bt, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(data.Dispath_date, "/", "-")+" 00:00:00", loc) + if data.ID == 529 { + fmt.Println(et, bt) + } + + var cnt int + var key int + b_key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + e_key := et.Year()*10000 + int(et.Month())*100 + et.Day() + key = b_key + + m := make(map[int]int) + sqlstr := fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, b_key) + fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("warn_ma_plan err:", err.Error()) + return + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + + if e_key > b_key { + for { + + if key >= e_key { + break + } + + bt = bt.Add(time.Hour * 24) + key = bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + } else if m[key] == 2 { + cnt++ + //fmt.Println(key) + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + } else { + cnt++ + //fmt.Println(key) + } + } + + } + if cnt > 5 { + if_warn = 1 + return + } + } + } + + //确认维修日期为空 + if data.Repair_quotation_date != "" && data.Repair_OK_date == "" { + et := time.Now() + bt, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(data.Repair_quotation_date, "/", "-")+" 00:00:00", loc) + if data.ID == 529 { + fmt.Println(et, bt) + } + + var cnt int + var key int + b_key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + e_key := et.Year()*10000 + int(et.Month())*100 + et.Day() + key = b_key + + m := make(map[int]int) + sqlstr := fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, b_key) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("warn_ma_plan err:", err.Error()) + return + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + + if e_key > b_key { + for { + + if key >= e_key { + break + } + + bt = bt.Add(time.Hour * 24) + key = bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + } else if m[key] == 2 { + cnt++ + //fmt.Println(key) + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + } else { + cnt++ + //fmt.Println(key) + } + } + + } + if cnt > 14 { + if_warn = 1 + return + } + } + } + + //发料日期为空 + /*if data.Repair_OK_date != "" && data.Date_of_issuance == "" { + et := time.Now() + bt, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(data.Repair_OK_date, "/", "-")+" 00:00:00", loc) + fmt.Println(et, bt) + + var cnt int + var key int + b_key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + e_key := et.Year()*10000 + int(et.Month())*100 + et.Day() + key = b_key + + m := make(map[int]int) + sqlstr := fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, b_key) + fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("warn_ma_plan err:", err.Error()) + return + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + + if e_key > b_key { + for { + + if key >= e_key { + break + } + + bt = bt.Add(time.Hour * 24) + key = bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + } else if m[key] == 2 { + cnt++ + //fmt.Println(key) + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + } else { + cnt++ + //fmt.Println(key) + } + } + + } + if cnt > 3 { + if_warn = 1 + return + } + } + }*/ + + //承诺完成日期 + if data.Committed_completed_date != "" && data.Actual_completed_date == "" { + bt := time.Now() + et, _ := time.ParseInLocation(g_time_format, strings.ReplaceAll(data.Committed_completed_date, "/", "-")+" 00:00:00", loc) + + if data.ID == 529 { + fmt.Println(et, bt) + } + + var cnt int + var key int + b_key := bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + e_key := et.Year()*10000 + int(et.Month())*100 + et.Day() + key = b_key + + m := make(map[int]int) + sqlstr := fmt.Sprintf(`select [day],[type] FROM [holiday] where [day] >%d `, b_key) + fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Info("warn_ma_plan err:", err.Error()) + return + } + + for rows.Next() { + var day, day_type int + if err = rows.Scan(&day, &day_type); err == nil { + m[day] = day_type + } + } + rows.Close() + + if e_key > b_key { + for { + + if key >= e_key { + break + } + + bt = bt.Add(time.Hour * 24) + key = bt.Year()*10000 + int(bt.Month())*100 + bt.Day() + + if _, ok := m[key]; ok { + //1--假期 2--上班 + if m[key] == 1 { + } else if m[key] == 2 { + cnt++ + //fmt.Println(key) + } + } else { + if int(bt.Weekday()) == 0 || int(bt.Weekday()) == 6 { + } else { + cnt++ + //fmt.Println(key) + } + } + + } + if cnt < 3 { + if_warn = 1 + return + } + } else { + if_warn = 1 + return + } + } + + return +} + +func get_done_ma_plan(req get_ma_plan_req) (resp get_ma_plan_resp) { + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var t_data []ma_plan + + var where_sql string + var if_where bool + + user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if user_data.RoleId != 1 && user_data.RoleId != 3 { + if if_where { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } else { + if req.Location != "" { + + if if_where { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } + + } + + if req.Station != "" { + + if if_where { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` and [station] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` [station] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_plan] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by [acd] desc) order by [acd] desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by [acd] desc) order by [acd] desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var mcn string + if err := rdRow.Scan(&id, &s, &mcn); err == nil { + json.Unmarshal([]byte(s), &d) + d.ID = id + d.If_warn = 0 + d.Mcn = mcn + + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + } + if len(d.Dispath_date) > 2 { + d.Dispath_date = d.Dispath_date[2:] + } + + if len(d.Repair_quotation_date) > 2 { + d.Repair_quotation_date = d.Repair_quotation_date[2:] + } + + if len(d.Repair_OK_date) > 2 { + d.Repair_OK_date = d.Repair_OK_date[2:] + } + + if len(d.Committed_completed_date) > 2 { + d.Committed_completed_date = d.Committed_completed_date[2:10] + d.Committed_completed_date = strings.ReplaceAll(d.Committed_completed_date, "-", "/") + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + } + + if len(d.Material_committed_date) > 2 { + d.Material_committed_date = d.Material_committed_date[2:] + } + + if len(d.Date_of_issuance) > 2 { + d.Date_of_issuance = d.Date_of_issuance[2:] + } + + if d.Actual_completed_date != "" && d.Committed_completed_date != "" { + if d.Actual_completed_date <= d.Committed_completed_date { + d.Overdue = "否" + } else { + d.Overdue = "是" + } + } else { + d.Overdue = "" + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + } + + if len(t_data) == 0 { + t_data = append(t_data, d) + } else { + if d.Repairer == t_data[len(t_data)-1].Repairer { + t_data = append(t_data, d) + } else { + //排序 + sort.Slice(t_data, func(i, j int) bool { + return t_data[i].Committed_completed_date > t_data[j].Committed_completed_date + }) + resp.Data = append(resp.Data, t_data...) + + t_data = []ma_plan{} + t_data = append(t_data, d) + } + } + + } else { + logs.Error("get_ma_plan scan Error", err.Error()) + } + } + +exit: + //fmt.Println(t_data) + if len(t_data) > 0 { + sort.Slice(t_data, func(i, j int) bool { + return t_data[i].Committed_completed_date > t_data[j].Committed_completed_date + }) + resp.Data = append(resp.Data, t_data...) + } + return +} + +func get_not_done_ma_plan(req get_ma_plan_req) (resp get_ma_plan_resp) { + logs.Info("get_not_done_ma_plan-------------") + recordCount := 0 + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + user_data, _ := getUserInfo(req.OpUser) + + if req.ID != "" { + likeStr := "%" + req.ID + "%" + if if_where { + where_sql += fmt.Sprintf(` and [ID] like '%s'`, likeStr) + } else { + where_sql += fmt.Sprintf(` [ID] like '%s'`, likeStr) + } + if_where = true + } + + if req.Rid != "" { + + if if_where { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(` and [repair_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Rid + "%" + where_sql += fmt.Sprintf(`[repair_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.If_done { + + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] ='不维修' or [rs]='维修完成')`) + if_where = true + } + } else { + if if_where { + where_sql += fmt.Sprintf(` and ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } else { + where_sql += fmt.Sprintf(` ([if_repair] !='不维修' and [rs]!='维修完成')`) + if_where = true + } + } + + if req.Repairer != "" { + + if if_where { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` and [repairer] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repairer + "%" + where_sql += fmt.Sprintf(` [repairer] like '%s'`, likeStr) + if_where = true + } + } + + if req.Repair_status != "" { + + if if_where { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` and [rs] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Repair_status + "%" + where_sql += fmt.Sprintf(` [rs] like '%s'`, likeStr) + if_where = true + } + } + + if req.Regional_head != "" { + + if if_where { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` and [regional_head] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Regional_head + "%" + where_sql += fmt.Sprintf(` [regional_head] like '%s'`, likeStr) + if_where = true + } + } + + if req.Material_status != "" { + + if if_where { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` and [ms] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Material_status + "%" + where_sql += fmt.Sprintf(` [ms] like '%s'`, likeStr) + if_where = true + } + } + + if req.Pid != "" { + + if if_where { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` and [p_id] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Pid + "%" + where_sql += fmt.Sprintf(` [p_id] like '%s'`, likeStr) + if_where = true + } + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` [p_name] like '%s'`, likeStr) + if_where = true + } + } + + if user_data.RoleId != 1 && user_data.RoleId != 3 { + if if_where { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + user_data.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } else { + if req.Location != "" { + + if if_where { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` and [location] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Location + "%" + where_sql += fmt.Sprintf(` [location] like '%s'`, likeStr) + if_where = true + } + } + + } + + if req.Station != "" { + + if if_where { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` and [station] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Station + "%" + where_sql += fmt.Sprintf(` [station] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [ma_plan]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [ma_plan] where %s", where_sql) + } + logs.Info("sqlstr---维保计划---", sqlstr) + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_ma_plan scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if req.Sort_field == "" { + + if req.Repair_status == "确认维修" { + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by ccd asc) order by ccd asc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by ccd asc) order by ccd asc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + } else { + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by ID desc) order by ID desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by ID desc) order by ID desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + } + } else { + var field string + if req.Sort_field == "客户名称" { + field = "[customer]" + } else if req.Sort_field == "负责人" { + field = "[regional_head]" + } else if req.Sort_field == "维修人员" { + field = "[repairer]" + } else if req.Sort_field == "维修状态" { + field = "[rs]" + } else if req.Sort_field == "承诺完成日期" { + field = "[ccd]" + } else { + field = "ID" + } + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where ID not in (select top %v ID from [ma_plan] order by %s desc) order by %s desc", req.Count, (req.Index-1)*req.Count, field, field) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[data],[if_warn],[mcn] from [ma_plan] where %s and ID not in (select top %v ID from [ma_plan] where %s order by %s desc) order by %s desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql, field, field) + } + } + logs.Info("sqlstr---维保计划111111111111111---", sqlstr) + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_ma_plan Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + logs.Info("开始遍历查询结果...") + + for rdRow.Next() { + var d ma_plan + var id int + var s string + var if_warn int + var mcn string + logs.Info(fmt.Sprintf("开始处理第 %d 条记录", recordCount+1)) + + if err := rdRow.Scan(&id, &s, &if_warn, &mcn); err == nil { + logs.Info(fmt.Sprintf("成功扫描记录 ID: %d, 数据长度: %d", id, len(s))) + + logs.Info(fmt.Sprintf("开始JSON反序列化, 原始数据前100字符: %.100s", s)) + json.Unmarshal([]byte(s), &d) + logs.Info(fmt.Sprintf("JSON反序列化完成, ID: %d", id)) + d.ID = id + d.Mcn = mcn + + logs.Info(fmt.Sprintf("开始处理日期字段, ID: %d", id)) + if len(d.Recv_date) > 2 { + d.Recv_date = d.Recv_date[2:] + logs.Info(fmt.Sprintf("处理Recv_date: %s", d.Recv_date)) + } + if len(d.Dispath_date) > 2 { + d.Dispath_date = d.Dispath_date[2:] + logs.Info(fmt.Sprintf("处理Dispath_date: %s", d.Dispath_date)) + } + + if len(d.Repair_quotation_date) > 2 { + d.Repair_quotation_date = d.Repair_quotation_date[2:] + logs.Info(fmt.Sprintf("处理Repair_quotation_date: %s", d.Repair_quotation_date)) + } + + if len(d.Repair_OK_date) > 2 { + d.Repair_OK_date = d.Repair_OK_date[2:] + logs.Info(fmt.Sprintf("处理Repair_OK_date: %s", d.Repair_OK_date)) + } + + if len(d.Committed_completed_date) > 2 { + // 修复:确保不会出现切片越界 + endIndex := 10 + if len(d.Committed_completed_date) < 10 { + endIndex = len(d.Committed_completed_date) + } + d.Committed_completed_date = d.Committed_completed_date[2:endIndex] + d.Committed_completed_date = strings.ReplaceAll(d.Committed_completed_date, "-", "/") + logs.Info(fmt.Sprintf("处理Committed_completed_date: %s", d.Committed_completed_date)) + } + + if len(d.Actual_completed_date) > 2 { + d.Actual_completed_date = d.Actual_completed_date[2:] + logs.Info(fmt.Sprintf("处理Actual_completed_date: %s", d.Actual_completed_date)) + } + + if len(d.Material_committed_date) > 2 { + d.Material_committed_date = d.Material_committed_date[2:] + logs.Info(fmt.Sprintf("处理Material_committed_date: %s", d.Material_committed_date)) + } + + if len(d.Date_of_issuance) > 2 { + d.Date_of_issuance = d.Date_of_issuance[2:] + logs.Info(fmt.Sprintf("处理Date_of_issuance: %s", d.Date_of_issuance)) + } + logs.Info(fmt.Sprintf("检查逾期状态, Actual: %s, Committed: %s", d.Actual_completed_date, d.Committed_completed_date)) + if d.Actual_completed_date != "" && d.Committed_completed_date != "" { + if d.Actual_completed_date <= d.Committed_completed_date { + d.Overdue = "否" + } else { + d.Overdue = "是" + } + logs.Info(fmt.Sprintf("逾期判断结果: %s", d.Overdue)) + } else { + d.Overdue = "" + logs.Info("逾期判断: 缺少必要日期数据") + } + + if len(d.Plan_data) == 0 { + d.Plan_data = []plan_info{} + logs.Info(fmt.Sprintf("Plan_data为空, 初始化为空数组")) + } else { + logs.Info(fmt.Sprintf("Plan_data有 %d 条记录", len(d.Plan_data))) + } + + d.If_warn = if_warn + resp.Data = append(resp.Data, d) + recordCount++ + logs.Info(fmt.Sprintf("成功处理第 %d 条记录, 当前resp.Data长度: %d", recordCount, len(resp.Data))) + } else { + logs.Error("get_ma_plan scan Error", err.Error()) + } + } + logs.Info(fmt.Sprintf("记录遍历完成, 总共处理了 %d 条记录", recordCount)) + + logs.Info(fmt.Sprintf("函数返回前, resp.Total: %d, resp.Data长度: %d", resp.Total, len(resp.Data))) + +exit: + return +} + +func get_ma_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_ma_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_ma_plan_req + var resp get_ma_plan_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + logs.Info("是否在线-----------------", b) + if !b { + goto exit + } + logs.Info("req.If_done-----------------", req.If_done) + if !req.If_done { //未处理 + resp = get_not_done_ma_plan(req) + } else { + resp = get_done_ma_plan(req) + } + +exit: + logs.Info("resp-----------------", resp) + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_ma_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func import_ma_temp_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("import_ma_temp_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var flag int + + var reqdata []byte + var req import_ma_temp_plan_Req + var resp CommonResp + var b bool + + ma_temp_plan_lock.Lock() + flag = ma_temp_plan_lock_n + ma_temp_plan_lock.Unlock() + + if flag == 1 { + resp.Ret = 1 + goto exit + } else { + ma_temp_plan_lock.Lock() + ma_temp_plan_lock_n = 1 + ma_temp_plan_lock.Unlock() + } + + reqdata, _ = ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b = checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.OpUser == "王真" || req.OpUser == "刘世界" || req.OpUser == "李俊杉" { + } else { + resp.Ret = -1 + goto exit + } + + for i := 0; i < len(req.Plan); i++ { + + var id int + + sqlstr := fmt.Sprintf(`SELECT ID from [ma_temp_plan] where [return_task]='%s' and [p_id]='%s' and [p_serial]='%s' `, req.Plan[i].Return_task, req.Plan[i].P_id, req.Plan[i].P_serial) + //fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf(`%s err:%s`, sqlstr, err.Error())) + resp.Ret = -1 + goto exit + } + + for rows.Next() { + if err := rows.Scan(&id); err != nil { + logs.Error(fmt.Sprintf(`%s scan err:%s`, sqlstr, err.Error())) + resp.Ret = -1 + goto exit + } + } + rows.Close() + + if id > 0 && req.Plan[i].Repair_type != "天工" { + resp.Ret = 2 + resp.Context = fmt.Sprintf(`维修任务(%s,%s,%s)已存在`, req.Plan[i].Return_task, req.Plan[i].P_id, req.Plan[i].P_serial) + goto exit + } + + req.Plan[i].Recv_date = strings.ReplaceAll(req.Plan[i].Recv_date, "-", "/") + t := strings.Split(req.Plan[i].Recv_date, "/") + if len(t) == 3 { + month, _ := strconv.Atoi(t[1]) + day, _ := strconv.Atoi(t[2]) + req.Plan[i].Recv_date = fmt.Sprintf(`%s/%02d/%02d`, t[0], month, day) + } + + var if_e1 int + if req.Plan[i].If_e1_str == "是" { + req.Plan[i].If_e1 = true + if_e1 = 1 + } + + jdata, _ := json.Marshal(req.Plan[i]) + sqlstr1 := fmt.Sprintf(`INSERT INTO [ma_temp_plan] + ([data] + ,[return_task] + ,[head] + ,[p_id] + ,[p_name] + ,[p_serial] + ,[repairer] + ,[rt] + ,[if_do] + ,[state] + ,[if_e1]) + VALUES + ('%s' + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,'%s' + ,%d + ,'%s',%d)`, string(jdata), req.Plan[i].Return_task, req.Plan[i].Head, req.Plan[i].P_id, req.Plan[i].P_name, + req.Plan[i].P_serial, req.Plan[i].Repairer, req.Plan[i].Repair_type, 0, "", if_e1) + + _, err = sqlConn.Exec(sqlstr1) + if err != nil { + logs.Info("import_ma_temp_plan Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + if resp.Ret != 1 { + ma_temp_plan_lock.Lock() + ma_temp_plan_lock_n = 0 + ma_temp_plan_lock.Unlock() + } + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("import_ma_temp_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func import_ma_plan(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("import_ma_plan recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var flag int + + var reqdata []byte + var req import_ma_plan_Req + var resp CommonResp + var b bool + + var user_data useInfo + + ma_plan_lock.Lock() + flag = ma_plan_lock_n + ma_plan_lock.Unlock() + + if flag == 1 { + resp.Ret = 1 + goto exit + } else { + ma_plan_lock.Lock() + ma_plan_lock_n = 1 + ma_plan_lock.Unlock() + } + + reqdata, _ = ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b = checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + user_data, _ = getUserInfo(req.OpUser) + + for i := 0; i < len(req.Plan); i++ { + var id int + + sqlstr := fmt.Sprintf(`SELECT ID from ma_plan where [repair_id]='%s'`, req.Plan[i].Repair_id) + //fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf(`%s err:%s`, sqlstr, err.Error())) + resp.Ret = -1 + goto exit + } + + for rows.Next() { + if err := rows.Scan(&id); err != nil { + logs.Error(fmt.Sprintf(`%s scan err:%s`, sqlstr, err.Error())) + resp.Ret = -1 + goto exit + } + } + rows.Close() + + if id > 0 { + resp.Ret = 2 + resp.Context = fmt.Sprintf(`维修订单号(%s)已存在`, req.Plan[i].Repair_id) + goto exit + } + + req.Plan[i].Recv_date = strings.ReplaceAll(req.Plan[i].Recv_date, "-", "/") + t := strings.Split(req.Plan[i].Recv_date, "/") + if len(t) == 3 { + month, _ := strconv.Atoi(t[1]) + day, _ := strconv.Atoi(t[2]) + req.Plan[i].Recv_date = fmt.Sprintf(`%s/%02d/%02d`, t[0], month, day) + } + + req.Plan[i].Dispath_date = strings.ReplaceAll(req.Plan[i].Dispath_date, "-", "/") + t = strings.Split(req.Plan[i].Dispath_date, "/") + if len(t) == 3 { + month, _ := strconv.Atoi(t[1]) + day, _ := strconv.Atoi(t[2]) + req.Plan[i].Dispath_date = fmt.Sprintf(`%s/%02d/%02d`, t[0], month, day) + } + + jdata, _ := json.Marshal(req.Plan[i]) + if id == 0 { + sqlstr = fmt.Sprintf(`INSERT INTO [ma_plan] ([data],[repair_id],[p_id],[p_name],[if_repair],[rs] ,[repairer],[regional_head],[ms],[customer],[ccd],[location] ,[if_warn],[station],[mcn]) + VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,'%s','%s')`, string(jdata), req.Plan[i].Repair_id, + req.Plan[i].P_id, req.Plan[i].P_name, + req.Plan[i].If_repair, req.Plan[i].Repair_status, req.Plan[i].Repairer, + req.Plan[i].Regional_head, req.Plan[i].Material_status, + req.Plan[i].Customer, req.Plan[i].Committed_completed_date, + user_data.Location, 0, req.Plan[i].Station, + req.Plan[i].Mcn) + } + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("import_ma_plan Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + if resp.Ret != 1 { + ma_plan_lock.Lock() + ma_plan_lock_n = 0 + ma_plan_lock.Unlock() + } + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("import_ma_plan recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func del_process(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("del_process recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var resp del_p_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + var req del_process_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + for i := 0; i < len(req.Ids); i++ { + + sqlstr := fmt.Sprintf(`DELETE FROM [process] where ID=%d`, req.Ids[i].ID) + fmt.Println(sqlstr) + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("del_process Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("del_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func update_process(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("update_process recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp post_p_resp + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req update_process_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.Data.ID == 0 { + logs.Info("update_process sap req id ==0") + resp.Ret = -1 + goto exit + } + + sqlstr = fmt.Sprintf(`UPDATE [process] SET [process_name] = '%s',[process_t] = '%s' WHERE ID=%d`, + req.Data.Process_name, req.Data.Process_t, req.Data.ID) + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("update_process Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("update_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func import_process(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("import_process recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var p_flag int + + var reqdata []byte + var req import_process_req + var resp import_p_resp + var b bool + + process_lock.Lock() + p_flag = process_lock_n + process_lock.Unlock() + + if p_flag == 1 { + resp.Ret = 1 + goto exit + } else { + process_lock.Lock() + process_lock_n = 1 + process_lock.Unlock() + } + + reqdata, _ = ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b = checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + for i := 0; i < len(req.Data); i++ { + var id int + + sqlstr := fmt.Sprintf(`SELECT ID from process where p_id='%s' and process_name='%s'`, req.Data[i].P_id, req.Data[i].Process_name) + //fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf(`SELECT ID from process where p_id='%s' err:%s`, req.Data[i].P_id, err.Error())) + resp.Ret = -1 + goto exit + } + + for rows.Next() { + if err := rows.Scan(&id); err != nil { + logs.Error(fmt.Sprintf(`SELECT ID from process where p_id='%s' scan err:%s`, req.Data[i].P_id, err.Error())) + resp.Ret = -1 + goto exit + } + } + rows.Close() + + if id == 0 { + sqlstr = fmt.Sprintf(`INSERT INTO [process] ([p_id],[p_name] ,[process_name],[process_t]) + VALUES ('%s','%s','%s','%s')`, req.Data[i].P_id, req.Data[i].P_name, req.Data[i].Process_name, req.Data[i].Process_t) + } else { + sqlstr = fmt.Sprintf(`UPDATE [process] + SET [p_id] = '%s' + ,[p_name]='%s' + ,[process_name] = '%s' + ,[process_t]= '%s' + WHERE ID=%d`, req.Data[i].P_id, req.Data[i].P_name, req.Data[i].Process_name, req.Data[i].Process_t, id) + } + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("import_process Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + if resp.Ret != 1 { + process_lock.Lock() + process_lock_n = 0 + process_lock.Unlock() + } + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("import_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_process(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_process recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_process_req + var resp get_process_resp + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_id != "" { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(`[p_id] like '%s'`, likeStr) + if_where = true + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(`[p_name] like '%s'`, likeStr) + if_where = true + } + } + + if req.Process_name != "" { + + if if_where { + likeStr := "%" + req.Process_name + "%" + where_sql += fmt.Sprintf(` and [process_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.Process_name + "%" + where_sql += fmt.Sprintf(`[process_name] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [process]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [process] where %s", where_sql) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_process query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_process scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[p_id],[p_name],[process_name],[process_t] from [process] where ID not in (select top %v ID from [process] order by ID desc) order by ID desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[p_id],[p_name],[process_name],[process_t] from [process] where %s and ID not in (select top %v ID from [process] where %s order by ID desc) order by ID desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_process Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d process_info + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name, &d.Process_name, &d.Process_t); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_process scan Error", err.Error()) + } + } + +exit: + + jdata, _ := json.Marshal(resp) + //fmt.Println(string(jdata)) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_process recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func download_file(rw http.ResponseWriter, r *http.Request) { + //获取请求参数 + /*var req download_file_req + reqdata, _ := ioutil.ReadAll(r.Body) + json.Unmarshal(reqdata, &req) + + fn := req.Filename*/ + + filename := r.FormValue("id") + base_file_path := modelePath + "/file/" + + if filename != "" { + //设置响应头 + header := rw.Header() + header.Add("Content-Type", "application/octet-stream") + //header.Add("Content-Disposition", "attachment;filename="+fn) + //使用ioutil包读取文件 + filepath := base_file_path + filename + fmt.Println(filepath) + b, _ := ioutil.ReadFile(filepath) + + //写入到响应流中 + rw.Write(b) + } + +} + +func export_sap(response http.ResponseWriter, request *http.Request) { + + beginTime := time.Now().UnixNano() + logs.Info("export_sap recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var csv_data [][]string + var filename string + filename = fmt.Sprintf(`./file/%v.csv`, beginTime) + f, err := os.Create(filename) + if err != nil { + fmt.Println(err) + return + } + defer f.Close() + + var req get_p_Req + var resp download_file_Resp + var data []p_sap + + var sqlstr string + var rdRow *sql.Rows + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_id != "" { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(`[p_id] like '%s'`, likeStr) + if_where = true + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(`[p_name] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name] from [sap] order by ID asc") + } else { + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name] from [sap] where %s order by ID asc", where_sql) + } + //fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("export_sap Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d p_sap + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name); err == nil { + data = append(data, d) + } else { + logs.Error("export_sap scan Error", err.Error()) + } + } + + csv_data = append(csv_data, []string{"产品编号", "产品名称"}) + + for i := 0; i < len(data); i++ { + v := data[i] + + csv_data = append(csv_data, []string{v.P_id, v.P_name}) + } + +exit: + + f.WriteString("\xEF\xBB\xBF") // 写入一个UTF-8 BOM 防止中文乱码 + w := csv.NewWriter(f) //创建一个新的写入文件流 + w.WriteAll(csv_data) + w.Flush() + resp.FileId = fmt.Sprintf(`%v.csv`, beginTime) + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("export_sap recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func import_p(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("import_p recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var p_flag int + + var reqdata []byte + var req import_p_Req + var resp import_p_resp + var b bool + + p_lock.Lock() + p_flag = p_import_f + p_lock.Unlock() + + if p_flag == 1 { + resp.Ret = 1 + goto exit + } else { + p_lock.Lock() + p_import_f = 1 + p_lock.Unlock() + } + + reqdata, _ = ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b = checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + for i := 0; i < len(req.Data); i++ { + var id int + + sqlstr := fmt.Sprintf(`SELECT ID from sap where p_id='%s'`, req.Data[i].P_id) + //fmt.Println(sqlstr) + rows, err := sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf(`SELECT ID from sap where p_id='%s' err:%s`, req.Data[i].P_id, err.Error())) + resp.Ret = -1 + goto exit + } + + for rows.Next() { + if err := rows.Scan(&id); err != nil { + logs.Error(fmt.Sprintf(`SELECT ID from sap where p_id='%s' scan err:%s`, req.Data[i].P_id, err.Error())) + resp.Ret = -1 + goto exit + } + } + rows.Close() + + if id == 0 { + sqlstr = fmt.Sprintf(`INSERT INTO [sap] ([p_id],[p_name]) + VALUES ('%s','%s')`, req.Data[i].P_id, req.Data[i].P_name) + } else { + sqlstr = fmt.Sprintf(`UPDATE [dbo].[sap] + SET [p_id] = '%s' + ,[p_name] = '%s' + WHERE ID=%d`, req.Data[i].P_id, req.Data[i].P_name, id) + } + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("import_p Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + if resp.Ret != 1 { + p_lock.Lock() + p_import_f = 0 + p_lock.Unlock() + } + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("import_p recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func del_p(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("del_p recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var resp del_p_resp + + reqdata, _ := ioutil.ReadAll(request.Body) + var req del_p_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + for i := 0; i < len(req.Ids); i++ { + + sqlstr := fmt.Sprintf(`DELETE FROM [sap] where ID=%d`, req.Ids[i].ID) + fmt.Println(sqlstr) + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("del_p Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + } + + resp.Ret = 0 + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("del_p recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func post_p(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("post_p recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var sqlstr string + var resp post_p_resp + + var jdata []byte + + reqdata, _ := ioutil.ReadAll(request.Body) + var req post_p_req + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if req.OperType == 2 && req.Id == 0 { + logs.Info("post_p sap req id ==0") + resp.Ret = -1 + goto exit + } + + //add op check user for same info + if req.OperType == 1 { + var cnt int + row, err := sqlConn.Query(fmt.Sprintf(`select ID from [sap] where [p_id] = '%s'`, req.P_id)) + if err != nil { + logs.Error(fmt.Sprintf("post_p get sap cnt err:%v", err.Error())) + resp.Ret = -1 + goto exit + } + + for row.Next() { + cnt++ + } + row.Close() + + if cnt > 0 { + resp.Ret = 1 + goto exit + } + } + + if req.OperType == 1 { //add + sqlstr = fmt.Sprintf(`INSERT INTO [sap] ([p_id],[p_name]) VALUES ('%s','%s')`, + req.P_id, req.P_name) + } else if req.OperType == 2 { //update + sqlstr = fmt.Sprintf(`UPDATE [sap] SET [p_id] = '%s',[p_name] = '%s' WHERE ID=%d`, + req.P_id, req.P_name, req.Id) + } else { + resp.Ret = -1 + goto exit + } + fmt.Println(sqlstr) + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("post_p Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + + resp.Ret = 0 + +exit: + + jdata, _ = json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("post_p recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_p(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("get_p recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req get_p_Req + var resp get_p_Resp + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + var where_sql string + var if_where bool + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.P_id != "" { + likeStr := "%" + req.P_id + "%" + where_sql += fmt.Sprintf(`[p_id] like '%s'`, likeStr) + if_where = true + } + + if req.P_name != "" { + + if if_where { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(` and [p_name] like '%s'`, likeStr) + if_where = true + } else { + likeStr := "%" + req.P_name + "%" + where_sql += fmt.Sprintf(`[p_name] like '%s'`, likeStr) + if_where = true + } + } + + if !if_where { + sqlstr = "select count(ID) from [sap]" + } else { + sqlstr = fmt.Sprintf("select count(ID) from [sap] where %s", where_sql) + } + //fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_p query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("get_p scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if !if_where { + sqlstr = fmt.Sprintf("select top %v [ID],[p_id],[p_name] from [sap] where ID not in (select top %v ID from [sap] order by ID desc) order by ID desc", req.Count, (req.Index-1)*req.Count) + } else { + sqlstr = fmt.Sprintf("select top %v [ID],[p_id],[p_name] from [sap] where %s and ID not in (select top %v ID from [sap] where %s order by ID desc) order by ID desc", req.Count, where_sql, (req.Index-1)*req.Count, where_sql) + } + //fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("get_p Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d p_sap + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("get_p scan Error", err.Error()) + } + } + +exit: + + jdata, _ := json.Marshal(resp) + //fmt.Println(string(jdata)) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("get_p recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func get_time_ex(search_time string) (st []string, b bool) { + t := strings.Split(search_time, "-") + if len(t) == 2 { + t0 := strings.Split(t[0], "/") + if len(t0) == 3 { + year, _ := strconv.Atoi(t0[0]) + month, _ := strconv.Atoi(t0[1]) + day, _ := strconv.Atoi(t0[2]) + + t0 := fmt.Sprintf(`20%02d/%02d/%02d`, year, month, day) + st = append(st, t0) + } else { + b = true + } + + t1 := strings.Split(t[1], "/") + if len(t1) == 3 { + year, _ := strconv.Atoi(t1[0]) + month, _ := strconv.Atoi(t1[1]) + day, _ := strconv.Atoi(t1[2]) + + t0 := fmt.Sprintf(`20%02d/%02d/%02d`, year, month, day) + st = append(st, t0) + } else { + b = true + } + + } else if len(t) == 1 { + tt := strings.Split(t[0], "/") + if len(tt) == 3 { + year, _ := strconv.Atoi(tt[0]) + month, _ := strconv.Atoi(tt[1]) + day, _ := strconv.Atoi(tt[2]) + + bt := fmt.Sprintf(`20%02d/%02d/%02d`, year, month, day) + et := fmt.Sprintf(`20%02d/%02d/%02d`, year, month, day) + st = append(st, bt) + st = append(st, et) + } else { + b = true + } + } + + if b { + st = []string{} + } + + return +} + +func get_time(search_time string) (whereSql string) { + t := strings.Split(search_time, "-") + if len(t) == 2 { + var if_where bool + t0 := strings.Split(t[0], "/") + if len(t0) == 2 { + year, _ := strconv.Atoi(t0[0]) + month, _ := strconv.Atoi(t0[1]) + t := (year+2000)*100 + month + whereSql += fmt.Sprintf(` [month] >= %d `, t) + if_where = true + } else if len(t0) == 3 { + year, _ := strconv.Atoi(t0[0]) + month, _ := strconv.Atoi(t0[1]) + day, _ := strconv.Atoi(t0[2]) + + t := fmt.Sprintf(`20%02d-%02d-%02d 00:00:00`, year, month, day) + whereSql += fmt.Sprintf(` [time]>='%s' `, t) + if_where = true + } + + t1 := strings.Split(t[1], "/") + if len(t1) == 2 { + year, _ := strconv.Atoi(t1[0]) + month, _ := strconv.Atoi(t1[1]) + t := (year+2000)*100 + month + if if_where { + whereSql += fmt.Sprintf(` and [month] <= %d `, t) + } else { + whereSql += fmt.Sprintf(` [month] <= %d `, t) + } + } else if len(t1) == 3 { + year, _ := strconv.Atoi(t1[0]) + month, _ := strconv.Atoi(t1[1]) + day, _ := strconv.Atoi(t1[2]) + + t := fmt.Sprintf(`20%02d-%02d-%02d 23:59:59`, year, month, day) + + if if_where { + whereSql += fmt.Sprintf(` and [time]<='%s' `, t) + } else { + whereSql += fmt.Sprintf(` [time]<='%s' `, t) + } + + if_where = true + } + + } else if len(t) == 1 { + tt := strings.Split(t[0], "/") + if len(tt) == 2 { + year, _ := strconv.Atoi(tt[0]) + month, _ := strconv.Atoi(tt[1]) + search_month := (year+2000)*100 + month + whereSql = fmt.Sprintf(` [month] = %d`, search_month) + } else if len(tt) == 3 { + year, _ := strconv.Atoi(tt[0]) + month, _ := strconv.Atoi(tt[1]) + day, _ := strconv.Atoi(tt[2]) + + bt := fmt.Sprintf(`20%02d-%02d-%02d 00:00:00`, year, month, day) + et := fmt.Sprintf(`20%02d-%02d-%02d 23:59:59`, year, month, day) + whereSql = fmt.Sprintf(` [time]>='%s' and [time] <='%s' `, bt, et) + } + } + + return +} + +//用户管理相关接口 + +func getUserNames(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + fmt.Println("getUserNames recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req getUserNamesReq + var resp getUserNamesResp + + var sqlstr string + var rdRow *sql.Rows + var err error + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkUserIfOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + sqlstr = fmt.Sprintf("select [username] from [user] order by ID asc") + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("getUserNames Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var name string + var v usernams + if err := rdRow.Scan(&name); err == nil { + v.Label = name + v.Value = name + resp.Names = append(resp.Names, v) + } else { + logs.Error("getUserNames scan Error", err.Error()) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + fmt.Println(fmt.Sprintf("getUserNames recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func checkIsSysUserOnline(username string, op_uuid string) bool { + + deesUserStatMaplck.RLock() + if v, ok := deesUserStatMap[username]; ok { + deesUserStatMaplck.RUnlock() + + v.RLock() + refreshTime := v.RefreshTime + userrole := v.UserRole + uuid := v.Uuid + v.RUnlock() + if int64(time.Since(refreshTime).Seconds()) > int64(refreshSpan+1) { + return false + } + + if op_uuid != uuid { + return false + } + + if userrole != 1 { + return false + } + + return true + } else { + deesUserStatMaplck.RUnlock() + + return false + } +} + +func postUser(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("postUser recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var roleid int + var err error + var sqlstr string + var resp PostUserResp + var departmentid int + + reqdata, _ := ioutil.ReadAll(request.Body) + var req PostUserReq + json.Unmarshal(reqdata, &req) + + b := checkIsSysUserOnline(req.OpUser, req.OpUserUuid) + if !b { + resp.Ret = -1 + goto exit + } + + if (req.OperType == 2 || req.OperType == 3) && req.Id == 0 { + logs.Info("update userinfo req id ==0") + resp.Ret = -1 + goto exit + } + + //add op check user for same username + if req.OperType == 1 { + var cnt int + row, err := sqlConn.Query(fmt.Sprintf(`select ID from [user] where [username] = '%s'`, req.Username)) + if err != nil { + logs.Error(fmt.Sprintf("postUser get user cnt err:%v", err.Error())) + resp.Ret = -1 + goto exit + } + + for row.Next() { + cnt++ + } + row.Close() + + if cnt > 0 { + resp.Ret = 1 + goto exit + } + } + + roleid = 2 + if req.Role == "管理员" { + roleid = 1 + } else if req.Role == "普通用户" { + roleid = 2 + } else { + roleid = 3 + } + + //1生产 2质检 3供应链 4交付 5研发 6 保温瓶 + /*if req.Department == "生产" { + departmentid = 1 + } else if req.Department == "质检" { + departmentid = 2 + } else if req.Department == "供应链" { + departmentid = 3 + } else if req.Department == "交付" { + departmentid = 4 + } else if req.Department == "研发" { + departmentid = 5 + } else if req.Department == "保温瓶" { + departmentid = 6 + } else if req.Department == "技术" { + departmentid = 7 + } else { + if req.OperType != 3 { + goto exit + } + }*/ + + if req.OperType == 1 { //add + //opType = 10001 + //opContent = fmt.Sprintf(`新增用户%s`, req.Username) + sqlstr = fmt.Sprintf(`INSERT INTO [user] ([username],[password],[role_name],[role_id],[department],[department_id],[state],[location]) VALUES ('%s','%s','%s',%d,'%s',%d,'%s','%s')`, + req.Username, req.Password, req.Role, roleid, req.Department, departmentid, + "", req.Location) + } else if req.OperType == 2 { //update + //opType = 10002 + //opContent = fmt.Sprintf(`修改用户%s`, req.Username) + sqlstr = fmt.Sprintf(`UPDATE [user] SET [username] = '%s',[password] = '%s',[role_name] = '%s',[role_id] = %d,[department]='%s',[department_id]=%d ,[state]='%s',[location]='%s' WHERE ID=%d`, + req.Username, req.Password, req.Role, roleid, req.Department, departmentid, "", + req.Location, + req.Id) + } else if req.OperType == 3 { + //opType = 10003 + // opContent = fmt.Sprintf(`删除用户%s`, req.Username) + sqlstr = fmt.Sprintf(`DELETE FROM [user] WHERE ID=%d`, req.Id) + } else { + resp.Ret = -1 + goto exit + } + fmt.Println(sqlstr) + + _, err = sqlConn.Exec(sqlstr) + if err != nil { + logs.Info("postUser Exec Error:", err.Error()) + resp.Ret = -1 + goto exit + } + + resp.Ret = 0 + +exit: + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("postUser recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func getUsers(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("getUsers recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req getUsersReq + var resp GetUsersResp + + var sqlstr string + var rcnt int + var cntRow *sql.Rows + var rdRow *sql.Rows + var err error + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + b := checkIsSysUserOnline(req.OpUser, req.OpUserUuid) + if !b { + goto exit + } + + if req.Id == "" { + sqlstr = "select count(ID) from [user] " + } else { + likeStr := "%" + req.Id + "%" + sqlstr = fmt.Sprintf("select count(ID) from [user] where [username] like '%s'", likeStr) + } + fmt.Println(sqlstr) + + cntRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("getUsers query %s err:%v", sqlstr, err.Error())) + goto exit + } + defer cntRow.Close() + + for cntRow.Next() { + if err = cntRow.Scan(&rcnt); err != nil { + logs.Error(fmt.Sprintf("getUsers scan %s err:%v", sqlstr, err.Error())) + goto exit + } + } + resp.Total = rcnt + + if req.Id == "" { + sqlstr = fmt.Sprintf("select top %v [ID],[username],[password],[role_name],[role_id],[department] ,[state],[location] from [user] where ID not in (select top %v ID from [user] order by ID asc) order by ID asc", req.Count, (req.Index-1)*req.Count) + } else { + likeStr := "%" + req.Id + "%" + sqlstr = fmt.Sprintf("select top %v [ID],[username],[password],[role_name],[role_id],[department] ,[state],[location] from [user] where username like '%s' and ID not in (select top %v ID from [user] where username like '%s' order by ID asc) order by ID asc", req.Count, likeStr, (req.Index-1)*req.Count, likeStr) + } + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("getUsers Query err:%v", err.Error())) + goto exit + } + defer rdRow.Close() + + for rdRow.Next() { + var d useInfo + + if err := rdRow.Scan(&d.Userid, &d.Username, &d.Password, &d.RoleName, &d.RoleId, + &d.Department, &d.State, &d.Location); err == nil { + resp.Data = append(resp.Data, d) + } else { + logs.Error("getUsers scan Error", err.Error()) + } + } + +exit: + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("getUsers recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func checkUserIfOnline(username string, uuid string) bool { + + deesUserStatMaplck.RLock() + if v, ok := deesUserStatMap[username]; ok { + deesUserStatMaplck.RUnlock() + + v.RLock() + refreshTime := v.RefreshTime + lastuuid := v.Uuid + v.RUnlock() + + if uuid != lastuuid { + return false + } + + if int64(time.Since(refreshTime).Seconds()) > int64(refreshSpan+1) { + return false + } + return true + } else { + deesUserStatMaplck.RUnlock() + + return false + } +} + +func getUserInfo(username string) (d useInfo, err error) { + + var sql string + sql = fmt.Sprintf("select [username],[password],[role_name],[role_id],[department],[department_id] ,[location] from [user] where [username] = '%s'", username) + row, err := sqlConn.Query(sql) + if err != nil { + logs.Info("getUserInfo Query Error", err.Error()) + return + } + + for row.Next() { + + if err = row.Scan(&d.Username, &d.Password, &d.RoleName, &d.RoleId, &d.Department, &d.DepartmentId, + &d.Location); err == nil { + + if d.Location == "" { + d.Location = "睿控维保" + } + } else { + logs.Info("Query Error", err.Error()) + } + } + row.Close() + + return +} + +func get_all_user() (resp []useInfo, err error) { + + var sql string + sql = fmt.Sprintf("select [username],[password],[role_name],[role_id],[department],[department_id],[location],[state] from [user] ") + row, err := sqlConn.Query(sql) + if err != nil { + logs.Info("get_all_user Query Error", err.Error()) + return + } + + for row.Next() { + + var d useInfo + if err = row.Scan(&d.Username, &d.Password, &d.RoleName, &d.RoleId, &d.Department, &d.DepartmentId, + &d.Location, &d.State); err == nil { + resp = append(resp, d) + } else { + logs.Info("get_all_user scan Error", err.Error()) + } + } + row.Close() + + return +} + +// 菜单 +func getMenu(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("getMenu recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var err error + var req GetMenuReq + var resp GetMenuResp + + var menu GetMenuRespData + var mItem menuItem + + var userInfo useInfo + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + ifOnline := checkUserIfOnline(req.UserName, req.Uuid) + if !ifOnline { + goto exit + } + + userInfo, err = getUserInfo(req.UserName) + if err != nil { + goto exit + } + + menu.Title = "计划管理" + menu.Index = "2" + //menu.Class = "el-icon-s-data" + //menu.SvgData.First = "M992.256 960 960 960 960 576.192C960 540.032 931.072 512 895.424 512l-126.784 0C732.352 512 704 540.736 704 576.192L704 960l-64 0L640 64.448C640 28.736 611.072 0 575.424 0L448.576 0C412.352 0 384 28.864 384 64.448L384 960 320 960 320 319.744C320 284.48 291.072 256 255.424 256L128.576 256C92.352 256 64 284.544 64 319.744L64 960 31.744 960C14.464 960 0 974.336 0 992 0 1009.152 14.208 1024 31.744 1024l960.448 0C1009.536 1024 1024 1009.664 1024 992 1024 974.848 1009.792 960 992.256 960z" + menu.SvgData.First = "M955.3 77.1H798.1V59.3c0-16.6-13.4-30-30-30s-30 13.4-30 30v17.8H278.3V59.3c0-16.6-13.4-30-30-30s-30 13.4-30 30v17.8H69.2c-22.1 0-40 17.9-40 40v837.1c0 22.1 17.9 40 40 40h886.1c22.1 0 40-17.9 40-40V117.1c0-22.1-17.9-40-40-40z m-29.9 847.1H99.2V376.4h826.2v547.8z m0-607.8H99.2V137.1h119.1v17.8c0 16.6 13.4 30 30 30s30-13.4 30-30v-17.8h459.9v17.8c0 16.6 13.4 30 30 30s30-13.4 30-30v-17.8h127.2v179.3z" + menu.SvgData.Second = "M470.4 551.3h321.4c18.2 0 33-14.8 33-33s-14.8-33-33-33H470.4c-18.2 0-33 14.8-33 33s14.8 33 33 33zM210.3 562.6l64.8 64.8 110.8-110.8c9.5-9.5 9.5-25 0-34.5s-25-9.5-34.5 0l-76.3 76.3-30.3-30.3c-9.5-9.5-25-9.5-34.5 0s-9.5 25 0 34.5zM470.4 785h321.4c18.2 0 33-14.8 33-33s-14.8-33-33-33H470.4c-18.2 0-33 14.8-33 33s14.8 33 33 33zM316.8 719.2h-67.9c-18.2 0-33 14.8-33 33s14.8 33 33 33h67.9c18.2 0 33-14.8 33-33s-14.8-33-33-33z" + menu.Key = menu.Index + + mItem.Index = "/scb" + mItem.Title = "维保计划" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + + if userInfo.RoleId == 1 || req.UserName == "霍涛" { + mItem.Index = "/mr" + mItem.Title = "维保审核" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + } + + mItem.Index = "/tw" + mItem.Title = "临时工作" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + + resp.MenuData = append(resp.MenuData, menu) + + if userInfo.RoleId == 1 { + menu.Title = "用户管理" + menu.Index = "1" + //menu.Class = "el-icon-user" + menu.SvgData.First = "M955.456 765.12a41.792 41.792 0 0 0-34.368-32.64 8.256 8.256 0 0 1-6.08-3.904 8.256 8.256 0 0 1-0.384-7.104 41.856 41.856 0 0 0-11.136-45.696 165.76 165.76 0 0 0-60.096-34.56 41.728 41.728 0 0 0-45.056 13.12c-1.216 1.472-3.328 3.264-6.336 3.264s-5.12-1.728-6.336-3.264a41.6 41.6 0 0 0-45.056-13.184 166.4 166.4 0 0 0-60.224 34.624 41.728 41.728 0 0 0-11.136 45.632 8.064 8.064 0 0 1-0.384 7.104 8.256 8.256 0 0 1-6.08 3.904 41.728 41.728 0 0 0-34.304 32.64 166.72 166.72 0 0 0 0 68.928c3.584 16.96 17.28 29.952 34.432 32.64 1.92 0.32 4.544 1.216 6.08 3.904a8.256 8.256 0 0 1 0.384 7.104 41.6 41.6 0 0 0 11.136 45.696c17.344 15.616 37.568 27.2 60.096 34.56a41.728 41.728 0 0 0 45.056-13.056c1.216-1.472 3.328-3.264 6.336-3.264s5.12 1.728 6.336 3.264a41.728 41.728 0 0 0 45.056 13.12c22.528-7.296 42.688-18.88 59.968-34.432 12.8-11.52 17.216-29.696 11.136-45.76a8.192 8.192 0 0 1 0.384-7.168 8.256 8.256 0 0 1 6.08-3.904 41.728 41.728 0 0 0 34.496-32.64 166.144 166.144 0 0 0 0-68.928z m-40.832 60.288a49.92 49.92 0 0 0-35.904 24.256 49.92 49.92 0 0 0-3.264 42.752 123.584 123.584 0 0 1-44.992 25.792 49.92 49.92 0 0 0-38.528-18.432 49.664 49.664 0 0 0-38.528 18.432 125.44 125.44 0 0 1-45.056-25.856 49.728 49.728 0 0 0-39.04-66.944 123.712 123.712 0 0 1 0-51.776 49.92 49.92 0 0 0 35.648-24.256 49.92 49.92 0 0 0 3.328-42.624c12.928-11.648 28.224-20.416 45.12-25.92a49.92 49.92 0 0 0 38.528 18.432c15.68 0 29.44-7.296 38.592-18.432 16.896 5.504 32.128 14.272 45.056 25.856a49.728 49.728 0 0 0 39.04 66.944 122.624 122.624 0 0 1 0 51.776z" + menu.SvgData.Second = "M791.936 736.96c-34.496 0-62.592 28.096-62.592 62.592s28.096 62.592 62.592 62.592 62.592-28.096 62.592-62.592-28.096-62.592-62.592-62.592z m0 83.456a20.864 20.864 0 1 1 0-41.728 20.864 20.864 0 0 1 0 41.728zM670.336 588.736c0.256 0.128 0.512 0.064 0.768 0.128l1.472 0.512 0.064-0.256a35.392 35.392 0 0 0 22.912-67.008l-0.384-0.064c-8.512-3.392-17.472-6.144-26.304-9.088a247.424 247.424 0 0 0 104.192-201.472 248.192 248.192 0 1 0-496.384 0c0 83.072 41.216 156.224 103.936 201.28-175.68 57.984-304.832 218.368-315.776 410.688 0 0.128 0.256 0.192 0.256 0.256a35.328 35.328 0 0 0 68.608 13.504c1.344-3.456 1.536-7.04 1.728-10.56l0.256-0.192a390.016 390.016 0 0 1 389.248-366.336c51.264 0 100.032 10.176 144.832 28.16 0.192 0.192 0.32 0.384 0.576 0.448zM347.648 311.424a177.28 177.28 0 1 1 354.56 0 177.28 177.28 0 0 1-354.56 0z" + menu.Key = menu.Index + menu.Items = []menuItem{} + + mItem.Index = "/user" + mItem.Title = "用户信息" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + + resp.MenuData = append(resp.MenuData, menu) + } + + if userInfo.RoleId == 1 { + menu.Title = "数据管理" + menu.Index = "3" + //menu.Class = "el-icon-user" + menu.SvgData.First = "M64 192V896h896V192H64zM0 128h1024v832H0V128z" + menu.SvgData.Second = "M64 384h896v64H64zM64 640h896v64H64zM128 256h192v64H128zM128 512h192v64H128zM128 768h192v64H128z" + menu.Key = menu.Index + menu.Items = []menuItem{} + + /*mItem.Index = "/base_data" + mItem.Title = "产品信息" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + */ + + mItem.Index = "/pf" + mItem.Title = "工序工时" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + + mItem.Index = "/rsm" + mItem.Title = "维修状态" + mItem.Key = mItem.Index + menu.Items = append(menu.Items, mItem) + + resp.MenuData = append(resp.MenuData, menu) + } + +exit: + jdata, _ := json.Marshal(resp) + + _, err = response.Write(jdata) + if err != nil { + logs.Error("getMenu:", err.Error()) + } + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("getMenu recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func checkFileExpired() { + + t := time.NewTicker(time.Minute * 3) + + for { + select { + case <-t.C: + modelePath, err := ModulePath.GetModuleCurrentPath() + if err != nil { + logs.Error("GetModuleCurrentPath() failed err:", err.Error()) + return + } + + fileInfoList, err := ioutil.ReadDir(modelePath + "/file") + if err != nil { + logs.Error("ioutil.ReadDir err:", err.Error()) + } + + for i := range fileInfoList { + index := strings.Index(fileInfoList[i].Name(), ".") + filename := fileInfoList[i].Name()[:index] + //filename := strings.TrimSuffix(fileInfoList[i].Name(), ".auf") + logs.Info(filename) //打印当前文件或目录下的文件或目录名 + + t, err := strconv.ParseInt(filename, 10, 64) + if err == nil { + t = t / 1e9 + + if time.Now().Unix()-t > 60 { + os.Remove(modelePath + "/file/" + fileInfoList[i].Name()) + } + } else { + //logs.Error("checkFileExpired err:", err.Error()) + } + } + + default: + time.Sleep(time.Minute * 1) + } + } +} + +// 登录 +func getUuid() string { + return uuid.NewV4().String() +} + +func refreshUser(response http.ResponseWriter, request *http.Request) { + //beginTime := time.Now().UnixNano() + //logs.Info("refreshUser recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var resp CommonResp + + reqdata, _ := ioutil.ReadAll(request.Body) + var req RefreshUserReq + json.Unmarshal(reqdata, &req) + + deesUserStatMaplck.RLock() + if v, ok := deesUserStatMap[req.Username]; ok { + deesUserStatMaplck.RUnlock() + + v.Lock() + if v.Uuid == req.Uuid { + + if time.Now().Before(v.ExpireTime) { + v.RefreshTime = time.Now() + v.ExpireTime = time.Now().Add(ExpireTimeSpan) + } else { + resp.Ret = -1 + } + + //logs.Info(fmt.Sprintf("refreshTime:%v expiretime:%v", v.RefreshTime.Format("2006-01-02 15:04:05"), v.ExpireTime.Format("2006-01-02 15:04:05"))) + + v.Unlock() + } else { + v.Unlock() + resp.Ret = -1 + + //fmt.Println("uuid:", v.Uuid) + //fmt.Println("req.uuid", req.Uuid) + } + + } else { + deesUserStatMaplck.RUnlock() + + resp.Ret = -1 + } + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + // endTime := time.Now().UnixNano() + //logs.Info(fmt.Sprintf("refreshUser recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func LoginOut(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("LoginOut recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var resp CommonResp + + reqdata, _ := ioutil.ReadAll(request.Body) + var req LoginOutReq + json.Unmarshal(reqdata, &req) + + /* + deesUserStatMaplck.Lock() + if _, ok := deesUserStatMap[req.Username]; ok { + delete(deesUserStatMap, req.Username) + } + deesUserStatMaplck.Unlock() + */ + resp.Ret = 0 + + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("LoginOut recv req end, use time: %v ms", (endTime-beginTime)/1e6)) + +} + +func Login(response http.ResponseWriter, request *http.Request) { + beginTime := time.Now().UnixNano() + logs.Info("Login recv req begin", time.Now().Format("2006-01-02 15:04:05")) + + var req LoginReq + var resp LoginResp + var err error + var uuid string + + reqdata, _ := ioutil.ReadAll(request.Body) + json.Unmarshal(reqdata, &req) + + userinfo, err := getUserInfo(req.Username) + fmt.Println(userinfo) + if err != nil { + resp.Ret = -1 + logs.Error("login::getUserInfo err:", err.Error()) + goto exit + } + + deesUserStatMaplck.RLock() + if v, ok := deesUserStatMap[req.Username]; ok { + deesUserStatMaplck.RUnlock() + + v.RLock() + uuid = v.Uuid + + if time.Now().Before(v.ExpireTime) { + refreshTime := v.RefreshTime + v.RUnlock() + + if int64(time.Since(refreshTime).Seconds()) <= refreshSpan { + resp.Ret = 1 + goto exit + } + + //online user nojust refresh + //... + } else { + v.RUnlock() + } + + uuid = getUuid() + + } else { + deesUserStatMaplck.RUnlock() + + uuid = getUuid() + } + + if req.Password != userinfo.Password { + resp.Ret = -1 + goto exit + } + +exit: + + if resp.Ret == 0 { + + resp.RoleId = userinfo.RoleId + resp.DId = userinfo.DepartmentId + resp.Location = userinfo.Location + + //refresh user state + var v DeesUserStat + v.Username = req.Username + v.RefreshTime = time.Now() + v.ExpireTime = time.Now().Add(ExpireTimeSpan) + v.Uuid = uuid + v.UserRole = userinfo.RoleId + + resp.Uuid = uuid + + deesUserStatMaplck.Lock() + deesUserStatMap[req.Username] = &v + deesUserStatMaplck.Unlock() + } + + resp.Url = "main.html" + jdata, _ := json.Marshal(resp) + fmt.Fprintf(response, string(jdata)) + + endTime := time.Now().UnixNano() + logs.Info(fmt.Sprintf("Login recv req end, use time: %v ms", (endTime-beginTime)/1e6)) +} + +// 跨域测试 +func test(response http.ResponseWriter, request *http.Request) { + fmt.Println("recv test req") + + response.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 + response.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型 + response.Header().Set("content-type", "application/json") //返回数据格式是json + + fmt.Fprintf(response, "3") + +} diff --git a/odbc/LICENSE b/odbc/LICENSE new file mode 100644 index 0000000..6119f54 --- /dev/null +++ b/odbc/LICENSE @@ -0,0 +1,24 @@ +Copyright 2011 Wei guangjing. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer + in the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/odbc/README b/odbc/README new file mode 100644 index 0000000..fb5f36b --- /dev/null +++ b/odbc/README @@ -0,0 +1,32 @@ +ODBC database driver for Go + +Install: + cd $GOPATH/src + git clone git://github.com/weigj/go-odbc.git odbc + cd odbc + go install + +Example: + +package main + +import ( + "odbc" +) + +func main() { + conn, _ := odbc.Connect("DSN=dsn;UID=user;PWD=password") + stmt, _ := conn.Prepare("select * from user where username = ?") + stmt.Execute("admin") + rows, _ := stmt.FetchAll() + for i, row := range rows { + println(i, row) + } + stmt.Close() + conn.Close() +} + +Tested on: + SQL Server 2005 and Windows 7 + SQL Server 2005 and Ubuntu 10.4 (UnixODBC+FreeTDS) + Oracle 10g and Windows 7 \ No newline at end of file diff --git a/odbc/doc.go b/odbc/doc.go new file mode 100644 index 0000000..80e50af --- /dev/null +++ b/odbc/doc.go @@ -0,0 +1,5 @@ +// Copyright (c) 2011, Wei guangjing . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package odbc diff --git a/odbc/driver/README.txt b/odbc/driver/README.txt new file mode 100644 index 0000000..c99516b --- /dev/null +++ b/odbc/driver/README.txt @@ -0,0 +1,32 @@ +Driver for database/sql + +Install: + go install + +Example: + +package main + +import ( + "database/sql" + _ "odbc/driver" + "fmt" +) + +func main() { + db, err := sql.Open("odbc", "DSN=test;") + defer db.Close() + + stmt, err := db.Prepare("select name from table") + defer stmt.Close() + + rows, err := stmt.Query() + defer rows.Close() + + for rows.Next() { + var name string + + _ = rows.Scan(&name) + fmt.Println(name) + } +} \ No newline at end of file diff --git a/odbc/driver/sql.go b/odbc/driver/sql.go new file mode 100644 index 0000000..ad5cf93 --- /dev/null +++ b/odbc/driver/sql.go @@ -0,0 +1,159 @@ +// Copyright (c) 2012, Wei guangjing . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package driver + +import ( + "database/sql" + "database/sql/driver" + "errors" + "io" + + "deescloud/odbc" +) + +func init() { + d := &Driver{} + sql.Register("odbc", d) +} + +type Driver struct { +} + +func (d *Driver) Open(dsn string) (driver.Conn, error) { + c, err := odbc.Connect(dsn) + if err != nil { + return nil, err + } + conn := &conn{c: c} + return conn, nil +} + +func (d *Driver) Close() error { + return nil +} + +type conn struct { + c *odbc.Connection + t *tx +} + +func (c *conn) Prepare(query string) (driver.Stmt, error) { + st, err := c.c.Prepare(query) + if err != nil { + return nil, err + } + + stmt := &stmt{st: st} + return stmt, nil +} + +func (c *conn) Begin() (driver.Tx, error) { + if err := c.c.AutoCommit(false); err != nil { + return nil, err + } + + return &tx{c: c}, nil +} + +func (c *conn) Close() error { + if c.c != nil { + return c.c.Close() + } + return nil +} + +type tx struct { + c *conn +} + +func (t *tx) Commit() error { + err := t.c.c.Commit() + return err +} + +func (t *tx) Rollback() error { + err := t.c.c.Rollback() + return err +} + +type stmt struct { + st *odbc.Statement +} + +func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { + if err := s.st.Execute2(args); err != nil { + return nil, err + } + + rowsAffected, err := s.st.RowsAffected() + r := &result{rowsAffected: int64(rowsAffected)} + return r, err +} + +func (s *stmt) NumInput() int { + return s.st.NumParams() +} + +func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { + //println(args) + if err := s.st.Execute2(args); err != nil { + return nil, err + } + rows := &rows{s: s} + + return rows, nil +} + +func (s *stmt) Close() error { + s.st.Close() + return nil +} + +type result struct { + rowsAffected int64 +} + +func (r *result) LastInsertId() (int64, error) { + return 0, errors.New("not supported") +} + +func (r *result) RowsAffected() (int64, error) { + return r.rowsAffected, nil +} + +type rows struct { + s *stmt +} + +func (r *rows) Columns() []string { + c, err := r.s.st.NumFields() + if err != nil { + return nil + } + columns := make([]string, c) + for i, _ := range columns { + f, err := r.s.st.FieldMetadata(i + 1) + if err != nil { + return nil + } + columns[i] = f.Name + } + return columns +} + +func (r *rows) Close() error { + return r.s.Close() +} + +func (r *rows) Next(dest []driver.Value) error { + eof, err := r.s.st.FetchOne2(dest) + if err != nil { + return err + } + if eof { + return io.EOF + } + return nil +} diff --git a/odbc/make.bash b/odbc/make.bash new file mode 100644 index 0000000..44af607 --- /dev/null +++ b/odbc/make.bash @@ -0,0 +1,4 @@ +#!/bin/bash + +export CGO_LDFLAGS=-lodbc +go install \ No newline at end of file diff --git a/odbc/make.bat b/odbc/make.bat new file mode 100644 index 0000000..bcbff12 --- /dev/null +++ b/odbc/make.bat @@ -0,0 +1,2 @@ +set CGO_LDFLAGS=-lodbc32 +go install \ No newline at end of file diff --git a/odbc/odbc.go b/odbc/odbc.go new file mode 100644 index 0000000..0b8cab0 --- /dev/null +++ b/odbc/odbc.go @@ -0,0 +1,765 @@ +// Copyright (c) 2011, Wei guangjing . All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package odbc + +/* +#cgo darwin LDFLAGS: -lodbc +#cgo freebsd LDFLAGS: -lodbc +#cgo linux LDFLAGS: -lodbc +#cgo windows LDFLAGS: -lodbc32 + +#include +#include + +#ifdef __MINGW32__ + #include +#else + typedef void* HANDLE; +#endif + +#include +#include +#include + +SQLRETURN _SQLColAttribute ( + SQLHSTMT StatementHandle, + SQLUSMALLINT ColumnNumber, + SQLUSMALLINT FieldIdentifier, + SQLPOINTER CharacterAttributePtr, + SQLSMALLINT BufferLength, + SQLSMALLINT * StringLengthPtr, + void * NumericAttributePtr) { + return SQLColAttribute(StatementHandle, + ColumnNumber, + FieldIdentifier, + CharacterAttributePtr, + BufferLength, + StringLengthPtr, + NumericAttributePtr); +} + +*/ +import "C" +import ( + "database/sql/driver" + "fmt" + "reflect" + "time" + "unsafe" +) + +const ( + BUFFER_SIZE = 10 * 1024 + INFO_BUFFER_LEN = 256 +) + +var ( + Genv C.SQLHANDLE +) + +type Connection struct { + Dbc C.SQLHANDLE + connected bool +} + +type Statement struct { + executed bool + prepared bool + scrollable bool + + handle C.SQLHANDLE +} + +type ODBCError struct { + SQLState string + NativeError int + ErrorMessage string +} + +func (e *ODBCError) Error() string { + return e.String() +} + +func (e *ODBCError) String() string { + if e != nil { + return e.SQLState + " " + e.ErrorMessage + } + return "" +} + +func initEnv() (err *ODBCError) { + ret := C.SQLAllocHandle(C.SQL_HANDLE_ENV, nil, &Genv) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_ENV, Genv) + return err + } + ret = C.SQLSetEnvAttr(C.SQLHENV(Genv), C.SQL_ATTR_ODBC_VERSION, C.SQLPOINTER(unsafe.Pointer(uintptr(C.SQL_OV_ODBC3))), C.SQLINTEGER(0)) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_ENV, Genv) + return err + } + return nil +} + +func Connect(dsn string, params ...interface{}) (conn *Connection, err *ODBCError) { + var h C.SQLHANDLE + ret := C.SQLAllocHandle(C.SQL_HANDLE_DBC, Genv, &h) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, h) + return nil, err + } + + var stringLength2 C.SQLSMALLINT + outBuf := make([]byte, BUFFER_SIZE*2) + outConnectionString := (*C.SQLWCHAR)(unsafe.Pointer(&outBuf[0])) + + ret = C.SQLDriverConnectW(C.SQLHDBC(h), + C.SQLHWND(unsafe.Pointer(uintptr(0))), + (*C.SQLWCHAR)(unsafe.Pointer(StringToUTF16Ptr(dsn))), + C.SQL_NTS, + outConnectionString, + BUFFER_SIZE, + &stringLength2, + C.SQL_DRIVER_NOPROMPT) + + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, h) + return nil, err + } + return &Connection{Dbc: h, connected: true}, nil +} + +func (conn *Connection) ExecDirect(sql string) (stmt *Statement, err *ODBCError) { + if stmt, err = conn.newStmt(); err != nil { + return nil, err + } + wsql := StringToUTF16Ptr(sql) + ret := C.SQLExecDirectW(C.SQLHSTMT(stmt.handle), (*C.SQLWCHAR)(unsafe.Pointer(wsql)), C.SQL_NTS) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + stmt.Close() + return nil, err + } + stmt.executed = true + return stmt, nil +} + +func (conn *Connection) newStmt() (*Statement, *ODBCError) { + stmt := &Statement{} + + ret := C.SQLAllocHandle(C.SQL_HANDLE_STMT, conn.Dbc, &stmt.handle) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return nil, err + } + return stmt, nil +} + +func (conn *Connection) Prepare(sql string, params ...interface{}) (*Statement, *ODBCError) { + wsql := StringToUTF16Ptr(sql) + stmt, err := conn.newStmt() + if err != nil { + return nil, err + } + ret := C.SQLPrepareW(C.SQLHSTMT(stmt.handle), (*C.SQLWCHAR)(unsafe.Pointer(wsql)), C.SQLINTEGER(len(sql))) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + stmt.Close() + return nil, err + } + stmt.prepared = true + return stmt, nil +} + +func (conn *Connection) Commit() (err *ODBCError) { + ret := C.SQLEndTran(C.SQL_HANDLE_DBC, conn.Dbc, C.SQL_COMMIT) + if !Success(ret) { + err = FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + } + return +} + +func (conn *Connection) AutoCommit(b bool) (err *ODBCError) { + var n C.int + if b { + n = C.SQL_AUTOCOMMIT_ON + } else { + n = C.SQL_AUTOCOMMIT_OFF + } + ret := C.SQLSetConnectAttr(C.SQLHDBC(conn.Dbc), C.SQL_ATTR_AUTOCOMMIT, C.SQLPOINTER(unsafe.Pointer(uintptr(n))), C.SQL_IS_UINTEGER) + if !Success(ret) { + err = FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + } + return +} + +func (conn *Connection) BeginTransaction() (err *ODBCError) { + ret := C.SQLSetConnectAttr(C.SQLHDBC(conn.Dbc), C.SQL_ATTR_AUTOCOMMIT, C.SQLPOINTER(unsafe.Pointer(uintptr(C.SQL_AUTOCOMMIT_OFF))), C.SQL_IS_UINTEGER) + if !Success(ret) { + err = FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + } + return +} + +func (conn *Connection) Rollback() (err *ODBCError) { + ret := C.SQLEndTran(C.SQL_HANDLE_DBC, conn.Dbc, C.SQL_ROLLBACK) + if !Success(ret) { + err = FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + } + return +} + +func (conn *Connection) ServerInfo() (string, string, string, *ODBCError) { + var info_len C.SQLSMALLINT + p := make([]byte, INFO_BUFFER_LEN) + ret := C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_DATABASE_NAME, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return "", "", "", err + } + db := string(p[0:info_len]) + ret = C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_DBMS_VER, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return db, "", "", err + } + ver := string(p[0:info_len]) + ret = C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_SERVER_NAME, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return db, ver, "", err + } + server := string(p[0:info_len]) + return db, ver, server, nil +} + +func (conn *Connection) ClientInfo() (string, string, string, *ODBCError) { + var info_len C.SQLSMALLINT + p := make([]byte, INFO_BUFFER_LEN) + ret := C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_DRIVER_NAME, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return "", "", "", err + } + drv_name := string(p[0:info_len]) + ret = C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_DRIVER_ODBC_VER, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return "", "", "", err + } + drv_odbc_ver := string(p[0:info_len]) + ret = C.SQLGetInfo(C.SQLHDBC(conn.Dbc), C.SQL_DRIVER_VER, C.SQLPOINTER(unsafe.Pointer(&p[0])), INFO_BUFFER_LEN, &info_len) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return "", "", "", err + } + drv_ver := string(p[0:info_len]) + return drv_name, drv_odbc_ver, drv_ver, nil +} + +func (conn *Connection) Close() *ODBCError { + if conn.connected { + ret := C.SQLDisconnect(C.SQLHDBC(conn.Dbc)) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return err + } + ret = C.SQLFreeHandle(C.SQL_HANDLE_DBC, conn.Dbc) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_DBC, conn.Dbc) + return err + } + conn.connected = false + } + return nil +} + +/* func (stmt *Statement) RowsAffected() (int, *ODBCError) + +修改成func (stmt *Statement) RowsAffected() (int, error) + +*/ +func (stmt *Statement) RowsAffected() (int, error) { + var nor C.SQLLEN + ret := C.SQLRowCount(C.SQLHSTMT(stmt.handle), &nor) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return -1, err + } + return int(nor), nil +} + +func (stmt *Statement) Cancel() *ODBCError { + ret := C.SQLCancel(C.SQLHSTMT(stmt.handle)) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + return nil +} + +func (stmt *Statement) NumParams() int { + var cParams C.SQLSMALLINT + ret := C.SQLNumParams(C.SQLHSTMT(stmt.handle), &cParams) + if !Success(ret) { + return -1 + } + return int(cParams) +} + +func (stmt *Statement) Execute(params ...interface{}) *ODBCError { + if params != nil { + var cParams C.SQLSMALLINT + ret := C.SQLNumParams(C.SQLHSTMT(stmt.handle), &cParams) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + for i := 0; i < int(cParams); i++ { + stmt.BindParam(i+1, params[i]) + } + } + ret := C.SQLExecute(C.SQLHSTMT(stmt.handle)) + if ret == C.SQL_NEED_DATA { + // TODO + // send_data(stmt) + } else if ret == C.SQL_NO_DATA { + // Execute NO DATA + } else if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + stmt.executed = true + return nil +} + +func (stmt *Statement) Execute2(params []driver.Value) *ODBCError { + if params != nil { + var cParams C.SQLSMALLINT + ret := C.SQLNumParams(C.SQLHSTMT(stmt.handle), &cParams) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + for i := 0; i < int(cParams); i++ { + stmt.BindParam(i+1, params[i]) + } + } + ret := C.SQLExecute(C.SQLHSTMT(stmt.handle)) + if ret == C.SQL_NEED_DATA { + // TODO + // send_data(stmt) + } else if ret == C.SQL_NO_DATA { + // Execute NO DATA + } else if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + stmt.executed = true + return nil +} + +func (stmt *Statement) Fetch() (bool, *ODBCError) { + ret := C.SQLFetch(C.SQLHSTMT(stmt.handle)) + if ret == C.SQL_NO_DATA { + return false, nil + } + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return false, err + } + return true, nil +} + +type Row struct { + Data []interface{} +} + +// Get(Columnindex) +// TODO Get(ColumnName) +func (r *Row) Get(a interface{}) interface{} { + value := reflect.ValueOf(a) + switch f := value; f.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return r.Data[f.Int()] + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + return r.Data[f.Uint()] + // case *reflect.StringValue: + // i := r.Meta[f.Get()] + // return r.Data[i] + } + return nil +} + +func (r *Row) GetInt(a interface{}) (ret int64) { + v := r.Get(a) + value := reflect.ValueOf(v) + switch f := value; f.Kind() { + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + ret = int64(f.Int()) + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: + ret = int64(f.Uint()) + } + return +} + +func (r *Row) GetFloat(a interface{}) (ret float64) { + v := r.Get(a) + value := reflect.ValueOf(v) + switch f := value; f.Kind() { + case reflect.Float32, reflect.Float64: + ret = float64(f.Float()) + } + return +} + +func (r *Row) GetString(a interface{}) (ret string) { + v := r.Get(a) + value := reflect.ValueOf(v) + switch f := value; f.Kind() { + case reflect.String: + ret = f.String() + } + return +} + +func (r *Row) Length() int { + return len(r.Data) +} + +func (stmt *Statement) FetchAll() (rows []*Row, err *ODBCError) { + for { + row, err := stmt.FetchOne() + if err != nil || row == nil { + break + } + rows = append(rows, row) + } + + return rows, err +} + +func (stmt *Statement) FetchOne() (*Row, *ODBCError) { + ok, err := stmt.Fetch() + if !ok { + return nil, err + } + n, _ := stmt.NumFields() + row := new(Row) + row.Data = make([]interface{}, n) + for i := 0; i < n; i++ { + v, _, _, _ := stmt.GetField(i) + row.Data[i] = v + } + return row, nil +} + +func (stmt *Statement) FetchOne2(row []driver.Value) (eof bool, err *ODBCError) { + ok, err := stmt.Fetch() + if !ok && err == nil { + return !ok, nil + } else if err != nil { + return false, err + } + n, _ := stmt.NumFields() + for i := 0; i < n; i++ { + v, _, _, _ := stmt.GetField(i) + row[i] = v + } + + //fmt.Println("row:", row) + return false, nil +} + +func (stmt *Statement) GetField(field_index int) (v interface{}, ftype int, flen int, err *ODBCError) { + var field_type C.int + var field_len C.SQLLEN + var ll C.SQLSMALLINT + ret := C._SQLColAttribute(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_DESC_CONCISE_TYPE, C.SQLPOINTER(unsafe.Pointer(uintptr(0))), C.SQLSMALLINT(0), &ll, unsafe.Pointer(&field_type)) + if !Success(ret) { + // TODO return err + } + ret = C._SQLColAttribute(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_DESC_LENGTH, C.SQLPOINTER(unsafe.Pointer(uintptr(0))), C.SQLSMALLINT(0), &ll, unsafe.Pointer(&field_len)) + if !Success(ret) { + // TODO return err + } + var fl C.SQLLEN = C.SQLLEN(field_len) + switch int(field_type) { + case C.SQL_BIT: + var value C.BYTE + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_BIT, C.SQLPOINTER(unsafe.Pointer(&value)), 0, &fl) + if fl == -1 { + v = byte(0) + } else { + v = byte(value) + } + case C.SQL_INTEGER, C.SQL_SMALLINT, C.SQL_TINYINT: + var value C.long + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_LONG, C.SQLPOINTER(unsafe.Pointer(&value)), 0, &fl) + if fl == -1 { + v = byte(0) + } else { + v = int(value) + } + case C.SQL_BIGINT: + var value C.longlong + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_SBIGINT, C.SQLPOINTER(unsafe.Pointer(&value)), 0, &fl) + if fl == -1 { + v = int64(0) + } else { + v = int64(value) + } + case C.SQL_FLOAT, C.SQL_REAL, C.SQL_DOUBLE: + var value C.double + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_DOUBLE, C.SQLPOINTER(unsafe.Pointer(&value)), 0, &fl) + if fl == -1 { + v = float64(0) + } else { + v = float64(value) + } + case C.SQL_CHAR, C.SQL_VARCHAR, C.SQL_LONGVARCHAR, C.SQL_WCHAR, C.SQL_WVARCHAR, C.SQL_WLONGVARCHAR: + value := make([]uint16, int(field_len)+8) + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_WCHAR, C.SQLPOINTER(unsafe.Pointer(&value[0])), field_len+4, &fl) + s := UTF16ToString(value) + v = s + case C.SQL_TYPE_TIMESTAMP, C.SQL_TYPE_DATE, C.SQL_TYPE_TIME, C.SQL_DATETIME: + var value C.TIMESTAMP_STRUCT + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_TYPE_TIMESTAMP, C.SQLPOINTER(unsafe.Pointer(&value)), C.SQLLEN(unsafe.Sizeof(value)), &fl) + if fl == -1 { + v = nil + } else { + v = time.Date(int(value.year), time.Month(value.month), int(value.day), int(value.hour), int(value.minute), int(value.second), int(value.fraction), time.UTC) + } + case C.SQL_BINARY, C.SQL_VARBINARY, C.SQL_LONGVARBINARY: + var vv int + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_BINARY, C.SQLPOINTER(unsafe.Pointer(&vv)), 0, &fl) + if fl == -1 { + v = nil + } else { + value := make([]byte, fl) + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_BINARY, C.SQLPOINTER(unsafe.Pointer(&value[0])), C.SQLLEN(fl), &fl) + v = value + } + default: + value := make([]byte, field_len) + ret = C.SQLGetData(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(field_index+1), C.SQL_C_BINARY, C.SQLPOINTER(unsafe.Pointer(&value[0])), field_len, &fl) + v = value + } + if !Success(ret) { + err = FormatError(C.SQL_HANDLE_STMT, stmt.handle) + } + return v, int(field_type), int(fl), err +} + +func (stmt *Statement) NumFields() (int, *ODBCError) { + var NOC C.SQLSMALLINT + ret := C.SQLNumResultCols(C.SQLHSTMT(stmt.handle), &NOC) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return -1, err + } + return int(NOC), nil +} + +func (stmt *Statement) GetParamType(index int) (int, int, int, int, *ODBCError) { + var data_type, dec_ptr, null_ptr C.SQLSMALLINT + var size_ptr C.SQLULEN + ret := C.SQLDescribeParam(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(index), &data_type, &size_ptr, &dec_ptr, &null_ptr) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return -1, -1, -1, -1, err + } + return int(data_type), int(size_ptr), int(dec_ptr), int(null_ptr), nil +} + +func (stmt *Statement) BindParam(index int, param interface{}) *ODBCError { + var ValueType C.SQLSMALLINT + var ParameterType C.SQLSMALLINT + var ColumnSize C.SQLULEN + var DecimalDigits C.SQLSMALLINT + var ParameterValuePtr C.SQLPOINTER + var BufferLength C.SQLLEN + var StrLen_or_IndPt C.SQLLEN + v := reflect.ValueOf(param) + if param == nil { + ft, _, _, _, err := stmt.GetParamType(index) + if err != nil { + return err + } + ParameterType = C.SQLSMALLINT(ft) + if ParameterType == C.SQL_UNKNOWN_TYPE { + ParameterType = C.SQL_VARCHAR + } + ValueType = C.SQL_C_DEFAULT + StrLen_or_IndPt = C.SQL_NULL_DATA + ColumnSize = 1 + } else { + switch v.Kind() { + case reflect.Bool: + ParameterType = C.SQL_BIT + ValueType = C.SQL_C_BIT + var b [1]byte + if v.Bool() { + b[0] = 1 + } else { + b[0] = 0 + } + ParameterValuePtr = C.SQLPOINTER(unsafe.Pointer(&b[0])) + BufferLength = 1 + StrLen_or_IndPt = 0 + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + switch v.Type().Kind() { + case reflect.Int: + case reflect.Int8, reflect.Int16, reflect.Int32: + ParameterType = C.SQL_INTEGER + ValueType = C.SQL_C_LONG + var l C.long = C.long(v.Int()) + ParameterValuePtr = C.SQLPOINTER(unsafe.Pointer(&l)) + BufferLength = 4 + StrLen_or_IndPt = 0 + case reflect.Int64: + ParameterType = C.SQL_BIGINT + ValueType = C.SQL_C_SBIGINT + var ll C.longlong = C.longlong(v.Int()) + ParameterValuePtr = C.SQLPOINTER(unsafe.Pointer(&ll)) + BufferLength = 8 + StrLen_or_IndPt = 0 + } + case reflect.Float32, reflect.Float64: + ParameterType = C.SQL_DOUBLE + ValueType = C.SQL_C_DOUBLE + var d C.double = C.double(v.Float()) + ParameterValuePtr = C.SQLPOINTER(unsafe.Pointer(&d)) + BufferLength = 8 + StrLen_or_IndPt = 0 + case reflect.Complex64, reflect.Complex128: + case reflect.String: + var slen C.SQLUINTEGER = C.SQLUINTEGER(len(v.String())) + ParameterType = C.SQL_VARCHAR + ValueType = C.SQL_C_CHAR + s := []byte(v.String()) + ParameterValuePtr = C.SQLPOINTER(unsafe.Pointer(&s[0])) + ColumnSize = C.SQLULEN(slen) + BufferLength = C.SQLLEN(slen + 1) + StrLen_or_IndPt = C.SQLLEN(slen) + default: + fmt.Println("Not support type", v) + } + } + ret := C.SQLBindParameter(C.SQLHSTMT(stmt.handle), C.SQLUSMALLINT(index), C.SQL_PARAM_INPUT, ValueType, ParameterType, ColumnSize, DecimalDigits, ParameterValuePtr, BufferLength, &StrLen_or_IndPt) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return err + } + + return nil +} + +func (stmt *Statement) NextResult() bool { + ret := C.SQLMoreResults(C.SQLHSTMT(stmt.handle)) + if ret == C.SQL_NO_DATA { + return false + } + return true +} + +func (stmt *Statement) NumRows() (int, *ODBCError) { + var NOR C.SQLLEN + ret := C.SQLRowCount(C.SQLHSTMT(stmt.handle), &NOR) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return -1, err + } + return int(NOR), nil +} + +func (stmt *Statement) HasRows() bool { + n, _ := stmt.NumRows() + return n > 0 +} + +type Field struct { + Name string + Type int + Size int + DecimalDigits int + Nullable int +} + +func (stmt *Statement) FieldMetadata(col int) (*Field, *ODBCError) { + var BufferLength C.SQLSMALLINT = INFO_BUFFER_LEN + var NameLength C.SQLSMALLINT + var DataType C.SQLSMALLINT + var ColumnSize C.SQLULEN + var DecimalDigits C.SQLSMALLINT + var Nullable C.SQLSMALLINT + ColumnName := make([]byte, INFO_BUFFER_LEN) + ret := C.SQLDescribeCol(C.SQLHSTMT(stmt.handle), + C.SQLUSMALLINT(col), + (*C.SQLCHAR)(unsafe.Pointer(&ColumnName[0])), + BufferLength, + &NameLength, + &DataType, + &ColumnSize, + &DecimalDigits, + &Nullable) + if !Success(ret) { + err := FormatError(C.SQL_HANDLE_STMT, stmt.handle) + return nil, err + } + field := &Field{string(ColumnName[0:NameLength]), int(DataType), int(ColumnSize), int(DecimalDigits), int(Nullable)} + return field, nil +} + +func (stmt *Statement) free() { + if stmt.handle != nil { + C.SQLFreeHandle(C.SQL_HANDLE_STMT, stmt.handle) + stmt.handle = nil + } +} + +func (stmt *Statement) Close() { + stmt.free() +} + +func Success(ret C.SQLRETURN) bool { + return int(ret) == C.SQL_SUCCESS || int(ret) == C.SQL_SUCCESS_WITH_INFO +} + +func FormatError(ht C.SQLSMALLINT, h C.SQLHANDLE) (err *ODBCError) { + sqlState := make([]uint16, 6) + var nativeError C.SQLINTEGER + messageText := make([]uint16, C.SQL_MAX_MESSAGE_LENGTH) + var textLength C.SQLSMALLINT + err = &ODBCError{} + i := 0 + for { + i++ + ret := C.SQLGetDiagRecW(C.SQLSMALLINT(ht), + h, + C.SQLSMALLINT(i), + (*C.SQLWCHAR)(unsafe.Pointer(&sqlState[0])), + &nativeError, + (*C.SQLWCHAR)(unsafe.Pointer(&messageText[0])), + C.SQL_MAX_MESSAGE_LENGTH, + &textLength) + if ret == C.SQL_INVALID_HANDLE || ret == C.SQL_NO_DATA { + break + } + if i == 1 { // first error message save the SQLSTATE. + err.SQLState = UTF16ToString(sqlState) + err.NativeError = int(nativeError) + } + err.ErrorMessage += UTF16ToString(messageText) + } + + return err +} + +func init() { + if err := initEnv(); err != nil { + panic("odbc init env error!" + err.String()) + } +} diff --git a/odbc/util.go b/odbc/util.go new file mode 100644 index 0000000..0514f58 --- /dev/null +++ b/odbc/util.go @@ -0,0 +1,25 @@ +package odbc + +import ( + "unicode/utf16" +) + +// StringToUTF16 returns the UTF-16 encoding of the UTF-8 string s, +// with a terminating NUL added. +func StringToUTF16(s string) []uint16 { return utf16.Encode([]rune(s + "\x00")) } + +// UTF16ToString returns the UTF-8 encoding of the UTF-16 sequence s, +// with a terminating NUL removed. +func UTF16ToString(s []uint16) string { + for i, v := range s { + if v == 0 { + s = s[0:i] + break + } + } + return string(utf16.Decode(s)) +} + +// StringToUTF16Ptr returns pointer to the UTF-16 encoding of +// the UTF-8 string s, with a terminating NUL added. +func StringToUTF16Ptr(s string) *uint16 { return &StringToUTF16(s)[0] } diff --git a/req.go b/req.go new file mode 100644 index 0000000..1c3e2ee --- /dev/null +++ b/req.go @@ -0,0 +1,301 @@ +package main + +type approval_provesses_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + ID int `json:"id"` + + Rid string `json:"rid"` + Serial_id int `json:"serial_id"` //工序序号 + + Undo bool `json:"undo"` +} + +type get_processes_resp struct { + Data []get_processes_resp_data `json:"data"` + Total int `json:"total"` +} + +type get_processes_resp_data struct { + ID int `json:"id"` //序号 + Repair_id string `json:"repair_id"` //维修订单号 + P_id string `json:"p_id"` //产品编号 + P_serial string `json:"p_serial"` //产品序列号 + Repair_plan string `json:"rp"` //维修方案 + + Serial_id int `json:"serial_id"` //工序序号 + Process_name string `json:"produce_plan"` + Process_t string `json:"produce_plan_use_t"` + Produce_user string `json:"produce_user"` + + Actual_finished_t string `json:"p_actual_finished_t"` + + State string `json:"state"` //已审核 未审核 + + Times int `json:"times"` + + Work string `json:"work"` //工作内容 + Work_h string `json:"work_h"` //天工时长 + + Head string `json:"head"` //负责人 +} + +type get_processes_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Index int `json:"index"` + Count int `json:"count"` + ID string `json:"id"` + Rid string `json:"rid"` + If_done bool `json:"if_done"` //已处理 + + Repairer string `json:"repairer"` //维修人员 + Repair_status string `json:"rs"` //维修状态 + Regional_head string `json:"regional_head"` //区域负责人 + Material_status string `json:"ms"` //缺料情况 + + Sort_field string `json:"sort_field"` //排序字段 + + Location string `json:"location"` + + Pid string `json:"pid"` + P_name string `json:"pname"` + + Station string `json:"station"` +} + +type get_p_process_options_resp struct { + Data []process_info `json:"data"` +} + +type get_p_process_options_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + P_id string `json:"pid"` +} + +type post_rs_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + ID int `json:"id"` + State string `json:"rs"` + Oper_type int `json:"oper_type"` +} + +type get_rs_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + State string `json:"state"` +} + +type cal_completion_date_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Bt string `json:"bt"` + Days string `json:"days"` +} + +type remove_ma_plan_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + ID int `json:"id"` +} + +type get_ma_username_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + + Location string `json:"location"` +} + +type get_p_name_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + P_id string `json:"p_id"` +} + +type get_p_id_options_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + P_like_id string `json:"p_like_id"` +} + +type update_ma_temp_plan_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Plan ma_temp_plan `json:"data"` +} + +type update_ma_plan_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Plan ma_plan `json:"data"` +} + +type get_ma_temp_plan_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Index int `json:"index"` + Count int `json:"count"` + ID string `json:"id"` + Rid string `json:"rid"` //rdm号 + + Head string `json:"head"` //负责人 + P_id string `json:"p_id"` //产品编号 + P_name string `json:"p_name"` //产品名称 + P_serial string `json:"p_serial"` //产品序列号 + + Repairer string `json:"repairer"` //维修人员 + Repair_type string `json:"rt"` //维修类型 + + If_done bool `json:"if_done"` //已处理 + + If_e1 bool `json:"if_e1"` +} + +type get_ma_plan_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Index int `json:"index"` + Count int `json:"count"` + ID string `json:"id"` + Rid string `json:"rid"` + If_done bool `json:"if_done"` //已处理 + + Repairer string `json:"repairer"` //维修人员 + Repair_status string `json:"rs"` //维修状态 + Regional_head string `json:"regional_head"` //区域负责人 + Material_status string `json:"ms"` //缺料情况 + + Sort_field string `json:"sort_field"` //排序字段 + + Location string `json:"location"` + + Pid string `json:"pid"` + P_name string `json:"pname"` + + Station string `json:"station"` + + Bt string `json:"bt"` + Et string `json:"et"` +} + +type import_ma_temp_plan_Req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Plan []ma_temp_plan `json:"plan"` +} + +type import_ma_plan_Req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Plan []ma_plan `json:"plan"` +} + +type del_process_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Ids []process_info `json:"ids"` +} + +type update_process_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Data process_info `json:"data"` +} + +type import_process_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Data []process_info `json:"data"` +} + +type get_process_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` + Process_name string `json:"process_name"` + Index int `json:"index"` + Count int `json:"count"` +} + +type import_p_Req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Data []p_sap `json:"data"` +} + +type del_p_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Ids []p_sap `json:"ids"` +} + +type post_p_req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Id int `json:"id"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` + OperType int `json:"oper_type"` +} + +type get_p_Req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` + Index int `json:"index"` + Count int `json:"count"` +} + +type download_template_file_Req struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` +} + +type getUserNamesReq struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` +} + +type PostUserReq struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Id int `json:"id"` + Username string `json:"username"` + Password string `json:"password"` + Role string `json:"role"` + Department string `json:"department"` + OperType int `json:"oper_type"` + State string `json:"state"` + Location string `json:"location"` +} + +type getUsersReq struct { + OpUser string `json:"opuser"` + OpUserUuid string `json:"opuser_uuid"` + Id string `json:"id"` + Index int `json:"index"` + Count int `json:"count"` +} + +type GetMenuReq struct { + UserName string `json:"username"` + Uuid string `json:"uuid"` +} + +type LoginOutReq struct { + Username string `json:"username"` +} + +type RefreshUserReq struct { + Uuid string `json:"uuid"` + Username string `json:"username"` +} + +type LoginReq struct { + Username string `json:"username"` + Password string `json:"password"` +} diff --git a/res.go b/res.go new file mode 100644 index 0000000..e75c392 --- /dev/null +++ b/res.go @@ -0,0 +1,160 @@ +package main + +type get_rs_resp struct { + Data []Repair_state `json:"data"` +} + +type Repair_state struct { + ID int `json:"id"` + Rs string `json:"rs"` +} + +type cal_completion_date_resp struct { + Completion_date string `json:"completion_date"` +} + +type get_ma_username_resp struct { + Data []string `json:"data"` +} + +type get_p_name_resp struct { + P_name string `json:"p_name"` +} + +type get_p_id_options_resp struct { + Data []string `json:"data"` +} + +type get_ma_temp_plan_resp struct { + Data []ma_temp_plan `json:"data"` + Total int `json:"total"` +} + +type get_ma_plan_resp struct { + Data []ma_plan `json:"data"` + Total int `json:"total"` +} + +type get_process_resp struct { + Data []process_info `json:"data"` + Total int `json:"total"` +} + +type process_info struct { + ID int `json:"id"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` + Process_name string `json:"process_name"` + Process_t string `json:"process_t"` +} + +type upload_resp struct { + Ret int `json:"ret"` +} + +type get_pf_Resp struct { + Data []plan_file `json:"data"` + Total int `json:"total"` +} + +type plan_file struct { + ID int `json:"id"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` + Plan_name string `json:"plan_name"` + + Plan_process_file string `json:"plan_process_file"` + Filing_time string `json:"filing_time"` + Filing_user string `json:"filing_user"` + Project_file string `json:"project_file"` + P_filing_time string `json:"p_filing_time"` +} + +type import_p_resp PostUserResp + +type del_p_resp PostUserResp + +type post_p_resp PostUserResp + +type get_p_Resp struct { + Data []p_sap `json:"data"` + Total int `json:"total"` +} + +type p_sap struct { + ID int `json:"id"` + P_id string `json:"p_id"` + P_name string `json:"p_name"` +} + +type download_file_Resp struct { + FileId string `json:"fileId"` +} + +type getUserNamesResp struct { + Names []usernams `json:"names"` +} + +type usernams struct { + Value string `json:"value"` + Label string `json:"label"` +} + +type PostUserResp struct { + Ret int `json:"r"` +} + +type GetMenuResp struct { + MenuData []GetMenuRespData `json:"data"` +} + +type Svg struct { + First string `json:"first"` + Second string `json:"second"` +} + +type GetMenuRespData struct { + Title string `json:"title"` + Class string `json:"classname"` + SvgData Svg `json:"svg"` + Index string `json:"index"` + Key string `json:"key"` + Items []menuItem `json:"items"` +} + +type menuItem struct { + Title string `json:"title"` + Index string `json:"index"` + Key string `json:"key"` +} + +type LoginResp struct { + Ret int `json:"r"` + Uuid string `json:"uuid"` + RoleId int `json:"roleid"` + Url string `json:"url"` + DId int `json:"did"` + Location string `json:"loc"` +} + +type GetUsersResp struct { + Data []useInfo `json:"data"` + Total int `json:"total"` +} + +type useInfo struct { + Userid int `json:"userid"` + Username string `json:"username"` + Password string `json:"password"` + RoleName string `json:"rolename"` + RoleId int `json:"roleid"` + Department string `json:"department"` + DepartmentId int `json:"departmentid"` + State string `json:"state"` + Location string `json:"location"` +} + +type CommonResp struct { + Ret int `json:"r"` + Context string `json:"context"` +} diff --git a/upload_file_cache.go b/upload_file_cache.go new file mode 100644 index 0000000..e777059 --- /dev/null +++ b/upload_file_cache.go @@ -0,0 +1,89 @@ +package main + +import ( + "fmt" + "time" + + "database/sql" + + "github.com/astaxie/beego/logs" +) + +var ( + file_cache_data map[string]plan_file + file_cache_time string + + file_ch chan int +) + +func init() { + file_cache_data = make(map[string]plan_file) + file_cache_time = "2023-01-01 00:00:00" + + file_ch = make(chan int, 100) + +} + +func sync_file_cache() { + + var sqlstr string + var rdRow *sql.Rows + var err error + + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name],[plan_name],[process_file],[filing_time],[project_file],[p_filing_time],[op_time] from [plan_file] order by ID asc") + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("sync_file_cache Query err:%v", err.Error())) + goto exit + } + + for rdRow.Next() { + var d plan_file + var op_t string + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name, &d.Plan_name, &d.Plan_process_file, &d.Filing_time, &d.Project_file, &d.P_filing_time, &op_t); err == nil { + file_cache_data[d.P_id+d.Plan_name] = d + + if op_t > file_cache_time { + file_cache_time = op_t + } + } else { + logs.Error("sync_file_cache scan Error", err.Error()) + } + } + rdRow.Close() + + for { + select { + case <-file_ch: + sqlstr = fmt.Sprintf("select [ID],[p_id],[p_name],[plan_name],[process_file],[filing_time],[project_file],[p_filing_time],[op_time] from [plan_file] where [op_time]>'%s' order by ID asc", file_cache_time) + fmt.Println(sqlstr) + + rdRow, err = sqlConn.Query(sqlstr) + if err != nil { + logs.Error(fmt.Sprintf("sync_file_cache Query err:%v", err.Error())) + } else { + for rdRow.Next() { + var d plan_file + var op_t string + if err := rdRow.Scan(&d.ID, &d.P_id, &d.P_name, &d.Plan_name, &d.Plan_process_file, &d.Filing_time, &d.Project_file, &d.P_filing_time, &op_t); err == nil { + file_cache_data[d.P_id+d.Plan_name] = d + + if op_t > file_cache_time { + file_cache_time = op_t + } + } else { + logs.Error("sync_file_cache scan Error", err.Error()) + } + } + rdRow.Close() + } + default: + time.Sleep(time.Second * 5) + } + } + +exit: + return +} diff --git a/userCache.go b/userCache.go new file mode 100644 index 0000000..e050967 --- /dev/null +++ b/userCache.go @@ -0,0 +1,43 @@ +package main + +import ( + "sync" + "time" +) + +type DeesUserStat struct { + Uuid string `json:"uuid"` + Username string `json:"username"` + State int `json:"state"` + RefreshTime time.Time `json:"refreshTime"` + ExpireTime time.Time `json:"expireTime"` + UserRole int `json:"userrole"` + + lck sync.RWMutex +} + +func (d *DeesUserStat) Lock() { + d.lck.Lock() +} + +func (d *DeesUserStat) Unlock() { + d.lck.Unlock() +} + +func (d *DeesUserStat) RLock() { + d.lck.RLock() +} + +func (d *DeesUserStat) RUnlock() { + d.lck.RUnlock() +} + +var ( + deesUserStatMap map[string]*DeesUserStat + + deesUserStatMaplck sync.RWMutex +) + +func init() { + deesUserStatMap = make(map[string]*DeesUserStat) +}