supplier.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "box-cost/log"
  6. "errors"
  7. "fmt"
  8. "sync"
  9. "time"
  10. "github.com/gin-gonic/gin"
  11. "go.mongodb.org/mongo-driver/bson"
  12. "go.mongodb.org/mongo-driver/bson/primitive"
  13. "go.mongodb.org/mongo-driver/mongo"
  14. "go.mongodb.org/mongo-driver/mongo/options"
  15. )
  16. // 供应商管理
  17. func Supplier(r *GinRouter) {
  18. // 创建供应商
  19. r.POST("/supplier/create", CreateSupplier)
  20. // 获取供应商详情
  21. r.GET("/supplier/detail/:id", GetSupplier)
  22. // 获取供应商列表
  23. r.GET("/supplier/list", GetSuppliers)
  24. // 更新供应商
  25. r.POST("/supplier/update", UpdateSupplier)
  26. // 删除供应商
  27. r.POST("/supplier/delete/:id", DelSupplier)
  28. // 获取供应商列表
  29. r.GET("/plan/supplier/list", GetPlanSuppliers)
  30. // 供应商获取自己的单据列表
  31. r.GETJWT("/supplier/bill/list", SupplierBillList)
  32. // 供应商接单
  33. r.POSTJWT("/supplier/bill/ack", SupplierBillAck)
  34. // 单据分配给供应商
  35. r.GET("/supplier/bill/alloc", SupplierBillAlloc)
  36. }
  37. const (
  38. PURCHASE_BILL_TYPE = "purchase"
  39. PRODUCE_BILL_TYPE = "produce"
  40. PRODUCT_BILL_TYPE = "product"
  41. )
  42. type SupplierSmsTempInfo struct {
  43. Product string // 产品名+数量
  44. SerialNumber string
  45. Phone string
  46. }
  47. func genSupplierSmsTemp(billId primitive.ObjectID, billType string, apictx *ApiSession) (*SupplierSmsTempInfo, error) {
  48. productName := ""
  49. supplierId := primitive.NilObjectID
  50. serialNumber := ""
  51. if billType == PURCHASE_BILL_TYPE {
  52. purchase := &model.PurchaseBill{}
  53. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  54. CollectName: repo.CollectionBillPurchase,
  55. Query: repo.Map{"_id": billId},
  56. Project: []string{"productName", "supplierId", "serialNumber", "isAck"},
  57. }, purchase)
  58. if !found || err != nil {
  59. return nil, errors.New("未找到该订单")
  60. }
  61. // 已经接单不发送提醒
  62. if *purchase.IsAck {
  63. return nil, errors.New("该供应商已经接单")
  64. }
  65. serialNumber = purchase.SerialNumber
  66. productName = purchase.ProductName
  67. supplierId = purchase.SupplierId
  68. }
  69. if billType == PRODUCE_BILL_TYPE {
  70. produce := &model.ProduceBill{}
  71. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  72. CollectName: repo.CollectionBillProduce,
  73. Query: repo.Map{"_id": billId},
  74. Project: []string{"productName", "supplierId", "serialNumber", "isAck"},
  75. }, produce)
  76. if !found || err != nil {
  77. return nil, errors.New("未找到该订单")
  78. }
  79. // 已经接单不发送提醒
  80. if *produce.IsAck {
  81. return nil, errors.New("该供应商已经接单")
  82. }
  83. serialNumber = produce.SerialNumber
  84. productName = produce.ProductName
  85. supplierId = produce.SupplierId
  86. }
  87. if billType == PRODUCT_BILL_TYPE {
  88. product := &model.ProductBill{}
  89. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  90. CollectName: repo.CollectionBillProduct,
  91. Query: repo.Map{"_id": billId},
  92. Project: []string{"productName", "supplierId", "serialNumber", "isAck"},
  93. }, product)
  94. if !found || err != nil {
  95. return nil, errors.New("未找到该订单")
  96. }
  97. // 已经接单不发送提醒
  98. if *product.IsAck {
  99. return nil, errors.New("该供应商已经接单")
  100. }
  101. serialNumber = product.SerialNumber
  102. productName = product.ProductName
  103. supplierId = product.SupplierId
  104. }
  105. // 查询供应商信息
  106. user, err := getUserById(apictx, supplierId)
  107. if user == nil || err != nil {
  108. return nil, errors.New("未找到该供应商信息")
  109. }
  110. if len(user.Phone) != 11 {
  111. return nil, errors.New("手机号信息错误")
  112. }
  113. return &SupplierSmsTempInfo{
  114. Product: productName,
  115. SerialNumber: serialNumber,
  116. Phone: user.Phone,
  117. }, nil
  118. }
  119. // 把订单分配给供应商
  120. // purchase produce product
  121. // id为订单id
  122. // /supplier/bill/alloc?id=xxx&type=purchase
  123. func SupplierBillAlloc(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  124. billId, _ := primitive.ObjectIDFromHex(c.Query("id"))
  125. if billId.IsZero() {
  126. return nil, errors.New("订单id不正确")
  127. }
  128. billType := c.Query("type")
  129. billTypes := []string{"purchase", "produce", "product"}
  130. flagType := false
  131. for _, bt := range billTypes {
  132. if bt == billType {
  133. flagType = true
  134. break
  135. }
  136. }
  137. if !flagType {
  138. return nil, errors.New("订单类型错误")
  139. }
  140. result := &mongo.UpdateResult{}
  141. var err error
  142. switch billType {
  143. case PURCHASE_BILL_TYPE:
  144. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId.Hex(), &model.PurchaseBill{IsSend: true, SendTime: time.Now()})
  145. case PRODUCE_BILL_TYPE:
  146. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, billId.Hex(), &model.ProduceBill{IsSend: true, SendTime: time.Now()})
  147. case PRODUCT_BILL_TYPE:
  148. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduct, billId.Hex(), &model.ProductBill{IsSend: true, SendTime: time.Now()})
  149. default:
  150. return result, nil
  151. }
  152. if err == nil {
  153. // 给供应商发送通知短信
  154. smsInfo, err := genSupplierSmsTemp(billId, billType, apictx)
  155. fmt.Println(smsInfo)
  156. if err == nil {
  157. var wg sync.WaitGroup
  158. wg.Add(1)
  159. go SendSmsNotify(smsInfo.Phone, &SupplierSmsReq{smsInfo.Product, smsInfo.SerialNumber}, &wg)
  160. wg.Wait()
  161. }
  162. }
  163. return result, err
  164. }
  165. // 供应商-接单
  166. // purchase produce product
  167. // POST /supplier/bill/ack
  168. // {"id":xxxx,"type":"purchase"}
  169. type SupplierBillAckReq struct {
  170. Type string
  171. Id primitive.ObjectID
  172. }
  173. func SupplierBillAck(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  174. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  175. form := SupplierBillAckReq{}
  176. err := c.ShouldBindJSON(&form)
  177. if err != nil {
  178. return nil, errors.New("参数错误")
  179. }
  180. billType := form.Type
  181. id := form.Id
  182. _id := form.Id.Hex()
  183. if id.IsZero() {
  184. return nil, errors.New("id为空")
  185. }
  186. if userId.IsZero() {
  187. return nil, errors.New("非法用户")
  188. }
  189. // purchase produce product
  190. billTypes := []string{"purchase", "produce", "product"}
  191. flagType := false
  192. for _, bt := range billTypes {
  193. if bt == billType {
  194. flagType = true
  195. break
  196. }
  197. }
  198. if !flagType {
  199. return nil, errors.New("订单类型错误")
  200. }
  201. isAck := true
  202. switch billType {
  203. case "purchase":
  204. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &model.PurchaseBill{IsAck: &isAck, AckTime: time.Now()})
  205. case "produce":
  206. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, _id, &model.ProduceBill{IsAck: &isAck, AckTime: time.Now()})
  207. case "product":
  208. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduct, _id, &model.ProductBill{IsAck: &isAck, AckTime: time.Now()})
  209. default:
  210. return nil, errors.New("更新类型错误")
  211. }
  212. }
  213. // 供应商-订单列表
  214. // purchase produce product
  215. // /supplier/bill/list?type=purchase&query={"status":"created"}
  216. func SupplierBillList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  217. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  218. billType := c.Query("type")
  219. page, size, query := UtilQueryPageSize(c)
  220. if userId.IsZero() {
  221. return nil, errors.New("非法用户")
  222. }
  223. // purchase produce product
  224. billTypes := []string{"purchase", "produce", "product"}
  225. flagType := false
  226. for _, bt := range billTypes {
  227. if bt == billType {
  228. flagType = true
  229. break
  230. }
  231. }
  232. if !flagType {
  233. return nil, errors.New("订单类型错误")
  234. }
  235. query["supplierId"] = userId
  236. query["isSend"] = true
  237. collectName := ""
  238. switch billType {
  239. case "purchase":
  240. collectName = repo.CollectionBillPurchase
  241. case "produce":
  242. collectName = repo.CollectionBillProduce
  243. case "product":
  244. collectName = repo.CollectionBillProduct
  245. default:
  246. return []map[string]interface{}{}, nil
  247. }
  248. return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  249. CollectName: collectName,
  250. Page: page,
  251. Size: size,
  252. Query: query,
  253. Sort: bson.M{"sendTime": -1},
  254. })
  255. }
  256. // 创建供应商
  257. func CreateSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  258. var supplier model.Supplier
  259. err := c.ShouldBindJSON(&supplier)
  260. if err != nil {
  261. fmt.Println(err)
  262. return nil, errors.New("参数错误!")
  263. }
  264. ctx := apictx.CreateRepoCtx()
  265. if supplier.Name == "" {
  266. return nil, errors.New("供应商名为空")
  267. }
  268. if supplier.Address == "" {
  269. return nil, errors.New("供应商地址为空")
  270. }
  271. if supplier.Phone == "" {
  272. return nil, errors.New("供应商联系电话为空")
  273. }
  274. supplier.CreateTime = time.Now()
  275. supplier.UpdateTime = time.Now()
  276. result, err := repo.RepoAddDoc(ctx, repo.CollectionSupplier, &supplier)
  277. return result, err
  278. }
  279. // 获取供应商信息
  280. func GetSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  281. supplierId := c.Param("id")
  282. id, err := primitive.ObjectIDFromHex(supplierId)
  283. if err != nil {
  284. return nil, errors.New("非法id")
  285. }
  286. var supplier model.Supplier
  287. option := &repo.DocSearchOptions{
  288. CollectName: repo.CollectionSupplier,
  289. Query: repo.Map{"_id": id},
  290. }
  291. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &supplier)
  292. if !found || err != nil {
  293. log.Info(err)
  294. return nil, errors.New("数据未找到")
  295. }
  296. return supplier, nil
  297. }
  298. // 获取供应商列表
  299. func GetSuppliers(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  300. page, size, query := UtilQueryPageSize(c)
  301. if _name, ok := query["name"]; ok {
  302. delete(query, "name")
  303. query["name"] = bson.M{"$regex": _name.(string)}
  304. }
  305. if cate, ok := query["category"]; ok {
  306. delete(query, "category")
  307. query["categorys"] = bson.M{"$in": []string{cate.(string)}}
  308. }
  309. option := &repo.PageSearchOptions{
  310. CollectName: repo.CollectionSupplier,
  311. Query: query,
  312. Page: page,
  313. Size: size,
  314. Sort: bson.M{"createTime": -1},
  315. }
  316. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  317. }
  318. // !暂时弃用
  319. func GetPlanSuppliers(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  320. page, size, query := UtilQueryPageSize(c)
  321. emtyPage := &repo.PageResult{
  322. Total: 0,
  323. Size: size,
  324. Page: page,
  325. List: []map[string]interface{}{},
  326. }
  327. listOut := []map[string]interface{}{}
  328. flag := false
  329. if query["matId"] != nil || query["craftId"] != nil || query["productId"] != nil {
  330. flag = true
  331. }
  332. filtter := repo.Map{}
  333. if _name, ok := query["name"]; ok {
  334. filtter["name"] = bson.M{"$regex": _name.(string)}
  335. }
  336. if cate, ok := query["category"]; ok {
  337. filtter["categorys"] = bson.M{"$in": []string{cate.(string)}}
  338. }
  339. if !flag {
  340. option := &repo.PageSearchOptions{
  341. CollectName: repo.CollectionSupplier,
  342. // Query: repo.Map{"categorys": bson.M{"$in": []string{cate.(string)}}},
  343. Query: filtter,
  344. Page: page,
  345. Size: size,
  346. Sort: bson.M{"createTime": -1},
  347. }
  348. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  349. }
  350. //category =>根据内容查询 供应对应内容的供应商
  351. if query["matId"] != nil {
  352. matId := query["matId"].(string)
  353. if len(matId) < 1 {
  354. return nil, fmt.Errorf("matId(string)为空")
  355. }
  356. id, _ := primitive.ObjectIDFromHex(matId)
  357. ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  358. CollectName: repo.CollectionSupplierMatprice,
  359. Query: repo.Map{"productId": id},
  360. Project: []string{"supplierId"},
  361. })
  362. if !ok {
  363. return emtyPage, nil
  364. }
  365. listOut = list
  366. }
  367. if query["craftId"] != nil {
  368. cratf := &model.Craft{}
  369. ok, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  370. Query: repo.Map{"_id": query["craftId"].(string)},
  371. CollectName: repo.CollectionCraft,
  372. }, cratf)
  373. if !ok {
  374. return nil, fmt.Errorf("没有对应的工艺信息")
  375. }
  376. //查询工艺分类
  377. pipleLine := []bson.M{
  378. {
  379. "$lookup": bson.M{
  380. "from": repo.CollectionCraft,
  381. "localField": "productId",
  382. "foreignField": "_id",
  383. "as": "craft_docs",
  384. },
  385. },
  386. {
  387. "$match": bson.M{
  388. "craft_docs.0.category": cratf.Category,
  389. },
  390. },
  391. {
  392. "$project": bson.M{
  393. "craft_docs": 0,
  394. "createTime": 0,
  395. "price": 0,
  396. "productId": 0,
  397. "updateTime": 0,
  398. },
  399. },
  400. }
  401. ctx := apictx.CreateRepoCtx()
  402. colls := ctx.Client.GetCollection(repo.CollectionSupplierCraftprice)
  403. findoptions := &options.AggregateOptions{}
  404. cur, err := colls.Aggregate(ctx.Ctx, pipleLine, findoptions)
  405. if err != nil {
  406. return nil, err
  407. }
  408. defer cur.Close(ctx.Ctx)
  409. err = cur.All(ctx.Ctx, &listOut)
  410. if err != nil {
  411. return nil, err
  412. }
  413. if len(listOut) < 1 {
  414. return emtyPage, nil
  415. }
  416. return listOut, nil
  417. // cratfId := query["craftId"].(string)
  418. // if len(cratfId) < 1 {
  419. // return nil, fmt.Errorf("cratfId(string)为空")
  420. // }
  421. // id, _ := primitive.ObjectIDFromHex(cratfId)
  422. // ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  423. // CollectName: repo.CollectionSupplierCraftprice,
  424. // Query: repo.Map{"craftId": id},
  425. // Project: []string{"supplierId"},
  426. // })
  427. // if !ok {
  428. // return emtyPage, nil
  429. // }
  430. // listOut = list
  431. }
  432. if query["productId"] != nil {
  433. productId := query["productId"].(string)
  434. if len(productId) < 1 {
  435. return nil, fmt.Errorf("productId(string)为空")
  436. }
  437. id, _ := primitive.ObjectIDFromHex(productId)
  438. ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  439. CollectName: repo.CollectionSupplierProductprice,
  440. Query: repo.Map{"productId": id},
  441. Project: []string{"supplierId"},
  442. })
  443. if !ok {
  444. return emtyPage, nil
  445. }
  446. listOut = list
  447. }
  448. //获取供应商列表
  449. suppliers := []primitive.ObjectID{}
  450. suppliersMap := map[string]bool{}
  451. for _, item := range listOut {
  452. if item["supplierId"] != nil {
  453. id, ok := item["supplierId"].(primitive.ObjectID)
  454. if !ok {
  455. continue
  456. }
  457. if !suppliersMap[id.Hex()] {
  458. suppliers = append(suppliers, id)
  459. suppliersMap[id.Hex()] = true
  460. }
  461. }
  462. }
  463. if len(suppliers) < 1 {
  464. return emtyPage, nil
  465. }
  466. filtter["_id"] = bson.M{"$in": suppliers}
  467. option := &repo.PageSearchOptions{
  468. CollectName: repo.CollectionSupplier,
  469. Query: filtter,
  470. // Query: repo.Map{"_id": bson.M{"$in": suppliers}},
  471. Page: page,
  472. Size: size,
  473. Sort: bson.M{"createTime": -1},
  474. }
  475. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  476. }
  477. // 更新供应商
  478. func UpdateSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  479. var supplier model.Supplier
  480. err := c.ShouldBindJSON(&supplier)
  481. if err != nil {
  482. return nil, errors.New("参数错误")
  483. }
  484. if supplier.Id.Hex() == "" {
  485. return nil, errors.New("id的为空")
  486. }
  487. supplier.UpdateTime = time.Now()
  488. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionSupplier, supplier.Id.Hex(), &supplier)
  489. }
  490. // 删除供应商
  491. func DelSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  492. supplierId := c.Param("id")
  493. if supplierId == "" {
  494. return nil, errors.New("id为空")
  495. }
  496. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionSupplier, supplierId)
  497. }