@@ -11,13 +11,13 @@ import (
1111 "go.mongodb.org/mongo-driver/mongo/options"
1212)
1313
14- func (b * Backend ) GetItems (ctx context.Context , categoryID string , page , size uint64 , state string , name string , fournisseur string ) ([]* models.Item , error ) {
14+ func (b * Backend ) GetItems (ctx context.Context , categoryID string , page , size uint64 , state string , name string , fournisseur string , sort bool ) ([]* models.Item , error ) {
1515 ctx , cancel := b .TimeoutContext (ctx )
1616 defer cancel ()
1717
1818 var items []* models.Item
1919
20- filter := bson.M {
20+ matchFilter := bson.M {
2121 "$or" : []bson.M {
2222 {
2323 "deleted_at" : bson.M {
@@ -30,12 +30,12 @@ func (b *Backend) GetItems(ctx context.Context, categoryID string, page, size ui
3030 },
3131 }
3232 if state != "" {
33- filter ["state" ] = state
33+ matchFilter ["state" ] = state
3434 if state == string (autogen .ItemBuyable ) {
35- // Get seconds since day start
35+ // Get seconds since day start
3636 t := time .Since (time .Now ().Truncate (24 * time .Hour )).Seconds ()
3737 // available_from <= t <= available_until or (available_from == nil && available_until == nil)
38- filter ["$and" ] = []bson.M {
38+ matchFilter ["$and" ] = []bson.M {
3939 {
4040 "$or" : []bson.M {
4141 {
@@ -64,19 +64,51 @@ func (b *Backend) GetItems(ctx context.Context, categoryID string, page, size ui
6464 }
6565 }
6666 if categoryID != "" {
67- filter ["category_id" ] = uuid .MustParse (categoryID )
67+ matchFilter ["category_id" ] = uuid .MustParse (categoryID )
6868 }
6969 if name != "" {
70- filter ["name" ] = bson.M {
70+ matchFilter ["name" ] = bson.M {
7171 "$regex" : name ,
7272 "$options" : "i" ,
7373 }
7474 }
7575 if fournisseur != "" {
76- filter ["fournisseur" ] = fournisseur
76+ matchFilter ["fournisseur" ] = fournisseur
7777 }
7878
79- cursor , err := b .db .Collection (ItemsCollection ).Find (ctx , filter , options .Find ().SetSkip (int64 (page * size )).SetLimit (int64 (size )))
79+ pipeline := []bson.M {
80+ {"$match" : matchFilter },
81+ }
82+
83+ if sort {
84+ pipeline = append (pipeline , bson.M {
85+ "$addFields" : bson.M {
86+ "sortPriority" : bson.M {
87+ "$cond" : bson.A {
88+ bson.M {"$eq" : bson.A {"$amount_left" , 0 }},
89+ 2 ,
90+ 1 ,
91+ },
92+ },
93+ },
94+ })
95+
96+ pipeline = append (pipeline , bson.M {
97+ "$sort" : bson.D {
98+ {"sortPriority" , 1 },
99+ },
100+ })
101+ }
102+ pipeline = append (pipeline , bson.M {"$skip" : int64 (page * size )})
103+ pipeline = append (pipeline , bson.M {"$limit" : int64 (size )})
104+
105+ if sort {
106+ pipeline = append (pipeline , bson.M {
107+ "$project" : bson.M {"sortPriority" : 0 },
108+ })
109+ }
110+
111+ cursor , err := b .db .Collection (ItemsCollection ).Aggregate (ctx , pipeline )
80112 if err != nil {
81113 return nil , err
82114 }
0 commit comments