Beispiel #1
0
    def test_latest_redirects_to_last_step(self):
        goal = Goal.objects.create(user=self.user,
                                   text='test',
                                   timezone='Europe/London',
                                   start=timezone.now())

        step1 = Step.create(goal, 'test')

        response = self.client.get(
            reverse('app_steps_latest', kwargs={'goal_id': goal.id}))

        self.assertRedirects(
            response,
            reverse('app_steps_track',
                    kwargs={
                        'goal_id': goal.id,
                        'step_id': step1.id
                    }))

        step2 = Step.create(goal, 'test')

        response = self.client.get(
            reverse('app_steps_latest', kwargs={'goal_id': goal.id}))

        self.assertRedirects(
            response,
            reverse('app_steps_track',
                    kwargs={
                        'goal_id': goal.id,
                        'step_id': step2.id
                    }))
Beispiel #2
0
def add_steps_to_db(obj, message):
    for o in obj:
        s = Step()
        if 'name' in o:
            s['name'] = o['name']
        if 'order' in o:
            s['order'] = o['order']
        if 'description' in o:
            s['description'] = o['description']
        if 'parameters' in o:
            # Query for steps and associate them with template
            for param in o['parameters']:
                parameter_object = Parameter.objects.filter(name=param).first()
                if parameter_object:
                    s['parameter'].append(parameter_object.pk)
        try:
            s.save()
        except ValidationError as e:
            message.append('Error creating the parameter: ' + str(e))
            pass
        except NotUniqueError:
            message.append(
                'Step with the name "{0}" has already been added.'.format(
                    o['name']))
            pass
    return message
Beispiel #3
0
def final_delivery(request, pk):
    audit = Audit.objects.get(id=pk)
    audit.is_complete = True
    audit.save()
    req = audit.match.requirement
    req.status = False
    req.save()
    step = Step(audit=audit, note='Item foi entregue para a instituicao')
    step.save()
    messages.success(request, 'Obrigado!')
    return redirect('/audits')
Beispiel #4
0
def accept_audit(request, pk):
    audit = Audit.objects.get(id=pk)
    item = audit.item
    item.status = False
    item.save()
    for au in audit.item.audit_set.all():
        au.is_deferred = 'INDEFERIDO'
        au.save()
    audit.is_deferred = 'DEFERIDO'
    audit.save()
    step = Step(audit=audit,
                note='Doador confirmou a proposta e irá doar o item')
    step.save()
    messages.success(request, 'Proposta Confirmada!')
    return redirect('/audits-user')
Beispiel #5
0
    def __create(self, args):
        result = {"status": "success", "msg": "操作成功"}

        case = Case.query.filter_by(id=args["case_id"]).first()
        if case is not None:
            try:
                step = Step(desc=args["desc"],
                            keyword=args["keyword"],
                            case_id=args["case_id"],
                            param_1=args["param_1"],
                            param_2=args["param_2"],
                            param_3=args["param_3"],
                            param_4=args["param_4"],
                            param_5=args["param_5"],
                            param_6=args["param_6"],
                            param_7=args["param_7"],
                            enable=args["enable"],
                            step=args["step"],
                            prev=args["prev"],
                            create_user_id=current_user.get_id(),
                            update_user_id=current_user.get_id())

                db.session.add(step)
                db.session.commit()
            except Exception as e:
                result["status"] = "fail"
                result["msg"] = "异常:%s" % str(e)
Beispiel #6
0
    def test_new(self, new_step_signal):
        text = uuid4()
        response = self.client.post(reverse('app_steps_new',
                                            kwargs={'goal_id': self.goal.id}),
                                    data={'text': text},
                                    follow=False)

        step = Step.objects.get(text=text)

        self.assertRedirects(
            response,
            reverse('app_steps_start',
                    kwargs={
                        'goal_id': self.goal.id,
                        'step_id': step.id
                    }))

        self.assertIsNotNone(step)
        self.assertEquals(self.goal.id, step.goal.id)

        self.assertAlmostEquals(step.start,
                                timezone.now(),
                                delta=timedelta(seconds=2))

        local_start = step.start.astimezone(self.tz)
        local_end = step.end.astimezone(self.tz)
        self.assertEquals(step.end, Step.deadline(step.start, self.tz))
        self.assertEquals((local_start + timedelta(days=2)).date(),
                          local_end.date())
        self.assertEquals(local_end.time(), time())

        new_step_signal.send.assert_called_with('app.views.steps.new',
                                                step=step)
Beispiel #7
0
def update_item():
    """修改事项."""
    req_dict = request.get_json()
    id = req_dict.get("id")
    subject_id = req_dict.get('subject_id')
    name = req_dict.get('name')
    step = req_dict.get("step")
    process = req_dict.get("process")
    level = req_dict.get("level")
    cate = req_dict.get("cate")
    industry = req_dict.get("industry")
    frequent = req_dict.get("frequent")
    timeout = req_dict.get("timeout")
    print("++++修改事项++++", req_dict)
    # 校验数据
    param_keys = [
        "id", "subject_id", "name", "step", "process", "level", "cate",
        "industry", "frequent", "timeout"
    ]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    try:
        current_item = Item.query.filter_by(id=id).first()
        if current_item.name != name:
            exist = Item.query.filter_by(name=name).all()
            if exist:
                return jsonify(errno=RET.DBERR, errmsg="数据有重复")
        current_item.name = name
        current_item.step = step
        current_item.process = process
        current_item.level = level
        current_item.cate = cate
        current_item.industry = industry
        current_item.frequent = frequent
        current_item.timeout = timeout
        current_item.subject_id = subject_id
        for i in current_item.steps.all():
            db.session.delete(i)
        db.session.add(current_item)
        db.session.commit()
        step_list = process.split("-", step - 1)
        for i in step_list:
            current_step = Step(name=i,
                                order=step_map[i],
                                item_id=current_item.id)
            db.session.add(current_step)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="更新失败")
    return jsonify(errno=RET.OK, errmsg="成功")
Beispiel #8
0
    def test_track_last_step_redirects_to_complete(self, step_complete_signal):
        goal = Goal.objects.create(user=self.user,
                                   text='test',
                                   timezone='Europe/London',
                                   start=timezone.now())

        for i in range(5):
            Step.create(goal, 'test')

        response = self.client.post(reverse('app_steps_track',
                                            kwargs={
                                                'goal_id': goal.id,
                                                'step_id': goal.current_step.id
                                            }),
                                    follow=False)

        self.assertRedirects(
            response, reverse('app_goals_complete',
                              kwargs={'goal_id': goal.id}))
Beispiel #9
0
 def addStepsToRecipe(stepsList, recipeId):
     orderCounter = 1
     for step in stepsList:
         newStepEntry = Step(order=orderCounter,
                             content=step,
                             recipe_id=recipeId)
         db.session.add(newStepEntry)
         orderCounter += 1
         print("Added", '"' + step + '"', "with oreder =", orderCounter - 1)
     print("\n")
Beispiel #10
0
    def test_new_step_email(self, add_event, send_email):
        goal = Goal.objects.create(user=self.user,
                                   text='test',
                                   timezone='Europe/London',
                                   start=timezone.now())

        step = Step.create(goal, 'test')

        receive_new_step(self, step=step)

        send_email.assert_called_with('n2_new_goal', goal.user, goal)

        for i in range(1, 4):
            step = Step.create(goal, 'test')

            receive_new_step(self, step=step)

            send_email.assert_called_with('n%d_step_%d_complete' % (i + 2, i),
                                          goal.user, goal)
Beispiel #11
0
def add_item():
    """添加事项."""
    req_dict = request.get_json()
    subject_id = req_dict.get("subject_id")
    name = req_dict.get("name")
    step = req_dict.get("step")
    process = req_dict.get("process")
    level = req_dict.get("level")
    cate = req_dict.get("cate")
    industry = req_dict.get("industry")
    frequent = req_dict.get("frequent")
    timeout = req_dict.get("timeout")
    print("++++添加事项++++", req_dict)
    # 校验数据
    param_keys = [
        "subject_id", "name", "step", "process", "level", "cate", "industry",
        "frequent", "timeout"
    ]
    param_dict = dict()
    for i in param_keys:
        param_dict.__setitem__(i, req_dict.get(i, ''))
    for key, value in param_dict.items():
        if not value:
            return jsonify(errno=RET.PARAMERR, errmsg="数据不完整,缺少%s" % key)
    try:
        exist = Item.query.filter_by(name=name).all()
        if exist:
            return jsonify(errno=RET.DBERR, errmsg="数据有重复")
        current_item = Item(name=name,
                            step=step,
                            process=process,
                            level=level,
                            cate=cate,
                            industry=industry,
                            frequent=frequent,
                            timeout=timeout,
                            subject_id=subject_id)
        db.session.add(current_item)
        db.session.commit()
        step_list = process.split("-", step - 1)
        for i in step_list:
            current_step = Step(name=i,
                                order=step_map[i],
                                item_id=current_item.id)
            db.session.add(current_step)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="添加失败")
    return jsonify(errno=RET.OK, errmsg="成功")
def format_steps_for_loading_in_view(preexisting_job_step_data,
                                     image_processing_db_id, reparameterize,
                                     configuration_object,
                                     remaining_step_names,
                                     succeeded_but_latter_step_failed):
    workflow_steps = OrderedDict()
    load_status = None
    # match data on step name
    if type(preexisting_job_step_data) is list:
        if image_processing_db_id != None:  # load data for an existing job
            for current_step_data in preexisting_job_step_data:
                if current_step_data:
                    # go through all steps and find those, which are used by the current job
                    current_step_name = current_step_data['name']
                    step = Step.objects(name=current_step_name).first()
                    checkbox_state = 'checked'
                    collapse_or_show = 'show'
                    if ("globalparameters" not in current_step_name.lower()
                        ) and reparameterize and (
                            (current_step_name not in remaining_step_names) or
                            (current_step_name
                             in succeeded_but_latter_step_failed)):
                        checkbox_state = 'unchecked'
                        collapse_or_show = ''

                    loaded_parameters = parse_json_data_no_forms(
                        current_step_data, current_step_name,
                        configuration_object)
                    # Pipeline steps is passed to index.html for formatting the html based
                    workflow_steps[current_step_name] = {
                        'stepName':
                        current_step_name,
                        'stepDescription':
                        step.description,
                        'pause':
                        current_step_data['pause']
                        if 'pause' in current_step_data else 0,
                        'inputJson':
                        None,
                        'checkboxState':
                        checkbox_state,
                        'collapseOrShow':
                        collapse_or_show,
                        'loadedParameters':
                        loaded_parameters
                    }
    elif type(preexisting_job_step_data) is dict:
        load_status = 'Job cannot be loaded.'
    return workflow_steps, load_status
    def test_templates(self):
        goal = Goal.objects.first()
        Step.create(goal, 'test')

        template_dir = join(settings.BASE_DIR, 'app/templates/emails')
        files = [f for f in listdir(template_dir)
                 if isfile(join(template_dir, f)) and f != 'base.html']

        if not files:
            self.fail('No email templates found')

        for file in files:
            name = file[:-5]

            print('Testing email ' + name)

            try:
                (html, text) = render_email(name, goal.user, goal)
            except Exception as e:
                print(e)
                self.fail('Failed to render %s email' % name)

            self.assertTrue('deactivate' in html)
            self.assertTrue('9141465' in html)
Beispiel #14
0
def add_step():
    req_dict = request.get_json()
    item_id = req_dict.get('item_id')
    name = req_dict.get('name')
    order = req_dict.get('order')
    if not all([item_id, name, order]):
        return jsonify(errno=RET.PARAMERR, errmsg="数据不完整")
    try:
        current_step = Step(name=name, order=order, item_id=item_id)
        db.session.add(current_step)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="添加失败")
    return jsonify(errno=RET.OK, errmsg="成功")
Beispiel #15
0
    def test_deadline(self):
        # Hong Kong UTC+8 - doesn't observe DST
        tz = pytz.timezone('Asia/Hong_Kong')

        start = tz.localize(datetime.utcnow())

        deadline = Step.deadline(start, 'Asia/Hong_Kong')

        self.assertTrue(is_aware(deadline))
        self.assertEquals(deadline.tzinfo, pytz.utc)

        local_deadline = deadline.astimezone(tz)
        print(deadline, local_deadline)
        self.assertEquals(start.date() + timedelta(days=2),
                          local_deadline.date())
        self.assertEquals(local_deadline.time(), time())
Beispiel #16
0
    def setUp(self):
        self.user = User.objects.create(email='*****@*****.**',
                                        username='******')
        self.user.set_password('test')
        self.user.save()

        self.goal = Goal.objects.create(user=self.user,
                                        text='test',
                                        timezone='Europe/London',
                                        start=timezone.now())
        self.step = Step.create(self.goal, 'text')

        self.client = Client()
        self.client.login(username='******', password='******')

        self.user.is_active = False
        self.user.save()
Beispiel #17
0
    def test_new_to_track_redirect(self):
        goal = Goal.objects.create(user=self.user,
                                   text='test',
                                   timezone='Europe/London',
                                   start=timezone.now())
        step = Step.create(goal, 'test')

        response = self.client.get(reverse('app_steps_new',
                                           kwargs={'goal_id': goal.id}),
                                   follow=False)

        self.assertRedirects(
            response,
            reverse('app_steps_track',
                    kwargs={
                        'goal_id': goal.id,
                        'step_id': step.id
                    }))
Beispiel #18
0
def add_recipe():
    form = NewRecipeForm()
    form.dish_type.choices = [(t.id, t.name) for t in DishType.query.all()]

    if form.validate_on_submit():
        recipe = Recipe(title=form.title.data,
                        description=form.description.data,
                        user_id=current_user.id,
                        dish_type_id=form.dish_type.data)

        db.session.add(recipe)

        ingredients = []
        lines = form.ingredients.data.splitlines()
        for line in lines:
            line = line.strip()
            if line != '':
                ingredients.append(line)
        for i in ingredients:
            ingredient = Ingredient(name=i, recipe=recipe)
            db.session.add(ingredient)

        steps = []
        lines = form.steps.data.splitlines()
        for line in lines:
            line = line.strip()
            if line != '':
                steps.append(line)
        for i in steps:
            step = Step(content=i, recipe=recipe)
            db.session.add(step)

        db.session.commit()

        image_url = form.image_url.data
        image = RecipeImage(recipe_id=recipe.id, url=image_url)

        db.session.add(image)
        db.session.commit()

        flash('Your recipe has been saved!')
        return redirect(url_for('main.recipe', recipe_id=recipe.id))

    return render_template('add_recipe.html', title='Add recipe', form=form)
Beispiel #19
0
    def test_new(self, new_step, new_goal):
        text = uuid1()
        response = self.client.post(reverse('app_goals_new'), data={
            'text': text,
            'first_step': 'step text',
            'timezone': 'Europe/London'
        }, follow=False)

        goal = Goal.objects.get(text=text)
        tz = pytz.timezone('Europe/London')

        self.assertEquals(len(goal.steps.all()), 1)

        self.assertRedirects(response, reverse('app_steps_start', kwargs={
            'goal_id': goal.id, 'step_id': goal.steps.first().id}))

        self.assertIsNotNone(goal)
        self.assertEquals(goal.lives, 3)
        self.assertEquals(self.user.id, goal.user.id)
        self.assertEquals(goal.timezone, 'Europe/London')
        self.assertAlmostEquals(goal.start, timezone.now(),
                                delta=timedelta(seconds=1))

        first_step = goal.steps.first()
        self.assertEquals(first_step.text, 'step text')
        self.assertEquals(first_step.start, goal.start)

        local_start = first_step.start.astimezone(tz)
        local_end = first_step.end.astimezone(tz)
        self.assertEquals(first_step.end, Step.deadline(first_step.start, tz))
        self.assertEquals((local_start + timedelta(days=2)).date(),
                          local_end.date())
        self.assertEquals(local_end.time(), time())

        new_goal.send.assert_called_with('app.views.goals.new',
                                         goal=goal)
        new_step.send.assert_called_with('app.views.goals.new',
                                         step=first_step)
Beispiel #20
0
def modify_recipe(search_string):
    search_result = Recipe.query.filter_by(title=search_string).filter_by(
        user_id=current_user.id).first()

    if not search_result:
        flash('Recipes not found')
        return redirect(url_for('main.dashboard'))

    form = NewRecipeForm()
    form.dish_type.choices = [(t.id, t.name) for t in DishType.query.all()]

    if form.validate_on_submit():
        recipe = Recipe.query.filter_by(id=search_result.id).first_or_404()

        # empty current ingredients and steps
        ingredients = Ingredient.query.filter_by(recipe_id=recipe.id).all()
        for i in ingredients:
            Ingredient.query.filter_by(id=i.id).delete()

        steps = Step.query.filter_by(recipe_id=recipe.id).all()
        for s in steps:
            Step.query.filter_by(id=s.id).delete()

        # collect new data
        recipe.title = form.title.data
        recipe.description = form.description.data
        recipe.dish_type_id = form.dish_type.data

        if form.image_url.data != 'undefined':
            if recipe.image and recipe.image[0].url:
                image = RecipeImage.query.filter_by(
                    recipe_id=recipe.id).first()
                image.url = form.image_url.data
            else:
                image_url = form.image_url.data
                image = RecipeImage(recipe_id=recipe.id, url=image_url)
                db.session.add(image)

        ingredients = []
        lines = form.ingredients.data.splitlines()
        for line in lines:
            line = line.strip()
            if line != '':
                ingredients.append(line)
        for i in ingredients:
            ingredient = Ingredient(name=i, recipe=recipe)
            db.session.add(ingredient)

        steps = []
        lines = form.steps.data.splitlines()
        for line in lines:
            line = line.strip()
            if line != '':
                steps.append(line)
        for i in steps:
            step = Step(content=i, recipe=recipe)
            db.session.add(step)

        db.session.commit()
        flash('Changes have been saved!')
        return redirect(url_for('main.recipe', recipe_id=recipe.id))

    elif request.method == 'GET':
        form.title.data = search_result.title
        form.description.data = search_result.description
        form.dish_type.data = search_result.dish_type_id

        if len(search_result.image):
            image_url = search_result.image[0].url
            image_preview_url = image_url.replace("upload",
                                                  "upload/w_200,h_200,c_fill")
            form.image_url.data = image_preview_url

        ingredients = ''
        for i in search_result.ingredients:
            ingredients += i.name
            ingredients += '\n'
        form.ingredients.data = ingredients

        steps = ''
        for s in search_result.steps:
            steps += s.content
            steps += '\n'
        form.steps.data = steps

    return render_template('add_recipe.html',
                           title='Modify recipe',
                           search_result=search_result,
                           form=form)
Beispiel #21
0
from app.models import Step


app = create_app('default')

with app.app_context():
    # delete old step templates
    for step in Step.query.filter(Step.template):
        db.session.delete(step)
    db.session.commit()

    # add step templates
    step_templates = [
        Step(
            name='Vorlösen',
            setpoint=20,
            duration=20,
            comment='Diese Raststufe folgt unmittelbar auf das Einmaischen und ermöglicht es den Malzenzymen besonders gut in Lösung zu gehen. Allerdings sind heutige Malze so hochwertig vorverarbeitet, daß dieser Schritt normalerweise nicht mehr notwendig ist.'
        ),
        Step(
            name='Gummirast',
            setpoint=39,
            duration=15,
            comment='Vor allem Roggen enthält einen hohen Anteil an Glukanen, die ein Bestandteil der Zellwand sind. Sie machen die Würze zähflüssig ("gummiartig"), sodaß ein mit Roggen gebrautes Bier beim Läutervorgang und, je nach Anteil, in der Gärung und sogar beim Trinken unerwünscht klebrig sein kann. Der Abbau durch eine Glukanaserast empfiehlt sich speziell bei Roggenbier.'
        ),
        Step(
            name='Weizenrast1',
            setpoint=45,
            duration=15,
            comment='Besonders Weizenmalz enthält einige Vorläuferstoffe der Ferulasäure, deren Abbauprodukte später zu einigen typischen Weizenbieraromen (wie etwa Nelken) führen. Diese Vorläufer werden zunächst gelöst (Rast 1) und dann zur Ferulasäure abgebaut (Rast 2). Die Rastbereiche liegen eng beieinander.'
        ),
        Step(