repo.go 13 KB

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