order.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. package service
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strconv"
  6. "strings"
  7. "time"
  8. _ "github.com/go-sql-driver/mysql"
  9. "github.com/jmoiron/sqlx"
  10. "github.com/pkg/errors"
  11. log "github.com/sirupsen/logrus"
  12. "kpt.xdmy/apiserver/config"
  13. "kpt.xdmy/apiserver/model"
  14. "kpt.xdmy/apiserver/model/http"
  15. "kpt.xdmy/pkg/util"
  16. )
  17. // 推送采购订单到sap(业务触发),已关闭
  18. func (s *Service) PurchaseOrder(p interface{}) {
  19. r := new(model.BigBuyDetailReq)
  20. if e := util.Unmarshal(p, r); e != nil {
  21. log.Errorf("purchaseorder param :%v ", e)
  22. log.Info(p)
  23. return
  24. }
  25. if r.ID == "" && r.Code == "" {
  26. log.Error("buy order request param is empty")
  27. return
  28. }
  29. bdetails := []model.BigBuyDetail{}
  30. bpp := new(model.Bigpartpurchase)
  31. if r.ID != "" {
  32. pid, err := strconv.ParseInt(r.ID, 10, 32)
  33. if err != nil {
  34. log.Errorf("parseInt purchase id :%v", err)
  35. }
  36. id := int(pid)
  37. if e := s.d.DB.First(bpp, model.Bigpartpurchase{ID: id}).Error; e != nil {
  38. log.Error("Bigpartpurchase query error", e)
  39. return
  40. }
  41. if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: bpp.OrderNumber}).Error; e != nil || len(bdetails) == 0 {
  42. log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e)
  43. return
  44. }
  45. } else if r.Code != "" {
  46. if e := s.d.DB.Where(" ZeroCou >0 ").Find(&bdetails, model.BigBuyDetail{MatchCode: r.Code}).Error; e != nil || len(bdetails) == 0 {
  47. log.Errorf("Bigbuydetail query :matchcode =%s,e=%v", r.Code, e)
  48. return
  49. }
  50. }
  51. for _, v := range bdetails {
  52. SapOrder(&v, "")
  53. SrmOrder(&v, "0")
  54. }
  55. }
  56. // AutoSapOrderJob 定时(每分钟 一次)读取未同步的采购订单,同步到sap
  57. // 同步失败的采购订单,变更状态,改为手动同步
  58. // 状态(sapStatus):0,未同步;1,成功;2,失败
  59. func AutoSapOrderJob() {
  60. orders := []model.BigBuyDetail{}
  61. 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
  62. 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 {
  63. log.Errorf("AutoSapOrderJob error: %v", e)
  64. return
  65. }
  66. var buyeCodes []string
  67. for _, v := range orders {
  68. buyeCodes = append(buyeCodes, v.BuyeCode)
  69. }
  70. if len(buyeCodes) > 0 {
  71. err := s.d.DB.Exec(` update bigbuydetail set sapStatus = 2 where buyeCode in (?)`, buyeCodes).Error
  72. fmt.Println(err)
  73. }
  74. for _, v := range orders {
  75. e, sapNumber := SapOrder(&v, "")
  76. up := model.BigBuyDetail{SapNumber: sapNumber}
  77. if e != nil {
  78. up.SapStatus = 2
  79. up.SapError = e.Error()
  80. } else {
  81. up.SapStatus = 1
  82. }
  83. if e := s.d.DB.Model(&v).Where("buyeCode =?", v.BuyeCode).Updates(up); e != nil {
  84. log.Errorf("BigBuyDetail update error: %v", e)
  85. }
  86. }
  87. }
  88. // 手动同步采购订单到sap
  89. func ManaulSapOrderJob(buyeCode string) (err error) {
  90. order := new(model.BigBuyDetail)
  91. if e := s.d.DB.First(order, model.BigBuyDetail{BuyeCode: buyeCode}).Error; e != nil {
  92. err = errors.Wrapf(e, "ManaulSapOrderJob BigBuyDetail query ")
  93. return
  94. }
  95. e, sapNumber := SapOrder(order, "")
  96. up := model.BigBuyDetail{SapNumber: sapNumber}
  97. if e != nil {
  98. up.SapStatus = 2
  99. up.SapError = e.Error()
  100. err = errors.Wrapf(e, "ManaulSapOrder sap ")
  101. } else {
  102. up.SapStatus = 1
  103. }
  104. if e := s.d.DB.Model(order).Where("buyeCode=?", buyeCode).Updates(up).Error; e != nil {
  105. log.Errorf("BigBuyDetail update error: %v", e)
  106. }
  107. return
  108. }
  109. // 发送采购订单到sap
  110. func SapOrder(p *model.BigBuyDetail, dflag string) (error, string) {
  111. r := new(http.SapOrderReq)
  112. rp := new(http.OrderResp)
  113. parts := []model.BuyDetail{}
  114. pa := new(model.Pasture)
  115. pv := new(model.Provider)
  116. //pc := new(model.Bigpartpurchase)
  117. //dp := new(model.Department)
  118. r.Dest.DestID = "EQMAN"
  119. r.Dest.BussTp = "MM007"
  120. //r.Dest.Url = "http://192.168.61.117/SAPQ0/Common/MM007/PurchaseOrder"
  121. //r.Dest.Url = "http://192.168.61.117/SAPP0/Common/MM007/PurchaseOrder"
  122. r.Dest.Url = fmt.Sprintf("%s/Common/MM007/PurchaseOrder", config.Conf.Http.Routing)
  123. if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil {
  124. return errors.Wrapf(e, "provider query:id=%d", p.ProviderID), ""
  125. }
  126. if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil {
  127. return errors.Wrapf(e, "pasture query:id=%d", p.PastureID), ""
  128. }
  129. if e := s.d.DB.Where("amount>0").Find(&parts, model.BuyDetail{BigID: p.ID}).Order("rowNumber").Error; e != nil || len(parts) == 0 {
  130. return errors.Wrapf(e, "buydetail query:bigid=%d", p.ID), ""
  131. }
  132. //if len(parts) > 0 {
  133. // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil {
  134. // }
  135. //}
  136. r.Data.IsCancle = ""
  137. r.Data.PayCondition = ""
  138. r.Data.SupplierCode = pv.SapCode
  139. r.Data.OrderDate = p.BuyerDate.Format("20060102")
  140. r.Data.CurrencyCode = "CNY"
  141. r.Data.ProofType = "ZNB4"
  142. r.Data.EqSysCode = p.BuyeCode
  143. //if dp.CompanyCode == "" {
  144. r.Data.CompanyCode = pa.CompanyCode
  145. r.Data.Organization = pa.ParchaseOrganization
  146. r.Data.Group = pa.PurchasingGroup
  147. //} else {
  148. // r.Data.CompanyCode = dp.CompanyCode
  149. // r.Data.Organization = dp.ParchaseOrganization
  150. // r.Data.Group = dp.PurchasingGroup
  151. //}
  152. for i, v := range parts {
  153. detail := http.SapOrderDetail{}
  154. c := new(model.Contract)
  155. bc := new(model.BigContract)
  156. par := new(model.Parts)
  157. if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
  158. //return errors.Wrapf(e, "contract query :id=%d", v.ContractID), ""
  159. }
  160. if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
  161. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  162. }
  163. if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil {
  164. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  165. }
  166. if v.RowNumber > 0 {
  167. detail.RowNumber = strconv.Itoa(v.RowNumber)
  168. } else {
  169. detail.RowNumber = fmt.Sprintf("%d", (i+1)*10)
  170. }
  171. //if dp.CompanyCode == "" {
  172. detail.Factory = pa.FactoryCode
  173. //} else {
  174. // detail.Factory = dp.Factory
  175. //}
  176. detail.Quantity = fmt.Sprintf("%d", v.Amount)
  177. detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  178. detail.TaxCode = "J0"
  179. detail.Per = "1"
  180. detail.Location = "1004"
  181. detail.IsOwn = util.ZeroStr(bc.IsZeroStock == 1, "K")
  182. detail.NetPrice = c.Price
  183. if c.PartCode != "" {
  184. detail.Unit = c.Unit
  185. detail.MaterialCode = c.PartCode
  186. } else {
  187. if detail.NetPrice == 0 {
  188. detail.NetPrice = v.Price
  189. }
  190. detail.Unit = par.Unit
  191. detail.MaterialCode = v.PartCode
  192. }
  193. detail.Dflag = dflag
  194. astr := strconv.FormatFloat(detail.NetPrice, 'f', -1, 64)
  195. b := strings.Index(astr, ".")
  196. if len(astr[b+1:]) > 2 && b > 0 {
  197. num, _ := strconv.ParseFloat(astr[b+1:], 64)
  198. if num > 0 {
  199. detail.NetPrice = detail.NetPrice * 1000
  200. detail.NetPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NetPrice), 64)
  201. detail.Per = "1000"
  202. }
  203. }
  204. r.Data.Detail = append(r.Data.Detail, detail)
  205. if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", detail.RowNumber).Error; e != nil {
  206. log.Errorln(e, v.ID)
  207. }
  208. }
  209. rbyte, _ := json.Marshal(r)
  210. e := s.SyncSap(r, &rp, rbyte)
  211. saplog := new(model.SapLog)
  212. if e == nil && rp.Dest.Status == "S" {
  213. s.d.DB.Create(saplog)
  214. log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber)
  215. return nil, rp.Data.SapNumber
  216. } else {
  217. if param, e := json.Marshal(r); e != nil {
  218. log.Errorf("sap order param marshal:%v", e)
  219. } else {
  220. saplog.Param = string(param)
  221. saplog.Name = "sap-order"
  222. s.d.DB.Create(saplog)
  223. }
  224. if e == nil {
  225. return errors.Errorf("sap order :%s", rp.Data.MsgText), ""
  226. } else {
  227. return errors.Wrapf(e, "sap order error:%v", e), ""
  228. }
  229. }
  230. //*/
  231. return nil, ""
  232. }
  233. func AutoSrmOrderJob() {
  234. orders := []model.BigBuyDetail{}
  235. 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 {
  236. log.Errorf("AutoSrmOrderJob error: %v", e)
  237. return
  238. }
  239. var buyeCodes []string
  240. for _, v := range orders {
  241. buyeCodes = append(buyeCodes, v.BuyeCode)
  242. }
  243. if len(buyeCodes) > 0 {
  244. s.d.DB.Exec(` update bigbuydetail set srmStatus = 2 where buyeCode in (?)`, buyeCodes)
  245. }
  246. for _, v := range orders {
  247. SrmOrder(&v, "0")
  248. }
  249. }
  250. func ManaulSrmOrderJob(buyeCode string) {
  251. orders := []model.BigBuyDetail{}
  252. if e := s.d.DB.Where("buyeCode=?", buyeCode).Where("sapStatus=1").Find(&orders, model.BigBuyDetail{SrmStatus: 0}).Error; e != nil {
  253. log.Errorf("ManaulSrmOrderJob error: %v", e)
  254. return
  255. }
  256. for _, v := range orders {
  257. SrmOrder(&v, "0")
  258. }
  259. }
  260. func SrmOrder(p *model.BigBuyDetail, IsReturn string) {
  261. r := new(http.SrmOrderReq)
  262. rp := new(http.SrmResp)
  263. parts := []model.BuyDetail{}
  264. pa := new(model.Pasture)
  265. pv := new(model.Provider)
  266. //pc := new(model.Bigpartpurchase)
  267. //dp := new(model.Department)
  268. r.Dest.Url = "http://srm.vip.xiandaimuye.com/gateway/serviceApi/invoke/QZbycode/saveByEquipment"
  269. if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil {
  270. log.Error(e)
  271. return
  272. }
  273. if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil {
  274. log.Errorf("pasture query :id=%d,%v", p.PastureID, e)
  275. return
  276. }
  277. if e := s.d.DB.Where("amount>0").Find(&parts, model.BuyDetail{BigID: p.ID}).Error; e != nil || len(parts) == 0 {
  278. log.Errorf("buydetail query :bigid=%d,%v", p.ID, e)
  279. return
  280. }
  281. //if e := s.d.DB.Where("matchCode = ? ", p.MatchCode).Find(&pc, model.Bigpartpurchase{}).Error; e != nil {
  282. // return
  283. //}
  284. //if e := s.d.DB.Where("id = ? ", pc.DepartmentID).Find(&dp, model.Department{}).Error; e != nil {
  285. // return
  286. //}
  287. //if len(parts) > 0 {
  288. // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil {
  289. // }
  290. //}
  291. //r.Data.CompanyCode = pa.CompanyCode
  292. r.Data.VendorErpCode = pv.SapCode
  293. r.Data.PurchaseOrderDate = p.BuyerDate.Format("20060102")
  294. r.Data.CurrencyCode = "CNY"
  295. r.Data.PurchaseOrderType = "ZNB4"
  296. r.Data.VendorName = pv.ProviderName
  297. r.Data.DeliveryTypeCode = "1"
  298. r.Data.IsReturn = "0"
  299. r.Data.Remark = ""
  300. r.Data.ErpPurchaseOrderNo = p.SapNumber
  301. r.Data.SapCode = pv.SapCode
  302. r.Data.PurchaseOrderNo = p.BuyeCode
  303. //if dp.CompanyCode == "" {
  304. r.Data.CompanyCode = pa.CompanyCode
  305. r.Data.PurchasingOrgCode = pa.ParchaseOrganization
  306. r.Data.PurchasingGroupCode = pa.PurchasingGroup
  307. //} else {
  308. // r.Data.CompanyCode = dp.CompanyCode
  309. // r.Data.PurchasingOrgCode = dp.ParchaseOrganization
  310. // r.Data.PurchasingGroupCode = dp.PurchasingGroup
  311. //}
  312. for _, v := range parts {
  313. detail := http.SrmOrderDetail{}
  314. c := new(model.Contract)
  315. bc := new(model.BigContract)
  316. pr := new(model.PartRepertory)
  317. par := new(model.Parts)
  318. //part := new(model.Parts)
  319. if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
  320. log.Errorf("order detail error:%v", e)
  321. //return
  322. }
  323. if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
  324. log.Errorf("order detail error:%v", e)
  325. //return
  326. }
  327. if len(c.PartCode) > 0 {
  328. if e := s.d.DB.First(par, model.Parts{PartCode: c.PartCode}).Error; e != nil {
  329. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  330. }
  331. } else if len(v.PartCode) > 0 {
  332. if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil {
  333. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  334. }
  335. }
  336. if c.Brand != "" {
  337. detail.Manufacturer = c.Brand
  338. } else {
  339. brand := new(model.Brand)
  340. if e := s.d.DB.First(brand, model.Brand{ID: v.BrandID}).Error; e != nil {
  341. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  342. }
  343. detail.Manufacturer = brand.BrandName
  344. }
  345. price := c.Price
  346. if price == 0 {
  347. price = v.Price
  348. }
  349. if c.PartCode != "" {
  350. detail.OrderUnitCode = c.Unit
  351. detail.MaterialCode = c.PartCode
  352. detail.MaterialName = c.PartName
  353. detail.PricingUnitCode = c.Unit
  354. } else {
  355. detail.OrderUnitCode = par.Unit
  356. detail.MaterialCode = par.PartCode
  357. detail.MaterialName = par.Name
  358. detail.PricingUnitCode = par.Unit
  359. }
  360. s.d.DB.First(pr, model.PartRepertory{ContractID: v.ContractID})
  361. r.Data.TotalNonTaxAmount += price
  362. r.Data.TotalTaxAmount += price
  363. detail.RowNo = strconv.Itoa(v.RowNumber)
  364. //detail.Manufacturer = pa.FactoryCode
  365. //detail.Manufacturer =
  366. //if dp.CompanyCode == "" {
  367. detail.Manufacturer = pa.FactoryCode
  368. detail.PlantCode = pa.FactoryCode
  369. //} else {
  370. // detail.Manufacturer = dp.Factory
  371. // detail.PlantCode = dp.Factory
  372. //}
  373. detail.OrderQty = fmt.Sprintf("%d", v.Amount)
  374. detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  375. detail.TaxRateCode = "J0"
  376. detail.NonTaxPrice = price
  377. detail.MaterialDesc = par.Specification
  378. if len(c.PartCode) > 0 {
  379. detail.MaterialGroupCode = strings.ReplaceAll(c.PartCode[:strings.LastIndex(c.PartCode, ".")], ".", "")
  380. } else if len(v.PartCode) > 0 {
  381. fmt.Println(v.PartCode)
  382. detail.MaterialGroupCode = strings.ReplaceAll(v.PartCode[:strings.LastIndex(v.PartCode, ".")], ".", "")
  383. }
  384. detail.Tax = "0"
  385. detail.ConfirmDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  386. //detail.PlantCode = pa.FactoryCode
  387. //if dp.CompanyCode == "" {
  388. //detail.PlantCode = pa.FactoryCode
  389. //} else {
  390. // detail.PlantCode = dp.Factory
  391. //}
  392. detail.StockLocationCode = "1004"
  393. detail.QualityCheck = "0"
  394. detail.IsReturn = "0"
  395. detail.OverDeliveryLimit = "0"
  396. detail.ShortDeliveryLimit = "0"
  397. detail.SourceNo = p.BuyeCode[4:]
  398. detail.ContractCode = bc.ContractCode
  399. detail.Remark = c.Remark
  400. //r.Data.Detail = append(r.Data.Detail, detail)
  401. if bc.IsZeroStock == 1 {
  402. detail.PurchaseCategory = "2"
  403. } else {
  404. detail.PurchaseCategory = "0"
  405. }
  406. detail.IsFree = "0"
  407. detail.PriceBase = "1"
  408. astr := strconv.FormatFloat(detail.NonTaxPrice, 'f', -1, 64)
  409. b := strings.Index(astr, ".")
  410. if len(astr[b+1:]) > 2 && b > 0 {
  411. num, _ := strconv.ParseFloat(astr[b+1:], 64)
  412. if num > 0 {
  413. detail.NonTaxPrice = detail.NonTaxPrice * 1000
  414. detail.NonTaxPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NonTaxPrice), 64)
  415. detail.PriceBase = "1000"
  416. }
  417. }
  418. detail.TaxAmount = detail.NonTaxPrice
  419. detail.TaxPrice = detail.NonTaxPrice
  420. detail.NonTaxAmount = detail.NonTaxPrice
  421. r.Data.Detail = append(r.Data.Detail, detail)
  422. //if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil {
  423. // log.Errorln(e, v.ID)
  424. //}
  425. }
  426. rbyte, _ := json.Marshal([]interface{}{r.Data})
  427. fmt.Println(string(rbyte))
  428. saplog := new(model.SapLog)
  429. if e := s.SyncSrm(r, rp, rbyte); e != nil {
  430. s.d.DB.Create(saplog)
  431. log.Errorf("sap buy order error: %v", e)
  432. p.SapStatus = 3
  433. } else {
  434. s.d.DB.Create(saplog)
  435. if rp.Success {
  436. // log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber)
  437. p.SapStatus = 1
  438. p.SapNumber = rp.Code
  439. } else {
  440. log.Warnf("buy order fail :msg=%s,r=%v", rp.Code, r)
  441. p.SapStatus = 2
  442. // pp.Print(r)
  443. }
  444. }
  445. if p.SapStatus == 1 {
  446. if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigBuyDetail{SrmStatus: p.SapStatus, SrmNumber: p.SapNumber}).Error; e != nil {
  447. log.Errorf("update big buy detail error: %v", e)
  448. }
  449. } else {
  450. if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigBuyDetail{SrmStatus: p.SapStatus, SrmError: rp.Message}).Error; e != nil {
  451. log.Errorf("update big buy detail error: %v", e)
  452. }
  453. }
  454. }
  455. // AutoSapReturnOrderJob 定时(每分钟 一次)读取未同步的采购订单,同步到sap
  456. // 同步失败的采购订单,变更状态,改为手动同步
  457. // 状态(sapStatus):0,未同步;1,成功;2,失败
  458. func AutoSapReturnOrderJob() {
  459. orders := []model.BigRefunddetail{}
  460. if e := s.d.DB.Raw(`SELECT
  461. b.*
  462. FROM
  463. bigrefunddetail b
  464. JOIN pasture p ON b.pastureId = p.id
  465. WHERE
  466. buyerDate > '2022-11-02'
  467. AND p.vendor = 1
  468. AND b.sapStatus = 0`).Find(&orders, model.BigRefunddetail{}).Error; e != nil {
  469. log.Errorf("AutoSapOrderJob error: %v", e)
  470. return
  471. }
  472. var buyeCodes []string
  473. for _, v := range orders {
  474. buyeCodes = append(buyeCodes, v.BuyeCode)
  475. }
  476. if len(buyeCodes) > 0 {
  477. err := s.d.DB.Exec(` update bigrefunddetail set sapStatus = 2 where buyeCode in (?)`, buyeCodes).Error
  478. fmt.Println(err)
  479. }
  480. for _, v := range orders {
  481. e, sapNumber := SapReturnOrder(&v, "")
  482. up := model.BigRefunddetail{SapNumber: sapNumber}
  483. if e != nil {
  484. up.SapStatus = 2
  485. up.SapError = e.Error()
  486. } else {
  487. up.SapStatus = 1
  488. }
  489. if e := s.d.DB.Model(&v).Where("buyeCode =?", v.BuyeCode).Updates(up); e != nil {
  490. log.Errorf("BigBuyDetail update error: %v", e)
  491. }
  492. }
  493. }
  494. // SapReturnOrder 发送采购订单到sap
  495. func SapReturnOrder(p *model.BigRefunddetail, dflag string) (error, string) {
  496. r := new(http.SapOrderReq)
  497. rp := new(http.OrderResp)
  498. parts := []model.Refunddetail{}
  499. pa := new(model.Pasture)
  500. pv := new(model.Provider)
  501. //pc := new(model.Bigpartpurchase)
  502. //dp := new(model.Department)
  503. r.Dest.DestID = "EQMAN"
  504. r.Dest.BussTp = "MM007"
  505. //r.Dest.Url = "http://192.168.61.117/SAPQ0/Common/MM007/PurchaseOrder"
  506. //r.Dest.Url = "http://192.168.61.117/SAPP0/Common/MM007/PurchaseOrder"
  507. r.Dest.Url = fmt.Sprintf("%s/Common/MM007/PurchaseOrder", config.Conf.Http.Routing)
  508. if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil {
  509. return errors.Wrapf(e, "provider query:id=%d", p.ProviderID), ""
  510. }
  511. if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil {
  512. return errors.Wrapf(e, "pasture query:id=%d", p.PastureID), ""
  513. }
  514. if e := s.d.DB.Where("amount>0").Find(&parts, model.Refunddetail{BigID: p.ID}).Order("rowNumber").Error; e != nil || len(parts) == 0 {
  515. return errors.Wrapf(e, "buydetail query:bigid=%d", p.ID), ""
  516. }
  517. //if len(parts) > 0 {
  518. // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil {
  519. // }
  520. //}
  521. //r.Data.IsCancle = ""
  522. r.Data.PayCondition = ""
  523. r.Data.SupplierCode = pv.SapCode
  524. r.Data.OrderDate = p.BuyerDate.Format("20060102")
  525. r.Data.CurrencyCode = "CNY"
  526. r.Data.ProofType = "ZNB4"
  527. r.Data.EqSysCode = p.BuyeCode
  528. //if dp.CompanyCode == "" {
  529. r.Data.CompanyCode = pa.CompanyCode
  530. r.Data.Organization = pa.ParchaseOrganization
  531. r.Data.Group = pa.PurchasingGroup
  532. //} else {
  533. // r.Data.CompanyCode = dp.CompanyCode
  534. // r.Data.Organization = dp.ParchaseOrganization
  535. // r.Data.Group = dp.PurchasingGroup
  536. //}
  537. r.Data.IsCancle = "X"
  538. for i, v := range parts {
  539. detail := http.SapOrderDetail{}
  540. c := new(model.Contract)
  541. bc := new(model.BigContract)
  542. par := new(model.Parts)
  543. if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
  544. //return errors.Wrapf(e, "contract query :id=%d", v.ContractID), ""
  545. }
  546. if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
  547. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  548. }
  549. if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil {
  550. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  551. }
  552. if v.RowNumber > 0 {
  553. detail.RowNumber = strconv.Itoa(v.RowNumber)
  554. } else {
  555. detail.RowNumber = fmt.Sprintf("%d", (i+1)*10)
  556. }
  557. //if dp.CompanyCode == "" {
  558. detail.Factory = pa.FactoryCode
  559. //} else {
  560. // detail.Factory = dp.Factory
  561. //}
  562. detail.Quantity = fmt.Sprintf("%d", v.Amount)
  563. detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  564. detail.TaxCode = "J0"
  565. detail.Per = "1"
  566. detail.Location = "1004"
  567. detail.IsOwn = util.ZeroStr(bc.IsZeroStock == 1, "K")
  568. detail.NetPrice = c.Price
  569. detail.Dflag = dflag
  570. if c.PartCode != "" {
  571. detail.Unit = c.Unit
  572. detail.MaterialCode = c.PartCode
  573. } else {
  574. if detail.NetPrice == 0 {
  575. detail.NetPrice = v.Price
  576. }
  577. detail.Unit = par.Unit
  578. detail.MaterialCode = v.PartCode
  579. }
  580. astr := strconv.FormatFloat(detail.NetPrice, 'f', -1, 64)
  581. b := strings.Index(astr, ".")
  582. if len(astr[b+1:]) > 2 && b > 0 {
  583. num, _ := strconv.ParseFloat(astr[b+1:], 64)
  584. if num > 0 {
  585. detail.NetPrice = detail.NetPrice * 1000
  586. detail.NetPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NetPrice), 64)
  587. detail.Per = "1000"
  588. }
  589. }
  590. r.Data.Detail = append(r.Data.Detail, detail)
  591. if e := s.d.DB.Model(&model.Refunddetail{}).Where("id=?", v.ID).Update("rowNumber", detail.RowNumber).Error; e != nil {
  592. log.Errorln(e, v.ID)
  593. }
  594. }
  595. rbyte, _ := json.Marshal(r)
  596. e := s.SyncSap(r, &rp, rbyte)
  597. saplog := new(model.SapLog)
  598. if e == nil && rp.Dest.Status == "S" {
  599. s.d.DB.Create(saplog)
  600. log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber)
  601. return nil, rp.Data.SapNumber
  602. } else {
  603. if param, e := json.Marshal(r); e != nil {
  604. log.Errorf("sap order param marshal:%v", e)
  605. } else {
  606. saplog.Param = string(param)
  607. saplog.Name = "sap-order"
  608. s.d.DB.Create(saplog)
  609. }
  610. if e == nil {
  611. return errors.Errorf("sap order :%s", rp.Data.MsgText), ""
  612. } else {
  613. return errors.Wrapf(e, "sap order error:%v", e), ""
  614. }
  615. }
  616. //*/
  617. return nil, ""
  618. }
  619. func AutoSrmReturnOrderJob() {
  620. orders := []model.BigRefunddetail{}
  621. 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 {
  622. log.Errorf("AutoSrmOrderJob error: %v", e)
  623. return
  624. }
  625. var buyeCodes []string
  626. for _, v := range orders {
  627. buyeCodes = append(buyeCodes, v.BuyeCode)
  628. }
  629. if len(buyeCodes) > 0 {
  630. s.d.DB.Exec(` update bigrefunddetail set srmStatus = 2 where buyeCode in (?)`, buyeCodes)
  631. }
  632. for _, v := range orders {
  633. SrmReturnOrder(&v, "1")
  634. }
  635. }
  636. func SrmReturnOrder(p *model.BigRefunddetail, isReturn string) {
  637. r := new(http.SrmOrderReq)
  638. rp := new(http.SrmResp)
  639. parts := []model.Refunddetail{}
  640. pa := new(model.Pasture)
  641. pv := new(model.Provider)
  642. //pc := new(model.Bigpartpurchase)
  643. //dp := new(model.Department)
  644. r.Dest.Url = "http://srm.vip.xiandaimuye.com/gateway/serviceApi/invoke/QZbycode/saveByEquipment"
  645. if e := s.d.DB.First(pv, model.Provider{ID: p.ProviderID}).Error; e != nil {
  646. log.Error(e)
  647. return
  648. }
  649. if e := s.d.DB.First(pa, model.Pasture{ID: p.PastureID}).Error; e != nil {
  650. log.Errorf("pasture query :id=%d,%v", p.PastureID, e)
  651. return
  652. }
  653. if e := s.d.DB.Where("amount>0").Find(&parts, model.Refunddetail{BigID: p.ID}).Error; e != nil || len(parts) == 0 {
  654. log.Errorf("buydetail query :bigid=%d,%v", p.ID, e)
  655. return
  656. }
  657. //if e := s.d.DB.Where("matchCode = ? ", p.MatchCode).Find(&pc, model.Bigpartpurchase{}).Error; e != nil {
  658. // return
  659. //}
  660. //if e := s.d.DB.Where("id = ? ", pc.DepartmentID).Find(&dp, model.Department{}).Error; e != nil {
  661. // return
  662. //}
  663. //if len(parts) > 0 {
  664. // if e := s.d.DB.Where("name = ? ", parts[0].DepartmentName).Where("pastureid = ? ", p.PastureID).First(&dp, model.Department{}).Error; e != nil {
  665. // }
  666. //}
  667. //r.Data.CompanyCode = pa.CompanyCode
  668. r.Data.VendorErpCode = pv.SapCode
  669. r.Data.PurchaseOrderDate = p.BuyerDate.Format("20060102")
  670. r.Data.CurrencyCode = "CNY"
  671. r.Data.PurchaseOrderType = "ZNB4"
  672. r.Data.VendorName = pv.ProviderName
  673. r.Data.DeliveryTypeCode = "1"
  674. r.Data.IsReturn = isReturn
  675. r.Data.Remark = ""
  676. r.Data.ErpPurchaseOrderNo = p.SapNumber
  677. r.Data.SapCode = pv.SapCode
  678. r.Data.PurchaseOrderNo = p.BuyeCode
  679. //if dp.CompanyCode == "" {
  680. r.Data.CompanyCode = pa.CompanyCode
  681. r.Data.PurchasingOrgCode = pa.ParchaseOrganization
  682. r.Data.PurchasingGroupCode = pa.PurchasingGroup
  683. //} else {
  684. // r.Data.CompanyCode = dp.CompanyCode
  685. // r.Data.PurchasingOrgCode = dp.ParchaseOrganization
  686. // r.Data.PurchasingGroupCode = dp.PurchasingGroup
  687. //}
  688. for _, v := range parts {
  689. detail := http.SrmOrderDetail{}
  690. c := new(model.Contract)
  691. bc := new(model.BigContract)
  692. pr := new(model.PartRepertory)
  693. par := new(model.Parts)
  694. //part := new(model.Parts)
  695. if e := s.d.DB.First(c, model.Contract{ID: v.ContractID}).Error; e != nil {
  696. log.Errorf("order detail error:%v", e)
  697. //return
  698. }
  699. if e := s.d.DB.First(bc, model.BigContract{ID: c.BigID}).Error; e != nil {
  700. log.Errorf("order detail error:%v", e)
  701. //return
  702. }
  703. if len(c.PartCode) > 0 {
  704. if e := s.d.DB.First(par, model.Parts{PartCode: c.PartCode}).Error; e != nil {
  705. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  706. }
  707. } else if len(v.PartCode) > 0 {
  708. if e := s.d.DB.First(par, model.Parts{PartCode: v.PartCode}).Error; e != nil {
  709. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  710. }
  711. }
  712. if c.Brand != "" {
  713. detail.Manufacturer = c.Brand
  714. } else {
  715. brand := new(model.Brand)
  716. if e := s.d.DB.First(brand, model.Brand{ID: v.BrandID}).Error; e != nil {
  717. //return errors.Wrapf(e, "bigcontract query :id=%d", c.BigID), ""
  718. }
  719. detail.Manufacturer = brand.BrandName
  720. }
  721. price := c.Price
  722. if price == 0 {
  723. price = v.Price
  724. }
  725. if c.PartCode != "" {
  726. detail.OrderUnitCode = c.Unit
  727. detail.MaterialCode = c.PartCode
  728. detail.MaterialName = c.PartName
  729. detail.PricingUnitCode = c.Unit
  730. } else {
  731. detail.OrderUnitCode = par.Unit
  732. detail.MaterialCode = par.PartCode
  733. detail.MaterialName = par.Name
  734. detail.PricingUnitCode = par.Unit
  735. }
  736. s.d.DB.First(pr, model.PartRepertory{ContractID: v.ContractID})
  737. r.Data.TotalNonTaxAmount += price
  738. r.Data.TotalTaxAmount += price
  739. detail.RowNo = strconv.Itoa(v.RowNumber)
  740. //detail.Manufacturer = pa.FactoryCode
  741. //detail.Manufacturer =
  742. //if dp.CompanyCode == "" {
  743. detail.Manufacturer = pa.FactoryCode
  744. detail.PlantCode = pa.FactoryCode
  745. //} else {
  746. // detail.Manufacturer = dp.Factory
  747. // detail.PlantCode = dp.Factory
  748. //}
  749. detail.OrderQty = fmt.Sprintf("%d", v.Amount)
  750. detail.DeliveryDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  751. detail.TaxRateCode = "J0"
  752. detail.NonTaxPrice = price
  753. detail.MaterialDesc = par.Specification
  754. if len(c.PartCode) > 0 {
  755. detail.MaterialGroupCode = strings.ReplaceAll(c.PartCode[:strings.LastIndex(c.PartCode, ".")], ".", "")
  756. } else if len(v.PartCode) > 0 {
  757. fmt.Println(v.PartCode)
  758. detail.MaterialGroupCode = strings.ReplaceAll(v.PartCode[:strings.LastIndex(v.PartCode, ".")], ".", "")
  759. }
  760. detail.Tax = "0"
  761. detail.ConfirmDate = p.BuyerDate.Add(time.Hour * 24 * 7).Format("20060102")
  762. //detail.PlantCode = pa.FactoryCode
  763. //if dp.CompanyCode == "" {
  764. //detail.PlantCode = pa.FactoryCode
  765. //} else {
  766. // detail.PlantCode = dp.Factory
  767. //}
  768. detail.StockLocationCode = "1004"
  769. detail.QualityCheck = "0"
  770. detail.IsReturn = isReturn
  771. detail.OverDeliveryLimit = "0"
  772. detail.ShortDeliveryLimit = "0"
  773. detail.SourceNo = p.BuyeCode[4:]
  774. detail.ContractCode = bc.ContractCode
  775. detail.Remark = c.Remark
  776. //r.Data.Detail = append(r.Data.Detail, detail)
  777. if bc.IsZeroStock == 1 {
  778. detail.PurchaseCategory = "2"
  779. } else {
  780. detail.PurchaseCategory = "0"
  781. }
  782. detail.IsFree = "0"
  783. detail.PriceBase = "1"
  784. astr := strconv.FormatFloat(detail.NonTaxPrice, 'f', -1, 64)
  785. b := strings.Index(astr, ".")
  786. if len(astr[b+1:]) > 2 && b > 0 {
  787. num, _ := strconv.ParseFloat(astr[b+1:], 64)
  788. if num > 0 {
  789. detail.NonTaxPrice = detail.NonTaxPrice * 1000
  790. detail.NonTaxPrice, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", detail.NonTaxPrice), 64)
  791. detail.PriceBase = "1000"
  792. }
  793. }
  794. detail.TaxAmount = detail.NonTaxPrice
  795. detail.TaxPrice = detail.NonTaxPrice
  796. detail.NonTaxAmount = detail.NonTaxPrice
  797. r.Data.Detail = append(r.Data.Detail, detail)
  798. //if e := s.d.DB.Model(&model.BuyDetail{}).Where("id=?", v.ID).Update("rowNumber", i+1).Error; e != nil {
  799. // log.Errorln(e, v.ID)
  800. //}
  801. }
  802. rbyte, _ := json.Marshal([]interface{}{r.Data})
  803. fmt.Println(string(rbyte))
  804. saplog := new(model.SapLog)
  805. saplog.Url = r.Dest.Url
  806. saplog.Param = string(rbyte)
  807. saplog.Name = "srm退货采购订单"
  808. if e := s.SyncSrm(r, rp, rbyte); e != nil {
  809. s.d.DB.Create(saplog)
  810. log.Errorf("sap buy order error: %v", e)
  811. p.SapStatus = 3
  812. } else {
  813. s.d.DB.Create(saplog)
  814. if rp.Success {
  815. // log.Infof("buy order success :eq=%s,sap=%s", rp.Data.EqNumber, rp.Data.SapNumber)
  816. p.SapStatus = 1
  817. p.SapNumber = rp.Code
  818. } else {
  819. log.Warnf("buy order fail :msg=%s,r=%v", rp.Code, r)
  820. p.SapStatus = 2
  821. // pp.Print(r)
  822. }
  823. }
  824. if p.SapStatus == 1 {
  825. if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigRefunddetail{SrmStatus: p.SapStatus, SrmNumber: p.SapNumber}).Error; e != nil {
  826. log.Errorf("update big buy detail error: %v", e)
  827. }
  828. } else {
  829. if e := s.d.DB.Where("id=?", p.ID).Updates(&model.BigRefunddetail{SrmStatus: p.SapStatus, SrmError: rp.Message}).Error; e != nil {
  830. log.Errorf("update big buy detail error: %v", e)
  831. }
  832. }
  833. }
  834. func NextProcurement(sqlname, procurementId string, tx *sqlx.Tx) error {
  835. if sqlname == "updateBigbuydetailStatu" {
  836. p := new(model.BigBuyDetail)
  837. s.d.DB.Where("id = ?", procurementId).First(&p)
  838. SapOrder(p, "X")
  839. //SrmOrder(p, "1")
  840. } else if sqlname == "shutDownBigrefunddetail" {
  841. p := new(model.BigRefunddetail)
  842. s.d.DB.Where("id = ?", procurementId).First(&p)
  843. SapReturnOrder(p, "X")
  844. //SrmReturnOrder(p, "1")
  845. }
  846. return nil
  847. }