github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/contact/group.go (about)

     1  package contact
     2  
     3  import (
     4  	"sort"
     5  
     6  	"github.com/cozy/cozy-stack/pkg/consts"
     7  	"github.com/cozy/cozy-stack/pkg/couchdb"
     8  	"github.com/cozy/cozy-stack/pkg/couchdb/mango"
     9  	"github.com/cozy/cozy-stack/pkg/prefixer"
    10  )
    11  
    12  // Group is a struct for a group of contacts.
    13  type Group struct {
    14  	couchdb.JSONDoc
    15  }
    16  
    17  // NewGroup returns a new blank group.
    18  func NewGroup() *Group {
    19  	return &Group{
    20  		JSONDoc: couchdb.JSONDoc{
    21  			M: make(map[string]interface{}),
    22  		},
    23  	}
    24  }
    25  
    26  // DocType returns the contact document type
    27  func (g *Group) DocType() string { return consts.Groups }
    28  
    29  // Name returns the name of the group
    30  func (g *Group) Name() string {
    31  	name, _ := g.Get("name").(string)
    32  	return name
    33  }
    34  
    35  // FindGroup returns the group of contacts stored in database from a given ID
    36  func FindGroup(db prefixer.Prefixer, groupID string) (*Group, error) {
    37  	doc := &Group{}
    38  	err := couchdb.GetDoc(db, consts.Groups, groupID, doc)
    39  	return doc, err
    40  }
    41  
    42  // GetAllContacts returns the list of contacts inside this group.
    43  func (g *Group) GetAllContacts(db prefixer.Prefixer) ([]*Contact, error) {
    44  	var docs []*Contact
    45  	req := &couchdb.FindRequest{
    46  		UseIndex: "by-groups",
    47  		Selector: mango.Map{
    48  			"relationships": map[string]interface{}{
    49  				"groups": map[string]interface{}{
    50  					"data": map[string]interface{}{
    51  						"$elemMatch": map[string]interface{}{
    52  							"_id":   g.ID(),
    53  							"_type": consts.Groups,
    54  						},
    55  					},
    56  				},
    57  			},
    58  		},
    59  		Limit: 1000,
    60  	}
    61  	err := couchdb.FindDocs(db, consts.Contacts, req, &docs)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	// XXX I didn't find a way to make a mango request with the correct sort
    67  	less := func(i, j int) bool {
    68  		a := docs[i].SortingKey()
    69  		b := docs[j].SortingKey()
    70  		return a < b
    71  	}
    72  	sort.Slice(docs, less)
    73  	return docs, nil
    74  }