supplier.go 17 KB

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