repo.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. package repo
  2. import (
  3. "box-cost/db"
  4. "box-cost/log"
  5. "context"
  6. "fmt"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/bson/primitive"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "go.mongodb.org/mongo-driver/mongo/options"
  11. )
  12. type RepoSession struct {
  13. Ctx context.Context
  14. Client *db.MongoDB
  15. }
  16. const (
  17. CollectionMaterial = "material"
  18. CollectionCraft = "craft"
  19. CollectionSupplier = "supplier"
  20. CollectionSupplierPrice = "supplier-price"
  21. CollectionPack = "pack"
  22. CollectionProductPlan = "product-plan"
  23. CollectionBillPurchase = "bill-purchase"
  24. CollectionBillProduce = "bill-produce"
  25. CollectionSupplierMatprice = "supplier-mats"
  26. CollectionSupplierCraftprice = "supplier-crafts"
  27. CollectionIncrement = "increment"
  28. CollectionSignature = "signature"
  29. CollectionUsers = "users"
  30. )
  31. type Map map[string]interface{}
  32. type PageResult struct {
  33. List []map[string]interface{} `json:"list"`
  34. Total int64 `json:"total"`
  35. Page int64 `json:"page"`
  36. Size int64 `json:"size"`
  37. }
  38. type PageSearchOptions struct {
  39. Db string
  40. CollectName string
  41. Page int64
  42. Size int64
  43. Query map[string]interface{}
  44. Project []string
  45. Sort interface{}
  46. }
  47. type DocSearchOptions struct {
  48. Db string
  49. CollectName string
  50. Query Map
  51. Project []string
  52. Sort bson.M
  53. }
  54. type DocFilterOptions struct {
  55. Db string
  56. CollectName string
  57. Query Map
  58. }
  59. func NewDocSearchOptions(filter Map, project []string) *DocSearchOptions {
  60. return &DocSearchOptions{
  61. Query: filter,
  62. Project: project,
  63. }
  64. }
  65. func RepoAddDoc(ctx *RepoSession, collectName string, doc interface{}) (string, error) {
  66. users := ctx.Client.GetCollection(collectName)
  67. result, err := users.InsertOne(ctx.Ctx, doc)
  68. if err != nil {
  69. return "", err
  70. }
  71. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  72. }
  73. func RepoDbAddDoc(ctx *RepoSession, dbName string, collectName string, doc interface{}) (string, error) {
  74. users := ctx.Client.GetDbCollection(dbName, collectName)
  75. result, err := users.InsertOne(ctx.Ctx, doc)
  76. if err != nil {
  77. return "", err
  78. }
  79. return result.InsertedID.(primitive.ObjectID).Hex(), nil
  80. }
  81. func RepoDeleteDoc(ctx *RepoSession, collectName string, id string) (interface{}, error) {
  82. uid, _ := primitive.ObjectIDFromHex(id)
  83. colls := ctx.Client.GetCollection(collectName)
  84. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  85. }
  86. func RepoDeleteDbDoc(ctx *RepoSession, dbName string, collectName string, id string) (interface{}, error) {
  87. uid, _ := primitive.ObjectIDFromHex(id)
  88. colls := ctx.Client.GetDbCollection(dbName, collectName)
  89. return colls.DeleteOne(ctx.Ctx, &bson.M{"_id": uid})
  90. }
  91. func RepoDeleteDocs(ctx *RepoSession, collectName string, query interface{}) (interface{}, error) {
  92. colls := ctx.Client.GetCollection(collectName)
  93. return colls.DeleteMany(ctx.Ctx, query)
  94. }
  95. func RepoUpdateSetDoc(ctx *RepoSession, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  96. colls := ctx.Client.GetCollection(collectName)
  97. update := bson.M{"$set": model}
  98. uid, _ := primitive.ObjectIDFromHex(idstr)
  99. return colls.UpdateByID(ctx.Ctx, uid, update)
  100. }
  101. func RepoUpdateSeDbDoc(ctx *RepoSession, db string, collectName string, idstr string, model interface{}) (*mongo.UpdateResult, error) {
  102. colls := ctx.Client.GetDbCollection(db, collectName)
  103. update := bson.M{"$set": model}
  104. uid, _ := primitive.ObjectIDFromHex(idstr)
  105. return colls.UpdateByID(ctx.Ctx, uid, update)
  106. }
  107. func RepoUpdateSetDocProps(ctx *RepoSession, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  108. colls := ctx.Client.GetCollection(collectName)
  109. // update := bson.M{"$set": model}
  110. uid, _ := primitive.ObjectIDFromHex(idstr)
  111. return colls.UpdateByID(ctx.Ctx, uid, update)
  112. }
  113. func RepoUpdateSetDocsProps(ctx *RepoSession, filter *DocFilterOptions, model interface{}) (*mongo.UpdateResult, error) {
  114. colls := ctx.Client.GetCollection(filter.CollectName)
  115. if len(filter.Db) > 0 {
  116. colls = ctx.Client.GetDbCollection(filter.Db, filter.CollectName)
  117. }
  118. update := bson.M{"$set": model}
  119. filterParams := bson.M{}
  120. if len(filter.Query) > 0 {
  121. for k, v := range filter.Query {
  122. if k == "_id" {
  123. if uid, ok := v.(string); ok {
  124. docId, _ := primitive.ObjectIDFromHex(uid)
  125. filterParams["_id"] = docId
  126. continue
  127. }
  128. }
  129. filterParams[k] = v
  130. }
  131. }
  132. return colls.UpdateMany(ctx.Ctx, filterParams, update)
  133. }
  134. func RepoUpdateSetDbDocProps(ctx *RepoSession, db string, collectName string, idstr string, update interface{}) (*mongo.UpdateResult, error) {
  135. colls := ctx.Client.GetDbCollection(db, collectName)
  136. // update := bson.M{"$set": model}
  137. uid, _ := primitive.ObjectIDFromHex(idstr)
  138. return colls.UpdateByID(ctx.Ctx, uid, update)
  139. }
  140. func RepoSeachDoc(ctx *RepoSession, param *DocSearchOptions, v interface{}) (bool, error) {
  141. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  142. opt := &options.FindOneOptions{}
  143. if len(param.Project) > 0 {
  144. prj := bson.M{}
  145. for _, v := range param.Project {
  146. prj[v] = 1
  147. }
  148. opt.SetProjection(prj)
  149. }
  150. if len(param.Sort) > 0 {
  151. opt.Sort = param.Sort
  152. }
  153. filter := bson.M{}
  154. if len(param.Query) > 0 {
  155. for k, v := range param.Query {
  156. if k == "_id" {
  157. if uid, ok := v.(string); ok {
  158. docId, _ := primitive.ObjectIDFromHex(uid)
  159. filter["_id"] = docId
  160. continue
  161. }
  162. }
  163. filter[k] = v
  164. }
  165. }
  166. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(v)
  167. if err == mongo.ErrNoDocuments {
  168. return false, nil
  169. }
  170. if err != nil {
  171. return false, err
  172. }
  173. return true, nil
  174. }
  175. func RepoSeachDocMap(ctx *RepoSession, param *DocSearchOptions) (bool, map[string]interface{}) {
  176. ret := map[string]interface{}{}
  177. ok := true
  178. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  179. opt := &options.FindOneOptions{}
  180. if len(param.Project) > 0 {
  181. prj := bson.M{}
  182. for _, v := range param.Project {
  183. prj[v] = 1
  184. }
  185. opt.SetProjection(prj)
  186. }
  187. if len(param.Sort) > 0 {
  188. opt.Sort = param.Sort
  189. }
  190. filter := bson.M{}
  191. if len(param.Query) > 0 {
  192. for k, v := range param.Query {
  193. if k == "_id" {
  194. if uid, ok := v.(string); ok {
  195. docId, _ := primitive.ObjectIDFromHex(uid)
  196. filter["_id"] = docId
  197. continue
  198. }
  199. }
  200. filter[k] = v
  201. }
  202. }
  203. ok = true
  204. err := colls.FindOne(ctx.Ctx, filter, opt).Decode(ret)
  205. if err == mongo.ErrNoDocuments {
  206. ok = false
  207. }
  208. if err != nil {
  209. ok = false
  210. }
  211. return ok, ret
  212. }
  213. // PageSearch 单表分页查询
  214. func RepoPageSearch(ctx *RepoSession, para *PageSearchOptions) (out *PageResult, err error) {
  215. var colls *mongo.Collection
  216. if len(para.Db) > 0 {
  217. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  218. } else {
  219. colls = ctx.Client.GetCollection(para.CollectName)
  220. }
  221. findoptions := &options.FindOptions{}
  222. if para.Size > 0 {
  223. findoptions.SetLimit(para.Size)
  224. findoptions.SetSkip(para.Size * (para.Page - 1))
  225. }
  226. if para.Sort != nil {
  227. findoptions.SetSort(para.Sort)
  228. }
  229. if len(para.Project) > 0 {
  230. prj := bson.M{}
  231. for _, v := range para.Project {
  232. prj[v] = 1
  233. }
  234. findoptions.SetProjection(prj)
  235. }
  236. filter := bson.M{}
  237. if len(para.Query) > 0 {
  238. for k, v := range para.Query {
  239. if value, ok := v.(string); ok {
  240. if len(value) > 0 {
  241. filter[k] = v
  242. continue
  243. }
  244. } else if v != nil {
  245. filter[k] = v
  246. }
  247. }
  248. }
  249. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  250. out = &PageResult{
  251. List: []map[string]interface{}{},
  252. Total: 0,
  253. Page: para.Page,
  254. Size: para.Size,
  255. }
  256. if err != nil {
  257. return out, err
  258. }
  259. defer cur.Close(ctx.Ctx)
  260. err = cur.All(ctx.Ctx, &out.List)
  261. out.Total, _ = colls.CountDocuments(ctx.Ctx, filter)
  262. return
  263. }
  264. func RepoDbCountDoc(ctx *RepoSession, db string, collectionName string, Query Map) (int64, error) {
  265. colls := ctx.Client.GetDbCollection(db, collectionName)
  266. filter := bson.M{}
  267. if len(Query) > 0 {
  268. for k, v := range Query {
  269. if value, ok := v.(string); ok {
  270. if len(value) > 0 {
  271. filter[k] = v
  272. continue
  273. }
  274. } else {
  275. filter[k] = v
  276. }
  277. }
  278. }
  279. return colls.CountDocuments(ctx.Ctx, filter)
  280. }
  281. func RepoCountDoc(ctx *RepoSession, collectionName string, Query Map) (int64, error) {
  282. colls := ctx.Client.GetCollection(collectionName)
  283. filter := bson.M{}
  284. if len(Query) > 0 {
  285. for k, v := range Query {
  286. if value, ok := v.(string); ok {
  287. if len(value) > 0 {
  288. filter[k] = v
  289. continue
  290. }
  291. } else {
  292. filter[k] = v
  293. }
  294. }
  295. }
  296. return colls.CountDocuments(ctx.Ctx, filter)
  297. }
  298. // PageSearch 单表分页查询
  299. func RepoDocsSearch(ctx *RepoSession, para *PageSearchOptions, out interface{}) (err error) {
  300. colls := ctx.Client.GetCollection(para.CollectName)
  301. if len(para.Db) > 0 {
  302. colls = ctx.Client.GetDbCollection(para.Db, para.CollectName)
  303. }
  304. findoptions := &options.FindOptions{}
  305. if para.Size > 0 {
  306. findoptions.SetLimit(para.Size)
  307. findoptions.SetSkip(para.Size * (para.Page - 1))
  308. }
  309. if para.Sort != nil {
  310. findoptions.SetSort(para.Sort)
  311. }
  312. if len(para.Project) > 0 {
  313. prj := bson.M{}
  314. for _, v := range para.Project {
  315. prj[v] = 1
  316. }
  317. findoptions.SetProjection(prj)
  318. }
  319. filter := bson.M{}
  320. if len(para.Query) > 0 {
  321. for k, v := range para.Query {
  322. if value, ok := v.(string); ok {
  323. if len(value) > 0 {
  324. filter[k] = v
  325. continue
  326. }
  327. } else {
  328. filter[k] = v
  329. }
  330. }
  331. }
  332. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  333. if err != nil {
  334. return err
  335. }
  336. defer cur.Close(ctx.Ctx)
  337. err = cur.All(ctx.Ctx, out)
  338. return
  339. }
  340. func RepoDocArrayAppend(ctx *RepoSession, collectName string, idstr string, fieldpath string, arrayItem interface{}) (*mongo.UpdateResult, error) {
  341. colls := ctx.Client.GetCollection(collectName)
  342. arrayOp := bson.M{}
  343. arrayOp[fieldpath] = arrayItem
  344. update := bson.M{"$push": arrayOp}
  345. uid, _ := primitive.ObjectIDFromHex(idstr)
  346. return colls.UpdateByID(ctx.Ctx, uid, update)
  347. }
  348. // { _id: 4, "grades.grade": 85 },
  349. // { $set: { "grades.$.std" : 6 } }
  350. type ArrayOneUpdateOption struct {
  351. Query Map
  352. Set Map
  353. CollectName string
  354. Id string
  355. }
  356. // if len(scene.Stickers) > 0 {
  357. // optSet["scenes.$.stickers"] = scene.Stickers
  358. // }
  359. // option := &repo.ArrayOneUpdateOption{
  360. // CollectName: repo.CollectionDesigns,
  361. // Id: id,
  362. // Query: repo.Map{"scenes.id": scene.Id},
  363. // Set: optSet,
  364. // }
  365. func RepoDocArrayOneUpdate(ctx *RepoSession, options *ArrayOneUpdateOption) (*mongo.UpdateResult, error) {
  366. colls := ctx.Client.GetCollection(options.CollectName)
  367. docId, _ := primitive.ObjectIDFromHex(options.Id)
  368. query := bson.M{"_id": docId}
  369. if len(options.Query) > 0 {
  370. for k, v := range options.Query {
  371. query[k] = v
  372. }
  373. }
  374. setOp := bson.M{}
  375. for k, v := range options.Set {
  376. setOp[k] = v
  377. }
  378. update := bson.M{"$set": setOp}
  379. return colls.UpdateOne(ctx.Ctx, query, update)
  380. }
  381. type ArrayOneRemoveOption struct {
  382. ArrayQuery Map
  383. CollectName string
  384. Id string
  385. }
  386. // { $pull: { "items" : { id: 23 } } }
  387. func RepoDocArrayOneRemove(ctx *RepoSession, options *ArrayOneRemoveOption) (*mongo.UpdateResult, error) {
  388. colls := ctx.Client.GetCollection(options.CollectName)
  389. docId, _ := primitive.ObjectIDFromHex(options.Id)
  390. query := bson.M{"_id": docId}
  391. arrayQuery := bson.M{}
  392. if len(options.ArrayQuery) > 0 {
  393. for k, v := range options.ArrayQuery {
  394. arrayQuery[k] = v
  395. }
  396. }
  397. update := bson.M{"$pull": arrayQuery}
  398. return colls.UpdateOne(ctx.Ctx, query, update)
  399. }
  400. type ArrayOneSearchOption struct {
  401. ArrayQuery Map
  402. CollectName string
  403. Id string
  404. Field string
  405. }
  406. func RepoDocArraySearch(ctx *RepoSession, options *ArrayOneSearchOption, entity interface{}) error {
  407. colls := ctx.Client.GetCollection(options.CollectName)
  408. docId, _ := primitive.ObjectIDFromHex(options.Id)
  409. match := []bson.E{}
  410. match = append(match, bson.E{"_id", docId})
  411. matchStage := bson.D{
  412. {"$match", match},
  413. }
  414. unwindStage := bson.D{
  415. {"$unwind", fmt.Sprintf("%s%s", "$", options.Field)},
  416. }
  417. pipe := mongo.Pipeline{matchStage, unwindStage}
  418. if len(options.ArrayQuery) > 0 {
  419. match2 := []bson.E{}
  420. for k, v := range options.ArrayQuery {
  421. match2 = append(match2, bson.E{k, v})
  422. }
  423. match2Stage := bson.D{
  424. {"$match", match2},
  425. }
  426. pipe = append(pipe, match2Stage)
  427. }
  428. curr, err := colls.Aggregate(ctx.Ctx, pipe)
  429. if err != nil {
  430. return err
  431. }
  432. defer curr.Close(ctx.Ctx)
  433. if curr.Next(ctx.Ctx) {
  434. err = curr.Decode(entity)
  435. if err != nil {
  436. return err
  437. }
  438. return nil
  439. }
  440. return nil
  441. }
  442. type DocsSearchOptions struct {
  443. CollectName string
  444. Query map[string]interface{}
  445. Project []string
  446. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  447. }
  448. func RepoSeachDocsMap(ctx *RepoSession, param *DocsSearchOptions) (ok bool, list []map[string]interface{}) {
  449. colls := ctx.Client.GetCollection(param.CollectName)
  450. findoptions := &options.FindOptions{}
  451. if len(param.Project) > 0 {
  452. prj := bson.M{}
  453. for _, v := range param.Project {
  454. prj[v] = 1
  455. }
  456. findoptions.SetProjection(prj)
  457. }
  458. if param.Sort != nil {
  459. findoptions.SetSort(param.Sort)
  460. }
  461. filter := bson.M{}
  462. if len(param.Query) > 0 {
  463. for k, v := range param.Query {
  464. if value, ok := v.(string); ok {
  465. if len(value) > 0 {
  466. filter[k] = v
  467. continue
  468. }
  469. } else {
  470. filter[k] = v
  471. }
  472. }
  473. }
  474. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  475. if err != nil {
  476. ok = false
  477. return
  478. }
  479. defer cur.Close(ctx.Ctx)
  480. listRes := []map[string]interface{}{}
  481. err = cur.All(ctx.Ctx, &listRes)
  482. if err != nil {
  483. log.Error(err)
  484. ok = false
  485. return
  486. }
  487. list = listRes
  488. ok = true
  489. return
  490. }
  491. type DbDocsSearchOptions struct {
  492. Db string
  493. CollectName string
  494. Query map[string]interface{}
  495. Project []string
  496. Sort interface{} //bson.D{ bson.E{"update_time", -1}, bson.E{"goods_id", -1},}
  497. }
  498. func DbRepoSeachDocsMap(ctx *RepoSession, param *DbDocsSearchOptions) (ok bool, list []map[string]interface{}) {
  499. colls := ctx.Client.GetDbCollection(param.Db, param.CollectName)
  500. findoptions := &options.FindOptions{}
  501. if len(param.Project) > 0 {
  502. prj := bson.M{}
  503. for _, v := range param.Project {
  504. prj[v] = 1
  505. }
  506. findoptions.SetProjection(prj)
  507. }
  508. if param.Sort != nil {
  509. findoptions.SetSort(param.Sort)
  510. }
  511. filter := bson.M{}
  512. if len(param.Query) > 0 {
  513. for k, v := range param.Query {
  514. if value, ok := v.(string); ok {
  515. if len(value) > 0 {
  516. filter[k] = v
  517. continue
  518. }
  519. } else {
  520. filter[k] = v
  521. }
  522. }
  523. }
  524. cur, err := colls.Find(ctx.Ctx, filter, findoptions)
  525. if err != nil {
  526. ok = false
  527. return
  528. }
  529. defer cur.Close(ctx.Ctx)
  530. listRes := []map[string]interface{}{}
  531. err = cur.All(ctx.Ctx, &listRes)
  532. if err != nil {
  533. log.Error(err)
  534. ok = false
  535. return
  536. }
  537. list = listRes
  538. ok = true
  539. return
  540. }