repo.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. package repo
  2. import (
  3. "box-cost/db"
  4. "box-cost/db/model"
  5. dm "box-cost/db/model"
  6. "box-cost/log"
  7. "context"
  8. "encoding/json"
  9. "fmt"
  10. "html"
  11. "regexp"
  12. "time"
  13. "github.com/sergi/go-diff/diffmatchpatch"
  14. "go.mongodb.org/mongo-driver/bson"
  15. "go.mongodb.org/mongo-driver/bson/primitive"
  16. "go.mongodb.org/mongo-driver/mongo"
  17. "go.mongodb.org/mongo-driver/mongo/options"
  18. )
  19. type RepoSession struct {
  20. Ctx context.Context
  21. Client *db.MongoDB
  22. }
  23. const (
  24. CollectionMaterial = "material"
  25. CollectionCraft = "craft"
  26. CollectionProduct = "product"
  27. CollectionSupplier = "supplier"
  28. CollectionSupplierPrice = "supplier-price"
  29. CollectionPack = "pack"
  30. CollectionProductPlan = "product-plan"
  31. CollectionBillPurchase = "bill-purchase"
  32. CollectionBillProduce = "bill-produce"
  33. CollectionBillProduct = "bill-product" // 成品采购
  34. CollectionSupplierMatprice = "supplier-mats"
  35. CollectionSupplierCraftprice = "supplier-crafts"
  36. CollectionSupplierProductprice = "supplier-product" // 成品采购
  37. CollectionIncrement = "increment"
  38. CollectionSignature = "signature"
  39. CollectionUsers = "users"
  40. // 更改日志记录
  41. CollectionLogs = "logs"
  42. CollectionRequestLogs = "request-logs"
  43. CollectionPlanTrack = "plan-track"
  44. )
  45. type Map map[string]interface{}
  46. type PageResult struct {
  47. List []map[string]interface{} `json:"list"`
  48. Total int64 `json:"total"`
  49. Page int64 `json:"page"`
  50. Size int64 `json:"size"`
  51. }
  52. type PageSearchOptions struct {
  53. Db string
  54. CollectName string
  55. Page int64
  56. Size int64
  57. Query map[string]interface{}
  58. Project []string
  59. Sort interface{}
  60. }
  61. type DocSearchOptions struct {
  62. Db string
  63. CollectName string
  64. Query Map
  65. Project []string
  66. Sort bson.M
  67. }
  68. type DocFilterOptions struct {
  69. Db string
  70. CollectName string
  71. Query Map
  72. }
  73. func NewDocSearchOptions(filter Map, project []string) *DocSearchOptions {
  74. return &DocSearchOptions{
  75. Query: filter,
  76. Project: project,
  77. }
  78. }
  79. func RepoAddDoc(ctx *RepoSession, collectName string, doc interface{}) (string, error) {
  80. users := ctx.Client.GetCollection(collectName)
  81. result, err := users.InsertOne(ctx.Ctx, doc)
  82. if err != nil {
  83. return "", err
  84. }
  85. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  86. }
  87. func RepoDbAddDoc(ctx *RepoSession, dbName string, collectName string, doc interface{}) (string, error) {
  88. users := ctx.Client.GetDbCollection(dbName, collectName)
  89. result, err := users.InsertOne(ctx.Ctx, doc)
  90. if err != nil {
  91. return "", err
  92. }
  93. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  94. }
  95. func RepoDeleteDoc(ctx *RepoSession, collectName string, id string) (interface{}, error) {
  96. uid, _ := primitive.ObjectIDFromHex(id)
  97. colls := ctx.Client.GetCollection(collectName)
  98. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  99. }
  100. func RepoDeleteDbDoc(ctx *RepoSession, dbName string, collectName string, id string) (interface{}, error) {
  101. uid, _ := primitive.ObjectIDFromHex(id)
  102. colls := ctx.Client.GetDbCollection(dbName, collectName)
  103. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  104. }
  105. func RepoDeleteDocs(ctx *RepoSession, collectName string, query interface{}) (interface{}, error) {
  106. colls := ctx.Client.GetCollection(collectName)
  107. return colls.DeleteMany(ctx.Ctx, query)
  108. }
  109. func RepoUpdateSetDoc(ctx *RepoSession, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  110. colls := ctx.Client.GetCollection(collectName)
  111. update := bson.M{"$set": model}
  112. uid, _ := primitive.ObjectIDFromHex(idstr)
  113. return colls.UpdateByID(ctx.Ctx, uid, update)
  114. }
  115. type RecordLogReq struct {
  116. Path string
  117. UserId string
  118. TargetId string
  119. }
  120. func RepoUpdateSetDoc1(ctx *RepoSession, collectName string, idstr string, model interface{}, recordLogReq *RecordLogReq) (*mongo.UpdateResult, error) {
  121. colls := ctx.Client.GetCollection(collectName)
  122. update := bson.M{"$set": model}
  123. // 获取模型对应的数据表
  124. collection := getModel2Collection(model)
  125. uid, _ := primitive.ObjectIDFromHex(idstr)
  126. // ========================记录更新日志 查询更新前数据============================
  127. var oldData Map
  128. err := colls.FindOne(ctx.Ctx, bson.M{"_id": uid}).Decode(&oldData)
  129. fmt.Println(err)
  130. // ============================================================================
  131. result, err1 := colls.UpdateByID(ctx.Ctx, uid, update)
  132. // ========================记录更新日志 查询更新后数据============================
  133. var newData Map
  134. colls.FindOne(ctx.Ctx, bson.M{"_id": uid}).Decode(&newData)
  135. // ============================================================================
  136. // ============================记录更新前后差异================================
  137. diff, err := diffUpdateData(oldData, newData)
  138. if err != nil {
  139. fmt.Println(err)
  140. }
  141. // fmt.Println(diff.Diff)
  142. userInfo, err := getUserById(ctx, recordLogReq.UserId)
  143. if err != nil {
  144. fmt.Println(err)
  145. }
  146. // 记录到数据库中
  147. changeLogs := &dm.Logs{
  148. Path: recordLogReq.Path,
  149. UserId: recordLogReq.UserId,
  150. TargetId: recordLogReq.TargetId,
  151. Collection: collection,
  152. UserInfo: userInfo,
  153. Diff: diff.Diff,
  154. Changes: diff.Changes,
  155. CreateTime: time.Now(),
  156. UpdateTime: time.Now(),
  157. }
  158. RepoAddDoc(ctx, CollectionLogs, changeLogs)
  159. // ==========================================================================
  160. return result, err1
  161. }
  162. func getUserById(ctx *RepoSession, id string) (*model.UserSmaple, error) {
  163. user := &model.UserSmaple{}
  164. _, err := RepoSeachDoc(ctx, &DocSearchOptions{
  165. Db: "box-user",
  166. CollectName: CollectionUsers,
  167. Query: Map{"_id": id},
  168. Project: []string{"name", "avatar", "city", "loginName", "roles", "phone"},
  169. }, user)
  170. return user, err
  171. }
  172. func getModel2Collection(omodel interface{}) string {
  173. // 订单
  174. if _, ok := omodel.(*dm.PurchaseBill); ok {
  175. return CollectionBillPurchase
  176. }
  177. // if _, ok := omodel.(*dm.ProduceBill); ok {
  178. // return CollectionBillProduce
  179. // }
  180. // test
  181. if _, ok := omodel.(*dm.ProduceBill); ok {
  182. return "bill-produce_copy1"
  183. }
  184. if _, ok := omodel.(*dm.ProductBill); ok {
  185. return CollectionBillProduct
  186. }
  187. // 计划
  188. // if _, ok := omodel.(*dm.ProductPlan); ok {
  189. // return CollectionProductPlan
  190. // }
  191. // test
  192. if _, ok := omodel.(*dm.ProductPlan); ok {
  193. return "product-plan_copy1"
  194. }
  195. if _, ok := omodel.(*dm.Product); ok {
  196. return CollectionProduct
  197. }
  198. // craft
  199. if _, ok := omodel.(*dm.Craft); ok {
  200. return CollectionCraft
  201. }
  202. // material
  203. if _, ok := omodel.(*dm.Material); ok {
  204. return CollectionMaterial
  205. }
  206. // pack
  207. if _, ok := omodel.(*dm.Pack); ok {
  208. return CollectionPack
  209. }
  210. if _, ok := omodel.(*dm.PlanTrack); ok {
  211. return CollectionPlanTrack
  212. }
  213. if _, ok := omodel.(*dm.Signature); ok {
  214. return CollectionSignature
  215. }
  216. if _, ok := omodel.(*dm.Supplier); ok {
  217. return CollectionSupplier
  218. }
  219. if _, ok := omodel.(*dm.Setting); ok {
  220. return "infos"
  221. }
  222. if _, ok := omodel.(*dm.Unit); ok {
  223. return "units"
  224. }
  225. if _, ok := omodel.(*dm.Category); ok {
  226. return "cates"
  227. }
  228. return ""
  229. }
  230. type DiffUpdateData struct {
  231. Diff string
  232. Changes []string
  233. }
  234. // 比较差异字符
  235. func diffUpdateData(oldObj any, newObj any) (*DiffUpdateData, error) {
  236. oldObjByte, err := json.Marshal(oldObj)
  237. if err != nil {
  238. return &DiffUpdateData{}, err
  239. }
  240. newObjByte, err := json.Marshal(newObj)
  241. if err != nil {
  242. return &DiffUpdateData{}, err
  243. }
  244. dmp := diffmatchpatch.New()
  245. diffs := dmp.DiffMain(string(oldObjByte), string(newObjByte), false)
  246. // 返回差异数据用于日志记录
  247. diff := &DiffUpdateData{}
  248. if len(diffs) > 0 {
  249. // return dmp.DiffPrettyText(diffs), nil
  250. htmlString := html.UnescapeString(dmp.DiffPrettyHtml(diffs))
  251. delInsRegex := regexp.MustCompile(`"([^"]+)":\s*"([^"]*(<del[^>]*>.*?</del>|<ins[^>]*>.*?</ins>)+[^"]*)",`)
  252. delInsMatches := delInsRegex.FindAllString(htmlString, -1)
  253. diff.Diff = htmlString
  254. diff.Changes = delInsMatches
  255. return diff, nil
  256. }
  257. return &DiffUpdateData{}, err
  258. }
  259. func RepoUpdateSeDbDoc(ctx *RepoSession, db string, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  260. colls := ctx.Client.GetDbCollection(db, collectName)
  261. update := bson.M{"$set": model}
  262. uid, _ := primitive.ObjectIDFromHex(idstr)
  263. return colls.UpdateByID(ctx.Ctx, uid, update)
  264. }
  265. func RepoUpdateSetDocProps(ctx *RepoSession, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  266. colls := ctx.Client.GetCollection(collectName)
  267. // update := bson.M{"$set": model}
  268. uid, _ := primitive.ObjectIDFromHex(idstr)
  269. return colls.UpdateByID(ctx.Ctx, uid, update)
  270. }
  271. func RepoUpdateSetDocsProps(ctx *RepoSession, filter *DocFilterOptions, model interface{}) (*mongo.UpdateResult, error) {
  272. colls := ctx.Client.GetCollection(filter.CollectName)
  273. if len(filter.Db) > 0 {
  274. colls = ctx.Client.GetDbCollection(filter.Db, filter.CollectName)
  275. }
  276. update := bson.M{"$set": model}
  277. filterParams := bson.M{}
  278. if len(filter.Query) > 0 {
  279. for k, v := range filter.Query {
  280. if k == "_id" {
  281. if uid, ok := v.(string); ok {
  282. docId, _ := primitive.ObjectIDFromHex(uid)
  283. filterParams["_id"] = docId
  284. continue
  285. }
  286. }
  287. filterParams[k] = v
  288. }
  289. }
  290. return colls.UpdateMany(ctx.Ctx, filterParams, update)
  291. }
  292. func RepoUpdateSetDbDocProps(ctx *RepoSession, db string, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  293. colls := ctx.Client.GetDbCollection(db, collectName)
  294. // update := bson.M{"$set": model}
  295. uid, _ := primitive.ObjectIDFromHex(idstr)
  296. return colls.UpdateByID(ctx.Ctx, uid, update)
  297. }
  298. func RepoSeachDoc(ctx *RepoSession, param *DocSearchOptions, v interface{}) (bool, error) {
  299. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  300. opt := &options.FindOneOptions{}
  301. if len(param.Project) > 0 {
  302. prj := bson.M{}
  303. for _, v := range param.Project {
  304. prj[v] = 1
  305. }
  306. opt.SetProjection(prj)
  307. }
  308. if len(param.Sort) > 0 {
  309. opt.Sort = param.Sort
  310. }
  311. filter := bson.M{}
  312. if len(param.Query) > 0 {
  313. for k, v := range param.Query {
  314. if k == "_id" {
  315. if uid, ok := v.(string); ok {
  316. docId, _ := primitive.ObjectIDFromHex(uid)
  317. filter["_id"] = docId
  318. continue
  319. }
  320. }
  321. filter[k] = v
  322. }
  323. }
  324. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(v)
  325. if err == mongo.ErrNoDocuments {
  326. return false, nil
  327. }
  328. if err != nil {
  329. return false, err
  330. }
  331. return true, nil
  332. }
  333. func RepoSeachDocMap(ctx *RepoSession, param *DocSearchOptions) (bool, map[string]interface{}) {
  334. ret := map[string]interface{}{}
  335. ok := true
  336. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  337. opt := &options.FindOneOptions{}
  338. if len(param.Project) > 0 {
  339. prj := bson.M{}
  340. for _, v := range param.Project {
  341. prj[v] = 1
  342. }
  343. opt.SetProjection(prj)
  344. }
  345. if len(param.Sort) > 0 {
  346. opt.Sort = param.Sort
  347. }
  348. filter := bson.M{}
  349. if len(param.Query) > 0 {
  350. for k, v := range param.Query {
  351. if k == "_id" {
  352. if uid, ok := v.(string); ok {
  353. docId, _ := primitive.ObjectIDFromHex(uid)
  354. filter["_id"] = docId
  355. continue
  356. }
  357. }
  358. filter[k] = v
  359. }
  360. }
  361. ok = true
  362. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(ret)
  363. if err == mongo.ErrNoDocuments {
  364. ok = false
  365. }
  366. if err != nil {
  367. ok = false
  368. }
  369. return ok, ret
  370. }
  371. // PageSearch 单表分页查询
  372. func RepoPageSearch(ctx *RepoSession, para *PageSearchOptions) (out *PageResult, err error) {
  373. var colls *mongo.Collection
  374. if len(para.Db) > 0 {
  375. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  376. } else {
  377. colls = ctx.Client.GetCollection(para.CollectName)
  378. }
  379. findoptions := &options.FindOptions{}
  380. if para.Size > 0 {
  381. findoptions.SetLimit(para.Size)
  382. findoptions.SetSkip(para.Size * (para.Page - 1))
  383. }
  384. if para.Sort != nil {
  385. findoptions.SetSort(para.Sort)
  386. }
  387. if len(para.Project) > 0 {
  388. prj := bson.M{}
  389. for _, v := range para.Project {
  390. prj[v] = 1
  391. }
  392. findoptions.SetProjection(prj)
  393. }
  394. filter := bson.M{}
  395. if len(para.Query) > 0 {
  396. for k, v := range para.Query {
  397. if value, ok := v.(string); ok {
  398. if len(value) > 0 {
  399. filter[k] = v
  400. continue
  401. }
  402. } else if v != nil {
  403. filter[k] = v
  404. }
  405. }
  406. }
  407. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  408. out = &PageResult{
  409. List: []map[string]interface{}{},
  410. Total: 0,
  411. Page: para.Page,
  412. Size: para.Size,
  413. }
  414. if err != nil {
  415. return out, err
  416. }
  417. defer cur.Close(ctx.Ctx)
  418. err = cur.All(ctx.Ctx, &out.List)
  419. out.Total, _ = colls.CountDocuments(ctx.Ctx, filter)
  420. return
  421. }
  422. func RepoDbCountDoc(ctx *RepoSession, db string, collectionName string, Query Map) (int64, error) {
  423. colls := ctx.Client.GetDbCollection(db, collectionName)
  424. filter := bson.M{}
  425. if len(Query) > 0 {
  426. for k, v := range Query {
  427. if value, ok := v.(string); ok {
  428. if len(value) > 0 {
  429. filter[k] = v
  430. continue
  431. }
  432. } else {
  433. filter[k] = v
  434. }
  435. }
  436. }
  437. return colls.CountDocuments(ctx.Ctx, filter)
  438. }
  439. func RepoCountDoc(ctx *RepoSession, collectionName string, Query Map) (int64, error) {
  440. colls := ctx.Client.GetCollection(collectionName)
  441. filter := bson.M{}
  442. if len(Query) > 0 {
  443. for k, v := range Query {
  444. if value, ok := v.(string); ok {
  445. if len(value) > 0 {
  446. filter[k] = v
  447. continue
  448. }
  449. } else {
  450. filter[k] = v
  451. }
  452. }
  453. }
  454. return colls.CountDocuments(ctx.Ctx, filter)
  455. }
  456. // PageSearch 单表分页查询
  457. func RepoDocsSearch(ctx *RepoSession, para *PageSearchOptions, out interface{}) (err error) {
  458. colls := ctx.Client.GetCollection(para.CollectName)
  459. if len(para.Db) > 0 {
  460. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  461. }
  462. findoptions := &options.FindOptions{}
  463. if para.Size > 0 {
  464. findoptions.SetLimit(para.Size)
  465. findoptions.SetSkip(para.Size * (para.Page - 1))
  466. }
  467. if para.Sort != nil {
  468. findoptions.SetSort(para.Sort)
  469. }
  470. if len(para.Project) > 0 {
  471. prj := bson.M{}
  472. for _, v := range para.Project {
  473. prj[v] = 1
  474. }
  475. findoptions.SetProjection(prj)
  476. }
  477. filter := bson.M{}
  478. if len(para.Query) > 0 {
  479. for k, v := range para.Query {
  480. if value, ok := v.(string); ok {
  481. if len(value) > 0 {
  482. filter[k] = v
  483. continue
  484. }
  485. } else {
  486. filter[k] = v
  487. }
  488. }
  489. }
  490. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  491. if err != nil {
  492. return err
  493. }
  494. defer cur.Close(ctx.Ctx)
  495. err = cur.All(ctx.Ctx, out)
  496. return
  497. }
  498. func RepoDocArrayAppend(ctx *RepoSession, collectName string, idstr string, fieldpath string, arrayItem interface{}) (*mongo.UpdateResult, error) {
  499. colls := ctx.Client.GetCollection(collectName)
  500. arrayOp := bson.M{}
  501. arrayOp[fieldpath] = arrayItem
  502. update := bson.M{"$push": arrayOp}
  503. uid, _ := primitive.ObjectIDFromHex(idstr)
  504. return colls.UpdateByID(ctx.Ctx, uid, update)
  505. }
  506. // { _id: 4, "grades.grade": 85 },
  507. // { $set: { "grades.$.std" : 6 } }
  508. type ArrayOneUpdateOption struct {
  509. Query Map
  510. Set Map
  511. CollectName string
  512. Id string
  513. }
  514. // if len(scene.Stickers) > 0 {
  515. // optSet["scenes.$.stickers"] = scene.Stickers
  516. // }
  517. // option := &repo.ArrayOneUpdateOption{
  518. // CollectName: repo.CollectionDesigns,
  519. // Id: id,
  520. // Query: repo.Map{"scenes.id": scene.Id},
  521. // Set: optSet,
  522. // }
  523. func RepoDocArrayOneUpdate(ctx *RepoSession, options *ArrayOneUpdateOption) (*mongo.UpdateResult, error) {
  524. colls := ctx.Client.GetCollection(options.CollectName)
  525. docId, _ := primitive.ObjectIDFromHex(options.Id)
  526. query := bson.M{"_id": docId}
  527. if len(options.Query) > 0 {
  528. for k, v := range options.Query {
  529. query[k] = v
  530. }
  531. }
  532. setOp := bson.M{}
  533. for k, v := range options.Set {
  534. setOp[k] = v
  535. }
  536. update := bson.M{"$set": setOp}
  537. return colls.UpdateOne(ctx.Ctx, query, update)
  538. }
  539. type ArrayOneRemoveOption struct {
  540. ArrayQuery Map
  541. CollectName string
  542. Id string
  543. }
  544. // { $pull: { "items" : { id: 23 } } }
  545. func RepoDocArrayOneRemove(ctx *RepoSession, options *ArrayOneRemoveOption) (*mongo.UpdateResult, error) {
  546. colls := ctx.Client.GetCollection(options.CollectName)
  547. docId, _ := primitive.ObjectIDFromHex(options.Id)
  548. query := bson.M{"_id": docId}
  549. arrayQuery := bson.M{}
  550. if len(options.ArrayQuery) > 0 {
  551. for k, v := range options.ArrayQuery {
  552. arrayQuery[k] = v
  553. }
  554. }
  555. update := bson.M{"$pull": arrayQuery}
  556. return colls.UpdateOne(ctx.Ctx, query, update)
  557. }
  558. type ArrayOneSearchOption struct {
  559. ArrayQuery Map
  560. CollectName string
  561. Id string
  562. Field string
  563. }
  564. func RepoDocArraySearch(ctx *RepoSession, options *ArrayOneSearchOption, entity interface{}) error {
  565. colls := ctx.Client.GetCollection(options.CollectName)
  566. docId, _ := primitive.ObjectIDFromHex(options.Id)
  567. match := []bson.E{}
  568. match = append(match, bson.E{"_id", docId})
  569. matchStage := bson.D{
  570. {"$match", match},
  571. }
  572. unwindStage := bson.D{
  573. {"$unwind", fmt.Sprintf("%s%s", "$", options.Field)},
  574. }
  575. pipe := mongo.Pipeline{matchStage, unwindStage}
  576. if len(options.ArrayQuery) > 0 {
  577. match2 := []bson.E{}
  578. for k, v := range options.ArrayQuery {
  579. match2 = append(match2, bson.E{k, v})
  580. }
  581. match2Stage := bson.D{
  582. {"$match", match2},
  583. }
  584. pipe = append(pipe, match2Stage)
  585. }
  586. curr, err := colls.Aggregate(ctx.Ctx, pipe)
  587. if err != nil {
  588. return err
  589. }
  590. defer curr.Close(ctx.Ctx)
  591. if curr.Next(ctx.Ctx) {
  592. err = curr.Decode(entity)
  593. if err != nil {
  594. return err
  595. }
  596. return nil
  597. }
  598. return nil
  599. }
  600. type DocsSearchOptions struct {
  601. CollectName string
  602. Query map[string]interface{}
  603. Project []string
  604. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  605. }
  606. func RepoSeachDocsMap(ctx *RepoSession, param *DocsSearchOptions) (ok bool, list []map[string]interface{}) {
  607. colls := ctx.Client.GetCollection(param.CollectName)
  608. findoptions := &options.FindOptions{}
  609. if len(param.Project) > 0 {
  610. prj := bson.M{}
  611. for _, v := range param.Project {
  612. prj[v] = 1
  613. }
  614. findoptions.SetProjection(prj)
  615. }
  616. if param.Sort != nil {
  617. findoptions.SetSort(param.Sort)
  618. }
  619. filter := bson.M{}
  620. if len(param.Query) > 0 {
  621. for k, v := range param.Query {
  622. if value, ok := v.(string); ok {
  623. if len(value) > 0 {
  624. filter[k] = v
  625. continue
  626. }
  627. } else {
  628. filter[k] = v
  629. }
  630. }
  631. }
  632. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  633. if err != nil {
  634. ok = false
  635. return
  636. }
  637. defer cur.Close(ctx.Ctx)
  638. listRes := []map[string]interface{}{}
  639. err = cur.All(ctx.Ctx, &listRes)
  640. if err != nil {
  641. log.Error(err)
  642. ok = false
  643. return
  644. }
  645. list = listRes
  646. ok = true
  647. return
  648. }
  649. type DbDocsSearchOptions struct {
  650. Db string
  651. CollectName string
  652. Query map[string]interface{}
  653. Project []string
  654. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  655. }
  656. func DbRepoSeachDocsMap(ctx *RepoSession, param *DbDocsSearchOptions) (ok bool, list []map[string]interface{}) {
  657. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  658. findoptions := &options.FindOptions{}
  659. if len(param.Project) > 0 {
  660. prj := bson.M{}
  661. for _, v := range param.Project {
  662. prj[v] = 1
  663. }
  664. findoptions.SetProjection(prj)
  665. }
  666. if param.Sort != nil {
  667. findoptions.SetSort(param.Sort)
  668. }
  669. filter := bson.M{}
  670. if len(param.Query) > 0 {
  671. for k, v := range param.Query {
  672. if value, ok := v.(string); ok {
  673. if len(value) > 0 {
  674. filter[k] = v
  675. continue
  676. }
  677. } else {
  678. filter[k] = v
  679. }
  680. }
  681. }
  682. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  683. if err != nil {
  684. ok = false
  685. return
  686. }
  687. defer cur.Close(ctx.Ctx)
  688. listRes := []map[string]interface{}{}
  689. err = cur.All(ctx.Ctx, &listRes)
  690. if err != nil {
  691. log.Error(err)
  692. ok = false
  693. return
  694. }
  695. list = listRes
  696. ok = true
  697. return
  698. }