repo.go 15 KB

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