# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render, get_object_or_404
from django.core.exceptions import PermissionDenied

from coin.billing.models import Invoice


def get_invoice_from_id_or_number(id):
    """
    Return an invoice using id as invoice id or failing as invoice number
    """
    try:
        return Invoice.objects.get(pk=id)
    except:
        return get_object_or_404(Invoice, number=id)


def assert_user_can_view_the_invoice(request, invoice):
    """
    Raise PermissionDenied if logged user can't access given invoice
    """
    if not invoice.has_owner(request.user.username)\
       and not request.user.is_superuser:
        raise PermissionDenied