stages.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. package api
  2. import (
  3. "box-cost/db/model"
  4. "box-cost/db/repo"
  5. "context"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  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. // StageRequest 用于添加和更新stage的请求结构
  17. type StageRequest struct {
  18. PlanId string `json:"planId"`
  19. PackId string `json:"packId"`
  20. CompId string `json:"componentId"`
  21. StageId string `json:"stageId,omitempty"`
  22. Stages []*model.ComponentStage `json:"stages"`
  23. }
  24. // 更新计划和部件的价格
  25. func updatePrices(ctx context.Context, db *mongo.Collection, planId primitive.ObjectID, compId string) error {
  26. // 1. 获取计划详情
  27. var plan model.ProductPlan
  28. err := db.FindOne(ctx, bson.M{"_id": planId}).Decode(&plan)
  29. if err != nil {
  30. return err
  31. }
  32. // 2. 遍历所有组件,找到目标组件并重新计算价格
  33. var totalPrice float64 = 0
  34. for _, comp := range plan.Pack.Components {
  35. compPrice := 0.0
  36. // 计算组件的所有stage总价
  37. for _, stage := range comp.Stages {
  38. stagePrice := stage.OrderPrice * float64(stage.OrderCount)
  39. compPrice += stagePrice
  40. }
  41. // 更新组件总价
  42. if comp.Id == compId {
  43. _, err = db.UpdateOne(ctx,
  44. bson.M{"_id": planId, "pack.components.id": compId},
  45. bson.M{"$set": bson.M{"pack.components.$.totalPrice": compPrice}})
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. totalPrice += compPrice
  51. }
  52. // 3. 更新计划总价
  53. _, err = db.UpdateOne(ctx,
  54. bson.M{"_id": planId},
  55. bson.M{"$set": bson.M{"totalPrice": &totalPrice}})
  56. return err
  57. }
  58. // 增加stage
  59. // 根据planId packId compentId定位到到计划中的compent
  60. // 注意更新计划价格 组件价格
  61. func AddStage(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  62. var req StageRequest
  63. if err := c.ShouldBindJSON(&req); err != nil {
  64. return nil, err
  65. }
  66. planId, err := primitive.ObjectIDFromHex(req.PlanId)
  67. if err != nil {
  68. return nil, err
  69. }
  70. // 更新数据库,添加多个stage
  71. update := bson.M{
  72. "$push": bson.M{
  73. "pack.components.$[components].stages": bson.M{
  74. "$each": req.Stages,
  75. },
  76. },
  77. "$set": bson.M{
  78. "updateTime": time.Now(),
  79. },
  80. }
  81. arrayFilters := []interface{}{
  82. bson.M{"components.id": req.CompId},
  83. }
  84. opts := options.Update().SetArrayFilters(options.ArrayFilters{
  85. Filters: arrayFilters,
  86. })
  87. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  88. result, err := db.UpdateOne(apictx.CreateRepoCtx().Ctx,
  89. bson.M{"_id": planId},
  90. update,
  91. opts,
  92. )
  93. if err != nil {
  94. return nil, err
  95. }
  96. // 更新价格
  97. err = updatePrices(apictx.CreateRepoCtx().Ctx, db, planId, req.CompId)
  98. if err != nil {
  99. return nil, err
  100. }
  101. _, err = AddPlanHistory(c, apictx, req.PlanId)
  102. if err != nil {
  103. fmt.Println("记录历史失败:", err)
  104. }
  105. return result, nil
  106. }
  107. // 删除stage
  108. // 根据planId packId compentId stageId定位到到计划中的stage
  109. // 注意更新计划价格 组件价格
  110. func DeleteStage(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  111. var req StageRequest
  112. if err := c.ShouldBindJSON(&req); err != nil {
  113. return nil, err
  114. }
  115. planId, err := primitive.ObjectIDFromHex(req.PlanId)
  116. if err != nil {
  117. return nil, err
  118. }
  119. if req.StageId == "" || req.CompId == "" {
  120. return nil, errors.New("stageId and compId are required")
  121. }
  122. // 更新数据库
  123. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  124. update := bson.M{
  125. "$pull": bson.M{
  126. "pack.components.$[components].stages": bson.M{
  127. "id": req.StageId,
  128. },
  129. },
  130. }
  131. arrayFilters := []interface{}{
  132. bson.M{"components.id": req.CompId},
  133. }
  134. opts := options.Update().SetArrayFilters(options.ArrayFilters{
  135. Filters: arrayFilters,
  136. })
  137. result, err := db.UpdateOne(apictx.CreateRepoCtx().Ctx,
  138. bson.M{"_id": planId},
  139. update,
  140. opts,
  141. )
  142. if err != nil {
  143. return nil, err
  144. }
  145. // 更新价格
  146. err = updatePrices(apictx.CreateRepoCtx().Ctx, db, planId, req.CompId)
  147. if err != nil {
  148. return nil, err
  149. }
  150. _, err = AddPlanHistory(c, apictx, req.PlanId)
  151. if err != nil {
  152. fmt.Println("记录历史失败:", err)
  153. }
  154. return result, nil
  155. }
  156. // 更新stages
  157. // 根据planId packId compentId stageId定位到到计划中的stage
  158. // 注意更新计划价格 组件价格
  159. func UpdateStage(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  160. var req StageRequest
  161. if err := c.ShouldBindJSON(&req); err != nil {
  162. return nil, err
  163. }
  164. // 参数检查
  165. if len(req.PlanId) == 0 || len(req.CompId) == 0 || len(req.Stages) == 0 {
  166. return nil, fmt.Errorf("invalid parameters: planId, componentId and stages are required")
  167. }
  168. planId, err := primitive.ObjectIDFromHex(req.PlanId)
  169. if err != nil {
  170. return nil, fmt.Errorf("invalid planId: %v", err)
  171. }
  172. // 获取更新前的数据用于验证
  173. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  174. var plan model.ProductPlan
  175. err = db.FindOne(apictx.CreateRepoCtx().Ctx, bson.M{"_id": planId}).Decode(&plan)
  176. if err != nil {
  177. return nil, fmt.Errorf("failed to find plan: %v", err)
  178. }
  179. // 验证组件是否存在
  180. componentExists := false
  181. if plan.Pack != nil {
  182. for _, comp := range plan.Pack.Components {
  183. if comp.Id == req.CompId {
  184. componentExists = true
  185. break
  186. }
  187. }
  188. }
  189. if !componentExists {
  190. return nil, fmt.Errorf("component %s not found in plan", req.CompId)
  191. }
  192. // 准备批量更新操作
  193. var models []mongo.WriteModel
  194. now := time.Now()
  195. for _, stage := range req.Stages {
  196. if stage.Id == "" {
  197. continue // 跳过没有ID的stage
  198. }
  199. update := bson.M{
  200. "$set": bson.M{
  201. "pack.components.$[components].stages.$[stage]": stage,
  202. "updateTime": now,
  203. },
  204. }
  205. arrayFilters := options.ArrayFilters{
  206. Filters: []interface{}{
  207. bson.M{"components.id": req.CompId},
  208. bson.M{"stage.id": stage.Id},
  209. },
  210. }
  211. model := mongo.NewUpdateOneModel().
  212. SetFilter(bson.M{"_id": planId}).
  213. SetUpdate(update).
  214. SetArrayFilters(arrayFilters)
  215. models = append(models, model)
  216. }
  217. if len(models) == 0 {
  218. return nil, fmt.Errorf("no valid stages to update")
  219. }
  220. // 执行批量更新
  221. opts := options.BulkWrite().SetOrdered(false) // 允许并行执行
  222. result, err := db.BulkWrite(apictx.CreateRepoCtx().Ctx, models, opts)
  223. if err != nil {
  224. return nil, fmt.Errorf("failed to update stages: %v", err)
  225. }
  226. // 更新价格
  227. err = updatePrices(apictx.CreateRepoCtx().Ctx, db, planId, req.CompId)
  228. if err != nil {
  229. return nil, fmt.Errorf("failed to update prices: %v", err)
  230. }
  231. // 记录历史
  232. _, err = AddPlanHistory(c, apictx, req.PlanId)
  233. if err != nil {
  234. fmt.Println("记录历史失败:", err)
  235. }
  236. return result, nil
  237. }
  238. type UpdatePlanFieldsReq struct {
  239. PlanId string `json:"planId"`
  240. Total int `json:"total,omitempty"`
  241. CreateUser string `json:"createUser,omitempty"`
  242. Name string `json:"name,omitempty"`
  243. }
  244. // 单独更新计划字段
  245. func UpdatePlanfileds(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  246. var req UpdatePlanFieldsReq
  247. if err := c.ShouldBindJSON(&req); err != nil {
  248. return nil, err
  249. }
  250. planId, _ := primitive.ObjectIDFromHex(req.PlanId)
  251. if planId.IsZero() {
  252. return nil, fmt.Errorf("invalid planId")
  253. }
  254. result, err := repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionProductPlan, req.PlanId, &model.ProductPlan{
  255. Total: req.Total,
  256. CreateUser: req.CreateUser,
  257. Name: req.Name,
  258. })
  259. if err != nil {
  260. return nil, err
  261. }
  262. // 记录历史
  263. _, err = AddPlanHistory(c, apictx, req.PlanId)
  264. if err != nil {
  265. fmt.Println("记录历史失败:", err)
  266. }
  267. return result, nil
  268. }
  269. // 新增组件
  270. func AddCompnonet(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  271. _planId := c.Param("id")
  272. planId, _ := primitive.ObjectIDFromHex(_planId)
  273. if planId.IsZero() {
  274. return nil, fmt.Errorf("planId is invalid")
  275. }
  276. var component model.PackComponent
  277. if err := c.ShouldBindJSON(&component); err != nil {
  278. return nil, err
  279. }
  280. // 计算新的总价
  281. newTotalPrice := component.TotalPrice
  282. oldPlan := &model.ProductPlan{}
  283. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  284. if err := db.FindOne(c, bson.M{"_id": planId}).Decode(&oldPlan); err != nil {
  285. return nil, err
  286. } else if oldPlan.TotalPrice != nil {
  287. newTotalPrice += *oldPlan.TotalPrice
  288. }
  289. update := bson.M{
  290. "$push": bson.M{
  291. "pack.components": component,
  292. },
  293. "$set": bson.M{
  294. "updateTime": time.Now(),
  295. "totalPrice": newTotalPrice,
  296. },
  297. "$inc": bson.M{
  298. "pack.compCounts": 1,
  299. },
  300. }
  301. filter := bson.M{"_id": planId}
  302. result := db.FindOneAndUpdate(c, filter, update)
  303. if result.Err() != nil {
  304. return nil, result.Err()
  305. }
  306. _, err := AddPlanHistory(c, apictx, _planId)
  307. if err != nil {
  308. fmt.Println("记录历史失败:", err)
  309. }
  310. return true, nil
  311. }
  312. func DeleteCompnonet(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  313. _planId := c.Param("id")
  314. planId, _ := primitive.ObjectIDFromHex(_planId)
  315. if planId.IsZero() {
  316. return nil, fmt.Errorf("planId is invalid")
  317. }
  318. componentId := c.Param("componentId")
  319. if len(componentId) == 0 {
  320. return nil, fmt.Errorf("componentId is invalid")
  321. }
  322. oldPlan := &model.ProductPlan{}
  323. // Find the component to be deleted and its price
  324. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  325. var componentPrice float64
  326. if err := db.FindOne(c, bson.M{"_id": planId}).Decode(&oldPlan); err != nil {
  327. return nil, err
  328. } else if oldPlan.Pack != nil {
  329. for _, comp := range oldPlan.Pack.Components {
  330. if comp.Id == componentId {
  331. componentPrice = comp.TotalPrice
  332. break
  333. }
  334. }
  335. }
  336. var newTotalPrice float64
  337. if oldPlan.TotalPrice != nil {
  338. newTotalPrice = *oldPlan.TotalPrice - componentPrice
  339. if newTotalPrice < 0 {
  340. newTotalPrice = 0
  341. }
  342. }
  343. update := bson.M{
  344. "$pull": bson.M{
  345. "pack.components": bson.M{"id": componentId},
  346. },
  347. "$set": bson.M{
  348. "updateTime": time.Now(),
  349. "totalPrice": newTotalPrice,
  350. },
  351. "$inc": bson.M{
  352. "pack.compCounts": -1,
  353. },
  354. }
  355. filter := bson.M{"_id": planId}
  356. result := db.FindOneAndUpdate(c, filter, update)
  357. if result.Err() != nil {
  358. return nil, result.Err()
  359. }
  360. _, err := AddPlanHistory(c, apictx, _planId)
  361. if err != nil {
  362. fmt.Println("记录历史失败:", err)
  363. }
  364. return true, nil
  365. }
  366. func UpdateCompnonetName(c *gin.Context, apictx *ApiSession) (interface{}, error) {
  367. _planId := c.Param("id")
  368. planId, _ := primitive.ObjectIDFromHex(_planId)
  369. if planId.IsZero() {
  370. return nil, fmt.Errorf("planId is invalid")
  371. }
  372. componentId := c.Param("componentId")
  373. if len(componentId) == 0 {
  374. return nil, fmt.Errorf("componentId is invalid")
  375. }
  376. var nameUpdate struct {
  377. Name string `json:"name"`
  378. }
  379. if err := c.ShouldBindJSON(&nameUpdate); err != nil {
  380. return nil, err
  381. }
  382. update := bson.M{
  383. "$set": bson.M{
  384. "pack.components.$.name": nameUpdate.Name,
  385. "updateTime": time.Now(),
  386. },
  387. }
  388. filter := bson.M{
  389. "_id": planId,
  390. "pack.components.id": componentId,
  391. }
  392. db := apictx.Svc.Mongo.GetCollection(repo.CollectionProductPlan)
  393. result := db.FindOneAndUpdate(c, filter, update)
  394. if result.Err() != nil {
  395. return nil, result.Err()
  396. }
  397. // 获取更新后的数据并记录历史
  398. _, err := AddPlanHistory(c, apictx, _planId)
  399. if err != nil {
  400. fmt.Println("记录历史失败:", err)
  401. }
  402. return true, nil
  403. }
  404. // 记录历史
  405. func AddPlanHistory(c *gin.Context, apictx *ApiSession, planId string) (interface{}, error) {
  406. // 获取更新后的数据并记录历史
  407. newPlan := &model.ProductPlan{}
  408. found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), &repo.DocSearchOptions{
  409. CollectName: repo.CollectionProductPlan,
  410. Query: repo.Map{"_id": planId},
  411. }, newPlan)
  412. if !found {
  413. return false, errors.New("数据未找到")
  414. }
  415. if err != nil {
  416. return false, err
  417. }
  418. newPlanBytes, _ := json.Marshal(newPlan)
  419. userId, _ := primitive.ObjectIDFromHex(apictx.User.ID)
  420. userInfo, err := getUserById(apictx, userId)
  421. if err != nil {
  422. return false, err
  423. }
  424. history := &model.History{
  425. Userinfo: userInfo,
  426. TargetId: planId,
  427. Path: c.Request.URL.Path,
  428. Collection: repo.CollectionProductPlan,
  429. Type: "update",
  430. Content: string(newPlanBytes),
  431. CreateTime: time.Now(),
  432. }
  433. _, err = repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionPlanHistory, history)
  434. if err != nil {
  435. return false, err
  436. }
  437. return true, nil
  438. }