Beispiel #1
0
def create(request):
    if request.method == 'POST':
        form = TaskCreateForm(request.POST)
        if form.is_valid():
            thisadmin = MyAdmin.objects.get(user_id=request.user.user_id)

            schema_name = request.POST.get('TaskDataTableName', '')
            schema = request.POST.get('TaskDataTableScheme', '')

            cursor = connection.cursor()
            cursor.execute(schema)
            cursor.close()

            tskobj = Task(task_name=request.POST.get('Name', ''),
                          admin=thisadmin,
                          description=request.POST.get('Comment', ''),
                          mincycle=request.POST.get('mincycle', ''))
            tskobj.save()

            task_schema = TaskSchema(task_id=tskobj,
                                     TaskDataTableName=schema_name,
                                     TaskDataTableScheme=schema)
            task_schema.save()

            return redirect('taskdatatableschema')
        #return redirect('/pjadmin')
        return render(request, 'TaskCreateFail.html')
    else:
        form = TaskCreateForm()

    return render(request, 'TaskCreate.html', {'form': form})
Beispiel #2
0
 def test_set_name_invalid_length(self):
     """任务名称长度不在规定的范围内"""
     task = Task(user=self.user, template=self.template)
     for name in ('t1', ' t1 ', '     ', 't' * 30):
         with self.assertRaises(ValueError) as cm:
             task.set_name(name)
         self.assertEqual('任务名长度应在3~20个字符之间', cm.exception.args[0])
Beispiel #3
0
    def post(self, request, *args, **kwargs):
        form = TaskAddForm(request.POST)
        user = request.user

        if form.is_valid():
            task = Task(
                name=form.cleaned_data["name"],
                task_status=form.cleaned_data["task_status"],
                start_date=form.cleaned_data["start_date"],
                start_time=form.cleaned_data["start_time"],
                # users=(user,)
            )
            try:
                task.save()
                task.users.add(user)
            except Exception as e:
                return HttpResponse(render(request, "task/task_list.html", {"form": form}))

            return HttpResponseRedirect(reverse("task_list"))
        else:
            tasks_list = user.task_set.all().order_by("-id")
            paginator = MyPaginator(tasks_list, per_page=5, max_range=3)
            tasks = paginator.page(1)
            return render(request, "task/task_list.html", {
                "form": form,
                "tasks": tasks,
            })
Beispiel #4
0
    def test_task_fromdict_dependencies_dont_exist_yet(self):
        user = self.create_user()
        task1_info = {
            'description': 'foobar',
            'uuid': '1234abc',
            'entry': '1234',
            'project': 'test',
            'user': user,
            'status': 'pending',
        }

        task2_info = {
            'description': 'baz',
            'uuid': 'aaaaaa',
            'entry': '1237',
            'depends': '1234abc',
            'user': user,
            'status': 'pending',
            'annotation_123456': 'some note'
        }

        task2 = Task.fromdict(task2_info)
        task1 = Task.fromdict(task1_info)

        task2_info.pop('user')
        task1_info.pop('user')
        self.assertEqual(task1.todict(), task1_info)
        self.assertEqual(task2.todict(), task2_info)
Beispiel #5
0
 def test_mark_task_done(self):
     user = self.create_user()
     task = Task(description='test', user=user)
     task.save()
     self.assertEqual(task.status, 'pending')
     task.done()
     self.assertEqual(task.status, 'completed')
Beispiel #6
0
def task_display(request, pk):
	if request.method == 'POST':
		form = TaskForm(request.POST)
		user = request.user if request.user.is_authenticated else None
		if form.is_valid():
			task = Task(
				tasklist_id = pk,
				description=request.POST['description'],
				created=timezone.now(),
				creator=user,
				)
			task.save()
			return redirect('task:task_display', pk)

	task_list = get_object_or_404(TaskList, pk=pk)
	user = request.user if request.user.is_authenticated else None
	tasks = task_list.tasks.filter(creator=user)
	length = task_list.count()
	complete_length = task_list.count_complete()
	incomplete_length = task_list.count_incomplete()
	if length != 0:
		progress = round((complete_length/length)*100, 0)
	else:
		progress = 0
	context = {
		'task_list':task_list,
		'tasks':tasks,
		'len':length,
		'complete':complete_length,
		'incomplete':incomplete_length,
		'progress':progress,
		'form':TaskForm(),
		}
	return render(request, 'task/tasks.html', context)
Beispiel #7
0
    def post(self, request, *args, **kwargs):
        form = TaskAddForm(request.POST)
        user = request.user

        if form.is_valid():
            task = Task(
                name=form.cleaned_data["name"],
                task_status=form.cleaned_data["task_status"],
                start_date=form.cleaned_data["start_date"],
                start_time=form.cleaned_data["start_time"],
                # users=(user,)
            )
            try:
                task.save()
                task.users.add(user)
            except Exception as e:
                return HttpResponse(
                    render(request, "task/task_list.html", {"form": form}))

            return HttpResponseRedirect(reverse("task_list"))
        else:
            tasks_list = user.task_set.all().order_by("-id")
            paginator = MyPaginator(tasks_list, per_page=5, max_range=3)
            tasks = paginator.page(1)
            return render(request, "task/task_list.html", {
                "form": form,
                "tasks": tasks,
            })
Beispiel #8
0
 def get_nav_items(self):
     nav_role = Task.get_nav_role(self.config.app)
     if (not nav_role) or (nav_role == self.config.cur_view_group.view_id):
         return None
     href = self.request.path
     if ('pk' in self.kwargs):
         pk = str(self.kwargs['pk']) + '/'
         if (pk in href):
             href = href.split(pk)[0]
     sort = 'name'
     nav_item_group = detect_group(self.request.user, self.config.app,
                                   'role', nav_role, '')
     if nav_item_group and nav_item_group.items_sort:
         sort = nav_item_group.items_sort
     ret = []
     for item in Task.get_role_tasks(self.request.user.id, self.config.app,
                                     nav_role).order_by(sort):
         ret.append({
             'id':
             item.id,
             'name':
             item.name,
             'qty':
             len(
                 Task.get_role_tasks(self.request.user.id, self.config.app,
                                     self.config.cur_view_group.view_id,
                                     item)),
             'href':
             href,
         })
     return ret
Beispiel #9
0
    def test_task_fromdict_dependencies_dont_exist_yet(self):
        user = self.create_user()
        task1_info = {'description': 'foobar',
                      'uuid': '1234abc',
                      'entry': '1234',
                      'project': 'test',
                      'user': user,
                      'status': 'pending',
                      }

        task2_info = {'description': 'baz',
                      'uuid': 'aaaaaa',
                      'entry': '1237',
                      'depends': '1234abc',
                      'user': user,
                      'status': 'pending',
                      'annotation_123456': 'some note'
                      }

        task2 = Task.fromdict(task2_info)
        task1 = Task.fromdict(task1_info)

        task2_info.pop('user')
        task1_info.pop('user')
        self.assertEqual(task1.todict(), task1_info)
        self.assertEqual(task2.todict(), task2_info)
Beispiel #10
0
def post_taskdb(request, filename):
    if filename not in TASK_FNAMES:
        return HttpResponseForbidden('Forbidden!')

    user = request.user
    data = request.raw_post_data

    if filename in ['pending.data', 'completed.data']:
        parsed = [decode_task(line) for line in data.splitlines()]
        if filename == 'pending.data':
            tasks = Task.objects.filter(status='pending', user=user)
        elif filename == 'completed.data':
            tasks = Task.objects.filter(status__in=['completed', 'deleted'])

        tasks.delete()

        for task in parsed:
            task.update({'user': user})
            Task.fromdict(task)

    elif filename == 'undo.data':
        Undo.objects.all().delete()
        parsed = parse_undo(data)
        for undo_dict in parsed:
            undo_dict.update({'user': user})
            Undo.fromdict(undo_dict)
    else:
        return HttpResponseNotFound()

    return HttpResponse()
Beispiel #11
0
def test_profile(users, tasks, patch_datetime_now):
    user = User.from_json(users[0])
    assert user.id_ == 1
    assert user.name == "Leanne Graham"
    assert user.username == "Bret"
    assert user.email == "*****@*****.**"
    assert user.company_name == "Romaguera-Crona"
    assert user.date == FAKE_TIME
    task1 = Task.from_json(tasks[0])
    assert task1.user_id == 1
    assert task1.id_ == 1
    assert task1.title == "delectus aut autem"
    assert task1.completed == False
    task2 = Task.from_json(tasks[3])
    profile = Profile(user, [task1, task2])
    print(profile.uncompleted)
    uncompleted = len(profile.uncompleted)
    assert uncompleted == 1
    completed = len(profile.completed)
    assert completed == 1
    with pytest.raises(ValidateError):
        task1.user_id = 2
        profile = Profile(user, [task1, task2])
    error_users = users
    error_users[0]["err"] = error_users[0].pop("name")
    with pytest.raises(SerializeError):
        user = User.from_json(error_users[0])
Beispiel #12
0
def create(request):
    if request.method == 'GET':
        return render(request, 'task/create.html')
    elif request.method == 'POST':
        text = request.POST.get('title')
        task = Task(text=text, creator=request.user)
        task.save()
        return redirect(todo_list)
Beispiel #13
0
def update_task_cache():
    Task.create_cache()
    DailyTask.create_cache()
    TaskCondition.create_cache()
    SevenDaysTask.create_cache()
    TaskReward.create_cache()
    DailyTaskActivity.create_cache()
    SevenDaysHalfPrice.create_cache()
Beispiel #14
0
 def test_create_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
     self.assertNotIn('old', Undo.serialize())
     self.assertEqual(len(Undo.serialize().splitlines()), 3)
     task.delete()
Beispiel #15
0
def index(request):
    if request.method == 'GET':
        name = request.GET.get('name', '')
        location = request.GET.get('location')
        acc_token = request.GET.get('token')
        if location:
            geolocator = Nominatim()
            location = geolocator.geocode(location)
            location = str(location.latitude) + ',' + str(location.longitude)
        else:
            lat = request.GET.get('lat')
            lon = request.GET.get('lon')
            location = str(lat) + ',' + str(lon)

        print name, location, acc_token

        if acc_token:
            graph = GraphAPI(acc_token)
        else:
            graph = GraphAPI(
                'CAACEdEose0cBAPJRZA8xHkMmbokHYBCUyjcKxZBohVhzJnGlm2ETlOYESQpEjG1Gj6ykTV4FMmhqMUrgFsJp0HdH4TszHwCkoMA8PS8L2MRFth3w3Wm7ucx4xMglc9ZBZAMhnyrr3XNAlH6MHZBtGmeWusWvzu4GSt4Mt9oS2KIOkWh70WhQ3ktOUC40PgChklQN31X0EgAZDZD'
            )

        search = name
        search = qp(search)

        result = graph.get('search?type=place&q=' + search + '&center=' +
                           location)
        page_id = result['data'][0]['id']

        params = 'fields=phone,likes,current_location,about,website,food_styles,description,hours,awards,price_range,location,booking_agent,is_verified,offers,public_transit,founded,products,emails,parking'
        a = str(page_id) + '?' + params
        cache = {}
        cache['facebook'] = {}
        cache['google'] = {}

        cache['facebook'] = {'fb_page_url': 'http://facebook.com/' + page_id}
        params = params.split(',')
        for each in params:
            try:
                cache['facebook'][each] = str(graph.get(a)[each])
            except:
                pass

#Google Data
        url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' + location + '&radius=5000&name=' + name + '&key=AIzaSyDAERlVmOrLWdq0pHF5fK3c2cHmCSvy55I'
        print url
        r = requests.get(url)
        google_result = json.loads(r.text)
        cache['google'] = google_result

        return HttpResponse(json.dumps(cache), content_type="application/json")

    elif request.method == 'POST':
        t = request.POST.get("task", "")
        a = Task(text=t, date=timezone.now())
        a.save()
        return redirect('/')
Beispiel #16
0
    def test_pending_tasks(self):
        user = self.create_user()
        task = Task(description='test, test', user=user)
        task.save()
        self.assertEqual(len(Task.objects.all()), 1)

        response = self.client.get('/pending/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context['datagrid'].rows), 1)
Beispiel #17
0
 def test_create_task_with_uuid(self):
     """ Verify that when instantiating a Task with a uuid specified,
         it uses that uuid.
     """
     user = self.create_user()
     uuid = 'foobar'
     task = Task(description='my description', uuid=uuid, user=user)
     task.save()
     self.assertEqual(task.uuid, uuid)
Beispiel #18
0
 def test_create_task_with_uuid(self):
     """ Verify that when instantiating a Task with a uuid specified,
         it uses that uuid.
     """
     user = self.create_user()
     uuid = 'foobar'
     task = Task(description='my description', uuid=uuid, user=user)
     task.save()
     self.assertEqual(task.uuid, uuid)
Beispiel #19
0
 def test_task_saving_without_data_change(self):
     """ Make sure that saving a task twice without
         a change in data doesn't create duplicate Undo's
     """
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
Beispiel #20
0
    def test_pending_tasks(self):
        user = self.create_user()
        task = Task(description='test, test', user=user)
        task.save()
        self.assertEqual(len(Task.objects.all()), 1)

        response = self.client.get('/pending/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.context['datagrid'].rows), 1)
Beispiel #21
0
 def test_task_saving_without_data_change(self):
     """ Make sure that saving a task twice without
         a change in data doesn't create duplicate Undo's
     """
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.save()
     self.assertEqual(len(Undo.objects.all()), 1)
Beispiel #22
0
def send_book_to_kindle():
    logging.info("推送订阅书本至kindle任务开始")
    start = time.time()
    total = 0
    fail = 0
    look = 0
    book_ids = (SubscribeBook.normal.filter(ready=True).values_list(
        "book_id", flat=True).distinct())
    user_id = 1
    for book_id in book_ids:
        subs = SubscribeBook.normal.filter(ready=True, book_id=book_id)

        start_chapter, end_chapter = subs[0].chapter, subs[
            0].book.latest_chapter()
        # 判断需要推送的章节是否都已可用
        send_chapters = Chapter.normal.filter(
            book_id=book_id,
            number__in=[
                x for x in range(start_chapter.number if start_chapter else 0,
                                 end_chapter.number + 1)
            ],
        ).values("active", flat=True)
        if not all(send_chapters):
            fail += 1
            look += 1
            logging.info("{}部分章节不可用,不予推送至kindle".format(subs[0].book.title))
            continue

        to_email = [sub.user.email for sub in subs]
        try:
            # if True:
            # 开启事务
            with transaction.atomic():
                task_makebook = Task.create_task_for_make_book(
                    user_id,
                    book_id,
                    start_chapter.id if start_chapter else 0,
                    end_chapter.id,
                )
                task_email = Task.create_task_for_send_email(
                    user_id, book_id, list(set(to_email)))
                model_task.delay([task_makebook.id, task_email.id])
                for sub in subs:
                    sub.chapter_id = subs[0].book.latest_chapter().id
                    sub.ready = False
                    sub.count = sub.count + 1
                    sub.save()
        except Exception as e:
            fail += 1
            look += len(to_email)
            logging.error(f"推送订阅书本至kindle任务book_id: {book_id}, 失败。原因: {e}")
            continue

    stop = time.time()
    logging.info("推送订阅书本至kindle任务创建结束,共推送{}本, 失败{}本, 受影响用户{}位, 共耗时{}秒".format(
        total - fail if total > fail else 0, fail, look, stop - start))
Beispiel #23
0
 def test_create_task_no_uuid(self):
     """ Verify that a `Task`s uuid field is automatically populated
         when not specified.
     """
     # description and user are the only required field
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertTrue(hasattr(task, 'uuid'))
     self.assertNotEqual(task.uuid, None)
Beispiel #24
0
 def test_create_task_no_uuid(self):
     """ Verify that a `Task`s uuid field is automatically populated
         when not specified.
     """
     # description and user are the only required field
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     self.assertTrue(hasattr(task, 'uuid'))
     self.assertNotEqual(task.uuid, None)
Beispiel #25
0
def index(request):
	if request.method == 'GET':
		a = Task.objects.all().order_by('date').reverse()
		context ={'tasks':a}
		return render(request,'task/index.html',context)
	elif request.method == 'POST':
		t =  request.POST.get("task", "")
		a = Task(text=t,date=timezone.now())
		a.save()
		return redirect('/')
Beispiel #26
0
def index(request):
    if request.method == 'GET':
        a = Task.objects.all().order_by('date').reverse()
        context = {'tasks': a}
        return render(request, 'task/index.html', context)
    elif request.method == 'POST':
        t = request.POST.get("task", "")
        a = Task(text=t, date=timezone.now())
        a.save()
        return redirect('/')
Beispiel #27
0
    def test_task_tags_single_tag(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # single tag
        tag = Tag.objects.create(tag='django')
        task.tags.add(tag)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag])
Beispiel #28
0
    def test_task_fromdict_dependencies(self):
        user = self.create_user()

        task1 = Task(user=user, description='test')
        task1.save(track=False)
        task2 = Task(user=user, description='test2')
        task2.save(track=False)

        data = {
            'description': 'foobar',
            'uuid': 'sssssssss',
            'status': 'pending',
            'entry': '12345',
            'user': user,
            'annotation_1324076995': u'this is an annotation',
            'depends': u','.join([t.uuid for t in (task1, task2)]),
            'priority': '',
        }

        task = Task.fromdict(data)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.get(description='foobar')
        self.assertEqual(list(Undo.objects.all()), [])
        data.pop('user')
        data.pop('priority')
        self.assertEqual(data, task.todict())
Beispiel #29
0
 def test_task_is_dirty(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['user', 'description'])
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     self.assertItemsEqual(task._get_dirty_fields().keys(), [])
     task.description = 'foobar2'
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['description'])
     self.assertTrue(task._is_dirty())
Beispiel #30
0
def create(request):
    if request.method =='GET':
        return render(request,'task/create.html')
    elif request.method =='POST':
        text = request.POST.get('title')

        task = Task(text=text,creator=request.user)  # 很重要的一点, creator =request.user

        # 创建模型的时候,创建了两个参数:text,creator,
        task.save()
        return redirect(list)
Beispiel #31
0
    def test_task_tags_multiple_tags(self):
        user = self.create_user()
        task = Task(description='foobar', user=user)
        task.save()

        # multiple tags
        tag1 = Tag.objects.create(tag='spam')
        tag2 = Tag.objects.create(tag='eggs')
        task.tags.add(tag1, tag2)
        task.save()
        self.assertEqual(list(task.tags.all()), [tag1, tag2])
Beispiel #32
0
 def test_edit_task_undo(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     task.save()
     task.annotate('annotation')
     self.assertEqual(len(Undo.objects.all()), 2)
     self.assertIn('old', Undo.serialize())
     # 'old' shouldn't have an annotation
     new_undo = Undo.objects.get(pk=2)
     self.assertNotIn('annotation_', new_undo.old)
     self.assertEqual(len(Undo.serialize().splitlines()), 7)
     self.assertNotIn('annotation_', Undo.serialize().splitlines()[4])
Beispiel #33
0
def new_task(request):
    name = unicode.strip(request.POST.get('name'))
    description = unicode.strip(request.POST.get('description'))
    pk = request.POST.get('pk')
    if pk:
        task = Task.objects.get(pk=pk)
        task.name = name
        task.description = description
    else:
        task = Task(name=name, description=description)
    task.save()
    return HttpResponseRedirect(reverse('tasks'))
Beispiel #34
0
def new(request):
    resp = {}
    if request.method != 'POST':
        resp['status'] = 1
        resp['message'] = 'Wrong http method!'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    approximate_fplace = request.POST['approximate_fplace']
    detailed_fplace = request.POST['detailed_fplace']
    pto = request.POST['pto']
    code = request.POST['code']
    fetch_btime = request.POST['fetch_btime']
    fetch_etime = request.POST['fetch_etime']
    owner = request.POST['owner']
    give_time = request.POST['give_time']
    curtime = datetime.datetime.now()
    user = User.objects.filter(id = owner)
    if not user.exists():
        resp['status'] = 1
        resp['message'] = 'No such user'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    elif len(user) > 1:
        resp['status'] = 2
        resp['message'] = 'Too many user found, impossible!'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')

    if user[0].status == 0:
        resp['status'] = 3
        resp['message'] = 'Not authenticated yet!'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    if user[0].bonus <= 0:
        resp['status'] = 4
        resp['message'] = 'You do not have enough bonus!'
        return HttpResponse(json.dumps(resp), content_type='application/json')

    task = Task(approximate_fplace = approximate_fplace, detailed_fplace = detailed_fplace,
                pto = pto, code = code, fetch_btime = datetime.datetime.strptime(fetch_btime, '%Y-%m-%d %H:%M:%S'),
                fetch_etime = datetime.datetime.strptime(fetch_etime, '%Y-%m-%d %H:%M:%S'), owner = user[0],
                give_time = datetime.datetime.strptime(give_time, '%Y-%m-%d %H:%M:%S'), build_time = curtime)
    task.save()
    if task.id is None:
        resp['status'] = 4
        resp['message'] = 'create task error'
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
    else:
        user[0].bonus -= 1
        user[0].save()
        resp['status'] = 0
        resp['message'] = 'Success'
        info = task.to_dict()
        info['owner'] = task.owner.to_dict()
        resp['data'] = info
        return HttpResponse(json.dumps(resp), content_type = 'application/json')
Beispiel #35
0
def new_task(request):
    name = unicode.strip(request.POST.get('name'))
    description = unicode.strip(request.POST.get('description'))
    pk = request.POST.get('pk')
    if pk:
        task = Task.objects.get(pk=pk)
        task.name = name
        task.description = description
    else:
        task = Task(name=name, description=description)
    task.save()
    return HttpResponseRedirect(reverse('tasks'))
Beispiel #36
0
 def test_task_is_dirty_foreign_key(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.priority = Priority.objects.get(weight=1)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['priority'])
     self.assertTrue(task._is_dirty())
Beispiel #37
0
 def post(self, request):
     """ Adding a new task. """
     serializer = TaskSerializer(data=request.DATA)
     if not serializer.is_valid():
         return Response(serializer.errors, status=
             status.HTTP_400_BAD_REQUEST)
     else:
         data = serializer.data
         owner = request.user
         t = Task(owner=owner,description=data['description'], done=False,due_date=data['due_date'])
         t.save()
         request.DATA['id'] = t.pk # return id
         return Response(data, status=status.HTTP_201_CREATED)
Beispiel #38
0
def get_taskdb(request, filename):
    if filename == 'pending.data':
        taskstr = Task.serialize('pending')
    elif filename == 'completed.data':
        taskstr = Task.serialize('completed')
    elif filename == 'undo.data':
        taskstr = Undo.serialize()
    else:
        return HttpResponseNotFound()

    response = HttpResponse(taskstr, mimetype='text/plain')
    response['Content-Length'] = len(taskstr)
    return response
Beispiel #39
0
def tasks_new_view(request):
	#TODO - check permissions
	try:
		o = Task(	project=Project.objects.get(id=request.GET['project']),
					title=request.GET['title'],
					type=request.GET['type'],
					severity=request.GET['severity'],
					description=request.GET['description'],
					created_by=request.user)
		o.save()
	except:
		return HttpResponse("Something went wrong!")
	return HttpResponse("1")
Beispiel #40
0
    def get_app_context(self,
                        user_id,
                        search_qty=None,
                        icon=None,
                        nav_items=None,
                        **kwargs):
        context = {}
        if hasattr(self, 'object') and self.object:
            title = self.object.name
        else:
            if 'title' in kwargs:
                title = kwargs['title']
            else:
                title = _(self.config.title).capitalize()
        nav_item = None
        if (Task.get_nav_role(self.config.app) != self.config.get_cur_role()):
            nav_item = Task.get_active_nav_item(user_id, self.config.app)
            if nav_item:
                title = (title, nav_item.name)
                context['nav_item'] = nav_item
        context.update(
            get_base_context(self.request,
                             self.config.app,
                             self.config.get_cur_role(),
                             self.config.cur_view_group,
                             (hasattr(self, 'object') and self.object != None),
                             title,
                             icon=icon))
        context['fix_list'] = self.get_fixes(self.config.views, search_qty)
        context['group_form'] = CreateGroupForm()
        context['config'] = self.config
        context['params'] = extract_get_params(self.request,
                                               self.config.group_entity)
        if nav_items:
            context['nav_items'] = nav_items
        context['add_item_placeholder'] = '{} {}'.format(
            _('add').capitalize(), self.config.item_name
            if self.config.item_name else self.config.get_cur_role())
        if self.config.add_button:
            context['add_item_template'] = 'base/add_item_button.html'
        else:
            context['add_item_template'] = 'base/add_item_input.html'

        if (self.config.group_entity in self.request.GET):
            context['current_group'] = self.request.GET[
                self.config.group_entity]
        elif ('ret' in self.request.GET):
            context['current_group'] = self.request.GET['ret']

        return context
Beispiel #41
0
def create_task(request, template_pk):
    """提交创建任务表单"""
    if not request.user.is_authenticated:
        return redirect(reverse('login'))
    template = get_object_or_404(Template, pk=template_pk)

    task = Task(user=request.user, template=template)
    try:
        task.set_name(request.POST['inputTaskName'])
        split_arg = task.set_args({
            param.name: request.POST[param.name]
            for param in template.param_set.all()
        })
    except ValueError as e:
        return JsonResponse({
            'status': 'ERROR',
            'message': e.args[0]
        },
                            json_dumps_params={'ensure_ascii': False})
    task.save()
    task_arg = task.args_dict()
    for i in range(split_arg):
        task_arg[template.split_param] = i + 1
        Job.objects.create(uuid=uuid.uuid4(),
                           task=task,
                           args=json.dumps(task_arg))
    return JsonResponse({
        'status': 'SUCCESS',
        'tasks': get_recent_tasks(request.user)
    })
Beispiel #42
0
def create_task(request):
	context_dict = {}
	employee = Employee.objects.get(pk=1)
	if request.user.is_authenticated():
		username = request.user.username
		employee = Employee.objects.get(user=request.user)
		context_dict['employee'] = employee
	if request.method == 'POST':
		title = request.POST['title']
		desc = request.POST['desc']
		date = request.POST['date']
		today = datetime.now().date()
		task = Task(owner=employee, date_published=today, date_due=date, title=title, description=desc, state=False)
		task.save()
	return render(request, 'task/create_task.html', context_dict)
Beispiel #43
0
def savetask(request):
    print "Inside task creation"
    pid = request.POST['data1']
    task = request.POST['task']
    task_desc = request.POST['task_desc']
    sdate = request.POST['sdate']
    edate = request.POST['edate']
    assignee = request.POST['assigne']
    user = request.user
    get_project = Projects.objects.get(id=int(pid))
    get_assignee = User.objects.get(username=assignee)
    create_task = Task(project=get_project, user=user, task=task, task_desc=task_desc, completed=False, start_date=sdate, end_date=edate, assigned_to=get_assignee, created=timezone.now())
    create_task.save()
    response = { 'message': 'Task Saved' }
    return HttpResponse(response)
Beispiel #44
0
 def get(self, request, *args, **kwargs):
     if not request.user.is_authenticated:
         raise Http404
     ret = super().get(request, *args, **kwargs)
     nav_role = Task.get_nav_role(self.config.app)
     cur_role = self.config.get_cur_role()
     if nav_role and (nav_role != cur_role):
         if (self.config.group_entity not in request.GET):
             nav_item = Task.get_active_nav_item(request.user.id,
                                                 self.config.app)
             if nav_item:
                 return HttpResponseRedirect(request.path + '?' +
                                             self.config.group_entity +
                                             '=' + str(nav_item.id))
     return ret
Beispiel #45
0
    def test_task_fromdict_track(self):
        user = self.create_user()
        data = {'description': 'foobar', 'uuid': 'sssssssss',
                'status': 'pending',
                'entry': '12345',
                'user': user,
                'annotation_1324076995': u'this is an annotation',
                'priority': 'H',
                }

        task = Task.fromdict(data, track=True)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.all()[0]

        # see reasoning in the add_tasks_POST test
        self.assertEqual(Undo.objects.count(), 2)

        # this is a brand new task, the firts undo shouldn't
        # have an 'old' field.
        self.assertEqual(Undo.objects.all()[0].old, None)
        data.pop('user')
        self.assertEqual(data, task.todict())

        undo2 = Undo.objects.all()[1]
        self.assertNotEqual(undo2.old, undo2.new)
Beispiel #46
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     context['add_item_template'] = 'fuel/add_service.html'
     nav_item = Task.get_active_nav_item(self.request.user.id, APP_FUEL)
     form = CreateForm(nav_item, self.request.user.id)
     context['form'] = form
     return context
Beispiel #47
0
    def test_task_fromdict_track(self):
        user = self.create_user()
        data = {
            'description': 'foobar',
            'uuid': 'sssssssss',
            'status': 'pending',
            'entry': '12345',
            'user': user,
            'annotation_1324076995': u'this is an annotation',
            'priority': 'H',
        }

        task = Task.fromdict(data, track=True)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.all()[0]

        # see reasoning in the add_tasks_POST test
        self.assertEqual(Undo.objects.count(), 2)

        # this is a brand new task, the firts undo shouldn't
        # have an 'old' field.
        self.assertEqual(Undo.objects.all()[0].old, None)
        data.pop('user')
        self.assertEqual(data, task.todict())

        undo2 = Undo.objects.all()[1]
        self.assertNotEqual(undo2.old, undo2.new)
Beispiel #48
0
def task_post_review(request, get_header=None):

    task = Task()
    task.title = request.POST["task_title"]
    task.describe = request.POST["task_describe"]
    task.private_describe = request.POST["task_private_describe"]
    task.price = request.POST["task_price"]
    task.helper_payment = request.POST["task_helper_payment"]
    task.task_type = Task_Type.objects.get(id=request.POST["task_type"])
    task.private_describe = request.POST["task_private_describe"]
    task.done_with_virtual = request.POST["done_with_virtual"]
    task.need_vehicle = request.POST["need_vehicle"]

    return wrapped_render_to_response(
        "task/post_review.html", {"HEADER_MENU": get_header(session=request.session), "TASK": task}
    )
Beispiel #49
0
def add_new_task(item):
    result = False
    message = "no process"
    # app.logger.debug(item)
    query_result = Task.query.filter(Task.id == item['id']).first()
    if item['id'] and not query_result:
        try:
            task = Task(**item)
            db.session.add(task)
            db.session.flush()
            if task.id:
                result = True
                message = "success"
            else:
                message = "failed"
        except Exception as ex:
            err = "Exception while processing item %s" % item['id']
            app.logger.error(err, ex)
            message = err
    else:
        message = "duplicate entry"
        result = True
        app.logger.warning(message)

    r = {'result': result, 'message': message}
    return r
Beispiel #50
0
 def test_task_is_dirty_foreign_key(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.priority = Priority.objects.get(weight=1)
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['priority'])
     self.assertTrue(task._is_dirty())
Beispiel #51
0
    def test_task_fromdict_dependencies(self):
        user = self.create_user()

        task1 = Task(user=user, description='test')
        task1.save(track=False)
        task2 = Task(user=user, description='test2')
        task2.save(track=False)

        data = {'description': 'foobar', 'uuid': 'sssssssss',
                'status': 'pending',
                'entry': '12345',
                'user': user,
                'annotation_1324076995': u'this is an annotation',
                'depends': u','.join([t.uuid for t in (task1, task2)]),
                'priority': '',
                }

        task = Task.fromdict(data)

        # ensure the data is in the db, not just the task
        # object from above
        task = Task.objects.get(description='foobar')
        self.assertEqual(list(Undo.objects.all()), [])
        data.pop('user')
        data.pop('priority')
        self.assertEqual(data, task.todict())
Beispiel #52
0
 def test_taskdb_PUT_completed(self):
     self._create_user_and_login()
     data = open(os.path.join(TASK_DATA, 'completed.data'), 'r').read()
     response = self.client.put('/taskdb/completed.data',
                     content_type='text/plain',
                     data=data)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(list(Undo.objects.all()), [])
     self.assertEqual(Task.serialize('completed'), data)
Beispiel #53
0
 def test_taskdb_PUT_pending(self):
     self._create_user_and_login()
     data = open(os.path.expanduser('~/.task/pending.data'), 'r').read()
     response = self.client.put('/taskdb/pending.data',
                     content_type='text/plain',
                     data=data)
     self.assertEqual(response.status_code, 200)
     self.assertEqual(list(Undo.objects.all()), [])
     self.assertEqual(Task.serialize('pending'), data)
Beispiel #54
0
def new(request):
    no_form = True
    if request.method == 'POST':
        form = newForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['name']
            content = form.cleaned_data['content']
            user = request.user
            x = Task(name=name, content=content, author=user)
            x.save()
            return HttpResponseRedirect('/task/new/finish/')
    else:
        form = newForm()
    
    return render_to_response('task_new.html', {
        'form': form,
        },
        context_instance=RequestContext(request),
    )
Beispiel #55
0
def add_task(request, template='task/add.html'):
    if request.method == 'POST':
        task = Task(user=request.user)
        form = forms.TaskForm(request.POST, instance=task)
        if form.is_valid():
            task = form.save()
            # silly extra save to create
            # undo object for m2m fields
            task.save()
            return HttpResponseRedirect('/')
    else:
        form = forms.TaskForm(initial={'user': request.user})

    context = {
                'method': 'add',
                'form': form,
                'title': "Add Task",
                }
    return render(request, template, context)
Beispiel #56
0
    def test_task_form(self):
        user = self.create_user()
        tags = Tag.objects.create(tag='tag1')
        task = Task()
        d = {'priority': '', 'description': 'foobar',
                'user': '******', 'tags': ['1'],
                'status': 'pending'}
        form = forms.TaskForm(d)
        valid = form.is_valid()
        self.assertTrue(valid)
        task = form.save()

        # silly extra save() to
        # add proper undo info for m2m
        task.save()

        tdict = task.todict()
        self.assertEqual(tdict['description'], 'foobar')
        self.assertEqual(Undo.objects.count(), 2)
Beispiel #57
0
 def test_task_is_dirty_m2m(self):
     user = self.create_user()
     task = Task(description='foobar', user=user)
     self.assertTrue(task._is_dirty())
     task.save()
     self.assertFalse(task._is_dirty())
     task.tags.add(Tag.objects.create(tag='foobar'))
     self.assertItemsEqual(task._get_dirty_fields().keys(), ['tags'])
     self.assertTrue(task._is_dirty())
Beispiel #58
0
def get_mock_task(project, owner,
                  is_reviewed=False, is_accepted=False, is_closed=False,
                  solution=None):
    """ Generate task.

    :return Task:

    """
    t = Task(
        title="A task by %s" % owner.username,
        owner=owner,
        project=project,
        parent=solution,
        is_reviewed=is_reviewed,
        time_reviewed=timezone.now() if is_reviewed else None,
        is_accepted=is_accepted,
        is_closed=is_closed,
        time_closed=timezone.now() if is_closed else None,
    )
    t.save()
    return t