コード例 #1
0
def evaluate(request, token, approved):
    '''
        This will allow you to decide if a token is approved or diapproved.
        You must have evaluate permission for this token otherwise you will get a nasty 403 Fobidden error.
        
        
    '''
    
    #get or 404 the token
    token_object = get_object_or_404(Token,pk=token)
    
    #check that the user has got the submit permission for the token
    

        
    if approved:
        transition_allowed = do_transition(token_object, 'approved', request.user)
    else:
        transition_allowed = do_transition(token_object, 'rejected', request.user)
    
    
    if not transition_allowed:
        raise PermissionDenied()
        
        
   
    return HttpResponseRedirect(reverse('home_view'))
コード例 #2
0
ファイル: views.py プロジェクト: VPH-Share/portal
def rejectRequest(request):
    if request.method == 'POST':
        name = request.POST.get('user')
        resource = Resource.objects.get(global_id=request.POST.get('resource'))
        principal = User.objects.get(username=name)
        # change request state if exists
        try:
            resource_request = ResourceRequest.objects.filter(requestor=principal, resource=resource)
            if resource_request.count() and is_request_pending(resource_request[0]):
                do_transition(resource_request[0], request_refuse_transition, request.user)
                resource_request[0].delete()
                # alert requestor
                alert_user_by_email(
                    mail_from='VPH-Share Webmaster <*****@*****.**>',
                    mail_to='%s %s <%s>' % (principal.first_name, principal.last_name, principal.email),
                    subject='[VPH-Share] Your request for sharing has been refused',
                    mail_template='request_for_sharing_refused',
                    dictionary={
                        'resource': resource,
                        'requestor': principal,
                        'message': request.POST.get('message')
                    }
                )
        except Exception, e:
            pass

        request.session['collapse'] = [resource.global_id]
        return redirect(reverse('manage-data') + "#" + str(resource.id))
コード例 #3
0
ファイル: views.py プロジェクト: VPH-Share/portal
def grant_role(request):
    """
        grant role to user or group
    """

    # if has_permission(request.user, "Manage sharing"):
    name = request.GET.get('name')
    role = Role.objects.get(name=request.GET.get('role'))
    resource = Resource.objects.get(global_id=request.GET.get('global_id'))

    principal = grant_permission(name, resource, role, request.ticket)

    # change request state if exists
    try:
        resource_request = ResourceRequest.objects.filter(requestor=principal, resource=resource)
        if resource_request.count() and is_request_pending(resource_request[0]):
            do_transition(resource_request[0], request_accept_transition, request.user)
            resource_request[0].delete()

            # alert requestor
            alert_user_by_email(
                mail_from='VPH-Share Webmaster <*****@*****.**>',
                mail_to='%s %s <%s>' % (principal.first_name, principal.last_name, principal.email),
                subject='[VPH-Share] Your request for sharing has been accepted',
                mail_template='request_for_sharing_accepted',
                dictionary={
                    'message': request.GET.get('requestmessage', ''),
                    'resource': resource,
                    'requestor': principal
                }
            )

    except ObjectDoesNotExist, e:
        pass
コード例 #4
0
ファイル: tests.py プロジェクト: GeoffreyOnRails/pydici
    def test_expense_wf(self):
        # Setup default workflow
        install_expense_workflow()

        ABR = Consultant.objects.get(trigramme="ABR")
        TCO = Consultant.objects.get(trigramme="TCO")
        tco = TCO.getUser()
        abr = ABR.getUser()
        fla = User.objects.get(username="******")
        category = ExpenseCategory.objects.create(name="repas")
        e = Expense.objects.create(user=tco, description="une grande bouffe",
                                   category=category, amount=123,
                                   creation_date=date.today(), expense_date=date.today())
        self.assertEqual(wf.get_state(e), None)
        wf.set_initial_state(e)
        self.assertNotEqual(wf.get_state(e), None)  # Now wf is setup

        # state = requested
        self.assertEqual(len(wf.get_allowed_transitions(e, tco)), 0)  # No transition allowed for user
        self.assertEqual(len(wf.get_allowed_transitions(e, fla)), 0)  # No transition allowed for paymaster
        self.assertEqual(len(wf.get_allowed_transitions(e, abr)), 2)  # But for his manager accept/reject

        # Reject it
        reject = Transition.objects.get(name="reject")
        self.assertTrue(wf.do_transition(e, reject, abr))
        for user in (tco, abr, fla):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed

        # Validate it
        wf.set_initial_state(e)  # Returns to requested state
        validate = Transition.objects.get(name="validate")
        self.assertTrue(wf.do_transition(e, validate, abr))
        for user in (tco, abr):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed
        self.assertEqual(len(wf.get_allowed_transitions(e, fla)), 2)  # Except paymaster accept/ask info

        # Ask information
        ask = Transition.objects.get(name="ask information")
        self.assertTrue(wf.do_transition(e, ask, fla))
        self.assertTrue(perm.has_permission(e, tco, "expense_edit"))
        wf.set_initial_state(e)  # Returns to requested state
        self.assertEqual(len(wf.get_allowed_transitions(e, tco)), 0)  # No transition allowed for user
        self.assertTrue(wf.do_transition(e, validate, abr))  # Validate it again

        # Check it
        control = Transition.objects.get(name="control")
        self.assertTrue(wf.do_transition(e, control, fla))
        for user in (tco, abr, fla):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed

        # Create a payment for that expense
        expensePayment = ExpensePayment(payment_date=date.today())
        expensePayment.save()
        e.expensePayment = expensePayment
        e.save()
        self.assertEqual(expensePayment.user(), tco)
        self.assertEqual(expensePayment.amount(), 123)
コード例 #5
0
ファイル: tests.py プロジェクト: agateau/pydici
    def test_expense_wf(self):
        # Setup default workflow
        install_expense_workflow()

        ABR = Consultant.objects.get(trigramme="ABR")
        TCO = Consultant.objects.get(trigramme="TCO")
        tco = TCO.getUser()
        abr = ABR.getUser()
        fla = User.objects.get(username="******")
        category = ExpenseCategory.objects.create(name="repas")
        e = Expense.objects.create(user=tco, description="une grande bouffe",
                                   category=category, amount=123,
                                   creation_date=date.today(), expense_date=date.today())
        self.assertEqual(wf.get_state(e), None)
        wf.set_initial_state(e)
        self.assertNotEqual(wf.get_state(e), None)  # Now wf is setup

        # state = requested
        self.assertEqual(len(wf.get_allowed_transitions(e, tco)), 0)  # No transition allowed for user
        self.assertEqual(len(wf.get_allowed_transitions(e, fla)), 0)  # No transition allowed for paymaster
        self.assertEqual(len(wf.get_allowed_transitions(e, abr)), 2)  # But for his manager accept/reject

        # Reject it
        reject = Transition.objects.get(name="reject")
        self.assertTrue(wf.do_transition(e, reject, abr))
        for user in (tco, abr, fla):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed

        # Validate it
        wf.set_initial_state(e)  # Returns to requested state
        validate = Transition.objects.get(name="validate")
        self.assertTrue(wf.do_transition(e, validate, abr))
        for user in (tco, abr):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed
        self.assertEqual(len(wf.get_allowed_transitions(e, fla)), 2)  # Except paymaster accept/ask info

        # Ask information
        ask = Transition.objects.get(name="ask information")
        self.assertTrue(wf.do_transition(e, ask, fla))
        self.assertTrue(perm.has_permission(e, tco, "expense_edit"))
        wf.set_initial_state(e)  # Returns to requested state
        self.assertEqual(len(wf.get_allowed_transitions(e, tco)), 0)  # No transition allowed for user
        self.assertTrue(wf.do_transition(e, validate, abr))  # Validate it again

        # Check it
        control = Transition.objects.get(name="control")
        self.assertTrue(wf.do_transition(e, control, fla))
        for user in (tco, abr, fla):
            self.assertEqual(len(wf.get_allowed_transitions(e, user)), 0)  # No transition allowed

        # Create a payment for that expense
        expensePayment = ExpensePayment(payment_date=date.today())
        expensePayment.save()
        e.expensePayment = expensePayment
        e.save()
        self.assertEqual(expensePayment.user(), tco)
        self.assertEqual(expensePayment.amount(), 123)
コード例 #6
0
ファイル: views.py プロジェクト: VPH-Share/portal
def manage_group_request(request):
    """
        accept or refuse an instution request
    """

    if request.method == 'POST':
        group_name = request.POST['group']
        group = get_group_by_name(group_name)

        if request.POST['operation'] == 'accept':
            do_transition(group, group_accept_subscription, request.user)
        else:
            do_transition(group, group_refuse_subscription, request.user)

        return redirect('/groups/%s/' % group.pk)
    return redirect('/groups/')
コード例 #7
0
def update_expense_state(request, expense_id, transition_id):
    """Do workflow transition for that expense"""
    redirect = HttpResponseRedirect(
        urlresolvers.reverse("expense.views.expenses"))
    try:
        expense = Expense.objects.get(id=expense_id)
        if expense.user == request.user and not perm.has_role(
                request.user, "expense administrator"):
            messages.add_message(request, messages.WARNING,
                                 _("You cannot manage your own expense !"))
            return redirect
    except Expense.DoesNotExist:
        messages.add_message(request, messages.WARNING,
                             _("Expense %s does not exist" % expense_id))
        return redirect
    try:
        transition = Transition.objects.get(id=transition_id)
    except Transition.DoesNotExist:
        messages.add_message(request, messages.ERROR,
                             _("Transition %s does not exist" % transition_id))
        return redirect

    if wf.do_transition(expense, transition, request.user):
        messages.add_message(request, messages.SUCCESS,
                             _("Successfully update expense"))
    else:
        messages.add_message(request, messages.ERROR,
                             _("You cannot do this transition"))
    return redirect
コード例 #8
0
ファイル: models.py プロジェクト: j2a/odesk-sprints
 def do_transition(self, transition=None, user=None):
     if user is None:
         user = self.owner
     if isinstance(transition, int):
         try:
             transition = workflows.Transition.objects.get(id=transition)
         except workflows.Transition.DoesNotExist:
             raise ValueError("There is no transition with id %s"
                              % transition)
     if transition is None:
         possible = self.state.get_allowed_transitions(self, user)
         if len(possible) == 0:
             raise ValueError("There is no any possible transitions "
                              "for %r" % self)
         elif len(possible) > 1:
             raise ValueError("Transition is not defined and there are "
                              "many possible transitions for %r" % self)
         transition = possible[0]
     utils.do_transition(self, transition, user)
コード例 #9
0
ファイル: views.py プロジェクト: VPH-Share/portal
def newshare(request):
    if request.method == 'POST':
        input = request.POST.getlist('Usersinput')
        resource = Resource.objects.get(global_id=request.POST.get('resource'))
        roles = []
        if request.POST.get('editor', None):
            roles.append(request.POST.get('editor', None))
        if request.POST.get('reader', None):
            roles.append(request.POST.get('reader', None))
        if request.POST.get('manager', None):
            roles.append(request.POST.get('manager', None))
        if len(roles) > 0:
            for usergroup in input:
                splitted = usergroup.split('_')[0]
                name = usergroup.replace(splitted + '_', '')
                for role in roles:
                    role = Role.objects.get(name=role)
                    principal = grant_permission(name, resource, role, request.ticket)
                    try:
                        resource_request = ResourceRequest.objects.filter(requestor=principal, resource=resource)
                        if resource_request.count() and is_request_pending(resource_request[0]):
                            do_transition(resource_request[0], request_accept_transition, request.user)
                            resource_request[0].delete()

                            # alert requestor
                            alert_user_by_email(
                                mail_from='VPH-Share Webmaster <*****@*****.**>',
                                mail_to='%s %s <%s>' % (principal.first_name, principal.last_name, principal.email),
                                subject='[VPH-Share] New resource shared with you',
                                mail_template='new_share',
                                dictionary={
                                    'resource': resource,
                                    'requestor': principal
                                }
                            )
                    except Exception, e:
                        pass
            request.session['collapse'] = [resource.global_id]
            return redirect(reverse('manage-data') + "#" + str(resource.id))
コード例 #10
0
ファイル: views.py プロジェクト: qt-pay/husky
    def post(self, request, version):
        result = {'code': 0, 'msg': '请求成功', 'data': {}}
        try:
            with transaction.atomic():
                approve_user = request.user
                raw_data = request.data
                wse_id = raw_data.get('wse_id')
                wse = WorkflowStateEvent.objects.get(pk=wse_id)
                dev_content = raw_data.get('dev_content', '')
                code_merge = raw_data.get('code_merge', '')
                # 如果有研发人员填写内容,则需要保存
                if dev_content:
                    wse.content_object.dev_content = dev_content
                if code_merge:
                    wse.content_object.code_merge = code_merge
                wse.content_object.save(
                    update_fields=['dev_content', 'code_merge'])
                # 审批权限检验
                success, msg = check_approve_perm(wse, approve_user)
                if not success:
                    raise Exception(msg)
                # 流程流转
                select = raw_data.get('select')
                opinion = raw_data.get('opinion', None)
                success, msg, new_wse = do_transition(wse, select, opinion,
                                                      approve_user)
                if success:
                    # 关联新审批人
                    relate_approve_user_to_wse(new_wse.state,
                                               new_wse.content_object, new_wse)
                    if new_wse.users.all():
                        # 发送钉钉通知给下一批审批人员
                        pass
                    else:
                        # 工单审批完成,继续下一步操作
                        pass
                else:
                    raise Exception(msg)

        except WorkflowStateEvent.DoesNotExist as e:
            result = {'code': 500, 'msg': str(e), 'data': {}}
        except PermissionError:
            result = {'code': 403, 'msg': '权限受限', 'data': {}}
        except IntegrityError:
            result = {'code': 200, 'msg': '记录重复', 'data': {}}
        except Exception as e:
            result = {'code': 500, 'msg': str(e), 'data': {}}
        finally:
            return JsonResponse(result)
コード例 #11
0
ファイル: views.py プロジェクト: VPH-Share/portal
def subscribe(request, idGroup=None, idStudy=None, iduser=None):
    """
        create a subscription_pending subscription to an institution
    """

    if request.method == 'POST':

        if idStudy is not None:
            group, gtype = get_group_by_id(idStudy)
        else:
            group, gtype = get_group_by_id(idGroup)

        if iduser is None:
            subscription = SubscriptionRequest(user=request.user, group=group)
            subscription.save()
            set_workflow(subscription, SubscriptionRequestWorkflow)
            set_state(subscription, subscription_pending)

        elif request.user in group.managers.all():
            user = User.objects.get(pk=iduser)
            subscription = SubscriptionRequest.objects.get(user=user, group=group)

            if request.POST['operation'] == 'accept':
                if do_transition(subscription, subscription_accept_subscription, request.user):
                    group.user_set.add(user)
                    subscription.delete()
            else:
                do_transition(subscription, subscription_refuse_subscription, request.user)
                subscription.delete()

        if gtype == 1:
            return redirect('/groups/%s/%s/' % (idGroup, idStudy))
        else:
            return redirect('/groups/%s/' % idGroup)

    return redirect('/groups')
コード例 #12
0
def submit(request, token):
    '''
        This will submit a given token for approval
        In order to do this, you must have the submit permission for the token otherwise you will get a nasty 403 Fobidden error.
    
    '''
    #get or 404 the token
    token_object = get_object_or_404(Token,pk=token)
    
    
    #attempt the token_submission transition, if not allowed raise permissiondenied!
    if not do_transition(token_object, 'token_submission', request.user):
        raise PermissionDenied()
    
    #set the object state to awaiting_approval
    
    return HttpResponseRedirect(reverse('home_view'))
コード例 #13
0
ファイル: views.py プロジェクト: bport/pydici
def update_expense_state(request, expense_id, transition_id):
    """Do workflow transition for that expense"""
    redirect = HttpResponseRedirect(urlresolvers.reverse("expense.views.expenses"))
    try:
        expense = Expense.objects.get(id=expense_id)
        if expense.user == request.user and not perm.has_role(request.user, "expense administrator"):
            messages.add_message(request, messages.WARNING, _("You cannot manage your own expense !"))
            return redirect
    except Expense.DoesNotExist:
        messages.add_message(request, messages.WARNING, _("Expense %s does not exist" % expense_id))
        return redirect
    try:
        transition = Transition.objects.get(id=transition_id)
    except Transition.DoesNotExist:
        messages.add_message(request, messages.ERROR, _("Transition %s does not exist" % transition_id))
        return redirect

    if wf.do_transition(expense, transition, request.user):
        messages.add_message(request, messages.SUCCESS, _("Successfully update expense"))
    else:
        messages.add_message(request, messages.ERROR, _("You cannot do this transition"))
    return redirect
コード例 #14
0
def evaluate_application_form(request, ethics_application_id, approved=False):
    '''
        This view will attempt to transition the ethics application to the 
        correct state depending on whether the approved flag is True, in which
        case it will have the Approved trnsition applied, otherwise it will have the 
        reject transition applied. All of this is dependent on the requesting user having
        the appropriate permissions to perform these transitions.
    '''
    ethics_application = get_object_or_404(EthicsApplication, pk=ethics_application_id)
    
    if approved:
        transition = 'approve'
        signal = application_accepted_by_reviewer
    else:
        transition = 'reject'
        signal = application_rejected_by_reviewer
    if not do_transition(ethics_application, transition, request.user):
        raise PermissionDenied()
    
    signal.send(None, application=ethics_application, reviewer=request.user)
    
    return HttpResponseRedirect(reverse('index_view'))
コード例 #15
0
def update_expense_state(request, expense_id, transition_id):
    """Do workflow transition for that expense."""
    error = False
    message = ""

    try:
        expense = Expense.objects.get(id=expense_id)
        if expense.user == request.user and not utils.has_role(request.user, "expense administrator"):
            message =  _("You cannot manage your own expense !")
            error = True
    except Expense.DoesNotExist:
        message =  _("Expense %s does not exist" % expense_id)
        error = True

    if not error:
        try:
            transition = Transition.objects.get(id=transition_id)
        except Transition.DoesNotExist:
            message = ("Transition %s does not exist" % transition_id)
            error = True

        if wf.do_transition(expense, transition, request.user):
            message = _("Successfully update expense")

            # Prune expense in terminal state (no more transition) and without payment (ie paid ith corporate card)
            # Expense that need to be paid are pruned during payment process.
            if expense.corporate_card and wf.get_state(expense).transitions.count() == 0:
                expense.workflow_in_progress = False
                expense.save()
        else:
            message = _("You cannot do this transition")
            error = True

    response = {"message": message,
                "expense_id": expense_id,
                "error": error}

    return HttpResponse(json.dumps(response), content_type="application/json")
コード例 #16
0
ファイル: models.py プロジェクト: aithonaltis/gasistafelice
 def do_transition(self, transition, user):
     return do_transition(self, transition, user)
コード例 #17
0
ファイル: utils.py プロジェクト: scsi110/mes-1
def productionline_do_transition(user,productionline,status):
    # import pdb; pdb.set_trace()
    result = 0

    #set current_operation_record status
    current_operation_record = productionline.current_operation_record
    current_operation_record.status = status
    current_operation_record.save()
    # logger.info(current_operation_record.status)

    transitions = get_allowed_transitions(productionline,user)
    # logger.info(transitions)
    if len(transitions) > 0:
        do_transition(productionline,transitions[0],user)

        #get current_operation_record
        current_state = get_state(productionline)
        for oper_group_record in productionline.oper_group_records.all():
            for operation_record in oper_group_record.operation_records.all():
                if operation_record.operation.state == current_state:
                    current_operation_record = operation_record

        #set productionline current_operation_record
        productionline.current_operation_record = current_operation_record
        productionline.save()

        #set current_operation_record status
        productionline.current_operation_record.status = 2
        productionline.current_operation_record.save()

        #set parent_operation_record status
        parent_operation_record = current_operation_record.parent_operation_record
        if parent_operation_record.status == 1:
            parent_operation_record.status = 2
            parent_operation_record.save()

        #set manufacture_item.status
        for manufacture_item in productionline.manufacture_items.all():
            manufacture_item.status = 2
            manufacture_item.save()


        #parent_productionline do_transition
        parent_productionline = productionline.parent_productionline
        order_code = parent_productionline.current_operation_record.order_code
        can_do_parent_transition_tag = True
        for mig in parent_productionline.manu_item_groups.all():
            for mi in mig.manufacture_items.all():
                if mi.current_operation_record.order_code <= order_code:
                    can_do_parent_transition_tag = False
        if can_do_parent_transition_tag:
            #set parent_current_operation_record status
            parent_current_operation_record = parent_productionline.current_operation_record
            parent_current_operation_record.status = status
            parent_current_operation_record.save()
            #do_transition
            parent_transitions = get_allowed_transitions(parent_productionline,user)
            if len(parent_transitions) > 0:
                do_transition(parent_productionline,parent_transitions[0],user)
                #get parent_current_operation_record
                current_state = get_state(parent_productionline)
                for oper_group_record in parent_productionline.oper_group_records.all():
                    for operation_record in oper_group_record.operation_records.all():
                        if operation_record.operation.state == current_state:
                            parent_current_operation_record = operation_record
                #set parent_current_operation_record status
                parent_productionline.current_operation_record = parent_current_operation_record
                parent_productionline.save()
                #set parent_current_operation_record status
                parent_productionline.current_operation_record.status = 2
                parent_productionline.current_operation_record.save()
            else:
                #do parent_productionline finish
                parent_productionline.state = 3
                parent_productionline.save()
                return 0
    else:
        #do parent_productionline finish
        productionline.state = 3
        productionline.save()
        
        parent_productionline = productionline.parent_productionline
        can_do_parent_transition_tag = True
        for mig in parent_productionline.manu_item_groups.all():
            for mi in mig.manufacture_items.all():
                if mi.productionline.state != 3:
                    can_do_parent_transition_tag = False
        if can_do_parent_transition_tag:
            #set parent_current_operation_record status
            parent_current_operation_record = parent_productionline.current_operation_record
            parent_current_operation_record.status = status
            parent_current_operation_record.save()
            #do parent_productionline finish
            parent_productionline.state = 3
            parent_productionline.save()
            return 0
        return 0
    return result
コード例 #18
0
ファイル: models.py プロジェクト: susheel/vphshare
 def accept(self, initiator):
     if do_transition(self, request_accept_transition, initiator):
         # grant Reader role to the requestor
         add_local_role(self.resource, self.requestor, resource_reader)
コード例 #19
0
def submit_for_review(request, ethics_application_id):
    '''
        This view will ascertain if the submit_for_review transition can be
        carried out on the specified ethicsApplication, by the logged in user.
        If any of the following goes wrong then a forbidden exception will be raised:
        1.User is not logged in
        2.User does not have the submit permission for this application
        3.The transition is not allowed
    '''
    ethics_application = get_object_or_404(EthicsApplication, pk=ethics_application_id)
    
    if not request.user.is_authenticated() or not has_permission(ethics_application, request.user, 'submit') or not do_transition(ethics_application, 'submit_for_review', request.user):
        raise PermissionDenied()
    
    reviewer = Committee.objects.get_next_free_reviewer()
    ethics_application.assign_reviewer(reviewer)
    
    application_submitted_for_review.send(None, application=ethics_application, reviewer=reviewer)
    return HttpResponseRedirect(reverse('index_view'))
コード例 #20
0
ファイル: order.py プロジェクト: domthu/gasistafelice
 def forward(self, user):
     """Apply default transition"""
     state = get_state(self)
     transition = DefaultTransition.objects.get(workflow=self.workflow, state=state).transition
     do_transition(self, transition, user)
コード例 #21
0
 def forward(self, user):
     """Apply default transition"""
     state = get_state(self)
     transition = DefaultTransition.objects.get(workflow=self.workflow,
                                                state=state).transition
     do_transition(self, transition, user)