Esempio n. 1
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
Esempio n. 2
0
def expense_receipt(request, expense_id):
    """Returns expense receipt if authorize to"""
    response = HttpResponse()
    try:
        expense = Expense.objects.get(id=expense_id)
        if expense.user == request.user or\
           perm.has_role(request.user, "expense paymaster") or\
           perm.has_role(request.user, "expense manager"):
            if expense.receipt:
                response['Content-Type'] = mimetypes.guess_type(expense.receipt.name)[0] or "application/stream"
                for chunk in expense.receipt.chunks():
                    response.write(chunk)
    except (Expense.DoesNotExist, OSError):
        pass

    return response
Esempio n. 3
0
def expenses_history(request):
    """Display expense history.
    @param year: year of history. If None, display recent items and year index"""
    expenses = Expense.objects.all().select_related().prefetch_related(
        "clientbill_set", "user", "lead")
    try:
        consultant = Consultant.objects.get(
            trigramme__iexact=request.user.username)
        user_team = consultant.userTeam()
    except Consultant.DoesNotExist:
        user_team = []

    if not perm.has_role(request.user, "expense paymaster"):
        expenses = expenses.filter(
            Q(user=request.user) | Q(user__in=user_team))

    expenseTable = ExpenseTable(expenses, orderable=True)
    RequestConfig(request, paginate={"per_page": 50}).configure(expenseTable)

    if "csv" in request.GET:
        return tableToCSV(expenseTable, filename="expenses.csv")

    return render(request, "expense/expense_archive.html", {
        "expense_table": expenseTable,
        "user": request.user
    })
Esempio n. 4
0
def expense_receipt(request, expense_id):
    """Returns expense receipt if authorize to"""
    response = HttpResponse()
    try:
        expense = Expense.objects.get(id=expense_id)
        if expense.user == request.user or\
           perm.has_role(request.user, "expense paymaster") or\
           perm.has_role(request.user, "expense manager"):
            if expense.receipt:
                response['Content-Type'] = mimetypes.guess_type(
                    expense.receipt.name)[0] or "application/stream"
                for chunk in expense.receipt.chunks():
                    response.write(chunk)
    except (Expense.DoesNotExist, OSError):
        pass

    return response
Esempio n. 5
0
def expense_payment_detail(request, expense_payment_id):
    """Display detail of this expense payment"""
    if not request.user.groups.filter(name="expense_requester").exists():
        return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
    try:
        if expense_payment_id:
            expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
        if not (expensePayment.user() == request.user or\
           perm.has_role(request.user, "expense paymaster") or\
           perm.has_role(request.user, "expense manager")):
            return HttpResponseRedirect(urlresolvers.reverse("forbiden"))

    except ExpensePayment.DoesNotExist:
        messages.add_message(request, messages.ERROR, _("Expense payment %s does not exist" % expense_payment_id))
        return redirect(expense_payments)

    return render(request, "expense/expense_payment_detail.html",
                  {"expense_payment": expensePayment,
                   "expense_table": ExpenseTable(expensePayment.expense_set.all()),
                   "user": request.user})
Esempio n. 6
0
def expense_payment_detail(request, expense_payment_id):
    """Display detail of this expense payment"""
    if not request.user.groups.filter(name="expense_requester").exists():
        return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
    try:
        if expense_payment_id:
            expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
        if not (expensePayment.user() == request.user or\
           perm.has_role(request.user, "expense paymaster") or\
           perm.has_role(request.user, "expense manager")):
            return HttpResponseRedirect(urlresolvers.reverse("forbiden"))

    except ExpensePayment.DoesNotExist:
        messages.add_message(
            request, messages.ERROR,
            _("Expense payment %s does not exist" % expense_payment_id))
        return redirect(expense_payments)

    return render(
        request, "expense/expense_payment_detail.html", {
            "expense_payment": expensePayment,
            "expense_table": ExpenseTable(expensePayment.expense_set.all()),
            "user": request.user
        })
Esempio n. 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
Esempio n. 8
0
def expenses_history(request):
    """Display expense history.
    @param year: year of history. If None, display recent items and year index"""
    expenses = Expense.objects.all().select_related().prefetch_related("clientbill_set", "user", "lead")
    try:
        consultant = Consultant.objects.get(trigramme__iexact=request.user.username)
        user_team = consultant.userTeam()
    except Consultant.DoesNotExist:
        user_team = []

    if not perm.has_role(request.user, "expense paymaster"):
        expenses = expenses.filter(Q(user=request.user) | Q(user__in=user_team))

    expenseTable = ExpenseTable(expenses, orderable=True)
    RequestConfig(request, paginate={"per_page": 50}).configure(expenseTable)

    if "csv" in request.GET:
        return tableToCSV(expenseTable, filename="expenses.csv")

    return render(request, "expense/expense_archive.html",
                  {"expense_table": expenseTable,
                   "user": request.user})
Esempio n. 9
0
def can_edit_dataset(request, dataset_id):
    """
    Может ли пользователь редактировать набор данных.

    @param dataset_id: идентификатор набора данных
    """
    try:
        admin_role = Role.objects.get(name=settings.ROLE_ADMIN_NAME)
        if has_role(request.user, admin_role):
            #logging.getLogger(__name__).info(u"Пользователь является администратором, может редактировать набор данных!")
            return {'canEdit': True}

        for dataset in get_datasets(request.user,
                                    settings.PERMISSION_EDIT_NAME):
            if dataset.id == dataset_id:
                return {'canEdit': True}
    except Exception as ex:
        traceback.print_exc(file=sys.stdout)
        return {'canEdit': False, 'message': unicode(ex)}

    return {
        'canEdit': False,
        'message': u"У вас нет прав редактировать набор данных"
    }
Esempio n. 10
0
def expenses(request, expense_id=None):
    """Display user expenses and expenses that he can validate"""
    if not request.user.groups.filter(name="expense_requester").exists():
        return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
    try:
        consultant = Consultant.objects.get(trigramme__iexact=request.user.username)
        user_team = consultant.userTeam(excludeSelf=False)
    except Consultant.DoesNotExist:
        user_team = []

    try:
        if expense_id:
            expense = Expense.objects.get(id=expense_id)
            if not (perm.has_permission(expense, request.user, "expense_edit")
                    and (expense.user == request.user or expense.user in user_team)):
                messages.add_message(request, messages.WARNING, _("You are not allowed to edit that expense"))
                expense_id = None
                expense = None
    except Expense.DoesNotExist:
        messages.add_message(request, messages.ERROR, _("Expense %s does not exist" % expense_id))
        expense_id = None

    if request.method == "POST":
        if expense_id:
            form = ExpenseForm(request.POST, request.FILES, instance=expense)
        else:
            form = ExpenseForm(request.POST, request.FILES)
        if form.is_valid():
            expense = form.save(commit=False)
            if not hasattr(expense, "user"):
                # Don't update user if defined (case of expense updated by manager or adminstrator)
                expense.user = request.user
            expense.creation_date = date.today()
            expense.save()
            wf.set_initial_state(expense)
            return HttpResponseRedirect(urlresolvers.reverse("expense.views.expenses"))
    else:
        if expense_id:
            form = ExpenseForm(instance=expense)  # A form that edit current expense
        else:
            form = ExpenseForm(initial={"expense_date": date.today()})  # An unbound form

    # Get user expenses
    user_expenses = Expense.objects.filter(user=request.user, workflow_in_progress=True).select_related()

    if user_team:
        team_expenses = Expense.objects.filter(user__in=user_team, workflow_in_progress=True).select_related()
    else:
        team_expenses = []

    # Paymaster manage all expenses
    if perm.has_role(request.user, "expense paymaster"):
        managed_expenses = Expense.objects.filter(workflow_in_progress=True).exclude(user=request.user).select_related()
    else:
        managed_expenses = team_expenses

    userExpenseTable = UserExpenseWorkflowTable(user_expenses)
    userExpenseTable.transitionsData = dict([(e.id, []) for e in user_expenses])  # Inject expense allowed transitions. Always empty for own expense
    userExpenseTable.expenseEditPerm = dict([(e.id, perm.has_permission(e, request.user, "expense_edit")) for e in user_expenses])  # Inject expense edit permissions
    RequestConfig(request, paginate={"per_page": 50}).configure(userExpenseTable)

    managedExpenseTable = ManagedExpenseWorkflowTable(managed_expenses)
    managedExpenseTable.transitionsData = dict([(e.id, e.transitions(request.user)) for e in managed_expenses])  # Inject expense allowed transitions
    managedExpenseTable.expenseEditPerm = dict([(e.id, perm.has_permission(e, request.user, "expense_edit")) for e in managed_expenses])  # Inject expense edit permissions
    RequestConfig(request, paginate={"per_page": 50}).configure(managedExpenseTable)

    return render(request, "expense/expenses.html",
                  {"user_expense_table": userExpenseTable,
                   "managed_expense_table": managedExpenseTable,
                   "modify_expense": bool(expense_id),
                   "form": form,
                   "user": request.user})
Esempio n. 11
0
def expense_payments(request, expense_payment_id=None):
    readOnly = False
    if not request.user.groups.filter(name="expense_paymaster").exists() and not request.user.is_superuser:
        readOnly = True
    try:
        if expense_payment_id:
            expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
    except ExpensePayment.DoesNotExist:
        messages.add_message(request, messages.ERROR, _("Expense payment %s does not exist" % expense_payment_id))
        expense_payment_id = None
        expensePayment = None

    if readOnly:
        expensesToPay = []
    else:
        expensesToPay = Expense.objects.filter(workflow_in_progress=True, corporate_card=False, expensePayment=None)
        expensesToPay = [expense for expense in expensesToPay if wf.get_state(expense).transitions.count() == 0]

    try:
        consultant = Consultant.objects.get(trigramme__iexact=request.user.username)
        user_team = consultant.userTeam()
    except Consultant.DoesNotExist:
        user_team = []

    expensePayments = ExpensePayment.objects.all()
    if not perm.has_role(request.user, "expense paymaster"):
        expensePayments = expensePayments.filter(Q(expense__user=request.user) | Q(expense__user__in=user_team)).distinct()

    if request.method == "POST":
        if readOnly:
            # A bad user is playing with urls...
            return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
        form = ExpensePaymentForm(request.POST)
        if form.is_valid():
            if expense_payment_id:
                expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
            else:
                expensePayment = ExpensePayment(payment_date=form.cleaned_data["payment_date"])
                expensePayment.save()
            for expense in Expense.objects.filter(expensePayment=expensePayment):
                expense.expensePayment = None  # Remove any previous association
                expense.save()
            if form.cleaned_data["expenses"]:
                for expense_id in form.cleaned_data["expenses"]:
                    expense = Expense.objects.get(id=expense_id)
                    expense.expensePayment = expensePayment
                    expense.workflow_in_progress = False
                    expense.save()

            return HttpResponseRedirect(urlresolvers.reverse("expense.views.expense_payments"))
    else:
        if expense_payment_id:
            form = ExpensePaymentForm({"expenses": "|".join([str(e.id) for e in Expense.objects.filter(expensePayment=expensePayment)]), "payment_date": expensePayment.payment_date})  # A form that edit current expense payment
        else:
            form = ExpensePaymentForm(initial={"payment_date": date.today()})  # An unbound form

    return render(request, "expense/expense_payments.html",
                  {"modify_expense_payment": bool(expense_payment_id),
                   "expense_payment_table": ExpensePaymentTable(expensePayments),
                   "expense_to_pay_table": ExpenseTable(expensesToPay),
                   "read_only": readOnly,
                   "form": form,
                   "user": request.user})
Esempio n. 12
0
def expenses(request, expense_id=None):
    """Display user expenses and expenses that he can validate"""
    if not request.user.groups.filter(name="expense_requester").exists():
        return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
    try:
        consultant = Consultant.objects.get(
            trigramme__iexact=request.user.username)
        user_team = consultant.userTeam(excludeSelf=False)
    except Consultant.DoesNotExist:
        user_team = []

    try:
        if expense_id:
            expense = Expense.objects.get(id=expense_id)
            if not (perm.has_permission(expense, request.user, "expense_edit")
                    and (expense.user == request.user
                         or expense.user in user_team)):
                messages.add_message(
                    request, messages.WARNING,
                    _("You are not allowed to edit that expense"))
                expense_id = None
                expense = None
    except Expense.DoesNotExist:
        messages.add_message(request, messages.ERROR,
                             _("Expense %s does not exist" % expense_id))
        expense_id = None

    if request.method == "POST":
        if expense_id:
            form = ExpenseForm(request.POST, request.FILES, instance=expense)
        else:
            form = ExpenseForm(request.POST, request.FILES)
        if form.is_valid():
            expense = form.save(commit=False)
            if not hasattr(expense, "user"):
                # Don't update user if defined (case of expense updated by manager or adminstrator)
                expense.user = request.user
            expense.creation_date = date.today()
            expense.save()
            wf.set_initial_state(expense)
            return HttpResponseRedirect(
                urlresolvers.reverse("expense.views.expenses"))
    else:
        if expense_id:
            form = ExpenseForm(
                instance=expense)  # A form that edit current expense
        else:
            form = ExpenseForm(initial={"expense_date":
                                        date.today()})  # An unbound form

    # Get user expenses
    user_expenses = Expense.objects.filter(
        user=request.user, workflow_in_progress=True).select_related()

    if user_team:
        team_expenses = Expense.objects.filter(
            user__in=user_team, workflow_in_progress=True).select_related()
    else:
        team_expenses = []

    # Paymaster manage all expenses
    if perm.has_role(request.user, "expense paymaster"):
        managed_expenses = Expense.objects.filter(
            workflow_in_progress=True).exclude(
                user=request.user).select_related()
    else:
        managed_expenses = team_expenses

    userExpenseTable = UserExpenseWorkflowTable(user_expenses)
    userExpenseTable.transitionsData = dict([
        (e.id, []) for e in user_expenses
    ])  # Inject expense allowed transitions. Always empty for own expense
    userExpenseTable.expenseEditPerm = dict([
        (e.id, perm.has_permission(e, request.user, "expense_edit"))
        for e in user_expenses
    ])  # Inject expense edit permissions
    RequestConfig(request, paginate={
        "per_page": 50
    }).configure(userExpenseTable)

    managedExpenseTable = ManagedExpenseWorkflowTable(managed_expenses)
    managedExpenseTable.transitionsData = dict([
        (e.id, e.transitions(request.user)) for e in managed_expenses
    ])  # Inject expense allowed transitions
    managedExpenseTable.expenseEditPerm = dict([
        (e.id, perm.has_permission(e, request.user, "expense_edit"))
        for e in managed_expenses
    ])  # Inject expense edit permissions
    RequestConfig(request, paginate={
        "per_page": 50
    }).configure(managedExpenseTable)

    # Prune old 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.
    for expense in Expense.objects.filter(workflow_in_progress=True,
                                          corporate_card=True,
                                          update_date__lt=(date.today() -
                                                           timedelta(30))):
        if wf.get_state(expense).transitions.count() == 0:
            expense.workflow_in_progress = False
            expense.save()

    # And prune every expense not updated since 180 days. For instance, rejected expense.
    for expense in Expense.objects.filter(workflow_in_progress=True,
                                          update_date__lt=(date.today() -
                                                           timedelta(180))):
        if wf.get_state(expense).transitions.count() == 0:
            expense.workflow_in_progress = False
            expense.save()

    return render(
        request, "expense/expenses.html", {
            "user_expense_table": userExpenseTable,
            "managed_expense_table": managedExpenseTable,
            "modify_expense": bool(expense_id),
            "form": form,
            "user": request.user
        })
Esempio n. 13
0
def expense_payments(request, expense_payment_id=None):
    readOnly = False
    if not request.user.groups.filter(name="expense_paymaster").exists(
    ) and not request.user.is_superuser:
        readOnly = True
    try:
        if expense_payment_id:
            expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
    except ExpensePayment.DoesNotExist:
        messages.add_message(
            request, messages.ERROR,
            _("Expense payment %s does not exist" % expense_payment_id))
        expense_payment_id = None
        expensePayment = None

    if readOnly:
        expensesToPay = []
    else:
        expensesToPay = Expense.objects.filter(workflow_in_progress=True,
                                               corporate_card=False,
                                               expensePayment=None)
        expensesToPay = [
            expense for expense in expensesToPay
            if wf.get_state(expense).transitions.count() == 0
        ]

    try:
        consultant = Consultant.objects.get(
            trigramme__iexact=request.user.username)
        user_team = consultant.userTeam()
    except Consultant.DoesNotExist:
        user_team = []

    expensePayments = ExpensePayment.objects.all()
    if not perm.has_role(request.user, "expense paymaster"):
        expensePayments = expensePayments.filter(
            Q(expense__user=request.user)
            | Q(expense__user__in=user_team)).distinct()

    if request.method == "POST":
        if readOnly:
            # A bad user is playing with urls...
            return HttpResponseRedirect(urlresolvers.reverse("forbiden"))
        form = ExpensePaymentForm(request.POST)
        if form.is_valid():
            if expense_payment_id:
                expensePayment = ExpensePayment.objects.get(
                    id=expense_payment_id)
                expensePayment.payment_date = form.cleaned_data["payment_date"]
            else:
                expensePayment = ExpensePayment(
                    payment_date=form.cleaned_data["payment_date"])
            expensePayment.save()
            for expense in Expense.objects.filter(
                    expensePayment=expensePayment):
                expense.expensePayment = None  # Remove any previous association
                expense.save()
            if form.cleaned_data["expenses"]:
                for expense in form.cleaned_data["expenses"]:
                    expense.expensePayment = expensePayment
                    expense.workflow_in_progress = False
                    expense.save()
            return HttpResponseRedirect(
                urlresolvers.reverse("expense.views.expense_payments"))
        else:
            print "form is not valid"

    else:
        if expense_payment_id:
            expensePayment = ExpensePayment.objects.get(id=expense_payment_id)
            form = ExpensePaymentForm({
                "expenses":
                list(Expense.objects.filter(expensePayment=expensePayment)),
                "payment_date":
                expensePayment.payment_date
            })  # A form that edit current expense payment
        else:
            form = ExpensePaymentForm(initial={"payment_date": date.today()
                                               })  # An unbound form

    return render(
        request, "expense/expense_payments.html", {
            "modify_expense_payment": bool(expense_payment_id),
            "expense_payment_table": ExpensePaymentTable(expensePayments),
            "expense_to_pay_table": ExpenseTable(expensesToPay),
            "read_only": readOnly,
            "form": form,
            "user": request.user
        })