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