def generate_credit_note(self, request, queryset):
    last_credite_note_created = None
    for invoice in queryset.all():
        if invoice.is_credit_note:
            messages.add_message(request, messages.ERROR,
                                 _(u"You cannot create a credit note for "
                                   u"a credit note! (%s)" %
                                   invoice.invoice_id))
            continue
        try:
            invoice.credit_note
            messages.add_message(request, messages.ERROR,
                                 _(u"This invoice has already a credit "
                                   u"note a credit note! (%s)" %
                                   invoice.invoice_id))
            continue
        except:
            pass
        credit_note = Invoice(recipient=invoice.recipient,
                              is_credit_note=True,
                              invoice_related=invoice,
                              invoice_cost_code=invoice.invoice_cost_code)
        credit_note.save()
        last_credite_note_created = credit_note
        for invoice_item in invoice.items.all():
            item = InvoiceItem(invoice=credit_note,
                               description=invoice_item.description,
                               unit_price=invoice_item.unit_price,
                               quantity=invoice_item.quantity)
            item.save()
    if last_credite_note_created:
        change_url = urlresolvers.reverse(
            'admin:invoice_invoice_change',
            args=(last_credite_note_created.pk,))
        return redirect(change_url)
def generate_credit_note(self, request, queryset):
    last_credite_note_created = None
    for invoice in queryset.all():
        if invoice.is_credit_note:
            messages.add_message(
                request, messages.ERROR,
                _(u"You cannot create a credit note for "
                  u"a credit note! (%s)" % invoice.invoice_id))
            continue
        try:
            invoice.credit_note
            messages.add_message(
                request, messages.ERROR,
                _(u"This invoice has already a credit "
                  u"note a credit note! (%s)" % invoice.invoice_id))
            continue
        except:
            pass
        credit_note = Invoice(recipient=invoice.recipient,
                              is_credit_note=True,
                              invoice_related=invoice,
                              invoice_cost_code=invoice.invoice_cost_code)
        credit_note.save()
        last_credite_note_created = credit_note
        for invoice_item in invoice.items.all():
            item = InvoiceItem(invoice=credit_note,
                               description=invoice_item.description,
                               unit_price=invoice_item.unit_price,
                               quantity=invoice_item.quantity)
            item.save()
    if last_credite_note_created:
        change_url = urlresolvers.reverse(
            'admin:invoice_invoice_change',
            args=(last_credite_note_created.pk, ))
        return redirect(change_url)
Ejemplo n.º 3
0
    def create(self, validated_data):
        items = validated_data.pop('items')
        invoice = Invoice(**validated_data)
        invoice.save()

        for item in items:
            ProductInvoice.objects.create(invoice=invoice, **item)
        return invoice
Ejemplo n.º 4
0
    def post(self, customer_id):
        """
        bills the customers current open cart

        --Bills the current open cart for customer
        --Create Invoice Record and Invoice Line Item Records
        --Automatically applies giftcard and credits
        --closes cart as 'billed'
        --store.credit_order_preference: determines if credits are giftcards are applied first
        """

        customer = Customer.get_customer(customer_id=customer_id, request=request)
        store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        cart = Cart.objects.filter(customer_id=customer_id, invoice_created_at=None, closed_at=None).first()

        if cart is None:
            return jsonify({"error": NO_OPEN_CART}), 404

        invoice = Invoice(
            invoice_id=str(uuid.uuid4().int),
            customer=customer,
            cart=cart
        ).save()

        invoice.create_invoice_line_items()

        if "coupon" in request.args:
            coupon = CouponCode.objects.filter(code=request.args.get("coupon"), store=store).first()
            if coupon is None:
                return jsonify({"error": "coupon code not found"}), 404

            redemption = coupon.redeem(invoice=invoice)

            if redemption is None:
                return jsonify({"error": "coupon code not found"}), 404

        if store.credit_order_preference == "credit":
            self.apply_credits(customer, invoice)
            self.apply_gift_cards(customer, invoice)
        else:
            self.apply_gift_cards(customer, invoice)
            self.apply_credits(customer, invoice)

        cart.state = "billed"
        cart.invoice_created_at = datetime.now()
        cart.save()

        response = {
            "result": "ok",
            "invoice": invoice_obj(invoice)
        }
        return jsonify(response), 201
def view_save_invoice(request, lu):
    reservation = lu['reservation']
    invoice_no = lu['invoice_no']
    datestring = reservation.start_datetime.strftime("%Y%m%d_%H%M")
    filename = "%s_%s.pdf" % (datestring, reservation.user.get_user_initials())
    html = render_to_string('reservation_history/view_download_pdf.html',
                            lu, context_instance=RequestContext(request))
    invoice = Invoice(reservation=reservation,
                      invoice_no=invoice_no,
                      filename=filename,
                      html=html)
    invoice.save()
    
    return download_invoice(request, filename, lu)
Ejemplo n.º 6
0
 def post(self, request, *args, **kwargs):
     form = self.form_class(request.POST)
     if form.is_valid():
         cd = form.cleaned_data
         my_loan = form.save()
         total_period = cd['total_periods']
         period = cd['payment_period']
         cost = cd['cost']
         initial_fee = cd['initial_fee']
         taxes = cd['taxes']
         debt = (cost - initial_fee)
         my_loan.company = request.user.company
         my_loan.expiration_date = get_expiration_date(
             cd['date'], total_period, period)
         my_loan.save()
         initial_invoice = Invoice(
             loan=my_loan,
             payment_date=cd['date'],
             subtotal=initial_fee,
             tax=0,
         )
         initial_invoice.save()
         initial_detail_invoice = DetailInvoice(
             invoice=initial_invoice,
             description="Pago inicial",
             value=initial_fee,
         )
         initial_detail_invoice.save()
         for i in range(int(total_period)):
             subtotal = (cost - initial_fee) / total_period
             tax = debt * (taxes / 100) * (1 / period.value)
             new_invoice = Invoice(
                 loan=my_loan,
                 payment_date=get_expiration_date(cd['date'], i + 1,
                                                  period),
                 subtotal=subtotal,
                 tax=tax,
             )
             new_invoice.save()
             new_detail_invoice = DetailInvoice(
                 invoice=new_invoice,
                 description="Pago por compra",
                 value=subtotal,
             )
             debt = debt - ((cost - initial_fee) / total_period)
             new_detail_invoice.save()
             new_invoice.save()
         return HttpResponseRedirect(self.get_success_url())
def make_invoice(user, invoice_date, contact):
    return clean_and_save(
        Invoice(
            user=user,
            invoice_date=invoice_date,
            contact=contact,
        ))
Ejemplo n.º 8
0
    def get(self, invoice_id=None):
        """
        returns an invoice number or list of invoice numbers

        params:
        closed: true if want to include closed invoices
        startdate: date range filter
        enddate: date range filter
        """
        if invoice_id:
            invoice = Invoice.objects.filter(invoice_id=invoice_id).first()
            store = Store.objects.filter(app_id=request.headers.get('APP-ID'), deleted_at=None).first()

            if invoice is None:
                return jsonify({"error": INVOICE_NOT_FOUND}), 404

            if invoice.customer.store_id != store:
                return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

            response = {
                "result": "ok",
                "invoice": invoice_obj(invoice)
            }
            return jsonify(response), 200
        else:
            try:
                invoices = Invoice.get_all_invoices(request=request)
            except IncorrectDateFormat:
                return jsonify({"error": INCORRECT_TIME_FORMAT})

            return paginated_results(objects=invoices, collection_name='invoice', request=request
                                     , per_page=self.PER_PAGE, serialization_func=invoice_objs), 200
Ejemplo n.º 9
0
def fetch_data(request):
    if request.method == 'GET' :
        invoice_obj = Invoice.objects.all()
        print(invoice_obj)
        invoice_json = serializers.serialize('json', invoice_obj)
        return JsonResponse(invoice_json,safe=False)
        #return HttpResponse(invoice_json, content_type='application/json')

    if request.method == 'POST' :
        print(request.POST[''])
        # request_dict = r.json()
        try :
            if Invoice.objects.filter(customer = request.POST['customer']).exists():
                invoice_obj = Invoice.objects.get(customer = request.POST['customer'])
            else :
                invoice_obj = Invoice(customer = request.POST['customer'])

            invoice_line_obj = Invoice_Line.objects.get(product = request.POST['product'],quantity=request.POST['quantity']
                                                        ,price_without_tax = float(request.POST['price_without_tax']),
                                                        tax_name=request.POST['tax_name'],tax_amount=request.POST['tax_amount'],
                                                        line_total=request.POST['line_total'],invoice=invoice_obj)
            invoice_line_obj.save()
            invoice_obj.total_quantity = Invoice_Line.objects.aggregate(Sum('quantity'))['quantity__sum']
            invoice_obj.total_amount = Invoice_Line.objects.aggregate(Sum('line_total'))['line_total']
            invoice_obj.date = datetime.datetime.now()
            invoice_obj.save()
            return JsonResponse(invoice_obj,safe=False)
        except :
            error={'error' : 'invoice cannot be saved'}
            return JsonResponse(error,safe=False)
Ejemplo n.º 10
0
    def post(self, request, format=None):
        # client = self.get_object(request.user)
        serializer = InvoiceCreateSerializer(data=request.data, many=True)

        if serializer.is_valid():
            new_crt_ids = []
            for invoice_data in serializer.validated_data:
                new_invoice = Invoice(**invoice_data)
                new_invoice.save()
                new_crt_ids.append(new_invoice.id)

            new_invoices = Invoice.objects.all().filter(id__in=new_crt_ids)
            new_serializer = InvoiceSerializer(new_invoices, many=True)
            return Response(new_serializer.data,
                            status=status.HTTP_201_CREATED)

        return Response({'error': serializer.errors},
                        status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 11
0
def createInvoice(request, username):
    if username == request.session['username']:
        user = UserDetail.objects.get(username=username)
        if user.user_type == 'NORMAL':
            if request.method == 'POST':
                invoice = Invoice()
                invoice.name = request.POST['invoice_name']
                invoice.date = request.POST['date']
                invoice.amount = request.POST['amount']
                invoice.image = request.POST['invoice_image']
                invoice.user = user
                invoice.save()
            return render(request, 'create_invoice.html',
                          {'username': username})
    return render(request, 'create_invoice.html', {'username': '******'})
Ejemplo n.º 12
0
def create(request):
    if request.method == 'POST':
        invoice_form = InvoiceForm(request.POST)
        item_formset = ItemFormSet(request.POST) 
        if invoice_form.is_valid() and item_formset.is_valid():
            invoice_form.clean()
            item_formset.clean()
            new_invoice = Invoice(bill_to=invoice_form['bill_to'].data,
                    date=invoice_form['date'].data, user=request.user)
            new_invoice.save()
            for form in item_formset:
                print form.cleaned_data
                print form['item_price'].data
                new_item = Item(name=form['item_name'].data,
                    price=form['item_price'].data, user=request.user)
                new_item.save()
                print type(new_item.price)
                new_invoice_item = InvoiceItem(count=form['item_count'].data,
                        item=new_item, user=request.user)
                new_invoice_item.save()
                new_invoice.items.add(new_invoice_item)
            new_invoice.save()
            return redirect('/dashboard/') 
    else:
        invoice_form = InvoiceForm()
        item_formset = ItemFormSet()
    return render(request, 'invoice/create.html', {'invoice_form': invoice_form,
                                'item_formset': item_formset,
                                'form_counter': len(item_formset.forms) - 1,})
Ejemplo n.º 13
0
 def handle(self, *args, **options):
     for run_date in options['run_date']:
         self.stdout.write(
             self.style.SUCCESS('Date: "%s"' %
                                datetime.strptime(run_date, "%Y-%m-%d")))
         scn_products = subscription_product.objects.filter(
             expiration_date__lte=datetime.strptime(run_date, "%Y-%m-%d"))
         for scn_item in scn_products:
             now = datetime.now()
             inv_num = now.strftime("%d%m%Y%S%M%H%f")
             inv = Invoice(invoice_number=inv_num,
                           title=scn_item.title,
                           due_date=scn_item.expiration_date,
                           customer=scn_item.customer,
                           subscription=scn_item,
                           description=scn_item.title,
                           status=True)
             inv.save()
             self.stdout.write(self.style.SUCCESS('Invoice: "%s"' %
                                                  inv_num))
             self.stdout.write(
                 self.style.SUCCESS('Subscription: "%s"' % scn_item.title))
Ejemplo n.º 14
0
    def get(self, customer_id):
        """
        returns extended customer object

        :return: customer snapshot object
        """
        customer = Customer.get_customer(customer_id=customer_id,
                                         request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        obj = customer_obj(customer=customer)

        cart = Cart.objects.filter(customer_id=customer.customer_id,
                                   closed_at=None).first()
        if cart:
            obj['cart'] = cart_obj(cart)

        invoices = Invoice.objects.filter(
            customer=customer).order_by("-created_at").paginate(page=1,
                                                                per_page=10)
        if invoices:
            obj["last_10_invoices"] = invoice_objs(invoices)

        orders = Order.get_orders(request=request, customer_id=customer_id).order_by("-created_at")\
            .paginate(page=1, per_page=10)
        if orders:
            obj["last_10_orders"] = order_objs(orders)

        gift_cards = GiftCard.objects.filter(recipient_customer=customer, current_balance_in_cents__gt=0)\
            .order_by("-created_at").paginate(page=1, per_page=10)

        if gift_cards:
            obj["active_giftcards"] = gift_card_objs(gift_cards)

        credits = Credit.objects.filter(customer=customer, current_balance_in_cents__gt=0) \
            .order_by("-created_at").paginate(page=1, per_page=10)

        if credits:
            obj["active_credits"] = credit_objs(credits)

        products = Invoice.get_top_N_products(customer=customer,
                                              num_items=10,
                                              request=request)

        if products:
            obj["top_10_ordered_products"] = products

        response = {"result": "ok", "customer": obj}
        return jsonify(response), 200
Ejemplo n.º 15
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)
    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)
    Base.metadata.create_all(engine)
    with transaction.manager:
        # Create one item and one invoice
        item = InvoiceItem(units=1, description='car', amount=2)
        invoice = Invoice(date=date.today())
        invoice.items.append(item)
        DBSession.add(item)
        DBSession.add(invoice)
Ejemplo n.º 16
0
def create_invoice():
    form = InvoiceForm()
    if form.validate_on_submit():
        invoice = Invoice(title=form.title.data,
                          recipient=form.recipient.data,
                          amount=form.amount.data,
                          user_id=current_user.id,
                          id=randint(100000000000, 999999999999))
        # TODO: Ensure no chance override of invoice id
        db.session.add(invoice)
        db.session.commit()
        flash('Your invoice has been created', 'success')
        return redirect(url_for('home'))
    return render_template('create_invoice.html',
                           title='New Invoice',
                           form=form)
Ejemplo n.º 17
0
    def get(self, customer_id):
        """
        return a list of invoice for customer

        params:
        closed: true if want to include closed invoices
        startdate: date range filter
        enddate: date range filter
        """
        try:
            invoices = Invoice.get_all_invoices(request=request)
        except IncorrectDateFormat:
            return jsonify({"error": INCORRECT_TIME_FORMAT})

        customer = Customer.get_customer(customer_id=customer_id, request=request)

        if customer is None:
            return jsonify({"error": CUSTOMER_NOT_FOUND}), 404

        invoices = invoices.filter(customer=customer_id)

        return paginated_results(objects=invoices, collection_name='invoice', request=request
                                 , per_page=self.PER_PAGE, serialization_func=invoice_objs), 200
Ejemplo n.º 18
0
def uploadFile(request):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            if 'user' in request.session:
                user_session = request.session["user"]
                user = User.objects.get(username=user_session)
                pdf_name = form.cleaned_data["pdf_copy"]
                initial_obj = form.save()
                invoice = Invoice()
                invoice.pdf_copy = initial_obj.pdf_copy
                invoice.date = initial_obj.created_at
                invoice.agent = user
                invoice.save()
            return redirect("/create_invoice/" + str(invoice.id) + "/" +
                            str(pdf_name))
        else:
            form = FileForm()
            return render(request, 'file_upload.html', {"form": form})
    else:
        form = FileForm()
        return render(request, "file_upload.html", {"form": form})
Ejemplo n.º 19
0
 def test_get_info(self):
     i = Invoice()
     assert i.get_info() is None
Ejemplo n.º 20
0
 def test_get_footer(self):
     i = Invoice()
     assert i.get_footer() is None
Ejemplo n.º 21
0
def register_invoice_enter(request):
	from participants.models import Participant
	from bookings.models import BookingLine
	from browsersessions.models import BrowserSession
	from invoice.models import Invoice
	from countries_plus.models import Country
	import decimal


	dbsession = BrowserSession.objects.get_session(request.session.session_key)

	entered_bookinglines = BookingLine.objects.filter(
				browser_session__name=request.session.session_key)


	stages = RegistrationStages()
	stages.set_active(RegistrationStages.STAGE_BILLING)


	first_bookingline = entered_bookinglines.first()
	try:
		invoice = first_bookingline.invoice
	except:
		# if the above fails, we might be here because of a inconsistent
		# session state, so we delete the entry, that brought us here
		del request.session['payment_id']
		bounce_target = reverse('register_participants')
		return HttpResponseRedirect(bounce_target)


	invoice_address = None

	if invoice:
		invoice_address = invoice.address

	if request.method == 'GET':
		form = InvoiceAddressForm(instance=invoice_address)

	if request.method == 'POST':
		form = InvoiceAddressForm(request.POST,instance=invoice_address)
		if form.is_valid():
			invoice_address = form.save(commit=False)


			if not invoice:
				invoice = Invoice()

			if invoice_address.vat_number[0:3] == 'ATU':
				invoice_address.country = Country.objects.get(iso='AT')

			invoice_address.save()
			invoice.address = invoice_address
			invoice.save()

			entered_bookinglines.update(invoice=invoice)

			form = InvoiceAddressForm(instance=invoice_address)

			bounce_target = reverse('register_invoice_order')
			return HttpResponseRedirect(bounce_target)


		else:
			# form is invalid
			form = InvoiceAddressForm(request.POST,instance=invoice_address)



	context =  {
			'form': form,
			'stages': stages.as_list(),
	}


	return render(request, 'ewtisite/register_invoice_enter.html', context)
Ejemplo n.º 22
0
 def test_create_url(self):
     self.assertEqual(Invoice.get_create_url(), reverse('invoice:create'))
Ejemplo n.º 23
0
 def test_list_url(self):
     self.assertEqual(Invoice.get_list_url(), reverse('invoice:list'))
Ejemplo n.º 24
0

names = !cat /home/maxim/random_names
streets = !cat /home/maxim/random_streets
items = !cat /home/maxim/random_items

for i in range(300):
    name = names[randint(0, len(names)-2)]
    street_number = randint(1,2000)
    street_name = streets[randint(0,len(streets)-2)]
    d = datetime.date(randint(2006,2010), randint(1,12), randint(1,27))
    shipping_pickup_date = datetime.date(randint(2000,2010), randint(1,12), randint(1,27))
    address = str(street_number) + " " + street_name
    city = "Toronto"
    shipping_handling = randint(10,50)
    invoice = Invoice(name=name, date=d, address=address, city=city, shipping_pickup_date=shipping_pickup_date, shipping_handling=shipping_handling)
    invoice.save()
    for i in range(randint(5,12)):
        item_name = items[randint(0, len(items)-2)]
        price = randint(50,300)
        quantity = randint(1,5)
        item = Item(name=item_name, invoice=invoice, price=price, quantity=quantity)
        item.save()
        print name + " - " + address + ": " + item_name + " = " + str(price) + " * " + str(quantity)


for i in range(100):
    name = names[randint(0, len(names)-2)]
    street_number = randint(1,2000)
    street_name = streets[randint(0,len(streets)-2)]
    d = datetime.date(2011, 1, randint(1,22))
Ejemplo n.º 25
0
 def test_str_none(self):
     i = Invoice(state=Invoice.STATE_PROFORMA)
     assert str(i) == "Proforma nr. None"
Ejemplo n.º 26
0
 def test_get_footer(self):
     i = Invoice()
     assert i.get_footer() is None
Ejemplo n.º 27
0
 def test_get_info(self):
     i = Invoice()
     assert i.get_info() is None
Ejemplo n.º 28
0
def create_doc(request):
    """
    Using the current url, assemble the data to be sent to the document app
    Send the data - the document app will send back a pdf and save copy of the invoice as a html (or just in the database)
    """
    #get the url for the current page, including the querystring
    source_url = "http://%s/%s/?%s%s" % (request.get_host(), "billing", 'format=json&', request.META['QUERY_STRING'])

    #log.debug("source_url: %s" % source_url)

    #get the user object from dokken using username and password
    username = '******' #move this later
    password = '******' #move and change this later
    try:
        user_info = get_user_info(username, password)
    except:
        return HttpResponse('No such user')
    user_uri = user_info[0]['resource_uri']
    
    #construct the name
    name = "Huib-"
    month = None
    bill_month = date(date.today().year, date.today().month, 1)
    if 'month' in request.GET:
        month = int(request.GET['month'])
        bill_month = date(date.today().year, month, 1)
        name += bill_month.strftime("%m")
    if 'year' in request.GET:
        year = int(request.GET['year'])
        if month and month >= 7:
            year = year - 1  #get year is fiscal year
        name += date(year, 1, 1).strftime("%y")
    else:
        name += date.today().strftime("%y")
    if 'expense_code' in request.GET:
        name += "-%s" % request.GET['expense_code']
    ec_root = None
    if 'ec_root' in request.GET:
        ec_root = request.GET['ec_root']
    # Remove ec_root from document name
    #    name += "-%s" % ec_root

    #get the last version number from the document with this name
    doc_version = get_doc_version_by_name(name, user_info, username, password)
    name = '-'.join([name, doc_version])

    #get the current time
    now = str(datetime.utcnow().replace(tzinfo=utc))  #format now as a string

    #get the html for this page using urllib (is there a better way to do this?)
    sessionid = request.COOKIES['sessionid']
    opener = urllib2.build_opener()
    opener.addheaders.append(('Cookie', 'sessionid=%s' % sessionid))
    response = opener.open(source_url)
    content = response.read()
    soup = BeautifulSoup(content)
    html = str(soup.find(id="bill_content"))

    data = {
        'name':  name,
        'user': user_uri,
        'html': html,
        'url': source_url,
        'created': now,
        'modified': now,
        }
    json_data = json.dumps(data)                          #json-fy the data

    #create the invoice
    user = User.objects.get(username=username)
    inv = Invoice()
    inv.invoice_number = name
    inv.bill_month = bill_month
    inv.expense_code_root = ec_root
    inv.html_content = html
    inv.user = user
    inv.created = now
    inv.modified = now
    inv.save()

    #create the django object in the document app
    destination_url = 'http://%s/a/api/document/' % settings.DOCUMENT_APP_HOST
    request = urllib2.Request(destination_url)
    request.add_header('Content-Type', 'application/json')
    request.add_header('Accept', 'application/json, text/html')
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    request.add_data(json_data)
    response = urllib2.urlopen(request)

    #get the uri id for the object that was created
    try:
        location = re.search( r'Location: (.+)$', response.headers.__str__(), re.M)
    except:
        return HttpResponse('No URI!')
    location = location.group(1)
    try:
        uri_id = re.search( r'http://%s/a/api/document/(\d+)/' % settings.DOCUMENT_APP_HOST, location, re.M)
    except:
        return HttpResponse('No ID!')
    uri_id = uri_id.group(1)

    #create the pdf using the uri id
    destination_url = 'http://%s/harvard_doc/pdf/%s/' % (settings.DOCUMENT_APP_HOST, uri_id)
    request = urllib2.Request(destination_url)
    request.add_header('Content-Type', 'application/json')
    request.add_header('Accept', 'application/json, text/html')
    base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
    request.add_header("Authorization", "Basic %s" % base64string)
    response = urllib2.urlopen(request)                       #this request creates the pdf on dokken

    #get the pdf from dokken
    destination_url = 'http://%s/uploads/%s.pdf' % (settings.DOCUMENT_APP_HOST, slugify(name))
    pdf = urllib2.urlopen(destination_url)
    output = cStringIO.StringIO()
    output.write(pdf.read())
    response = HttpResponse(output.getvalue(), content_type="application/pdf")
    output.close()
    response['Content-Disposition'] = 'attachment; filename=%s.pdf' % slugify(name)
    return response