repo.go 15 KB

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