package service import ( "encoding/json" "fmt" "strconv" "strings" "time" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "kpt.xdmy/apiserver/config" "kpt.xdmy/apiserver/model" "kpt.xdmy/apiserver/model/http" "kpt.xdmy/pkg/util" ) // 推送采购订单到sap(业务触发),已关闭 func (s *Service) PurchaseOrder(p interface{}) { r := new(model.BigBuyDetailReq) if e := util.Unmarshal(p, r); e != nil { log.Errorf("purchaseorder param :%v ", e) log.Info(p) return } if r.ID == "" && r.Code == "" { log.Error("buy order request param is empty") return } bdetails := []model.BigBuyDetail{} bpp := new(model.Bigpartpurchase) if r.ID != "" { pid, err := strconv.ParseInt(r.ID, 10, 32) if err != nil { log.Errorf("parseInt purchase id :%v", err) } id := int(pid) if e := s.d.DB.First(bpp, model.Bigpartpurchase{ID: id}).Error; e != nil { log.Error("Bigpartpurchase query error", e) return } if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: bpp.OrderNumber}).Error; e != nil || len(bdetails) == 0 { log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e) return } } else if r.Code != "" { if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: r.Code}).Error; e != nil || len(bdetails) == 0 { log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e) return } } for _, v := range bdetails { SapOrder(&v, "") SrmOrder(&v, "0") } } // AutoSapOrderJob 定时(每分钟 一次)读取未同步的采购订单,同步到sap // 同步失败的采购订单,变更状态,改为手动同步 // 状态(sapStatus):0,未同步;1,成功;2,失败 func AutoSapOrderJob() { orders := []model.BigBuyDetail{} if e := s.d.DB.Raw(`select b.* from bigbuydetail b join pasture p on b.pastureId = p.id left join bigpartdeal bpd on bpd.matchCode = b.matchCode where buyerDate >'2022-11-02' and p.vendor = 1 and b.sapStatus =0 and (bpd.statue = 1 or b.matchCode like '%SG%' )`).Find(&orders, model.BigBuyDetail{}).Error; e != nil { log.Errorf("AutoSapOrderJob error: %v", e) return } var buyeCodes []string for _, v := range orders { buyeCodes = append(buyeCodes, v.BuyeCode) } if len(buyeCodes) > 0 { err := s.d.DB.Exec(` update bigbuydetail set sapStatus = 2 where buyeCode in (?)`, buyeCodes).Error fmt.Println(err) } for _, v := range orders { e, sapNumber := SapOrder(&v, "") up := model.BigBuyDetail{SapNumber: sapNumber} if e != nil { up.SapStatus = 2 up.SapError = e.Error() } else { up.SapStatus = 1 } if e := s.d.DB.Model(&v).Where("buyeCode =?", v.BuyeCode).Updates(up); e != nil { log.Errorf("BigBuyDetail update error: %v", e) } } } // 手动同步采购订单到sap func ManaulSapOrderJob(buyeCode string) (err error) { order := new(model.BigBuyDetail) if e := s.d.DB.First(order, model.BigBuyDetail{BuyeCode: buyeCode}).Error; e != nil { err = errors.Wrapf(e, "ManaulSapOrderJob BigBuyDetail query ") return } e, sapNumber := SapOrder(order, "") up := model.BigBuyDetail{SapNumber: sapNumber} if e != nil { up.SapStatus = 2 up.SapError = e.Error() err = errors.Wrapf(e, "ManaulSapOrder sap ") } else { up.SapStatus = 1 } if e := s.d.DB.Model(order).Where("buyeCode=?", buyeCode).Updates(up).Error; e != nil { log.Errorf("BigBuyDetail update error: %v", e) } return } // 发送采购订单到sap func SapOrder(p *model.BigBuyDetail, dflag string) (error, string) { r := new(http.SapOrderReq) rp := new(http.OrderResp) parts := []model.BuyDetail{} pa := new(model.Pasture) pv := new(model.Provider) //pc := new(model.Bigpartpurchase) //dp := new(model.Department) r.Dest.DestID = "EQMAN" r.Dest.BussTp = "MM007" //r.Dest.Url = "http://192.168.61.117/SAPQ0/Common/MM007/PurchaseOrder" //r.Dest.Url = "http://192.168.61.117/SAPP0/Common/MM007/PurchaseOrder" r.Dest.Url = fmt.Sprintf("%s/Common/MM007/PurchaseOrder", config.Conf.Http.Routing) if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil { return errors.Wrapf(e, "provider query:id=%d", p.ProviderID), "" } if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil { return errors.Wrapf(e, "pasture query:id=%d", p.PastureID), "" } if e := s.d.DB.Where("amount>0").Find(&parts, model.BuyDetail{BigID: p.ID}).Order("rowNumber").Error; e != nil || len(parts) == 0 { return errors.Wrapf(e, "buydetail query:bigid=%d", p.ID), "" } //if len(parts) > 0 { // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil { // } //} r.Data.IsCancle = "" r.Data.PayCondition = "" r.Data.SupplierCode = pv.SapCode r.Data.OrderDate = p.BuyerDate.Format("20060102") r.Data.CurrencyCode = "CNY" r.Data.ProofType = "ZNB4" r.Data.EqSysCode = p.BuyeCode //if dp.CompanyCode == "" { r.Data.CompanyCode = pa.CompanyCode r.Data.Organization = pa.ParchaseOrganization r.Data.Group = pa.PurchasingGroup //} else { // r.Data.CompanyCode = dp.CompanyCode // r.Data.Organization = dp.ParchaseOrganization // r.Data.Group = dp.PurchasingGroup //} for i, v := range parts { detail := http.SapOrderDetail{} c := new(model.Contract) bc := new(model.BigContract) par := new(model.Parts) if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil { //return errors.Wrapf(e, "contract query :id=%d", v.ContractID), "" } if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } if v.RowNumber > 0 { detail.RowNumber = strconv.Itoa(v.RowNumber) } else { detail.RowNumber = fmt.Sprintf("%d", (i+1)*10) } //if dp.CompanyCode == "" { detail.Factory = pa.FactoryCode //} else { // detail.Factory = dp.Factory //} detail.Quantity = fmt.Sprintf("%d", v.Amount) detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") detail.TaxCode = "J0" detail.Per = "1" detail.Location = "1004" detail.IsOwn = util.ZeroStr(bc.IsZeroStock == 1, "K") detail.NetPrice = c.Price if c.PartCode != "" { detail.Unit = c.Unit detail.MaterialCode = c.PartCode } else { if detail.NetPrice == 0 { detail.NetPrice = v.Price } detail.Unit = par.Unit detail.MaterialCode = v.PartCode } detail.Dflag = dflag astr := strconv.FormatFloat(detail.NetPrice, 'f', -1, 64) b := strings.Index(astr, ".") if len(astr[b+1:]) > 2 && b > 0 { num, _ := strconv.ParseFloat(astr[b+1:], 64) if num > 0 { detail.NetPrice = detail.NetPrice * 1000 detail.NetPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NetPrice), 64) detail.Per = "1000" } } r.Data.Detail = append(r.Data.Detail, detail) if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", detail.RowNumber).Error; e != nil { log.Errorln(e, v.ID) } } rbyte, _ := json.Marshal(r) e := s.SyncSap(r, &rp, rbyte) saplog := new(model.SapLog) if e == nil && rp.Dest.Status == "S" { s.d.DB.Create(saplog) log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber) return nil, rp.Data.SapNumber } else { if param, e := json.Marshal(r); e != nil { log.Errorf("sap order param marshal:%v", e) } else { saplog.Param = string(param) saplog.Name = "sap-order" s.d.DB.Create(saplog) } if e == nil { return errors.Errorf("sap order :%s", rp.Data.MsgText), "" } else { return errors.Wrapf(e, "sap order error:%v", e), "" } } //*/ return nil, "" } func AutoSrmOrderJob() { orders := []model.BigBuyDetail{} if e := s.d.DB.Where("srmStatus=0 and buyerDate >= '2022-10-25' and sapStatus=1 and ifnull(sapNumber,0) > 0 ").Find(&orders, model.BigBuyDetail{SrmStatus: 0}).Error; e != nil { log.Errorf("AutoSrmOrderJob error: %v", e) return } var buyeCodes []string for _, v := range orders { buyeCodes = append(buyeCodes, v.BuyeCode) } if len(buyeCodes) > 0 { s.d.DB.Exec(` update bigbuydetail set srmStatus = 2 where buyeCode in (?)`, buyeCodes) } for _, v := range orders { SrmOrder(&v, "0") } } func ManaulSrmOrderJob(buyeCode string) { orders := []model.BigBuyDetail{} if e := s.d.DB.Where("buyeCode=?", buyeCode).Where("sapStatus=1").Find(&orders, model.BigBuyDetail{SrmStatus: 0}).Error; e != nil { log.Errorf("ManaulSrmOrderJob error: %v", e) return } for _, v := range orders { SrmOrder(&v, "0") } } func SrmOrder(p *model.BigBuyDetail, IsReturn string) { r := new(http.SrmOrderReq) rp := new(http.SrmResp) parts := []model.BuyDetail{} pa := new(model.Pasture) pv := new(model.Provider) //pc := new(model.Bigpartpurchase) //dp := new(model.Department) r.Dest.Url = "http://srm.vip.xiandaimuye.com/gateway/serviceApi/invoke/QZbycode/saveByEquipment" if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil { log.Error(e) return } if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil { log.Errorf("pasture query :id=%d,%v", p.PastureID, e) return } if e := s.d.DB.Where("amount>0").Find(&parts, model.BuyDetail{BigID: p.ID}).Error; e != nil || len(parts) == 0 { log.Errorf("buydetail query :bigid=%d,%v", p.ID, e) return } //if e := s.d.DB.Where("matchCode = ? ", p.MatchCode).Find(&pc, model.Bigpartpurchase{}).Error; e != nil { // return //} //if e := s.d.DB.Where("id = ? ", pc.DepartmentID).Find(&dp, model.Department{}).Error; e != nil { // return //} //if len(parts) > 0 { // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil { // } //} //r.Data.CompanyCode = pa.CompanyCode r.Data.VendorErpCode = pv.SapCode r.Data.PurchaseOrderDate = p.BuyerDate.Format("20060102") r.Data.CurrencyCode = "CNY" r.Data.PurchaseOrderType = "ZNB4" r.Data.VendorName = pv.ProviderName r.Data.DeliveryTypeCode = "1" r.Data.IsReturn = "0" r.Data.Remark = "" r.Data.ErpPurchaseOrderNo = p.SapNumber r.Data.SapCode = pv.SapCode r.Data.PurchaseOrderNo = p.BuyeCode //if dp.CompanyCode == "" { r.Data.CompanyCode = pa.CompanyCode r.Data.PurchasingOrgCode = pa.ParchaseOrganization r.Data.PurchasingGroupCode = pa.PurchasingGroup //} else { // r.Data.CompanyCode = dp.CompanyCode // r.Data.PurchasingOrgCode = dp.ParchaseOrganization // r.Data.PurchasingGroupCode = dp.PurchasingGroup //} for _, v := range parts { detail := http.SrmOrderDetail{} c := new(model.Contract) bc := new(model.BigContract) pr := new(model.PartRepertory) par := new(model.Parts) //part := new(model.Parts) if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil { log.Errorf("order detail error:%v", e) //return } if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil { log.Errorf("order detail error:%v", e) //return } if len(c.PartCode) > 0 { if e := s.d.DB.First(par, model.Parts{PartCode: c.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } } else if len(v.PartCode) > 0 { if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } } if c.Brand != "" { detail.Manufacturer = c.Brand } else { brand := new(model.Brand) if e := s.d.DB.First(brand, model.Brand{ID: v.BrandID}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } detail.Manufacturer = brand.BrandName } price := c.Price if price == 0 { price = v.Price } if c.PartCode != "" { detail.OrderUnitCode = c.Unit detail.MaterialCode = c.PartCode detail.MaterialName = c.PartName detail.PricingUnitCode = c.Unit } else { detail.OrderUnitCode = par.Unit detail.MaterialCode = par.PartCode detail.MaterialName = par.Name detail.PricingUnitCode = par.Unit } s.d.DB.First(pr, model.PartRepertory{ContractID: v.ContractID}) r.Data.TotalNonTaxAmount += price r.Data.TotalTaxAmount += price detail.RowNo = strconv.Itoa(v.RowNumber) //detail.Manufacturer = pa.FactoryCode //detail.Manufacturer = //if dp.CompanyCode == "" { detail.Manufacturer = pa.FactoryCode detail.PlantCode = pa.FactoryCode //} else { // detail.Manufacturer = dp.Factory // detail.PlantCode = dp.Factory //} detail.OrderQty = fmt.Sprintf("%d", v.Amount) detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") detail.TaxRateCode = "J0" detail.NonTaxPrice = price detail.MaterialDesc = par.Specification if len(c.PartCode) > 0 { detail.MaterialGroupCode = strings.ReplaceAll(c.PartCode[:strings.LastIndex(c.PartCode, ".")], ".", "") } else if len(v.PartCode) > 0 { fmt.Println(v.PartCode) detail.MaterialGroupCode = strings.ReplaceAll(v.PartCode[:strings.LastIndex(v.PartCode, ".")], ".", "") } detail.Tax = "0" detail.ConfirmDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") //detail.PlantCode = pa.FactoryCode //if dp.CompanyCode == "" { //detail.PlantCode = pa.FactoryCode //} else { // detail.PlantCode = dp.Factory //} detail.StockLocationCode = "1004" detail.QualityCheck = "0" detail.IsReturn = "0" detail.OverDeliveryLimit = "0" detail.ShortDeliveryLimit = "0" detail.SourceNo = p.BuyeCode[4:] detail.ContractCode = bc.ContractCode detail.Remark = c.Remark //r.Data.Detail = append(r.Data.Detail, detail) if bc.IsZeroStock == 1 { detail.PurchaseCategory = "2" } else { detail.PurchaseCategory = "0" } detail.IsFree = "0" detail.PriceBase = "1" astr := strconv.FormatFloat(detail.NonTaxPrice, 'f', -1, 64) b := strings.Index(astr, ".") if len(astr[b+1:]) > 2 && b > 0 { num, _ := strconv.ParseFloat(astr[b+1:], 64) if num > 0 { detail.NonTaxPrice = detail.NonTaxPrice * 1000 detail.NonTaxPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NonTaxPrice), 64) detail.PriceBase = "1000" } } detail.TaxAmount = detail.NonTaxPrice detail.TaxPrice = detail.NonTaxPrice detail.NonTaxAmount = detail.NonTaxPrice r.Data.Detail = append(r.Data.Detail, detail) //if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil { // log.Errorln(e, v.ID) //} } rbyte, _ := json.Marshal([]interface{}{r.Data}) fmt.Println(string(rbyte)) saplog := new(model.SapLog) if e := s.SyncSrm(r, rp, rbyte); e != nil { s.d.DB.Create(saplog) log.Errorf("sap buy order error: %v", e) p.SapStatus = 3 } else { s.d.DB.Create(saplog) if rp.Success { // log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber) p.SapStatus = 1 p.SapNumber = rp.Code } else { log.Warnf("buy order fail :msg=%s,r=%v", rp.Code, r) p.SapStatus = 2 // pp.Print(r) } } if p.SapStatus == 1 { if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigBuyDetail{SrmStatus: p.SapStatus, SrmNumber: p.SapNumber}).Error; e != nil { log.Errorf("update big buy detail error: %v", e) } } else { if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigBuyDetail{SrmStatus: p.SapStatus, SrmError: rp.Message}).Error; e != nil { log.Errorf("update big buy detail error: %v", e) } } } // AutoSapReturnOrderJob 定时(每分钟 一次)读取未同步的采购订单,同步到sap // 同步失败的采购订单,变更状态,改为手动同步 // 状态(sapStatus):0,未同步;1,成功;2,失败 func AutoSapReturnOrderJob() { orders := []model.BigRefunddetail{} if e := s.d.DB.Raw(`SELECT b.* FROM bigrefunddetail b JOIN pasture p ON b.pastureId = p.id WHERE buyerDate > '2022-11-02' AND p.vendor = 1 AND b.sapStatus = 0`).Find(&orders, model.BigRefunddetail{}).Error; e != nil { log.Errorf("AutoSapOrderJob error: %v", e) return } var buyeCodes []string for _, v := range orders { buyeCodes = append(buyeCodes, v.BuyeCode) } if len(buyeCodes) > 0 { err := s.d.DB.Exec(` update bigrefunddetail set sapStatus = 2 where buyeCode in (?)`, buyeCodes).Error fmt.Println(err) } for _, v := range orders { e, sapNumber := SapReturnOrder(&v, "") up := model.BigRefunddetail{SapNumber: sapNumber} if e != nil { up.SapStatus = 2 up.SapError = e.Error() } else { up.SapStatus = 1 } if e := s.d.DB.Model(&v).Where("buyeCode =?", v.BuyeCode).Updates(up); e != nil { log.Errorf("BigBuyDetail update error: %v", e) } } } // SapReturnOrder 发送采购订单到sap func SapReturnOrder(p *model.BigRefunddetail, dflag string) (error, string) { r := new(http.SapOrderReq) rp := new(http.OrderResp) parts := []model.Refunddetail{} pa := new(model.Pasture) pv := new(model.Provider) //pc := new(model.Bigpartpurchase) //dp := new(model.Department) r.Dest.DestID = "EQMAN" r.Dest.BussTp = "MM007" //r.Dest.Url = "http://192.168.61.117/SAPQ0/Common/MM007/PurchaseOrder" //r.Dest.Url = "http://192.168.61.117/SAPP0/Common/MM007/PurchaseOrder" r.Dest.Url = fmt.Sprintf("%s/Common/MM007/PurchaseOrder", config.Conf.Http.Routing) if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil { return errors.Wrapf(e, "provider query:id=%d", p.ProviderID), "" } if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil { return errors.Wrapf(e, "pasture query:id=%d", p.PastureID), "" } if e := s.d.DB.Where("amount>0").Find(&parts, model.Refunddetail{BigID: p.ID}).Order("rowNumber").Error; e != nil || len(parts) == 0 { return errors.Wrapf(e, "buydetail query:bigid=%d", p.ID), "" } //if len(parts) > 0 { // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil { // } //} //r.Data.IsCancle = "" r.Data.PayCondition = "" r.Data.SupplierCode = pv.SapCode r.Data.OrderDate = p.BuyerDate.Format("20060102") r.Data.CurrencyCode = "CNY" r.Data.ProofType = "ZNB4" r.Data.EqSysCode = p.BuyeCode //if dp.CompanyCode == "" { r.Data.CompanyCode = pa.CompanyCode r.Data.Organization = pa.ParchaseOrganization r.Data.Group = pa.PurchasingGroup //} else { // r.Data.CompanyCode = dp.CompanyCode // r.Data.Organization = dp.ParchaseOrganization // r.Data.Group = dp.PurchasingGroup //} r.Data.IsCancle = "X" for i, v := range parts { detail := http.SapOrderDetail{} c := new(model.Contract) bc := new(model.BigContract) par := new(model.Parts) if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil { //return errors.Wrapf(e, "contract query :id=%d", v.ContractID), "" } if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } if v.RowNumber > 0 { detail.RowNumber = strconv.Itoa(v.RowNumber) } else { detail.RowNumber = fmt.Sprintf("%d", (i+1)*10) } //if dp.CompanyCode == "" { detail.Factory = pa.FactoryCode //} else { // detail.Factory = dp.Factory //} detail.Quantity = fmt.Sprintf("%d", v.Amount) detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") detail.TaxCode = "J0" detail.Per = "1" detail.Location = "1004" detail.IsOwn = util.ZeroStr(bc.IsZeroStock == 1, "K") detail.NetPrice = c.Price detail.Dflag = dflag if c.PartCode != "" { detail.Unit = c.Unit detail.MaterialCode = c.PartCode } else { if detail.NetPrice == 0 { detail.NetPrice = v.Price } detail.Unit = par.Unit detail.MaterialCode = v.PartCode } astr := strconv.FormatFloat(detail.NetPrice, 'f', -1, 64) b := strings.Index(astr, ".") if len(astr[b+1:]) > 2 && b > 0 { num, _ := strconv.ParseFloat(astr[b+1:], 64) if num > 0 { detail.NetPrice = detail.NetPrice * 1000 detail.NetPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NetPrice), 64) detail.Per = "1000" } } r.Data.Detail = append(r.Data.Detail, detail) if e := s.d.DB.Model(&model.Refunddetail{}).Where("id=?", v.ID).Update("rowNumber", detail.RowNumber).Error; e != nil { log.Errorln(e, v.ID) } } rbyte, _ := json.Marshal(r) e := s.SyncSap(r, &rp, rbyte) saplog := new(model.SapLog) if e == nil && rp.Dest.Status == "S" { s.d.DB.Create(saplog) log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber) return nil, rp.Data.SapNumber } else { if param, e := json.Marshal(r); e != nil { log.Errorf("sap order param marshal:%v", e) } else { saplog.Param = string(param) saplog.Name = "sap-order" s.d.DB.Create(saplog) } if e == nil { return errors.Errorf("sap order :%s", rp.Data.MsgText), "" } else { return errors.Wrapf(e, "sap order error:%v", e), "" } } //*/ return nil, "" } func AutoSrmReturnOrderJob() { orders := []model.BigRefunddetail{} if e := s.d.DB.Where("srmStatus=0 and buyerDate >= '2022-10-25' and sapStatus=1 and ifnull(sapNumber,0) > 0 ").Find(&orders, model.BigRefunddetail{SrmStatus: 0}).Error; e != nil { log.Errorf("AutoSrmOrderJob error: %v", e) return } var buyeCodes []string for _, v := range orders { buyeCodes = append(buyeCodes, v.BuyeCode) } if len(buyeCodes) > 0 { s.d.DB.Exec(` update bigrefunddetail set srmStatus = 2 where buyeCode in (?)`, buyeCodes) } for _, v := range orders { SrmReturnOrder(&v, "1") } } func SrmReturnOrder(p *model.BigRefunddetail, isReturn string) { r := new(http.SrmOrderReq) rp := new(http.SrmResp) parts := []model.Refunddetail{} pa := new(model.Pasture) pv := new(model.Provider) //pc := new(model.Bigpartpurchase) //dp := new(model.Department) r.Dest.Url = "http://srm.vip.xiandaimuye.com/gateway/serviceApi/invoke/QZbycode/saveByEquipment" if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil { log.Error(e) return } if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil { log.Errorf("pasture query :id=%d,%v", p.PastureID, e) return } if e := s.d.DB.Where("amount>0").Find(&parts, model.Refunddetail{BigID: p.ID}).Error; e != nil || len(parts) == 0 { log.Errorf("buydetail query :bigid=%d,%v", p.ID, e) return } //if e := s.d.DB.Where("matchCode = ? ", p.MatchCode).Find(&pc, model.Bigpartpurchase{}).Error; e != nil { // return //} //if e := s.d.DB.Where("id = ? ", pc.DepartmentID).Find(&dp, model.Department{}).Error; e != nil { // return //} //if len(parts) > 0 { // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil { // } //} //r.Data.CompanyCode = pa.CompanyCode r.Data.VendorErpCode = pv.SapCode r.Data.PurchaseOrderDate = p.BuyerDate.Format("20060102") r.Data.CurrencyCode = "CNY" r.Data.PurchaseOrderType = "ZNB4" r.Data.VendorName = pv.ProviderName r.Data.DeliveryTypeCode = "1" r.Data.IsReturn = isReturn r.Data.Remark = "" r.Data.ErpPurchaseOrderNo = p.SapNumber r.Data.SapCode = pv.SapCode r.Data.PurchaseOrderNo = p.BuyeCode //if dp.CompanyCode == "" { r.Data.CompanyCode = pa.CompanyCode r.Data.PurchasingOrgCode = pa.ParchaseOrganization r.Data.PurchasingGroupCode = pa.PurchasingGroup //} else { // r.Data.CompanyCode = dp.CompanyCode // r.Data.PurchasingOrgCode = dp.ParchaseOrganization // r.Data.PurchasingGroupCode = dp.PurchasingGroup //} for _, v := range parts { detail := http.SrmOrderDetail{} c := new(model.Contract) bc := new(model.BigContract) pr := new(model.PartRepertory) par := new(model.Parts) //part := new(model.Parts) if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil { log.Errorf("order detail error:%v", e) //return } if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil { log.Errorf("order detail error:%v", e) //return } if len(c.PartCode) > 0 { if e := s.d.DB.First(par, model.Parts{PartCode: c.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } } else if len(v.PartCode) > 0 { if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } } if c.Brand != "" { detail.Manufacturer = c.Brand } else { brand := new(model.Brand) if e := s.d.DB.First(brand, model.Brand{ID: v.BrandID}).Error; e != nil { //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), "" } detail.Manufacturer = brand.BrandName } price := c.Price if price == 0 { price = v.Price } if c.PartCode != "" { detail.OrderUnitCode = c.Unit detail.MaterialCode = c.PartCode detail.MaterialName = c.PartName detail.PricingUnitCode = c.Unit } else { detail.OrderUnitCode = par.Unit detail.MaterialCode = par.PartCode detail.MaterialName = par.Name detail.PricingUnitCode = par.Unit } s.d.DB.First(pr, model.PartRepertory{ContractID: v.ContractID}) r.Data.TotalNonTaxAmount += price r.Data.TotalTaxAmount += price detail.RowNo = strconv.Itoa(v.RowNumber) //detail.Manufacturer = pa.FactoryCode //detail.Manufacturer = //if dp.CompanyCode == "" { detail.Manufacturer = pa.FactoryCode detail.PlantCode = pa.FactoryCode //} else { // detail.Manufacturer = dp.Factory // detail.PlantCode = dp.Factory //} detail.OrderQty = fmt.Sprintf("%d", v.Amount) detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") detail.TaxRateCode = "J0" detail.NonTaxPrice = price detail.MaterialDesc = par.Specification if len(c.PartCode) > 0 { detail.MaterialGroupCode = strings.ReplaceAll(c.PartCode[:strings.LastIndex(c.PartCode, ".")], ".", "") } else if len(v.PartCode) > 0 { fmt.Println(v.PartCode) detail.MaterialGroupCode = strings.ReplaceAll(v.PartCode[:strings.LastIndex(v.PartCode, ".")], ".", "") } detail.Tax = "0" detail.ConfirmDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102") //detail.PlantCode = pa.FactoryCode //if dp.CompanyCode == "" { //detail.PlantCode = pa.FactoryCode //} else { // detail.PlantCode = dp.Factory //} detail.StockLocationCode = "1004" detail.QualityCheck = "0" detail.IsReturn = isReturn detail.OverDeliveryLimit = "0" detail.ShortDeliveryLimit = "0" detail.SourceNo = p.BuyeCode[4:] detail.ContractCode = bc.ContractCode detail.Remark = c.Remark //r.Data.Detail = append(r.Data.Detail, detail) if bc.IsZeroStock == 1 { detail.PurchaseCategory = "2" } else { detail.PurchaseCategory = "0" } detail.IsFree = "0" detail.PriceBase = "1" astr := strconv.FormatFloat(detail.NonTaxPrice, 'f', -1, 64) b := strings.Index(astr, ".") if len(astr[b+1:]) > 2 && b > 0 { num, _ := strconv.ParseFloat(astr[b+1:], 64) if num > 0 { detail.NonTaxPrice = detail.NonTaxPrice * 1000 detail.NonTaxPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NonTaxPrice), 64) detail.PriceBase = "1000" } } detail.TaxAmount = detail.NonTaxPrice detail.TaxPrice = detail.NonTaxPrice detail.NonTaxAmount = detail.NonTaxPrice r.Data.Detail = append(r.Data.Detail, detail) //if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil { // log.Errorln(e, v.ID) //} } rbyte, _ := json.Marshal([]interface{}{r.Data}) fmt.Println(string(rbyte)) saplog := new(model.SapLog) saplog.Url = r.Dest.Url saplog.Param = string(rbyte) saplog.Name = "srm退货采购订单" if e := s.SyncSrm(r, rp, rbyte); e != nil { s.d.DB.Create(saplog) log.Errorf("sap buy order error: %v", e) p.SapStatus = 3 } else { s.d.DB.Create(saplog) if rp.Success { // log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber) p.SapStatus = 1 p.SapNumber = rp.Code } else { log.Warnf("buy order fail :msg=%s,r=%v", rp.Code, r) p.SapStatus = 2 // pp.Print(r) } } if p.SapStatus == 1 { if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigRefunddetail{SrmStatus: p.SapStatus, SrmNumber: p.SapNumber}).Error; e != nil { log.Errorf("update big buy detail error: %v", e) } } else { if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigRefunddetail{SrmStatus: p.SapStatus, SrmError: rp.Message}).Error; e != nil { log.Errorf("update big buy detail error: %v", e) } } } func NextProcurement(sqlname, procurementId string, tx *sqlx.Tx) error { if sqlname == "updateBigbuydetailStatu" { p := new(model.BigBuyDetail) s.d.DB.Where("id = ?", procurementId).First(&p) SapOrder(p, "X") //SrmOrder(p, "1") } else if sqlname == "shutDownBigrefunddetail" { p := new(model.BigRefunddetail) s.d.DB.Where("id = ?", procurementId).First(&p) SapReturnOrder(p, "X") //SrmReturnOrder(p, "1") } return nil }