supplier.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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.GETJWT("/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: fmt.Sprintf("%s。<%s>", 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. // ?验证当前账户是否可发送订单
  125. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  126. user, err1 := getUserById(apictx, userId)
  127. if err1 != nil {
  128. return nil, errors.New("用户错误")
  129. }
  130. if !isSender(user.Roles) {
  131. return nil, errors.New("没有发送权限")
  132. }
  133. billId, _ := primitive.ObjectIDFromHex(c.Query("id"))
  134. if billId.IsZero() {
  135. return nil, errors.New("订单id不正确")
  136. }
  137. billType := c.Query("type")
  138. billTypes := []string{"purchase", "produce", "product"}
  139. flagType := false
  140. for _, bt := range billTypes {
  141. if bt == billType {
  142. flagType = true
  143. break
  144. }
  145. }
  146. if !flagType {
  147. return nil, errors.New("订单类型错误")
  148. }
  149. result := &mongo.UpdateResult{}
  150. var err error
  151. switch billType {
  152. case PURCHASE_BILL_TYPE:
  153. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, billId.Hex(), &model.PurchaseBill{IsSend: true, SendTime: time.Now()})
  154. case PRODUCE_BILL_TYPE:
  155. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, billId.Hex(), &model.ProduceBill{IsSend: true, SendTime: time.Now()})
  156. case PRODUCT_BILL_TYPE:
  157. result, err = repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduct, billId.Hex(), &model.ProductBill{IsSend: true, SendTime: time.Now()})
  158. default:
  159. return result, nil
  160. }
  161. if err == nil {
  162. // 给供应商发送通知短信
  163. smsInfo, err := genSupplierSmsTemp(billId, billType, apictx)
  164. fmt.Println(smsInfo)
  165. if err == nil {
  166. var wg sync.WaitGroup
  167. wg.Add(1)
  168. go SendSmsNotify(smsInfo.Phone, &SupplierSmsReq{smsInfo.Product, smsInfo.SerialNumber}, &wg)
  169. // err = SendSmsNotify1(smsInfo.Phone, &SupplierSmsReq{smsInfo.Product, smsInfo.SerialNumber})
  170. wg.Wait()
  171. }
  172. }
  173. return result, err
  174. }
  175. // 供应商-接单
  176. // purchase produce product
  177. // POST /supplier/bill/ack
  178. // {"id":xxxx,"type":"purchase"}
  179. type SupplierBillAckReq struct {
  180. Type string
  181. Id primitive.ObjectID
  182. }
  183. func SupplierBillAck(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  184. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  185. form := SupplierBillAckReq{}
  186. err := c.ShouldBindJSON(&form)
  187. if err != nil {
  188. return nil, errors.New("参数错误")
  189. }
  190. billType := form.Type
  191. id := form.Id
  192. _id := form.Id.Hex()
  193. if id.IsZero() {
  194. return nil, errors.New("id为空")
  195. }
  196. if userId.IsZero() {
  197. return nil, errors.New("非法用户")
  198. }
  199. // purchase produce product
  200. billTypes := []string{"purchase", "produce", "product"}
  201. flagType := false
  202. for _, bt := range billTypes {
  203. if bt == billType {
  204. flagType = true
  205. break
  206. }
  207. }
  208. if !flagType {
  209. return nil, errors.New("订单类型错误")
  210. }
  211. isAck := true
  212. switch billType {
  213. case "purchase":
  214. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillPurchase, _id, &model.PurchaseBill{IsAck: &isAck, AckTime: time.Now()})
  215. case "produce":
  216. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduce, _id, &model.ProduceBill{IsAck: &isAck, AckTime: time.Now()})
  217. case "product":
  218. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionBillProduct, _id, &model.ProductBill{IsAck: &isAck, AckTime: time.Now()})
  219. default:
  220. return nil, errors.New("更新类型错误")
  221. }
  222. }
  223. // 供应商-订单列表
  224. // purchase produce product
  225. // /supplier/bill/list?type=purchase&query={"status":"created"}
  226. func SupplierBillList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  227. userId, _ := primitive.ObjectIDFromHex(apictx.User.Parent)
  228. billType := c.Query("type")
  229. page, size, query := UtilQueryPageSize(c)
  230. if userId.IsZero() {
  231. return nil, errors.New("非法用户")
  232. }
  233. // purchase produce product
  234. billTypes := []string{"purchase", "produce", "product"}
  235. flagType := false
  236. for _, bt := range billTypes {
  237. if bt == billType {
  238. flagType = true
  239. break
  240. }
  241. }
  242. if !flagType {
  243. return nil, errors.New("订单类型错误")
  244. }
  245. query["supplierId"] = userId
  246. query["isSend"] = true
  247. collectName := ""
  248. switch billType {
  249. case "purchase":
  250. collectName = repo.CollectionBillPurchase
  251. case "produce":
  252. collectName = repo.CollectionBillProduce
  253. case "product":
  254. collectName = repo.CollectionBillProduct
  255. default:
  256. return []map[string]interface{}{}, nil
  257. }
  258. return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
  259. CollectName: collectName,
  260. Page: page,
  261. Size: size,
  262. Query: query,
  263. Sort: bson.M{"sendTime": -1},
  264. })
  265. }
  266. // 创建供应商
  267. func CreateSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  268. var supplier model.Supplier
  269. err := c.ShouldBindJSON(&supplier)
  270. if err != nil {
  271. fmt.Println(err)
  272. return nil, errors.New("参数错误!")
  273. }
  274. ctx := apictx.CreateRepoCtx()
  275. if supplier.Name == "" {
  276. return nil, errors.New("供应商名为空")
  277. }
  278. if supplier.Address == "" {
  279. return nil, errors.New("供应商地址为空")
  280. }
  281. if supplier.Phone == "" {
  282. return nil, errors.New("供应商联系电话为空")
  283. }
  284. supplier.CreateTime = time.Now()
  285. supplier.UpdateTime = time.Now()
  286. result, err := repo.RepoAddDoc(ctx, repo.CollectionSupplier, &supplier)
  287. return result, err
  288. }
  289. // 获取供应商信息
  290. func GetSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  291. supplierId := c.Param("id")
  292. id, err := primitive.ObjectIDFromHex(supplierId)
  293. if err != nil {
  294. return nil, errors.New("非法id")
  295. }
  296. var supplier model.Supplier
  297. option := &repo.DocSearchOptions{
  298. CollectName: repo.CollectionSupplier,
  299. Query: repo.Map{"_id": id},
  300. }
  301. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &supplier)
  302. if !found || err != nil {
  303. log.Info(err)
  304. return nil, errors.New("数据未找到")
  305. }
  306. return supplier, nil
  307. }
  308. // 获取供应商列表
  309. func GetSuppliers(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  310. page, size, query := UtilQueryPageSize(c)
  311. if _name, ok := query["name"]; ok {
  312. delete(query, "name")
  313. query["name"] = bson.M{"$regex": _name.(string)}
  314. }
  315. if cate, ok := query["category"]; ok {
  316. delete(query, "category")
  317. query["categorys"] = bson.M{"$in": []string{cate.(string)}}
  318. }
  319. option := &repo.PageSearchOptions{
  320. CollectName: repo.CollectionSupplier,
  321. Query: query,
  322. Page: page,
  323. Size: size,
  324. Sort: bson.M{"createTime": -1},
  325. }
  326. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  327. }
  328. // !暂时弃用
  329. func GetPlanSuppliers(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  330. page, size, query := UtilQueryPageSize(c)
  331. emtyPage := &repo.PageResult{
  332. Total: 0,
  333. Size: size,
  334. Page: page,
  335. List: []map[string]interface{}{},
  336. }
  337. listOut := []map[string]interface{}{}
  338. flag := false
  339. if query["matId"] != nil || query["craftId"] != nil || query["productId"] != nil {
  340. flag = true
  341. }
  342. filtter := repo.Map{}
  343. if _name, ok := query["name"]; ok {
  344. filtter["name"] = bson.M{"$regex": _name.(string)}
  345. }
  346. if cate, ok := query["category"]; ok {
  347. filtter["categorys"] = bson.M{"$in": []string{cate.(string)}}
  348. }
  349. if !flag {
  350. option := &repo.PageSearchOptions{
  351. CollectName: repo.CollectionSupplier,
  352. // Query: repo.Map{"categorys": bson.M{"$in": []string{cate.(string)}}},
  353. Query: filtter,
  354. Page: page,
  355. Size: size,
  356. Sort: bson.M{"createTime": -1},
  357. }
  358. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  359. }
  360. //category =>根据内容查询 供应对应内容的供应商
  361. if query["matId"] != nil {
  362. matId := query["matId"].(string)
  363. if len(matId) < 1 {
  364. return nil, fmt.Errorf("matId(string)为空")
  365. }
  366. id, _ := primitive.ObjectIDFromHex(matId)
  367. ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  368. CollectName: repo.CollectionSupplierMatprice,
  369. Query: repo.Map{"productId": id},
  370. Project: []string{"supplierId"},
  371. })
  372. if !ok {
  373. return emtyPage, nil
  374. }
  375. listOut = list
  376. }
  377. if query["craftId"] != nil {
  378. cratf := &model.Craft{}
  379. ok, _ := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  380. Query: repo.Map{"_id": query["craftId"].(string)},
  381. CollectName: repo.CollectionCraft,
  382. }, cratf)
  383. if !ok {
  384. return nil, fmt.Errorf("没有对应的工艺信息")
  385. }
  386. //查询工艺分类
  387. pipleLine := []bson.M{
  388. {
  389. "$lookup": bson.M{
  390. "from": repo.CollectionCraft,
  391. "localField": "productId",
  392. "foreignField": "_id",
  393. "as": "craft_docs",
  394. },
  395. },
  396. {
  397. "$match": bson.M{
  398. "craft_docs.0.category": cratf.Category,
  399. },
  400. },
  401. {
  402. "$project": bson.M{
  403. "craft_docs": 0,
  404. "createTime": 0,
  405. "price": 0,
  406. "productId": 0,
  407. "updateTime": 0,
  408. },
  409. },
  410. }
  411. ctx := apictx.CreateRepoCtx()
  412. colls := ctx.Client.GetCollection(repo.CollectionSupplierCraftprice)
  413. findoptions := &options.AggregateOptions{}
  414. cur, err := colls.Aggregate(ctx.Ctx, pipleLine, findoptions)
  415. if err != nil {
  416. return nil, err
  417. }
  418. defer cur.Close(ctx.Ctx)
  419. err = cur.All(ctx.Ctx, &listOut)
  420. if err != nil {
  421. return nil, err
  422. }
  423. if len(listOut) < 1 {
  424. return emtyPage, nil
  425. }
  426. return listOut, nil
  427. // cratfId := query["craftId"].(string)
  428. // if len(cratfId) < 1 {
  429. // return nil, fmt.Errorf("cratfId(string)为空")
  430. // }
  431. // id, _ := primitive.ObjectIDFromHex(cratfId)
  432. // ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  433. // CollectName: repo.CollectionSupplierCraftprice,
  434. // Query: repo.Map{"craftId": id},
  435. // Project: []string{"supplierId"},
  436. // })
  437. // if !ok {
  438. // return emtyPage, nil
  439. // }
  440. // listOut = list
  441. }
  442. if query["productId"] != nil {
  443. productId := query["productId"].(string)
  444. if len(productId) < 1 {
  445. return nil, fmt.Errorf("productId(string)为空")
  446. }
  447. id, _ := primitive.ObjectIDFromHex(productId)
  448. ok, list := repo.RepoSeachDocsMap(apictx.CreateRepoCtx(), &repo.DocsSearchOptions{
  449. CollectName: repo.CollectionSupplierProductprice,
  450. Query: repo.Map{"productId": id},
  451. Project: []string{"supplierId"},
  452. })
  453. if !ok {
  454. return emtyPage, nil
  455. }
  456. listOut = list
  457. }
  458. //获取供应商列表
  459. suppliers := []primitive.ObjectID{}
  460. suppliersMap := map[string]bool{}
  461. for _, item := range listOut {
  462. if item["supplierId"] != nil {
  463. id, ok := item["supplierId"].(primitive.ObjectID)
  464. if !ok {
  465. continue
  466. }
  467. if !suppliersMap[id.Hex()] {
  468. suppliers = append(suppliers, id)
  469. suppliersMap[id.Hex()] = true
  470. }
  471. }
  472. }
  473. if len(suppliers) < 1 {
  474. return emtyPage, nil
  475. }
  476. filtter["_id"] = bson.M{"$in": suppliers}
  477. option := &repo.PageSearchOptions{
  478. CollectName: repo.CollectionSupplier,
  479. Query: filtter,
  480. // Query: repo.Map{"_id": bson.M{"$in": suppliers}},
  481. Page: page,
  482. Size: size,
  483. Sort: bson.M{"createTime": -1},
  484. }
  485. return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
  486. }
  487. // 更新供应商
  488. func UpdateSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  489. var supplier model.Supplier
  490. err := c.ShouldBindJSON(&supplier)
  491. if err != nil {
  492. return nil, errors.New("参数错误")
  493. }
  494. if supplier.Id.Hex() == "" {
  495. return nil, errors.New("id的为空")
  496. }
  497. supplier.UpdateTime = time.Now()
  498. return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionSupplier, supplier.Id.Hex(), &supplier)
  499. }
  500. // 删除供应商
  501. func DelSupplier(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  502. supplierId := c.Param("id")
  503. if supplierId == "" {
  504. return nil, errors.New("id为空")
  505. }
  506. return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionSupplier, supplierId)
  507. }