Ejemplo n.º 1
0
 def add_player_on_tournament(self):
     """Add a player in a tournament"""
     self.screen.clear()
     report = Reports(players_db, tournaments_db)
     self.screen.info_users(report.list_of_players('id'))
     self.screen.add_infos([
         "{} joueurs ajoutés au tournoi".format(
             len(self.tournament.players_list))
     ])
     self.screen.on_screen()
     id_player = input_menu_verification(
         max_id(players_db),
         "Entrez le numéro du joueur à ajouter au tournoi")
     while id_player in self.players_on_load:
         self.screen.warning(
             "Le joueur {} est déjà inscrit dans ce tournoi".format(
                 id_player))
         id_player = input_menu_verification(
             max_id(players_db),
             "Entrez le numéro du joueur à ajouter au tournoi")
     valid_player = search_db(id_player, players_db)
     if valid_player is not False:
         self.tournament.add_player(valid_player)
         self.players_on_load.append(id_player)
     else:
         self.screen.warning("Le joueur {} n'existe pas.".format(id_player))
         sleep(1)
Ejemplo n.º 2
0
    def load(self):
        """Load a tournament"""
        report = Reports(players_db, tournaments_db)
        self.screen.clear()
        self.screen.info_users(report.tournaments_list())
        self.screen.on_screen()
        tournament_id = input_menu_verification(
            max_id(tournaments_db), "Saisissez le numéro du tournoi à charger")

        valid_tournament = search_db(tournament_id, tournaments_db)

        if valid_tournament is False:
            self.screen.warning(
                "Le tournoi {} n'existe pas.".format(tournament_id))
            sleep(1)
            self.load()
        else:
            tournament_on_load = Tournament(valid_tournament)
            tournament_on_load.deserialized()
            self.tournament = tournament_on_load
        self.players_on_load = []
        for player in self.tournament.players_list:
            self.players_on_load.append(player.player_id)

        while len(self.tournament.players_list) < TOURNAMENT_PLAYERS_NB:
            self.add_player_on_tournament()

        self.play()
Ejemplo n.º 3
0
    def modify_player_rank(self):
        """Modify a player's rank"""
        self.screen.clear()
        report = Reports(players_db, tournaments_db)
        self.screen.info_users(
            report.t_players_list(self.tournament.id, 'surname'))
        self.screen.on_screen()
        id_player = input_menu_verification(
            self.max_player_id_tournament(),
            "Saisissez l'id du joueur dont vous souhaitez modifier le rang")
        id_players_list = []
        for player in self.tournament.players_list:
            id_players_list.append(player.player_id)

        if id_player not in id_players_list:
            self.screen.warning(
                "Le joueur {} n'est pas présent dans le tournoi.".format(
                    id_player))
            sleep(1)
            self.modify_player_rank()
        new_ranking = input_menu_verification(
            1000000000, "Saisissez le nouveau classement du joueur")
        for player in self.tournament.players_list:
            if player.player_id == id_player:
                player.modify_ranking(new_ranking)
                update_item_in_db(players_db, 'elo_ranking', new_ranking,
                                  id_player)
        self.screen.clear()
Ejemplo n.º 4
0
    def modify(self):
        """Modify info for a tournament"""
        report = Reports(players_db, tournaments_db)
        self.screen.clear()
        self.screen.info_users(report.tournaments_list())
        self.screen.on_screen()

        tournament_id = input_menu_verification(
            max_id(tournaments_db),
            "Saisissez le numéro du tournoi à modifier")

        self.screen.info_users([
            "Choix de la modification :\n", "           [1] Nom \n",
            "           [2] Lieu \n", "           [3] Description \n"
        ])
        self.screen.on_screen()
        modify = input_menu_verification(
            3, "Saisissez le numéro de la donnée à modifier")
        info_modify = input("Saisissez la modification : ")
        if modify == 1:
            key = 'name'
        if modify == 2:
            key = 'location'
        if modify == 3:
            key = 'description'
        update_item_in_db(tournaments_db, key, info_modify, tournament_id)
        self.modify()
Ejemplo n.º 5
0
    def modify(self):
        """Modify a player info"""
        self.screen.info_users(
            ["              MODIFICATION D'UN JOUEUR           \n\n\n"])
        self.screen.clear()
        self.screen.on_screen()
        report = Reports(players_db, tournaments_db)
        self.screen.info_users(report.list_of_players('id'))
        self.screen.clear()
        self.screen.on_screen()
        id_player = input_menu_verification(
            max_id(players_db), "Saisissez le numéro du joueur à modifier")
        if search_db(id_player, players_db) is not False:
            pass
        else:
            self.screen.warning("Le joueur {} n'existe pas.".format(id_player))
            sleep(1)
            self.modify()

        self.screen.add_infos([
            "Choix de la modification :\n", "           [1] Nom \n",
            "           [2] Prénom \n", "           [3] Classement \n",
            "           [4] Date de naissance \n", "           [5] Sexe \n"
        ])
        self.screen.clear()
        self.screen.on_screen()
        modify = input_menu_verification(
            5, "Saisissez le numéro de la donnée à modifier")
        info_modify = input("Saisissez la modification : ")
        if modify == 1:
            key = 'surname'
            info_modify = info_modify.upper()
        if modify == 2:
            key = 'name'
            info_modify = info_modify.capitalize()
        if modify == 3:
            key = 'elo_ranking'
            try:
                info_modify = int(info_modify)
            except ValueError:
                info_modify = input_menu_verification(
                    100000000, "Le classement doit être chiffre positif")
        if modify == 4:
            key = 'birthday'
        if modify == 5:
            info_modify = info_modify.capitalize()
            key = 'sexe'

        update_item_in_db(players_db, key, info_modify, id_player)
        self.screen.warning("Modification appliquée")
        sleep(1)
        self.modify()
Ejemplo n.º 6
0
    def delete(self):
        """Delete a player"""
        self.screen.info_users(
            ["              SUPPRESSION D'UN JOUEUR           \n\n\n"])
        self.screen.clear()
        self.screen.on_screen()
        report = Reports(players_db, tournaments_db)
        self.screen.info_users(report.list_of_players('id'))
        self.screen.clear()
        self.screen.on_screen()

        id_player = input_menu_verification(
            players_db.__len__(), "Saisissez le numéro du joueur à effacer")
        remove_in_db(players_db, id_player)
        self.delete()
Ejemplo n.º 7
0
    def stadisticsByComuna(cls, idComuna):
        """
        """
        results = {
            "total_cases": 0,
            "total_complaint": 0,
            "stages": {},
            "neighborhood": {},
            "collective": {},
        }
        
        if Comunas.validComuna(idComuna):
            neighborhoods = {}
            for item in Neighborhood.readAll().values():
                if item.get("idComuna") == idComuna:
                    item["cases"] = 0
                    del item["idComuna"]
                    neighborhoods[item.get("idNeighborhood")] = item

            dataStage = {}
            for item in Stage.readAll().values():
                item["cases"] = 0
                dataStage[item.get("idStages")] = item

            collective = {}
            for item in Collectivegroup.readAll().values():
                item["cases"] = 0
                collective[item.get("idCollective")] = item

            # cases by neighborhood
            for item in Reports.readAll().values():
                if item.get("idNeighborhood") in neighborhoods.keys():                    
                    neighborhoods[item.get("idNeighborhood")]["cases"] = neighborhoods[item.get("idNeighborhood")]["cases"] + 1
                    dataStage[item.get("idStage")]["cases"] = dataStage[item.get("idStage")]["cases"] + 1
                    collective[item.get("idCollective")]["cases"] = collective[item.get("idCollective")]["cases"] + 1
                    results["total_cases"] = results["total_cases"] + 1

                if item.get("complaint") != "No":
                    results["total_cases"] = results["total_cases"] + 1

            copy = dataStage.copy()
            for key, value in copy.items():
                if value.get("cases") == 0:
                    del dataStage[key]

            copy = neighborhoods.copy()
            for key, value in copy.items():
                if value.get("cases") == 0:
                    del neighborhoods[key]

            copy = collective.copy()
            for key, value in copy.items():
                if value.get("cases") == 0:
                    del collective[key]

            results["stages"] = dataStage
            results["neighborhood"] = neighborhoods
            results["collective"] = collective
        return results
Ejemplo n.º 8
0
 def put(self) -> Response:
     body = request.get_json()
     report = Reports.objects(reportID=body['reportID'])
     if len(report) > 0:
         Reports.objects(reportID=body['reportID']).update(
             set__header=body['header'],
             set__detail=body['detail'],
             set__update_at=str(datetime.utcnow()))
         response = jsonify({
             "data": body,
             "message": "success",
             "status": 200
         })
         response.status_code = 200
         return response
     else:
         response = jsonify({
             "data": None,
             "message": "booking id not found",
             "status": 204
         })
         response.status_code = 204
         return response
Ejemplo n.º 9
0
def create_report():
    userid = session['user']
    if not User.validUserId(userid):
        session['message'] = 'invalid-user'
        return redirect(urlfor + 'reports')
    try:
        notification = Notification('Sin notificacion')
        notification.write()
        alert = Alert('Sin alerta', notification.idNotification)
        alert.write()
        report = Reports(alert.idAlert, request.form['description'],
                         request.form['neighborhood'], request.form['stage'],
                         request.form['aggressor'], request.form['complaint'],
                         request.form['collective'], userid)
        report.write()
        mapping = Mapping(report.idReport, request.form['alertType'],
                          float(request.form['latitude']),
                          float(request.form['longitude']), userid)
        mapping.write()
    except Exception:
        session['message'] = 'error'
        return redirect(urlfor + 'reports')
    session['message'] = 'success'
    return redirect(urlfor + 'reports')
Ejemplo n.º 10
0
    def post(self) -> Response:
        body = request.get_json()
        report_ID = body['reportID']
        report = Reports.objects(reportID=report_ID)
        if len(report) > 0:
            for data in body.get('meds_ref'):

                medObj = Medicine.objects.get(medicineID=data['med_id'])
                key = uuid.uuid4().int
                if (data['med_id'] == medObj.medicineID) and (
                        medObj.amount - data['med_amount'] >= 0):
                    amount = int(medObj.amount - data['med_amount'])
                    Medicine.objects(medicineID=data['med_id']).update(
                        set__amount=amount,
                        set__update_at=str(datetime.utcnow()))
                    print(amount)
                    queryDisensesMed = {
                        'dispenseMedID': str(key)[0:7],
                        'reportID': report_ID,
                        'medID': data['med_id'],
                        'status': "รอรับยา",
                        'amount': str(data['med_amount']),
                        'create_at': str(datetime.utcnow()),
                        'update_at': str(datetime.utcnow())
                    }

                    DispensesMed(**queryDisensesMed).save()

                else:
                    return Response(status=204)

            response = jsonify({
                "data": None,
                "message": "success",
                "status": 200
            })
            response.status_code = 200
            return response
        else:
            response = jsonify({
                "data": None,
                "message": "Report id exit",
                "status": 204
            })
            response.status_code = 204
            return response
Ejemplo n.º 11
0
    def get(self) -> Response:
        report = Reports.objects()
        if len(report) > 0:
            response = jsonify({
                "data": report,
                "message": "success",
                "status": 200
            })
            response.status_code = 200
            return response

        else:
            response = jsonify({
                "data": None,
                "message": "report id null",
                "status": 400
            })
            response.status_code = 400
            return response
Ejemplo n.º 12
0
 def delete(self) -> Response:
     body = request.get_json()
     reportObj = Reports.objects(reportID=body['reportID'])
     if len(reportObj) > 0:
         reportObj.delete()
         response = jsonify({
             "data": None,
             "message": "success",
             "status": 200
         })
         response.status_code = 200
         return response
     else:
         response = jsonify({
             "data": None,
             "message": "error",
             "status": 204
         })
         response.status_code = 204
         return response
Ejemplo n.º 13
0
 def get(self) -> Response:
     id = request.args.get('patientID')
     report = Reports.objects(patentID=id)
     print(report)
     if len(report) > 0:
         response = jsonify({
             "data": report,
             "message": "Success",
             "status": 200
         })
         response.status_code = 200
         return response
     else:
         response = jsonify({
             "data": None,
             "message": "Patient ID is exit, Does found report",
             "status": 204
         })
         response.status_code = 204
         return response
Ejemplo n.º 14
0
 def valid_args(cls, args):
     """
     verify if all the values are correct
         0: report id
         1: alert type id
         2: latitude
         3: longitude
         4: user id
     """
     if len(args) != 5:
         raise SyntaxError("Incorrect number of attributes")
     if len(args[0]) == 0 or not Reports.validReport(args[0]):
         raise ValueError("Empty or not a valid report id")
     if len(args[1]) == 0 or not Alerttype.validAlerttype(args[1]):
         raise ValueError("Empty or not a valid alert type id")
     if type(args[2]) is not float:
         raise ValueError("Latitude needs to be a float data type")
     if type(args[3]) is not float:
         raise ValueError("Longitude needs to be a float data type")
     if len(args[4]) == 0 or not User.validUserId(args[4]):
         raise ValueError("Empty or not a valid user id")
     return True
Ejemplo n.º 15
0
 def get(self) -> Response:
     reportID = request.args.get('reportID')
     print(reportID)
     bill = Payments.objects(reportID=reportID)
     report = Reports.objects(reportID=reportID)
     data = {'bill': bill, 'report': report}
     print(report)
     if len(bill) > 0:
         response = jsonify({
             "data": data,
             "message": "success",
             "status": 200
         })
         response.status_code = 200
         return response
     else:
         response = jsonify({
             "data": None,
             "message": "error",
             "status": 204
         })
         response.status_code = 204
         return response
Ejemplo n.º 16
0
 def __init__(self):
     self.report = Reports(players_db, tournaments_db)
     self.screen = Screen()
Ejemplo n.º 17
0
class ReportsControler:
    """Go to reports menu"""
    def __init__(self):
        self.report = Reports(players_db, tournaments_db)
        self.screen = Screen()

    def main(self):
        self.screen.clear()
        self.screen.add_infos(self.report.menu)
        self.screen.on_screen()
        menu = input_menu_verification(
            7, "Saisissez le numéro du rapport souhaité")
        self.screen.clear()

        if menu == 1:
            self.players_list('surname')
        elif menu == 2:
            self.players_list('elo_ranking')
        elif menu == 3:
            self.players_list_tournament('surname')
        elif menu == 4:
            self.players_list_tournament('elo_ranking')
        elif menu == 5:
            self.tournaments_list()
        elif menu == 6:
            self.tournament_rounds_list()
        elif menu == 7:
            self.tournament_matchs_list()

        self.screen.on_screen()
        menu = input_menu_verification(
            1, "Saisir [1] pour revenir au menu des rapports")
        report = ReportsControler()
        report.main()

    def players_list(self, key):
        self.screen.info_users(self.report.list_of_players(key))

    def tournaments_list(self):
        self.screen.info_users(self.report.tournaments_list())

    def choice_tournament(self):
        self.tournaments_list()
        self.screen.on_screen()
        tournament_index = input_menu_verification(
            max_id(tournaments_db), "Saisissez le numéro du tournoi")
        self.screen.clear()
        return tournament_index

    def players_list_tournament(self, key):
        tournament_index = self.choice_tournament()
        self.screen.info_users(
            self.report.t_players_list(tournament_index, key))

    def tournament_rounds_list(self):
        tournament_index = self.choice_tournament()
        self.screen.info_users(
            self.report.tournament_rounds_list(tournament_index))

    def tournament_matchs_list(self):
        tournament_index = self.choice_tournament()
        self.screen.info_users(
            self.report.tournament_matchs_list(tournament_index))
Ejemplo n.º 18
0
    def post(self) -> Response:
        body = request.get_json()
        booking = Bookings.objects(bookingID=body['bookingID'])
        print(len(booking))
        if len(booking) > 0:
            schema = Kanpai.Object({
                'reportID': Kanpai.String().required(),
                'bookingID': Kanpai.String().required(),
                'staffID': Kanpai.String().required(),
                'patentID': Kanpai.String().required(),
                'header': Kanpai.String().required(),
                'detail': Kanpai.String().required(),
                'create_at': Kanpai.String(),
                'update_at': Kanpai.String()
            })

            key = uuid.uuid4().int
            data = {
                'reportID': str(key)[0:6] + '_' + body['patentID'],
                'bookingID': body['bookingID'],
                'staffID': body['staffID'],
                'patentID': body['patentID'],
                'header': body['header'],
                'detail': body['detail'],
                'create_at': str(datetime.utcnow()),
                'update_at': str(datetime.utcnow())
            }

            validate_result = schema.validate(data)
            if validate_result.get('success', False) is False:
                response = jsonify({
                    "data": None,
                    "message": "error",
                    "status": 400
                })
                response.status_code = 400
                return response

            try:
                Bookings.objects(bookingID=body['bookingID']).update(
                    set__status="ตรวจเสร็จสิ้น",
                    set__update_at=str(datetime.utcnow()))

                Reports(**data).save()

                response = jsonify({
                    "data":
                    str(key)[0:6] + '_' + body['patentID'],
                    "message":
                    "success",
                    "status":
                    201
                })
                response.status_code = 201
                return response

            except NotUniqueError:
                response = jsonify({
                    "data": None,
                    "message": "ReportID already add to storage",
                    "status": 400
                })
                response.status_code = 400
                return response
        else:
            response = jsonify({
                "data": None,
                "message": "ReportID does not exist",
                "status": 400
            })
            response.status_code = 400
            return response