probo/lib/store/participant.go
2023-12-27 15:05:11 +01:00

70 lines
1.4 KiB
Go

package store
import (
"os"
"git.andreafazzi.eu/andrea/probo/lib/models"
"github.com/gocarina/gocsv"
)
type ParticipantStore struct {
*FilterStore[*models.Participant]
}
func NewParticipantStore() *ParticipantStore {
store := new(ParticipantStore)
store.FilterStore = NewFilterStore[*models.Participant]()
return store
}
func (s *ParticipantStore) ImportCSV(path string) ([]*models.Participant, error) {
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
return nil, err
}
defer file.Close()
participants := make([]*models.Participant, 0)
if err := gocsv.UnmarshalFile(file, &participants); err != nil {
return nil, err
}
memParticipants := make([]*models.Participant, 0)
for _, p := range participants {
memParticipant, err := s.Create(p)
if err != nil {
return nil, err
}
memParticipants = append(memParticipants, memParticipant)
}
return memParticipants, nil
}
func (s *ParticipantStore) FilterInGroup(group *models.Group, filter map[string]string) []*models.Participant {
participants := s.ReadAll()
if filter == nil {
return participants
}
filteredParticipants := s.Filter(participants, func(p *models.Participant) bool {
for pk, pv := range p.Attributes {
for fk, fv := range filter {
if pk == fk && pv == fv {
return true
}
}
}
return false
})
group.Participants = filteredParticipants
return group.Participants
}