class UserModel(db.Document):
    username = db.StringField(required=True, unique=True)
    email = db.StringField(required=True, unique=True)
    password = db.StringField()
    spotify_id = db.StringField()
    avatar_url = db.StringField()
    pref_genres = db.ListField(db.StringField())

    song_ids = db.ListField(db.StringField())

    meta = {'collection': 'users', 'indexes': ['username', 'email']}

    def json(self):
        return {
            'id': str(self.id),
            'username': self.username,
            'email': self.email,
            'avatar_url': self.avatar_url,
            'pref_genres': list(self.pref_genres)
        }

    @classmethod
    def find_by_id(cls, _id: ObjectId) -> "UserModel":
        return cls.objects(id=_id).first()

    @classmethod
    def find_by_username(cls, username: str) -> "UserModel":
        return cls.objects(username=username).first()

    @classmethod
    def find_by_email(cls, email: str) -> "UserModel":
        return cls.objects(email=email).first()

    def save_to_db(self) -> None:
        self.save()

    def delete_from_db(self) -> None:
        self.delete()

    @classmethod
    def find_all_by_ids(cls, ids: List[ObjectId]) -> List["UserModel"]:
        return list(cls.objects(id__in=ids))
class Movimentacao(db.Document):
    codigo = db.StringField(required=False, unique=False)
    tipo = db.StringField(required=False, unique=False)
    equipamentos_id = db.ListField(db.ReferenceField(Equipamento))
    instituicao_destino = db.StringField(required=False, unique=False)
    cidade_destino = db.StringField(required=False, unique=False)
    cnpj_destino = db.StringField(required=False, unique=False)
    endereco_destino = db.StringField(required=False, unique=False)
    nome_responsavel_destino = db.StringField(required=False, unique=False)
    contato_responsavel_destino = db.StringField(required=False, unique=False)
    nome_responsavel_transporte = db.StringField(required=False, unique=False)
    contato_responsavel_transporte = db.StringField(required=False,
                                                    unique=False)
    data_entrega = db.DateTimeField(required=False)
    acessorios = db.DictField(requried=False)
    created_at = db.DateTimeField(default=datetime.utcnow(), required=False)
    updated_at = db.DateTimeField(default=datetime.utcnow(), required=False)
Exemplo n.º 3
0
class MarcasFabricante(db.EmbeddedDocument):
    marca = db.StringField(required=True)
    modelos = db.ListField(db.StringField(), required=True)
class SongModel(db.Document):
    track_id = db.StringField(primary_key=True)
    name = db.StringField()
    album = db.StringField()
    artist = db.ListField(db.StringField())
    genres = db.ListField(db.StringField())
    duration = db.IntField()
    image_url = db.StringField()

    meta = {'collection': 'songs', 'indexes': ['genres']}

    def json(self):
        return {
            'track_id': self.track_id,
            'name': self.name,
            'album': self.album,
            'artist': self.artist,
            'genres': self.genres,
            'duration': self.duration,
            'image_url': self.image_url,
        }

    @classmethod
    def find_by_id(cls, track_id: str) -> "SongModel":
        return cls.objects(track_id=track_id).first()

    @classmethod
    def find_all_genres(cls) -> List[str]:
        return list(cls.objects().distinct("genres"))

    @classmethod
    def find_all_by_ids(cls, ids: List[str]) -> List["SongModel"]:
        return list(cls.objects(track_id__in=ids))

    @classmethod
    def random_from_genre(cls, genre: str) -> "SongModel":
        song_list = list(cls.objects().aggregate([{
            "$match": {
                "genres": genre
            }
        }, {
            "$sample": {
                "size": 1
            }
        }]))

        return cls.objects(track_id=song_list[0]['_id']).first()

    @classmethod
    def random_from_genres(cls, genres: dict):
        song_list = []
        for key in genres:
            song_list += list(cls.objects().aggregate([{
                "$match": {
                    "genres": key
                }
            }, {
                "$sample": {
                    "size": genres[key]
                }
            }]))

        return song_list

    @classmethod
    def find_top_genres(cls, quantity: int) -> List[str]:
        return list(cls.objects().aggregate([{
            "$unwind": "$genres"
        }, {
            "$group": {
                "_id": "$genres",
                "count": {
                    "$sum": 1
                }
            }
        }, {
            "$sort": {
                "count": -1
            }
        }, {
            "$limit": quantity
        }]))

    def save_to_db(self) -> None:
        self.save()
class EventModel(db.Document):
    name = db.StringField(required=True)
    description = db.StringField()
    invitation_link = db.StringField()
    start_date = db.DateTimeField()
    end_date = db.DateTimeField()
    duration_time = db.IntField()
    image_url = db.StringField()

    playlist = db.ListField(db.StringField())
    participants = db.EmbeddedDocumentListField(ParticipantModel,
                                                required=True)

    meta = {
        'collection': 'events',
        'indexes': ['invitation_link', 'participants.user_id']
    }

    def json(self, users: List[UserModel] = None) -> Dict:
        users_dict = {user.id: user for user in users} if users else None
        return {
            'id':
            str(self.id),
            'name':
            self.name,
            'description':
            self.description,
            'invitation_link':
            self.invitation_link,
            'start_date':
            str(self.start_date),
            'end_date':
            str(self.end_date),
            'duration_time':
            self.duration_time,
            'image_url':
            self.image_url,
            'playlist':
            self.playlist if len(self.playlist) > 0 else [],
            'participants':
            list(map(lambda participant: participant.json(),
                     self.participants)) if users is None else list(
                         map(
                             lambda participant: participant.json(users_dict[
                                 participant.user_id]), self.participants))
        }

    def json_with_playlist(self,
                           songs: List[SongModel],
                           users: List[UserModel] = None) -> Dict:
        users_dict = {user.id: user for user in users} if users else None
        return {
            'id':
            str(self.id),
            'name':
            self.name,
            'description':
            self.description,
            'invitation_link':
            self.invitation_link,
            'start_date':
            str(self.start_date),
            'end_date':
            str(self.end_date),
            'duration_time':
            self.duration_time,
            'image_url':
            self.image_url,
            'playlist':
            list(map(lambda song: song.json(), songs))
            if len(songs) > 0 else [],
            'participants':
            list(map(lambda participant: participant.json(),
                     self.participants)) if users is None else list(
                         map(
                             lambda participant: participant.json(users_dict[
                                 participant.user_id]), self.participants))
        }

    @classmethod
    def find_by_id(cls, _id: bson.ObjectId) -> "EventModel":
        return cls.objects(id=_id).first()

    @classmethod
    def find_by_id_and_admin_id(cls, _id: bson.ObjectId,
                                admin_id: bson.ObjectId) -> "EventModel":
        return cls.objects(id=_id,
                           participants__user_id=admin_id,
                           participants__role=Role.ADMIN).first()

    @classmethod
    def find_by_invitation_link(cls, invitation_link: str) -> "EventModel":
        return cls.objects(invitation_link=invitation_link).first()

    @classmethod
    def find_all_by_participant_id(
            cls, user_id: bson.ObjectId) -> List["EventModel"]:
        return list(cls.objects(participants__user_id=user_id))

    @classmethod
    def find_all_by_admin_id(cls,
                             admin_id: bson.ObjectId) -> List["EventModel"]:
        return list(
            cls.objects(participants__user_id=admin_id,
                        participants__role=Role.ADMIN))

    def add_new_participant(self, user_id: bson.ObjectId) -> bool:
        new_participant = ParticipantModel(user_id=user_id, role=Role.MEMBER)
        result = self.update(push__participants=new_participant)
        return result == 1

    def remove_participant(self, user_id: bson.ObjectId) -> bool:
        result = self.update(pull__participants__user_id=user_id)
        return result == 1

    def save_to_db(self) -> None:
        self.save()