Exemplo n.º 1
0
def services_upsert(args, current_user, action="update"):
    if args["name"] == "":
        return {
            'message': "Inserisci il nome del servizio per proseguire"
        }, 400

    if args["price"] < 0:
        return {
            'message': "Il prezzo del servizio non puo' essere minore di 0 Eur"
        }, 400

    if is_admin(current_user["user_id"], args["business_id"]) is True:
        update = {}
        for name in [
                "name", "description", "price", "business_id", "duration_m"
        ]:
            if args[name] is not None:
                update[name] = args[name]

        if action == "update":
            query = Service.update(
                update).where((Service.service_id == int(args["id"]))
                              & (Service.business == int(args["business_id"])))
            if query.execute() != 0:
                update["updated_date"] = datetime.datetime.now()
                update["updated_by"] = current_user["user_id"]

            service = Service.get_or_none(
                (Service.service_id == int(args["id"]))
                & (Service.business == int(args["business_id"])))
            service = model_to_dict(
                service,
                recurse=True,
                backrefs=True,
                max_depth=1,
                exclude=[User.password, Business.time_table])
            return service, 200
        else:
            update["created_by_id"] = current_user["user_id"]
            update["updated_by_id"] = current_user["user_id"]
            service = Service.create(**update)
            service = model_to_dict(
                service,
                recurse=True,
                backrefs=True,
                max_depth=1,
                exclude=[User.password, Business.time_table])
            return service, 200
    else:
        return {
            'message':
            "Impossibile eseguire, sei sicuro di avere i permessi per eseguire queta operazione?"
        }, 400
Exemplo n.º 2
0
 def get_service():
     current_service = Service.current()
     last_cleaned = (Service.objects(
         master=True, cleaned=True).order_by('-date').first())
     service = {
         'uid':
         str(current_service.user.id),
         'last_cleaned':
         last_cleaned.date if last_cleaned else 'Never',
         'upcoming': [
             dict(week=s['_id'], user=str(s['user']))
             for s in Service.upcoming()
         ]
     } if current_service else None
     return service
Exemplo n.º 3
0
 def insert_serv(self, name_service, doc_serv, date_get, period, cost_unit,
                 unit, peny_data, peny):
     from database import User, Service, select_obj
     import datetime
     self.name_services = name_service
     self.doc_servs = doc_serv
     self.date_gets = date_get
     self.periods = period
     self.cost_units = cost_unit
     self.units = unit
     self.peny_dates = peny_data
     self.penys = peny
     self.ids = select_obj(Service.id, Service.name_service,
                           self.name_services, None, None)
     if len(self.ids) != 0:
         self.ids1 = self.ids[len(self.ids) - 1]
     else:
         self.ids1 = -1
     self.b = Service(id=self.ids1 + 1,
                      date=datetime.datetime.now(),
                      name_service=self.name_services,
                      doc_serv=self.doc_servs,
                      date_get=self.__date(self.date_gets),
                      period=int(self.periods),
                      cost_unit=float(self.cost_units.replace(",", ".")),
                      unit=self.units,
                      peny_data=self.__date(self.peny_dates),
                      peny=int(self.penys))
     return session.add(self.b)
Exemplo n.º 4
0
 def get_service():
     current_service = Service.current()
     service = {
         'uid': str(current_service.user.id),
         'cleaned': current_service.cleaned,
         'cleaningProgram': current_service.cleaning_program,
         'decalcifyProgram': current_service.decalcify_program,
     } if current_service else None
     return service
Exemplo n.º 5
0
def admin_api(function):
    def listofshame():
        return [{
            'name':
            u.name,
            'balance':
            u.balance,
            'score':
            u.score,
            'id':
            str(u.id),
            'switch_url':
            url_for('coffee.administrate_switch_user', username=u.username),
            'vip':
            u.vip,
            'last_service':
            getattr(u.last_service, 'date', None),
        } for u in User.objects(active=True)]

    def next_service_periods():
        latestDate = (
            Service.objects.order_by('-date').first().date.timestamp()
            if Service.objects else pendulum.now().timestamp())
        latest_service = pendulum.from_timestamp(latestDate)
        periods = []
        for _ in range(8):
            nmo = latest_service.next(pendulum.MONDAY)
            nfr = nmo.next(pendulum.FRIDAY)
            periods.append('%s:%s' %
                           (nmo.to_date_string(), nfr.to_date_string()))
            latest_service = nfr
        return periods

    if function == 'listofshame':
        return jsonify(list=listofshame(),
                       nextServicePeriods=next_service_periods())

    if function == 'add_service':
        data = request.get_json()
        user = User.objects.get(id=data.get('uid'))
        start, end = [
            pendulum.parse(d) for d in data.get('interval').split(':')
        ]
        for day in pendulum.period(start, end):
            Service(user=user, date=day).save()
        return jsonify(list=listofshame(),
                       nextServicePeriods=next_service_periods())
Exemplo n.º 6
0
def reinigungsfachkraft(service):
    key = 'reinigungsfachkraft'
    if pendulum.instance(service.date).day_of_week == pendulum.FRIDAY:
        previous = Service.objects(date__lte=service.date).limit(5)
        if all([p.user == service.user and p.cleaned for p in previous]):
            print('yay')
Exemplo n.º 7
0
def api(function):
    prices = {p[0]: p[1] for p in app.config['COFFEE_PRICES']}
    products = {p[1]: p[0] for p in app.config['COFFEE_PRICES']}

    def get_userlist():
        # always calculate user list
        today = pendulum.today(app.config['TZ'])
        users = []
        for user in User.objects(active=True).order_by('-vip', 'name'):
            # build user dictionary manually
            user_dict = {
                'name':
                user.name,
                'username':
                user.username,
                'id':
                str(user.id),
                'consume': [],
                # fill in all of todays achievements
                'achievements': [{
                    'key': a.key,
                    'date': a.date,
                } for a in user.achievements if a.date > pendulum.today()]
            }
            # perform a query for todays consumptions for each user
            # @TODO: try to move this to the mongo query... instead of hitting
            # the DB n + 1 times.
            for consume in Consumption.objects(user=user, date__gte=today):
                if consume.price_per_unit in prices:
                    user_dict['consume'].extend(
                        consume.units * [prices.get(consume.price_per_unit)])
            users.append(user_dict)
        return users

    def get_service():
        current_service = Service.current()
        last_cleaned = (Service.objects(
            master=True, cleaned=True).order_by('-date').first())
        service = {
            'uid':
            str(current_service.user.id),
            'last_cleaned':
            last_cleaned.date if last_cleaned else 'Never',
            'upcoming': [
                dict(week=s['_id'], user=str(s['user']))
                for s in Service.upcoming()
            ]
        } if current_service else None
        return service

    if function == 'user_list':
        return jsonify(users=get_userlist(), service=get_service())

    if function == 'add_consumption':
        data = request.get_json()
        user = User.objects.get(id=data.get('id'))
        created = Consumption(user=user,
                              price_per_unit=products.get(
                                  data['consumption_type']),
                              units=data['cur_consumption'],
                              date=datetime.now()).save()
        if user.balance < app.config['BUDGET_WARN_BELOW']:
            alert = {
                'text': 'Geringes Guthaben, bitte laden Sie bald wieder auf.',
                'type': 'warning',
            }
        else:
            alert = None
        status = 'success' if created else 'failure'
        return jsonify(status=status, users=get_userlist(), alert=alert)

    if function == 'finish_service':
        data = request.get_json()
        service = Service.current()
        service.__setattr__(data.get('service'), True)
        service.save()
        return jsonify(service=get_service(),
                       alert={
                           'text': 'Service eingetragen',
                           'type': 'success'
                       })

    return abort(404)
Exemplo n.º 8
0
def admin_api(function):
    def listofshame():
        return [{
            'name':
            u.name,
            'balance':
            u.balance,
            'score':
            u.score,
            'id':
            str(u.id),
            'switch_url':
            url_for('coffee.administrate_switch_user', username=u.username),
            'vip':
            u.vip,
            'last_service':
            getattr(u.last_service, 'date', None),
        } for u in User.objects(active=True)]

    def next_service_periods():
        """ Return a list of date perios where no master service is defined
        """
        # get all upcoming services
        upcomingServices = list(
            Service.objects.aggregate(
                {
                    '$match': {
                        'date': {
                            '$gte': pendulum.today()
                        },
                        'master': True,
                    }
                },
                {
                    '$group': {
                        '_id': {
                            '$dateToString': {
                                # group by Year-Week
                                'format': '%Y%U',
                                'date': '$date'
                            }
                        }
                    }
                }))
        # also get upcoming 8 weeks if no service is set for this week
        upcoming_weeks = []
        nextMonday = pendulum.today().next(pendulum.MONDAY)
        for weekDelta in range(8):
            nextStartDate = nextMonday.add(weeks=weekDelta)
            if nextStartDate.format('%Y%U') not in [
                    s['_id'] for s in upcomingServices
            ]:
                nextEndDate = nextStartDate.next(pendulum.FRIDAY)
                upcoming_weeks.append(
                    f'{nextStartDate.to_date_string()}:{nextEndDate.to_date_string()}'
                )
        return upcoming_weeks

    if function == 'listofshame':
        return jsonify(list=listofshame(),
                       nextServicePeriods=next_service_periods())

    if function == 'add_service':
        data = request.get_json()
        user = User.objects.get(id=data.get('uid'))
        start, end = [
            pendulum.parse(d) for d in data.get('interval').split(':')
        ]
        for day in pendulum.period(start, end):
            Service(user=user, date=day).save()
        return jsonify(list=listofshame(),
                       nextServicePeriods=next_service_periods())

    return abort(404)
Exemplo n.º 9
0
def api(function):
    prices = {p[0]: p[1] for p in app.config['COFFEE_PRICES']}
    products = {p[1]: p[0] for p in app.config['COFFEE_PRICES']}

    def get_userlist():
        # always calculate user list
        today = pendulum.today(app.config['TZ'])
        users = []
        for user in User.objects(active=True).order_by('-vip', 'name'):
            user_dict = {
                'name': user.name,
                'username': user.username,
                'id': str(user.id),
                'consume': []
            }
            for consume in Consumption.objects(user=user, date__gte=today):
                if consume.price_per_unit in prices:
                    user_dict['consume'].extend(
                        consume.units * [prices.get(consume.price_per_unit)])
            users.append(user_dict)
        return users

    def get_service():
        current_service = Service.current()
        service = {
            'uid': str(current_service.user.id),
            'cleaned': current_service.cleaned,
            'cleaningProgram': current_service.cleaning_program,
            'decalcifyProgram': current_service.decalcify_program,
        } if current_service else None
        return service

    if function == 'user_list':
        return jsonify(users=get_userlist(), service=get_service())

    if function == 'add_consumption':
        data = request.get_json()
        user = User.objects.get(id=data.get('id'))
        created = Consumption(user=user,
                              price_per_unit=products.get(
                                  data['consumption_type']),
                              units=data['cur_consumption'],
                              date=datetime.now()).save()
        if user.balance < app.config['BUDGET_WARN_BELOW']:
            alert = {
                'text': 'Geringes Guthaben, bitte laden Sie bald wieder auf.',
                'type': 'warning',
            }
        else:
            alert = None
        status = 'success' if created else 'failure'
        return jsonify(status=status, users=get_userlist(), alert=alert)

    if function == 'finish_service':
        data = request.get_json()
        service = Service.current()
        service.__setattr__(data.get('service'), True)
        service.save()
        return jsonify(service=get_service(),
                       alert={
                           'text': 'Service eingetragen',
                           'type': 'success'
                       })

    return abort(404)