repo.go 14 KB

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