Esempio n. 1
0
def csv_download(self, _from, _till):
    csvList = []
    # Creating a new Task and assigning state to PROCESSING
    task_id = self.request.id
    task = Task(id=task_id, operation='Download', state='PROCESSING')
    db.session.add(task)
    db.session.commit()
    # Filtering out the User entries
    from_date = _from
    till_date = _till
    users = User.query.filter(User.record_date.between(from_date, till_date))
    for user in users:
        # Keeping track of AsyncResult state
        if (AsyncResult(task_id, app=celery).state == 'PENDING'):
            csvList.append([
                user.name, user.age, user.phone, user.email, user.address,
                user.record_date.strftime("%Y-%m-%d")
            ])
        else:
            break
    # Sending csvList to csv_result Function
    res = csv_result(csvList, task_id)
    if (res == False):
        # Pause Action on Download Operation
        task = Task.query.filter_by(id=task_id).first()
        task.state = 'PAUSED'
        db.session.commit()
        return "Downloading Operation Paused!!"
    return 'Downloaded Data!!'
Esempio n. 2
0
def seed_tasks():

    task1 = Task(
        projectId=1,
        userId=1,
        title="The First Task",
        description="There's a lot that goes into an app. Get this done first!",
        completed=False)

    db.session.add(task1)

    task2 = Task(
        projectId=1,
        userId=1,
        title="The Second Task",
        description="There's a lot that goes into an app. Get this done first!",
        completed=False)
    db.session.add(task2)

    task3 = Task(
        projectId=1,
        userId=1,
        title="The Third Task",
        description="There's a lot that goes into an app. Get this done first!",
        completed=False)
    db.session.add(task3)

    db.session.commit()
Esempio n. 3
0
def get_results():
    """ Receive LCA calculation request and dispatch the job to the Redis server """

    job_id = str(uuid.uuid1())

    # Add task to db
    task = Task(
        id=job_id,
        progress=0,
    )
    db.session.add(task)
    db.session.commit()

    lang = session.get("language", "en")
    d = app.calc.format_dictionary(request.get_json(), lang, job_id)

    # Create a connection to the Redis server
    q = Queue(connection=conn)
    job = q.enqueue_call(
        func=app.calc.process_results,
        args=(d, lang, job_id),
        result_ttl=3600,
        job_id=job_id,
    )

    print("JOB SENT with job_id {}".format(job_id))

    task = Task.query.filter_by(id=job_id).first()
    task.progress = 30
    db.session.commit()

    res = make_response(jsonify({"job id": job.get_id()}), 200)
    return res
Esempio n. 4
0
 def change_task(self, id, form):
     if user['id'] == - 1:
         return jsonify({"error":"you must be logged in"})
     if not Task().check_task(id):
         return jsonify({"error": "task id does not exist"})
     Task().edit_task(id, form['title'], form['status'], form['begin'], form['end'], User().get_id(form['username']))
     return jsonify({"result": "update done"})
Esempio n. 5
0
    def setUp(self):
        super().setUp()

        now = dt.datetime.now()

        self.mitch = AppUser(phone_number=self.inviter_number,
                             username='******',
                             timezone=US_TIMEZONES['b'])
        self.db.session.add(self.mitch)

        self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT,
                                 user=self.mitch)
        self.db.session.add(self.exchange)

        self.task1 = Task(description='clean',
                          due_date=now - dt.timedelta(days=6),
                          active=True,
                          user=self.mitch,
                          exchange=self.exchange)
        self.db.session.add(self.task1)

        self.task2 = Task(description='cook',
                          due_date=now - dt.timedelta(days=8),
                          active=True,
                          user=self.mitch,
                          exchange=self.exchange)
        self.db.session.add(self.task2)

        self.db.session.commit()

        self.mitch = self.mitch.to_dict()
Esempio n. 6
0
    def test_read_task_list_valid_with_tasks(self):
        task_list = TaskList()
        self.db.session.add(task_list)
        self.db.session.commit()
        tasks = [
            Task(description="Foo", list_id=task_list.id),
            Task(description="Bar", list_id=task_list.id, is_complete=True),
        ]
        self.db.session.add_all(tasks)
        self.db.session.commit()

        self.client.get_received()
        self.client.emit("read_task_list", {"id": task_list.id})
        received = self.client.get_received()

        self.assertEqual(len(received), 1)
        self.assertEqual(received[0]["args"], [{
            "id": 1,
            "tasks": [
                {
                    "id": 1,
                    "description": "Foo",
                    "is_complete": False,
                    "list_id": 1,
                    "sublist_id": None,
                },
                {
                    "id": 2,
                    "description": "Bar",
                    "is_complete": True,
                    "list_id": 1,
                    "sublist_id": None,
                },
            ],
        }])
    def test_UserModel_IsTaskAssignable_SameOutletShouldBeAssignable(self):
        u1 = User(username='******')
        u2 = User(username='******')
        u1.assign_zone(Zone.A)
        u2.assign_zone(Zone.A)
        u1.assign_role(Role.SALES_REP)
        u2.assign_role(Role.SALES_REP)
        o1 = Outlet()
        o2 = Outlet()
        o1.assign_zone(Zone.A)
        o2.assign_zone(Zone.A)
        u1.assign_outlet(o1)
        u2.assign_outlet(o2)
        t1 = Task(creator=u1, outlet=o1, type=TaskType.CUSTOM)
        t2 = Task(creator=u1, outlet=o2, type=TaskType.CUSTOM)

        db.session.add_all([u1, u2, o1, o2, t1, t2])
        db.session.commit()

        result1 = u1.is_task_assignable(t1, u1)
        result2 = u1.is_task_assignable(t2, u1)
        result3 = u2.is_task_assignable(t1, u2)
        result4 = u2.is_task_assignable(t2, u2)

        self.assertEqual(result1, True)
        self.assertEqual(result2, False)
        self.assertEqual(result3, False)
        self.assertEqual(result4, True)
Esempio n. 8
0
def add_tasks(data):
    response = []
    for task_data in data:
        error_msg = check_fields(task_data,
                                 ('title', 'description', 'author', 'users'))
        if error_msg is not None:
            response.append(error_msg)
            continue

        is_exist, task_or_msg = check_task_exist(task_data)
        if is_exist:
            response.append({
                'result': False,
                'message': 'Task exist',
                'data': task_data
            })
            continue

        Task.create(source=task_data)
        response.append({
            'result': True,
            'message': 'Task successfully added',
            'data': task_data,
        })

    return response
def start_train(method="MultinomialNB"):
    """
    Helper to start training process, for cli or api
    :return:
    """
    result = {'status': 'error', 'code': 2, 'hours_limit': current_app.config['TRAIN_PERIOD_LIMIT']}
    if AvailableMethod.has_value(method):
        spam_model = SpamModel.get_last_record({"classifier": method})  # type: SpamModel
        if spam_model is None or (spam_model is not None and (
                spam_model.status == TaskStatus.COMPLETE or spam_model.status == TaskStatus.DROPPED or time.time() - spam_model.created_at >
                result[
                    'hours_limit'])):
            result['code'] = 1
            spam_model = SpamModel(status="PENDING", classifier=method)
            spam_model.save()
            task = Task(name='train',
                        description=json.dumps(spam_model.serialize(exclude=['created_at', 'modified_at']),
                                               cls=JsonEncoder),
                        status="PENDING")
            task.save()
            if 'TESTING' not in current_app.config or not current_app.config['TESTING']:
                train_model.delay(json.dumps(task.serialize(), cls=JsonEncoder), method)
            result['code'] = 0
            result['status'] = 'success'
            result['message'] = 'Training ' + method + ' started'
        else:
            if spam_model is not None:
                local_timezone = tzlocal.get_localzone()  # get pytz timezone
                local_time = datetime.fromtimestamp(spam_model.created_at, local_timezone)
                result['message'] = 'Training can\'t be started yet. Last started : {}'.format(
                    local_time.strftime("%Y-%m-%d %H:%M:%S (%Z %z)"))
    else:
        result['message'] = "Method not available"
    return result
Esempio n. 10
0
def task_maker():
    form=TaskForm()
    form.person_assigned.choices = [(e.employee_id, e.full_name) for e in User.query.order_by('last_name')]
    if form.validate_on_submit():
        red=False
        dt = datetime.now()
        x= dt.strftime("%Y-%m-%d %H:%M:%S")
        new_task=Task(person_created=current_user.employee_id, datetime_created=datetime_sql(x), person_who_assigned=current_user.employee_id, datetime_assigned=datetime_sql(x), \
                        person_assigned=form.person_assigned.data, task=form.task.data, task_description=form.task_description.data)
        if form.datetime_due.data:
            new_task.datetime_due=form.datetime_due.data
            if form.datetime_due.data < date.today():
                    red=True
        if form.priority.data:
            new_task.priority=True
        db.session.add(new_task)
        db.session.commit()
        employee=User.query.filter_by(employee_id=new_task.person_who_assigned).first()
        if employee:
            full_name_for_table=employee.full_name
        else:
            full_name_for_table=new_task.person_who_assigned
        return {'success' : 'New task created.', 'task_id' : new_task.task_id, 'datetime_assigned' : new_task.datetime_assigned, 'person_who_assigned' : new_task.person_who_assigned, \
                'person_assigned' : new_task.person_assigned, 'task' : new_task.task, 'task_description' : new_task.task_description, 'datetime_due' : new_task.datetime_due, \
                'priority' : new_task.priority, 'task_completed' : False, 'person_assigned_previous' : new_task.person_assigned, 'full_name_for_table' : full_name_for_table, 'red' : red}
    if request.method=='POST':
        return {'error': 'Problem submitting form. Make sure all required fields are entered.', 'task_description_error' : form.task_description.errors, \
                'task_datetime_due_error' : form.datetime_due.errors}
    return render_template('task_create.html', user=current_user, form=form, edit=None, task=None)
Esempio n. 11
0
def screen_detail(sid):
    company = g.user.company
    screen = Screen.query.filter(Screen.company_id == company.id,
                                 Screen.id == sid).first()
    if screen is None:
        return error_result(ErrorCode.ERROR_SCREEN_NOT_EXIST)

    if request.method == 'GET':
        return success_result(screen.get_json())
    elif request.method == 'PUT':
        params = request.get_json()
        fields = ('box_id', 'name', 'camera_name', 'camera_address',
                  'camera_position', 'network_switcher',
                  'network_switcher_token'
                  'description', 'allow_all_subjects', 'allow_visitor',
                  'allowed_subject_ids')
        screen.update(fields, params)
        screen.display_devices.update({'reload_timestamp': g.TIMESTAMP})
        db.session.add(screen)
        update_company_data_version(company)
        return success_result(screen.get_json())
    elif request.method == 'DELETE':
        content = generate_delete_screen_task_content(company.id, sid)
        task = Task()
        task.name = u'删除相机'
        task.content = content
        db.session.add(task)
        db.session.commit()
        delete_screen.delay(task.id, company.id, sid)
        return success_result()
    def __call__(self, task: Task):
        task.complete(at=self._now)
        self._session.commit()

        # TODO: Do some more complex stuff here...

        return task
    def test_TaskModel_TaskConstructor_InvalidDateShouldThrow(self):
        u1 = User(username='******')
        start = datetime(2021, 2, 22)
        t1 = Task(creator=u1,
                  type=TaskType.CUSTOM,
                  start_date=start,
                  end_date=start)
        t2 = Task(creator=u1,
                  type=TaskType.CUSTOM,
                  start_date=start,
                  end_date=start + timedelta(days=1))
        t3 = Task(creator=u1,
                  type=TaskType.CUSTOM,
                  start_date=start + timedelta(days=-1),
                  end_date=start)

        with self.assertRaises(ValueError):
            t4 = Task(creator=u1,
                      type=TaskType.CUSTOM,
                      start_date=start,
                      end_date=start + timedelta(days=-1))

        with self.assertRaises(ValueError):
            t5 = Task(creator=u1,
                      type=TaskType.CUSTOM,
                      start_date=start + timedelta(days=1),
                      end_date=start)
Esempio n. 14
0
def add_task():
    try:
        assigned_staff = request.json['staffId']
        assigned_patient = request.json['patientId']
        visit_type = request.json['visitType']
        scheduled_date = datetime(request.json['visitYear'],
                                  request.json['visitMonth'],
                                  request.json['visitDay'])
        status = request.json['status']

        new_task = Task(user_id=assigned_staff,
                        patient_id=assigned_patient,
                        type=visit_type,
                        scheduled_visit=scheduled_date,
                        completed=status)

        db.session.add(new_task)
        db.session.commit()

        return new_task.to_dict()
    except AttributeError:
        return {'error': 'Error 404. Task does not exist in the database'}, 404
    except UnmappedInstanceError:
        return {'error': 'Error 404. Task does not exist in the database'}, 404
    except:
        return {
            'error': 'Error 500. Contact your administrator for more details.'
        }, 500
Esempio n. 15
0
File: views.py Progetto: ztdroid/PMS
def add_ys(request):
    if not request.user.has_perm('app.add_ys'):
        request.session['msg'] = u'你没有权限进行此操作!'
        request.session['type'] = 'warning'
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        form = YSForm(request.POST)
        if form.is_valid():
            #print request.POST.get('result')
            ys = form.save(commit=False)
            ys.save()
            request.session['msg'] = u'成功添加预决算!'
            request.session['type'] = 'success'
            #try:
            filelist = request.FILES.getlist('filelist')
            for f in filelist:
                filename,sysfilename = utils.upload_file(f)
                print filename,sysfilename,ys.id
                ysatt = YSatt(ys=ys, filename=filename, sysfilename=sysfilename)
                ysatt.save()
            #except Exception, e:
            #    pass
            task = Task(name=ys.gc.name[0:30] + u'预决算审核', who='auth.audit', status='c', type='ys', item=ys.id)
            task.save()
            return HttpResponseRedirect('/')
        request.session['msg'] = u'添加预决算失败!请检查信息是否准确填写,或是联系管理员。'
        request.session['type'] = 'danger'
        return HttpResponseRedirect('/')
    else:
        form = YSForm()
    
    return render_to_response('app/add_ys.html',{'form': form, 'year':datetime.now().year,'title':u'创建工程','templates':Template.objects.all(),'norms': Norm.objects.all(), 'projects':GC.objects.filter(status='a')},RequestContext(request))
Esempio n. 16
0
def ctasks(request, team_name_t):
    if logged_in(request):
        if is_admin(request,team_name_t):
            if request.method=='POST':
                task_object = Task(
                    task_name=request.POST['task_name'],
                    tags=request.POST['tags'],
                    team=Team.objects.filter(team_name=team_name_t).get(),
                    created_by=User.objects.filter(uname=request.COOKIES['username']).get(),
                    assigned_to=User.objects.filter(uname=request.POST['assigned_to']).get(),
                    deadline_time=request.POST['deadline']
                )
                task_object.save()
                return HttpResponse("<html><h1>Successfully saved</h1></html>")
            else:
                permissions = Permissions.objects.filter(team=Team.objects.filter(team_name=team_name_t))
                users = set()
                for permission in permissions:
                    users.add(str(permission.user))
                context = {
                    "team": team_name_t,
                    "users": users,
                    "round": get_formatted_team_name(team_name_t),
                }
                return render(request, 'home/ctasks.html', context)
        else:
            raise Http404
    else:
        return redirect("/")
Esempio n. 17
0
def task_do_submit():
	method = request.method
	if (method == "POST"):

		form = request.form
		project_id = form.get("project_id", "").strip()
		env_id = form.get("env_id", "").strip()
		task_title = form.get("task_title").strip()
		branch = form.get("branch").strip()
		commit = form.get("commit").strip()

		task_count = Task.query.filter_by(project_id=project_id, env_id=env_id).count()
		roll_back = "no"
		if (task_count > 0):
			roll_back = "yes"

		task = Task()
		task.task_title = task_title.strip()
		task.branch_id = branch
		task.commit_id = commit
		task.user_id = 0
		task.project_id = project_id
		task.env_id = env_id
		task.rollback_enable = roll_back
		task.status = "create"
		task.action_id = "deploy"

		DBSession.save(task)

		return Result("succ", 0, url_for(".project_list")).getIframeResponse()
	else:
		return Result("error", 1)
def add_user_task(req):
    t = Task()
    t.get(req)
    try:
        return t.add()
    except ValueError as e:
        return {'fname': 'add_user_task', 'err': e, 'data': req}
Esempio n. 19
0
    def test_remove_task_with_sublist(self):
        mainlist = TaskList()
        sublist = TaskList()
        self.db.session.add(mainlist)
        self.db.session.add(sublist)
        self.db.session.commit()

        task = Task(description="mainlisttask", list_id=1, sublist_id=2)
        task1 = Task(description="sublisttask", list_id=2)

        self.db.session.add(task)
        self.db.session.add(task1)
        self.db.session.commit()

        self.assertIsNotNone(Task.query.filter_by(id=1).first())

        self.assertIsNotNone(Task.query.filter_by(id=2).first())
        data = task.as_json()
        self.client.get_received()
        self.client.emit("remove_task", data)

        self.assertIsNone(Task.query.filter_by(id=1).first())

        self.assertIsNone(Task.query.filter_by(id=2).first())

        self.assertIsNotNone(TaskList.query.filter_by(id=1).first())

        self.assertIsNone(TaskList.query.filter_by(id=2).first())
Esempio n. 20
0
 def del_task(self, id):
     Task().delete_task(id)
     if user['id'] == - 1:
         return jsonify({"error":"you must be logged in"})
     if not Task().check_task(id):
         return jsonify({"error":"task id does not exist"})
     Task().delete_task(id)
     return jsonify({"result":"task deleted"})
def task_incomplete_endpoint(
        task: Task = Depends(get_task),
        session: Session = Depends(get_session),
):
    task.incomplete()
    session.commit()

    return task
Esempio n. 22
0
def update_task(uuid):
    result = {'data': ''}
    attr = request.json['data']['attributes']
    task = Task(uuid, attr['name'], isComplete=attr['is-complete'])
    task = dbh.update_task(task)

    result['data'] = task.to_dict()
    return jsonify(**result)
Esempio n. 23
0
def store():
    task = Task()
    task.title = request.form['title']
    task.memo = request.form['memo']
    db.session.add(task)
    db.session.commit()
    flash('create new task.')
    return redirect(url_for('tasks.index'))
 def mutate(self, info, title, description, createdBy):
     user = User.query.filter_by(username=createdBy).first()
     task = Task(title=title, description=description, status="incomplete")
     if user is not None:
         task.created_by = user.uuid
     db.session.add(task)
     db.session.commit()
     return CreateTask(task=task)
Esempio n. 25
0
def stop_broken_tasks(print_lock):
    """Stop all tasks with status_code 0"""
    app = create_app()
    with app.app_context():
        try:
            Task.stop_tasks(prefix='[Scheduler] ', print_lock=print_lock)
        except OperationalError:
            pass
Esempio n. 26
0
    def test_task_find(self):
        task = Task.create(total=100)
        found = Task.find_recent(task.id)

        self.assertTrue(task.id is found.id)
        self.assertFalse(Task.find_recent(10))

        with self.assertRaises(TypeError):
            Task.find_recent('asdasd')
Esempio n. 27
0
def form_task_create():
    if 'user_id' not in session:
        return redirect('/login')
    try:
        Task.insert(session['user_id'], request.form['title'])
        return redirect('/tasks')
    except Exception as e:
        print(e)
        return render_template('task_create.html',
                               error='Internal server error')
Esempio n. 28
0
 def one_task(self, id):
     if user['id'] == - 1:
         return jsonify({"error":"you must be logged in"})
     if not Task().check_task(id):
         return jsonify({"error": "task id does not exist"})
     task = Task().get_task_with_id(id)
     if task:
         return jsonify({"result":task})
     else:
         return jsonify({"error":"internal error"})
Esempio n. 29
0
def add_entry():
    """Add new todo item to db
        :param json with ['due', 'title', 'description']
        :returns code 201, success or Error
    """
    res = request.get_json(force=True)
    entry = Task(datetime.datetime.strptime(res.get('due'), '%Y-%m-%d').date(), res.get('title'), res.get('description'))
    db.session.add(entry)
    db.session.commit()
    return jsonify({'msg': 'success', 'added': Task.as_dict(entry)}), 201
Esempio n. 30
0
def create_task(id):
    data = request.get_json() or {}
    task = Task(title=data['title'],
                description=data['description'],
                user_id=id)
    db.session.add(task)
    db.session.commit()
    response = jsonify(task.to_dict())
    response.status_code = 201
    return response
Esempio n. 31
0
 def test_compelte_task_true(self):
     t = Task()
     db.session.add(t)
     db.session.commit()
     t = Task.query.get(1)
     self.assertTrue(t.completed is False)
     t.complete_task()
     self.assertTrue(t.completed is True)
     db.session.delete(t)
     db.session.commit()
Esempio n. 32
0
 def del_task(self, id):
     if user['id'] == -1:
         print({"error": "you must be logged in"})
         return redirect(url_for('main_route'))
     if not Task().check_task(id):
         print({"error": "task id does not exist"})
         return redirect(url_for('tasks_route'))
     Task().delete_task(id)
     print({"result": "task deleted"})
     return redirect(url_for('tasks_route'))
Esempio n. 33
0
 def add_task(self, form):
     if user['id'] == -1:
         print({"error": "you must be logged in"})
         return redirect(url_for('main_route'))
     Task().create_task(form["title"], form['status'], form['begin'],
                        form['end'])
     task = Task().get_last_task()
     Task().add_user_to_task(task[0], user['id'])
     print({"result": "new task added"})
     return redirect(url_for('tasks_route'))
Esempio n. 34
0
File: hemul.py Progetto: Lovis/hemul
def create_task():
    if not request.json or not "title" in request.json:
        abort(400)
    d = json.loads(request.data)
    task = Task(d["title"])
    db.session.add(task)
    db.session.commit()
    task_order = TaskOrder(task.id, task.id)
    db.session.add(task_order)
    db.session.commit()

    return jsonify({"task": task.to_json()}), 201
Esempio n. 35
0
    def test_task_create(self):
        task = Task.create(total=100)
        self.assertTrue(isinstance(task, Task))
        self.assertTrue(task.total is 100)
        self.assertTrue(task.progress is 0)
        self.assertTrue(isinstance(task, Task))
        self.assertTrue(isinstance(task, Task))

        with self.assertRaises(TypeError):
            Task.create()

        with self.assertRaises(TypeError):
            Task.create('asdasd')
Esempio n. 36
0
    def test_update_view(self):
        response = self.client.put(
            url_for('main.update_task', task_id=1),
            data=dict(total=1)
        )

        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(response.status_code, 404)
        self.assertEqual(data['status'], 'not found')

        task = Task.create(total=100)

        response = self.client.put(
            url_for('main.update_task', task_id=task.id),
        )

        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(response.status_code, 404)
        self.assertEqual(data['status'], 'not found')

        response = self.client.put(
            url_for('main.update_task', task_id=task.id),
            data=dict(progress=20)
        )

        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['task']['progress'], 20)
Esempio n. 37
0
def _tasks_from_json(app, content=''):
    if 'tasks' in content:
        for obj in content['tasks']:
            user = User.query.filter_by(email=obj['user']).first()
            if user is None:
                app.logger.error('Task: %s, Unknown user: %s' % (obj['name'], obj['user']))
                break

            task = Task.query.filter_by(user=user, name=obj['name']).first()
            if task is None:
                task = Task()
            task.user = user
            task.name = obj['name']
            task.description = obj['description']

            app.logger.debug('adding task: %s' % task)
            db.session.add(task)
        db.session.commit()
Esempio n. 38
0
    def test_task_delete(self):
        task1 = Task.create(total=1)
        task2 = Task.create(total=2)
        self.assertTrue(Task.delete(task1.id))
        self.assertFalse(Task.find_recent(task1.id))
        self.assertTrue(Task.find_recent(task2.id))

        with self.assertRaises(TypeError):
            Task.delete('asdasd')
Esempio n. 39
0
    def test_task_update(self):
        task = Task.create(total=100)
        prev_updated_at = task.updated_at

        self.assertTrue(Task.update(task.id, progress=1))
        self.assertTrue(task.total is 100)
        self.assertTrue(task.progress is 1)
        self.assertTrue(task.updated_at > prev_updated_at)

        Task.update(task.id, progress=100, inc=True)
        self.assertTrue(task.progress is 101)

        with self.assertRaises(TypeError):
            Task.update(task.id, 'asdasd')

        with self.assertRaises(TypeError):
            Task.update('asdasd', '12')

        with self.assertRaises(ValueError):
            Task.update(task.id, -10)
Esempio n. 40
0
    def test_delete_view(self):

        response = self.client.delete(url_for('main.delete_task', task_id=1))
        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(data['status'], 'not found')

        task = Task.create(total=100)

        response = self.client.delete(url_for('main.delete_task', task_id=task.id))
        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['status'], 'deleted')
Esempio n. 41
0
    def test_task_recent(self):
        task1 = Task.create(total=1)
        task2 = Task.create(total=2)
        task3 = Task.create(total=3)

        self.assertEqual(len(Task.get_recent_tasks()), 3)

        task3.updated_at = task3.updated_at - timedelta(60)
        db.session.add(task3)
        db.session.commit()

        self.assertEqual(len(Task.get_recent_tasks()), 2)

        task2.updated_at = task2.updated_at - timedelta(60)
        db.session.add(task2)
        db.session.commit()

        self.assertEqual(len(Task.get_recent_tasks()), 1)


        task1.updated_at = task1.updated_at - timedelta(60)
        db.session.add(task1)
        db.session.commit()

        self.assertEqual(len(Task.get_recent_tasks()), 0)

        task1.updated_at = datetime.utcnow()
        task2.updated_at = datetime.utcnow()
        task3.updated_at = datetime.utcnow()

        db.session.add(task1)
        db.session.add(task2)
        db.session.add(task3)
        db.session.commit()

        self.assertEqual(len(Task.get_recent_tasks()), 3)

        with self.assertRaises(TypeError):
            Task.get_recent_tasks('asdasd')
Esempio n. 42
0
    def post(self):
        data = request.json
        if data is None or data.get('title') is None \
            or data.get('users') is None \
            or data.get('question') is None:
            return jsonify({'Success': 0})

        title = data.get('title').strip()
        question = data.get('question')
        users = data.get('users') or []
        duration = data.get('duration')
        reminder = data.get('reminder')
        if len(users) < 1:
            return jsonify({'Success': 0})

        for key in users:
            u = User.objects(uid=key).first()
            if u is not None and question not in u.question:
                u.update(push__question=question)

        task = Task(title=title, question=question, users=users, duration=duration, reminder=reminder)
        task.saveNews()
        return jsonify({'Success': 1, 'id': task.sid})
Esempio n. 43
0
def init_dummy_data():
    """Prefill database with random ."""

    current_time = datetime.utcnow()
    past_time = datetime.utcnow() - timedelta(seconds=100)

    # up to date tasks
    for x in range(0, 10):
        task = Task(randint(100, 1000))
        task.progress = randint(100, 200)
        task.created_at = current_time
        task.updated_at = current_time
        db.session.add(task)
    #
    for x in range(0, 10):
        task = Task(randint(100, 1000))
        task.progress = randint(100, 200)
        task.created_at = past_time
        task.updated_at = past_time
        db.session.add(task)
    db.session.commit()
Esempio n. 44
0
    def get_tasks_in_date_range(group_id, personal, start_date, end_date):
        """Load all tasks for a given group in a daterange."""

        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden', 'danger')
            return redirect(url_for('pimpy.view_tasks'))

        status_meanings = Task.get_status_meanings()

        tasks_rel = TaskUserRel.query.join(Task).join(User)

        groups = UserAPI.get_groups_for_current_user()
        groups = map(lambda x: x.id, groups)

        if group_id == 'all':
            tasks_rel = tasks_rel.filter(Task.group_id.in_(groups))

        else:
            group_id = int(group_id)
            if group_id not in groups:
                return abort(403)

            tasks_rel = tasks_rel.filter(Task.group_id == group_id)

        if personal:
            tasks_rel = tasks_rel.filter(User.id == current_user.id)

        tasks_rel = tasks_rel.filter(~Task.status.in_((4, 5))).join(Group).\
            filter(start_date <= Task.timestamp,
                   Task.timestamp <= end_date)
        tasks_rel = tasks_rel.order_by(Group.name.asc(), User.first_name.asc(),
                                       User.last_name.asc(), Task.id.asc())

        return Markup(render_template('pimpy/api/tasks.htm',
                                      personal=personal,
                                      group_id=group_id,
                                      tasks_rel=tasks_rel,
                                      type='tasks',
                                      status_meanings=status_meanings,
                                      title='PimPy'))
Esempio n. 45
0
    def get_all_tasks(group_id):
        """
        Show all tasks ever made.

        Can specify specific group.
        No internal permission system made yet.
        Do not make routes to this module yet.
        """
        if not ModuleAPI.can_read('pimpy'):
            return abort(403)
        if current_user.is_anonymous:
            flash('Huidige gebruiker niet gevonden.', 'danger')
            return redirect(url_for('pimpy.view_tasks'))

        status_meanings = Task.get_status_meanings()

        list_items = {}
        if group_id == 'all':
            for group in UserAPI.get_groups_for_current_user():
                list_users = {}
                list_users['Iedereen'] = group.tasks
                list_items[group.name] = list_users
        else:
            list_users = {}
            tasks = Task.query.filter(Task.group_id == group_id).all()
            group = Group.query.filter(Group.id == group_id).first()
            if not group:
                return abort(404)
            if group not in UserAPI.get_groups_for_current_user():
                return abort(403)
            list_users['Iedereen'] = tasks
            list_items[group.name] = list_users

        return Markup(render_template('pimpy/api/tasks.htm',
                                      list_items=list_items, type='tasks',
                                      group_id=group_id, personal=False,
                                      status_meanings=status_meanings,
                                      title='PimPy'))
Esempio n. 46
0
    def test_tasks_view(self):
        response = self.client.get(url_for('main.tasks'))
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(data['tasks']), 0)
        self.assertEqual(data['total'], 0)

        task = Task.create(total=100)

        response = self.client.get(url_for('main.tasks'))
        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(data['tasks']), 1)
        self.assertEqual(data['tasks'][0]['id'], task.id)
        self.assertEqual(data['total'], 1)

        task.updated_at = datetime.utcnow() - timedelta(seconds=100)
        db.session.add(task)
        db.session.commit()

        response = self.client.get(url_for('main.tasks'))
        data = json.loads(response.get_data(as_text=True))
        self.assertEqual(len(data['tasks']), 0)
        self.assertEqual(data['total'], 0)
Esempio n. 47
0
def add_task(request):
    context = RequestContext(request)

    edit_task = request.user.staff.role.editTask
    global g_parent_add
    if request.method == 'POST':

        my_dict = dict(request.POST.iterlists())

        name = my_dict['name'][0].strip()
        create_date = datetime.now()
        begin_date = request.POST.get('begin_date')
        end_date = request.POST.get('end_date')
        state = my_dict['state'][0].strip()
        importance = my_dict['importance'][0].strip()
        content = my_dict['content'][0].strip()
        finish = my_dict['finish'][0].strip()

        principal = None
        if my_dict.get('principal'):
            did = my_dict['principal'][0].strip()
            if did != '' and did != 0 and did != 'undefined':
                principal = Staff.objects.get(id=did)

        t_parent = None
        parent_v = []
        if my_dict.get('parent'):
            pid = my_dict['parent'][0].strip()
            if pid != 'None' and pid != '-1' and pid != 0:
                t_parent = Task.objects.get(id=pid)
                tmp_t = t_parent
                while tmp_t is not None:
                    parent_v.append(tmp_t.creator)
                    parent_v.append(tmp_t.principal)
                    tmp_t = tmp_t.parent
        else:
            pid = 0

        t_group = []
        if my_dict.get('group'):
            tmp_group = my_dict['group']
            for tg in tmp_group:
                t_group.append(Group.objects.get(id=tg))

        executor = []
        if my_dict.get("executor"):
            tmp_exe = my_dict["executor"]
            for e in tmp_exe:
                executor.append(Staff.objects.get(id=e))

        visible = []
        if my_dict.get("visible"):
            tmp_visible = my_dict["visible"]
            for v in tmp_visible:
                visible.append(Staff.objects.get(id=v))
        if name == '':
            messages.error(request, '名称不能为空!')
        elif re.search(r'/|\\|:|\*|<|>|\?|:|\"|\|', name):
            messages.error(request, '名称不能包含下列任何字符“ \ / : * ? " < > | ”')
        elif t_parent == None and Task.objects.filter(name=name, mptt_level=0, istemp=0).count() > 0:
            messages.error(request, '名称已存在!')
        elif begin_date == '' or end_date == '':
            messages.error(request, '开始日期和结束日期不能为空!')
        elif content == '':
            messages.error(request, '任务内容不能为空!')
        elif principal is None:
            messages.error(request, '负责人不能为空!')
        elif (not edit_task and pid == 0) or pid == '-1':
            messages.error(request, '您没有权限创建该任务!')
        elif not valid_time(begin_date):
            messages.error(request, '开始日期格式错误!')
        elif not valid_time(end_date):
            messages.error(request, '结束日期格式错误!')
        else:
            tsk = Task()
            tsk.name = name
            tsk.create_date = create_date
            tsk.begin_date = begin_date
            tsk.end_date = end_date
            tsk.state = state
            tsk.importance = importance
            tsk.content = content
            ff = finish
            if len(ff) > 50:
                finish = ff[0:49]
            tsk.finish = finish
            tsk.parent = t_parent
            tsk.creator = request.user.staff
            tsk.principal = principal

            tsk.save()

            tsk.group.clear()
            for g in t_group:
                tsk.group.add(g)

            tsk.executor.clear()
            for e in executor:
                tsk.executor.add(e)

            tsk.viewing.clear()
            tsk.viewing.add(request.user.staff)
            tsk.viewing.add(principal)

            for v in visible:
                if not tsk.viewing.filter(id=v.id):
                    tsk.viewing.add(v)

            for e in executor:
                if not tsk.viewing.filter(id=e.id):
                    tsk.viewing.add(e)
            for tp in parent_v:
                if not tsk.viewing.filter(id=tp.id):
                    tsk.viewing.add(tp)
            # cache.clear()
            messages.success(request, "创建任务成功!")
            if my_dict.get('temp'):
                temp_id = my_dict['temp'][0].strip()
                if temp_id != '-1':
                    createTaskBy(request, temp_id, tsk.id)

                    #parent = Task.objects.all()
        staff = Staff.objects.filter(visible=True)
        group = Group.objects.all()
        ngroup = Staff.objects.filter(group=None)
        temps = Task.objects.filter(Q(istemp=1) & Q(parent=None))
        return render_to_response('task/add_task.html',
                                  {'parent': g_parent_add, 'staff': request.user.staff, 'group': group,
                                   'ngroup': ngroup,
                                   't_name': name, 't_begin_date': begin_date, 't_end_data': end_date, 't_state': state,
                                   't_importance': importance, 't_content': content, 't_finish': finish,
                                   't_principal': principal, 't_parent': t_parent, 't_group': t_group, 'temps': temps,
                                   't_executor': executor, 't_visible': visible, 'edit_task': edit_task}, context)
    else:

        p_parent = []
        task_execute = request.user.staff.task
        task_cp = Task.objects.filter(
            Q(istemp=False) & (Q(creator=request.user.staff) | Q(principal=request.user.staff)))
        task_viewing = request.user.staff.viewing.all()
        for t1 in task_execute.all():
            has = False
            for p in p_parent:
                if p == t1:
                    has = True
                    break
            if not has:
                p_parent.append(t1)

        for t2 in task_cp:
            has = False
            for p in p_parent:
                if p == t2:
                    has = True
                    break
            if not has:
                p_parent.append(t2)
        for t3 in task_viewing:
            p_parent.append(t3)
        g_parent_add = Task.objects.filter(istemp=0)
        for p in g_parent_add:
            has = False
            for t1 in p_parent:
                if p == t1:
                    has = True
                    break
            if not has:
                p.name = "没有权限的项目"
                p.id = -1

        staff = Staff.objects.filter(visible=True)
        group = Group.objects.all()
        ngroup = Staff.objects.filter(group=None)
        temps = Task.objects.filter(Q(istemp=1) & Q(parent=None))
        return render_to_response('task/add_task.html',
                                  {'parent': g_parent_add, 'staff': request.user.staff, 'group': group,
                                   'edit_task': edit_task, 'ngroup': ngroup, 'temps': temps}, context)
Esempio n. 48
0
 def get(self, sid):
     task = Task.objects(sid=sid).first()
     if not task:
         return jsonify({'Success': 0, 'message': 'Not Task!'})
     return jsonify({'Success': 1, 'data': filterTaskModel(task)})
Esempio n. 49
0
def main():
    for task in Task.load_all():
        if task.active and task.is_due:
            print 'Executing task #{} (due:{})'.format(task.id, task.time)
            success, response = task.execute()
            log_task(task, success, response)