repo.go 14 KB

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