123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628 |
- package service
- import (
- "fmt"
- "github.com/360EntSecGroup-Skylar/excelize"
- "github.com/astaxie/beego/logs"
- "github.com/gin-gonic/gin"
- "github.com/goccy/go-json"
- "github.com/k0kubun/pp/v3"
- "github.com/pkg/errors"
- log "github.com/sirupsen/logrus"
- "gorm.io/gorm"
- "kpt.xdmy/apiserver/model"
- "kpt.xdmy/apiserver/model/http"
- "kpt.xdmy/pkg/util"
- "strconv"
- "strings"
- "time"
- )
- func (s *Service) InsertDieselData(req *http.DieselReq) error {
- code := new(model.CreateCodeN)
- s.d.DB.Raw(`call createCodeN(?,?)`, req.PastureId, "CY").First(code)
- return s.d.DB.Transaction(func(tx *gorm.DB) error {
- diesel := &model.Diesel{
- PastureId: req.PastureId,
- DeptId: req.DepartmentId,
- EqId: req.EqId,
- EqCode: req.EqCode,
- OilcardId: req.OilcardId,
- CardNumber: req.CardNumber,
- OilClass: req.OilClass,
- OilAmount: req.OilAmount,
- NowPrice: req.NowPrice,
- Price: req.Price,
- EmpId: req.EmpId,
- InputId: req.InputId,
- SelTime: req.SelTime,
- Note: req.Note,
- OilName: req.OilName,
- OilType: req.OilType,
- DieselCode: code.OrderCode,
- }
- resp := tx.Create(diesel)
- if resp.Error != nil {
- logs.Error("DieseUseProof0: ", resp.Error)
- return resp.Error
- }
- req.Id = diesel.Id
- err := tx.Exec(`update oilcard set lastcardAmount=cardAmount,cardAmount =cardAmount -? where id =?`, req.Id, req.NowPrice).Error
- if err != nil {
- logs.Error(err)
- return err
- }
- dieselList := make([]*model.Diesel, 0)
- dieselList = append(dieselList, diesel)
- err = s.DieseUseProof(dieselList, tx, strconv.FormatInt(req.PastureId, 10), code.OrderCode, req.SelTime)
- if err != nil {
- logs.Error("DieseUseProof2: ", err)
- return err
- }
- return nil
- })
- }
- func (s *Service) ImportExcel(c *gin.Context) (map[string]interface{}, error) {
- inputdata := ""
- if err := c.Request.ParseForm(); err != nil {
- return nil, err
- }
- params := c.Request.Form
- // file, _, err := c.Request.FormFile("file")
- fileHeader, err := c.FormFile("file")
- file, err := fileHeader.Open()
- if err != nil {
- return nil, err
- }
- if err != nil {
- return nil, err
- }
- pastureId := params.Get("pastureId")
- sqlnamestr := params.Get("name")
- sheetname := params.Get("sheetname")
- importParams := params.Get("importParams")
- //sql, _ := restful.GetSqlByNameDB(sqlnamestr)
- // 备件编号,备件名称,规格型号,计量单位,品牌,计划量,单价,备注,jwt_username
- paramslist := strings.Split(importParams, ",")
- if sqlnamestr != "importGasoline" && sqlnamestr != "importCoal" && sqlnamestr != "importBiomass" && sqlnamestr != "importEnergy" {
- paramslist = append(paramslist, "jwt_username")
- }
- queryData := make([]interface{}, 0)
- xlsx1, err := excelize.OpenReader(file)
- if err != nil {
- return nil, err
- }
- ok := 0
- error := 0
- rows := xlsx1.GetRows(sheetname)
- if len(rows) > 10000 {
- rows = rows[:10000]
- }
- dieselList := make([]*model.Diesel, 0)
- errBool := false
- var selTime string
- code := new(model.CreateCodeN)
- s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(&code)
- if code.OrderCode == "" {
- s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(&code)
- if code.OrderCode == "" {
- outentry := make(map[string]interface{})
- outentry["error_msg"] = "上传失败,请重新导入"
- error++
- queryData = append(queryData, outentry)
- data := make(map[string]interface{})
- data["result"] = queryData
- //data["success"] = ok
- data["err_count"] = 1
- return data, nil
- }
- }
- tx := s.d.DB.Begin()
- var dateList []string
- for i, row := range rows {
- if i > 0 {
- if len(paramslist) > 0 {
- s_params := make([]interface{}, 0)
- entry := make(map[string]string)
- outentry := make(map[string]interface{})
- inputdata = ""
- for _, value := range paramslist {
- if strings.ToLower(strings.Trim(value, " ")) == "jwt_username" {
- if tempv, exists := c.Get("jwt_username"); exists {
- s_params = append(s_params, tempv.(string))
- } else {
- s_params = append(s_params, "")
- }
- } else {
- for j, colCell := range rows[0] {
- if strings.Trim(value, " ") == colCell {
- for k, colCell1 := range row {
- if j == k {
- outentry[colCell] = colCell1
- entry[colCell] = colCell1
- //inputdata = inputdata + colCell + ":" + colCell1 + ";"
- }
- }
- }
- }
- s_params = append(s_params, entry[strings.Trim(value, " ")])
- }
- }
- outentry["input"] = inputdata
- diesel := new(model.Diesel)
- fmt.Println(entry)
- //牧场,油卡编号,设备名称,设备编号,加油日期,加油量(升),单价,录入人,加油人,加油工班,备注,柴油类型,jwt_username
- if _, ok := entry["加油量(升)"]; ok {
- diesel.OilAmount = entry["加油量(升)"]
- }
- if _, ok := entry["单价"]; ok {
- diesel.Price = entry["单价"]
- }
- if _, ok := entry["单价"]; ok {
- diesel.Price = entry["单价"]
- }
- if diesel.OilAmount == "" {
- outentry["error_msg"] = "加油量必须输入"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- if diesel.Price == "" {
- outentry["error_msg"] = "单价不能为空"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- if _, ok := entry["牧场"]; !ok {
- outentry["error_msg"] = "牧场不能为空"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- if _, ok := entry["油卡编号"]; !ok {
- outentry["error_msg"] = "油卡编号不能为空"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- jyTime, err := time.Parse("2006-01-02", entry["加油日期"])
- if err != nil {
- outentry["error_msg"] = err.Error()
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- if len(dateList) == 0 {
- dateList = append(dateList, jyTime.Format("2006-01-02"))
- } else {
- exist := false
- for _, date := range dateList {
- if date == jyTime.Format("2006-01-02") {
- exist = true
- break
- }
- }
- if !exist {
- dateList = append(dateList, jyTime.Format("2006-01-02"))
- }
- }
- now, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
- if jyTime.Unix() > now.Unix() {
- outentry["error_msg"] = "本次抄表日期不可大于当前日期"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- pasture := new(model.Pasture)
- tx.Where("name = ?", entry["牧场"]).First(pasture)
- if pasture.ID == 0 {
- outentry["error_msg"] = "牧场不存在"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- diesel.CardNumber = entry["油卡编号"]
- diesel.SelTime = entry["加油日期"]
- oilcard := new(model.Oilcard)
- tx.Where("cardCode = ? and pastureId = ? ", entry["油卡编号"], pasture.ID).First(oilcard)
- if oilcard.Id == "" {
- outentry["error_msg"] = entry["油卡编号"] + "油卡不存在"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- if oilcard.CardType != "外部" {
- equipment := new(model.Equipment)
- tx.Debug().Where("eqCode = ? and pastureId =? ", entry["设备编号"], pasture.ID).First(equipment)
- diesel.EqCode = equipment.EqCode
- diesel.EqId = int64(equipment.Id)
- deptId, _ := strconv.ParseInt(equipment.DepartmentId, 10, 64)
- diesel.DeptId = deptId
- if equipment.EqCode == "" {
- outentry["error_msg"] = entry["设备编号"] + "资产不存在或不在本牧场"
- error++
- queryData = append(queryData, outentry)
- errBool = true
- continue
- }
- }
- if _, ok := entry["录入人"]; ok {
- emp := new(model.Emp)
- tx.Where("empname = ? and pastureId = ?", entry["录入人"], pasture.ID).First(emp)
- diesel.InputId = emp.Id
- }
- diesel.PastureId = int64(pasture.ID)
- price, _ := strconv.ParseFloat(diesel.Price, 64)
- oilAmount, _ := strconv.ParseFloat(diesel.OilAmount, 64)
- diesel.NowPrice = price * oilAmount
- if _, ok := entry["备注"]; ok {
- diesel.Note = entry["备注"]
- }
- if _, ok := entry["录入人"]; ok {
- emp := new(model.Emp)
- tx.Where("empname = ? and pastureId = ?", entry["录入人"], pasture.ID).First(emp)
- diesel.EmpId = emp.Empname
- }
- if _, ok := entry["加油工班"]; ok {
- diesel.OilClass = entry["加油工班"]
- }
- if diesel.DeptId == 0 {
- deptId, _ := strconv.ParseInt(oilcard.DepartmentId, 10, 64)
- diesel.DeptId = deptId
- }
- oilcardId, _ := strconv.ParseInt(oilcard.Id, 10, 64)
- diesel.OilcardId = oilcardId
- //WHEN '0#' THEN
- //1
- //WHEN '-10#' THEN
- //2
- //WHEN '-20#' THEN
- //3
- //WHEN '-30#' THEN
- //4
- //WHEN '-35#' THEN
- if _, ok := entry["柴油类型"]; ok {
- if entry["柴油类型"] == "" {
- outentry["error_msg"] = "柴油类型不能为空"
- error++
- queryData = append(queryData, outentry)
- //tx.Rollback()
- errBool = true
- continue
- }
- diesel.OilName = entry["柴油类型"]
- if entry["柴油类型"] == "0号" {
- diesel.OilType = 1
- } else if entry["柴油类型"] == "10号" {
- //diesel.OilName = "-10#"
- diesel.OilType = 2
- } else if entry["柴油类型"] == "20号" {
- //diesel.OilName = "-20#"
- diesel.OilType = 3
- } else if entry["柴油类型"] == "30号" {
- //diesel.OilName = "-30#"
- diesel.OilType = 4
- } else if entry["柴油类型"] == "35号" {
- //diesel.OilName = "-35#"
- diesel.OilType = 5
- }
- } else {
- outentry["error_msg"] = "柴油类型不能为空"
- error++
- queryData = append(queryData, outentry)
- //tx.Rollback()
- errBool = true
- continue
- }
- diesel.DieselCode = code.OrderCode
- err = tx.Create(diesel).Error
- if err != nil {
- outentry["error_msg"] = err.Error()
- error++
- queryData = append(queryData, outentry)
- //tx.Rollback()
- logs.Error("DieseUseProof0: ", err)
- errBool = true
- continue
- }
- err = tx.Exec(` UPDATE
- oilcard
- SET
- lastcardAmount = cardAmount,
- cardAmount = cardAmount-CAST( ?*? as decimal(10,2))
- WHERE id = ?;`, oilAmount, price, oilcard.Id).Error
- if err != nil {
- outentry["error_msg"] = err.Error()
- error++
- queryData = append(queryData, outentry)
- //tx.Rollback()
- errBool = true
- continue
- }
- selTime = diesel.SelTime
- dieselList = append(dieselList, diesel)
- ok++
- }
- }
- }
- if len(dateList) > 1 {
- tx.Rollback()
- data := make(map[string]interface{})
- outentry := make(map[string]interface{})
- outentry["error_msg"] = "请勿上传多个日期数据!"
- error++
- queryData = append(queryData, outentry)
- data["result"] = queryData
- data["result"] = queryData
- //data["success"] = ok
- data["err_count"] = 1
- return data, nil
- }
- if errBool {
- tx.Rollback()
- data := make(map[string]interface{})
- data["result"] = queryData
- //data["success"] = ok
- data["err_count"] = 1
- return data, nil
- }
- err = s.DieseUseProof(dieselList, tx, pastureId, code.OrderCode, selTime)
- if err != nil {
- outentry := make(map[string]interface{})
- outentry["error_msg"] = err.Error()
- error++
- queryData = append(queryData, outentry)
- data := make(map[string]interface{})
- data["result"] = queryData
- //data["success"] = ok
- data["err_count"] = 1
- tx.Rollback()
- return data, nil
- }
- err = tx.Commit().Error
- if err != nil {
- outentry := make(map[string]interface{})
- outentry["error_msg"] = "上传失败"
- error++
- queryData = append(queryData, outentry)
- data := make(map[string]interface{})
- data["result"] = queryData
- //data["success"] = ok
- data["err_count"] = 1
- tx.Rollback()
- return data, nil
- }
- data := make(map[string]interface{})
- data["result"] = queryData
- data["success"] = len(dieselList)
- //data["err_count"] = error
- return data, nil
- }
- func (s *Service) DieseUseProof(reqList []*model.Diesel, tx *gorm.DB, pastureId, dieselCode, selTime string) error {
- //pr := new(http.ProofPartReq)
- r := new(http.ProofReq)
- rp := new(http.ProofResp)
- //parts := make([]*model.PartUseStr, 0)
- //bp := new(model.BigPartUse)
- pa := new(model.Pasture)
- if e := tx.Where("id = ? ", pastureId).First(pa).Error; e != nil {
- log.Error(e)
- return errors.New(fmt.Sprintf("查询牧场信息 errors:%v", e))
- }
- proofDest(r)
- //{"DEST":{"DEST_ID":"EQMAN","BUSS_TP":"MM001","MESS_ID":"","STATUS":"","MESS_TEXT":"","STATUS_OS":"",
- // "Url":"http://192.168.61.117/SAPP0/Common/MM001/ModifyMblnr"},"DATA":{"BLDAT":"20221105",
- // "BUDAT":"20221101","FRBNR":"CK03221105003","MSEG":[{"ZEILE":"1","MATNR":"14.02.15.06.000091",
- // "WERKS":"M003","LGORT":"1004","MENGE":"1.000000","MEINS":"桶","EBELN":"","EBPLP":"",
- // "BWART":"201","SOBKZ":"K","KOSTL":"1002030505","ANLN1":"50300000007","ANLN2":"","LIFNR":"100869"}]}}
- //b, _ := json.Marshal(pr)
- //restful.Dbs.DB.Exec(` insert into equipmentlingshi(text)values(?)`, string(b))
- r.Dest.MESSIDOS = dieselCode
- r.Dest.BUSSDOCOS = dieselCode
- r.Data.EqNumber = dieselCode
- r.Data.CreateTime = time.Now().Format("20060102")
- if t, e := util.ParseDate(selTime[:10]); e != nil {
- log.Error(e, selTime)
- } else {
- r.Data.PostDate = t.Format("20060102")
- }
- diesePartMap := map[string]string{
- "0号": "20.04.01.01.000001",
- "10号": "20.04.01.01.000002",
- "20号": "20.04.01.01.000003",
- "30号": "20.04.01.01.000004",
- "35号": "20.04.01.01.000005",
- }
- //for i, v := range parts {
- //bc := new(model.BigContract)
- //c := new(model.Contract)
- //w := new(model.Warehouse)
- //pv := new(model.Provider)
- //contractID, _ := strconv.Atoi(v.ContractID.(string))
- //if e := s.d.DB.First(storage, model.PartRepertory{ContractID: contractID}).Error; e != nil {
- // log.Errorln(e, v.ContractID)
- // return errors.New(fmt.Sprintf("查询库存信息出错 errors:%v", e))
- //}
- //if e := s.d.DB.First(pv, model.Provider{ID: storage.ProviderID}).Error; e != nil {
- // log.Errorln(e, storage.ProviderID)
- // return errors.New(fmt.Sprintf("查询供应商信息出错 errors:%v", e))
- //}
- //dict := new(model.Dictlist)
- //tx.First(dict, model.Dictlist{Pid: 21, Value: "物耗"})
- //if e := s.d.DB.First(w, model.Warehouse{ID: v.LocationID}).Error; e != nil {
- // log.Errorln(e, v.LocationID)
- // return errors.New(fmt.Sprintf("errors:%v", e))
- //}
- for i, req := range reqList {
- eq := new(model.Equipment)
- dp := new(model.Department)
- if e := tx.Where("id = ? ", req.DeptId).First(dp).Error; e != nil {
- log.Error(e)
- return errors.New(fmt.Sprintf("查询部门信息出错 errors:%v", e))
- }
- sdetail := http.ProofDetail{}
- if req.EqCode != "" {
- if e := tx.Where("id = ? and pastureid = ? ", req.EqId, req.PastureId).First(eq).Error; e != nil {
- return errors.New(fmt.Sprintf("errors:%v", e))
- }
- sdetail.AssetCode = eq.SapCode
- sdetail.AssetSon = eq.SonCode
- }
- sdetail.EXT01 = "6601011703"
- sdetail.MoveType = "201"
- sdetail.CostCenter = dp.CostCenterCode
- sdetail.Factory = pa.FactoryCode
- if sdetail.Factory == "M005" && strings.Contains(dp.Name, "二期") {
- sdetail.Factory = "M017"
- }
- sdetail.RowNumber = fmt.Sprintf("%d", i+1)
- sdetail.Quantity = fmt.Sprintf("%s", req.OilAmount)
- sdetail.Code = diesePartMap[req.OilName]
- sdetail.Location = "1005"
- r.Data.Detail = append(r.Data.Detail, sdetail)
- tx.Exec(` update diesel set sort = ? where id = ? `, sdetail.RowNumber, req.Id)
- }
- //_, err = tx.Exec(` update partuse set rowNumber = ? where id = ? `, sdetail.RowNumber, v.ID)
- //if err != nil {
- // return err
- //}
- //}
- //}
- ///*
- pp.Print(r)
- //log.Infof("bp.pastureId:%d,pa.name:%s,pa.companycode:%s", bp.PastureID, pa.Name, pa.CompanyCode)
- rbyte, _ := json.Marshal(r)
- fmt.Println(string(rbyte))
- if e := s.SyncSap(r, rp, rbyte); e != nil {
- log.Errorf("laid proof error:%v", e)
- return errors.New(fmt.Sprintf("errors:%s", r.MessText))
- } else {
- if rp.Dest.Status == "S" {
- log.Printf("use proof success:eqcode=%s,sapcode=%s", rp.Data.EqNumber, rp.Data.SapNumber)
- //if e := s.d.DB.Model(&model.BigPartUse{}).Where("useform = ?", rp.Data.EqNumber).Update("ProofCode", rp.Data.SapNumber).Error; e != nil {
- // log.Errorln(e)
- //}
- err := tx.Exec(` update diesel set ProofCode = ? where dieselCode = ? `, rp.Data.SapNumber, dieselCode).Error
- if err != nil {
- log.Printf("%s", err.Error())
- }
- } else {
- log.Warnf(" use proof :%s", rp.Dest.MessText)
- return errors.New(fmt.Sprintf("errors:%s", rp.Dest.MessText))
- }
- }
- return nil
- }
- func (s *Service) zdDieselData(pastureId, date, code string) error {
- //code := new(model.CreateCodeN)
- //s.d.DB.Raw(`call createCodeN(?,?)`, pastureId, "CY").First(code)
- return s.d.DB.Transaction(func(tx *gorm.DB) error {
- deselOffList := make([]*model.Diesel, 0)
- tx.Debug().Where("pastureId = ?", pastureId).Where("selTime = ?", date).Where(" dieselCode = ? ", code).Find(&deselOffList)
- //fmt.Println(err)
- //if err != nil {
- // //logs.Error(err)
- // return err
- //}
- //if len(deselOffList) == 0 {
- // return nil
- //}
- //dieselList := make([]*model.Diesel, 0)
- //for _, item := range deselOffList {
- //fmt.Println(item)
- //var targetTime = ""
- //t, err := time.Parse("2006-01-02 15:04:05", item.SelTime)
- //if err != nil {
- // fmt.Println("解析错误:", err)
- // targetTime = item.SelTime
- //} else {
- // targetTime = t.Format("2006-01-02 15:04:05")
- //}
- //
- //// 转换为指定格式的时间字符串
- //fmt.Println(targetTime)
- //diesel := &model.Diesel{
- // Id: item.Id,
- // PastureId: item.PastureId,
- // DeptId: item.DeptId,
- // EqId: item.EqId,
- // EqCode: item.EqCode,
- // OilcardId: item.OilcardId,
- // CardNumber: item.CardNumber,
- // OilClass: item.OilClass,
- // OilAmount: item.OilAmount,
- // NowPrice: item.NowPrice,
- // Price: item.Price,
- // EmpId: item.EmpId,
- // InputId: item.InputId,
- // SelTime: targetTime,
- // Note: item.Note,
- // OilName: item.OilName,
- // OilType: item.OilType,
- // DieselCode: item.DieselCode,
- //}
- //tx.Create(diesel)
- //dieselList = append(dieselList, diesel)
- //tx.Exec(`delete from diesel_off where id = ?`, item.Id)
- //}
- err := s.DieseUseProof(deselOffList, tx, pastureId, code, date)
- if err != nil {
- logs.Error(err)
- return err
- }
- return nil
- })
- }
|