示例#1
0
    def invoice_form():
        invoice_details = InvoiceDetails.query.one_or_none()
        positions_form = PositionsForm(prefix='positions')
        invoice_form = InvoiceForm(prefix='invoice', obj=invoice_details)

        if request.method == 'POST':
            if positions_form.validate_on_submit():
                unit = positions_form.unit.data
                amount = positions_form.amount.data
                price = positions_form.price.data
                description = positions_form.description.data
                total = amount * price
                new_position = Positions(unit=unit,
                                         amount=amount,
                                         price=price,
                                         description=description,
                                         total=total)
                new_position.insert()

                flash('Position succesfully added!', 'success')
            elif invoice_form.validate_on_submit():
                form_invoice_details = invoice_form.data
                form_invoice_details.pop('csrf_token', None)
                if invoice_details is None:
                    invoice_details = InvoiceDetails(**form_invoice_details)
                    invoice_details.insert()
                else:
                    invoice_details.update(**form_invoice_details)

                positions = Positions.query.all()
                total = 0
                for position in positions:
                    total += position.total
                created = datetime.date.today()
                payment_due = created + datetime.timedelta(days=14)

                return render_template('/invoice_details.html',
                                       title='Invoice Details',
                                       invoice_details=invoice_details,
                                       positions=positions,
                                       created=created,
                                       payment_due=payment_due,
                                       total=total)
            else:
                flash('Please check your form input!', 'error')

        positions = Positions.query.all()

        return render_template('/invoice_form.html',
                               title='Invoice Form',
                               active_page='form',
                               positions_form=positions_form,
                               invoice_form=invoice_form,
                               positions=positions)
示例#2
0
文件: views.py 项目: dimashiro/sfacts
def update_invoice(uid):
    invoice = Invoice.query.get_or_404(uid)
    form = InvoiceForm(request.form, obj=invoice)

    if request.method == "POST":
        if form.validate(current_user):
            save = False
            if invoice.org_uid != form.org_uid.data:
                invoice.org_uid = form.org_uid.data
                save = True
            if invoice.agent_uid != form.agent_uid.data:
                invoice.agent_uid = form.agent_uid.data
                save = True
            if invoice.ninvoice != form.ninvoice.data:
                if int(form.inv_type.data) == CONST.INVOICE_IN:
                    invoice.ninvoice = form.ninvoice.data
                    save = True
                else:
                    flash(u"Запрещено изменение номера счет-факутры книги продаж", "alert-danger")

            if invoice.dinvoice.date() != form.dinvoice.data:
                invoice.dinvoice = form.dinvoice.data
                save = True
            if invoice.sum_snds != form.sum_snds.data:
                invoice.sum_snds = form.sum_snds.data
                save = True
            if invoice.sum_no_nds18 != form.sum_no_nds18.data:
                invoice.sum_no_nds18 = form.sum_no_nds18.data
                save = True
            if invoice.sum_nds18 != form.sum_nds18.data:
                invoice.sum_nds18 = form.sum_nds18.data
                save = True
            if invoice.sum_no_nds10 != form.sum_no_nds10.data:
                invoice.sum_no_nds10 = form.sum_no_nds10.data
                save = True
            if invoice.sum_nds10 != form.sum_nds10.data:
                invoice.sum_nds10 = form.sum_nds10.data
                save = True

            if save:
                invoice.change_date = datetime.now()
                invoice.commission = invoice.get_commission()
                db.session.add(invoice)
                db.session.commit()
                flash(u"Изменения в счет-фактуре сохранены", "alert-success")
                return redirect(url_for("invoices", invoice_type=CONST.INVOICE_TYPE[int(form.inv_type.data)]))
            else:
                flash(u"Данные не менялись. Изменения не сохранены", "alert-info")
                return redirect(url_for("invoices", invoice_type=CONST.INVOICE_TYPE[int(form.inv_type.data)]))

    return render_template('invoice.html', form=form, edit=1)
示例#3
0
文件: views.py 项目: dimashiro/sfacts
def invoices(invoice_type=CONST.INVOICE_TYPE[CONST.INVOICE_IN]):
    form = InvoiceForm()
    form_elem = ElemForm()

    if invoice_type == CONST.INVOICE_TYPE[CONST.INVOICE_IN]:
        inv_type = CONST.INVOICE_IN
    elif invoice_type == CONST.INVOICE_TYPE[CONST.INVOICE_OUT]:
        inv_type = CONST.INVOICE_OUT
        del form.ninvoice


    if request.method == "POST":
        if form.validate(current_user):
            if inv_type == CONST.INVOICE_OUT:
                ninvoice = Invoice.make_unique_num(form.dinvoice.data, form.org_uid.data)
                flash(u"Счет-фактуре присвоен номер "+ninvoice, "alert-success")
            else:
                ninvoice = form.ninvoice.data
            newinvoice = Invoice(inv_type, form.org_uid.data, form.agent_uid.data,
                                 ninvoice, form.dinvoice.data,
                                 form.sum_snds.data, form.sum_no_nds18.data,
                                 form.sum_nds18.data, form.sum_no_nds10.data,
                                 form.sum_nds10.data, current_user.uid)
            db.session.add(newinvoice)
            db.session.commit()
            flash(u"Добавлена новая счет-фактура", "alert-success")

            # clean fields
            lst_fields = ['dinvoice', 'sum_snds',
                          'sum_no_nds18', 'sum_nds18',
                          'sum_no_nds10', 'sum_nds10']
            if inv_type == CONST.INVOICE_IN:
                lst_fields.append('ninvoice')
            for fld in lst_fields:
                form[fld].raw_data = None
                form[fld].data = None

    invoices = current_user.available_invoices(inv_type=inv_type)
    sums = invoices.with_entities(func.sum(Invoice.sum_snds),
                                  func.sum(Invoice.sum_no_nds18),
                                  func.sum(Invoice.sum_nds18),
                                  func.sum(Invoice.sum_no_nds10),
                                  func.sum(Invoice.sum_nds10),
                                  func.sum(Invoice.commission)).first()

    return render_template('invoices.html', form=form, form_elem=form_elem,
                           invoices=invoices.all(),
                           invoice_type=invoice_type,
                           sums=sums,
                           edit=0)
示例#4
0
def main():
    print("Загружаю главную страницу")
    form1 = InvoiceForm()
    if form1.validate_on_submit():
        print("Обнаружены данные из формы")
        controller.add_item(form1)

    items_data = db.get_all_items()
    items = [(item.id, item.name, item.size_x, item.size_y, item.size_z, item.weight, item.stowage_id) for item in items_data]

    stowages_data = db.get_all_stowages()
    stowages = [(stowage.id, stowage.row, stowage.level, stowage.size_x, stowage.size_y, stowage.size_z, stowage.json, stowage.empty) for stowage in stowages_data]

    print("Загрузка главной страницы")
    return render_template('main.html', items=items, stowages=stowages, form1=form1)
示例#5
0
def check():
    form = InvoiceForm()
    if form.validate_on_submit():
        invoice = Invoice(
            form.data['amount'],
            form.data['currency'],
            form.data['description']
        )
        db.session.add(invoice)
        db.session.commit()
        app.logger.info(u"invoice created: {}".format(invoice))

        # hack for passing signature check
        amount = int(invoice.amount) if (
            int(invoice.amount) == float(invoice.amount)) else invoice.amount

        payload = {
            "shop_id": SHOP_ID,
            "amount": amount,
            "currency": invoice.currency,
            'shop_invoice_id': invoice.id,
            "description": invoice.description
        }
        if invoice.currency == '980':
            payload["payway"] = 'w1_uah'
            sign = _get_sign(payload, INVOICE_KEYS)
            payload['sign'] = sign
            resp = requests.post(UAH_INVOICE_URL, json=payload)
            data = json.loads(resp.content)['data']
            app.logger.info("data: {}".format(data))
            if not data:
                return jsonify(json.loads(resp.content))
            url = data['source']
            data = data['data']

        elif invoice.currency == '643':
            sign = _get_sign(payload, TIP_KEYS)
            payload['sign'] = sign
            data = payload
            url = TIP_URL

        else:
            return jsonify({'result': 'error', 'message': 'Wrong currency'})

        app.logger.info("data sent: {}".format(data))

        return jsonify({'result': 'ok', 'data': data, 'url': url})
    return jsonify({'result': 'error', 'message': 'Form validation error'})
示例#6
0
    def get(self, request, *args, **kwargs):
        context = {}
        if 'invoice' in request.GET:
            invoice = Invoice.objects.get(pk=request.GET['invoice'])

            # Update to the latest invoice
            updated_invoice = invoice_user(invoice.user, invoice.first_day,
                                           invoice.last_day)
            if updated_invoice:
                invoice = updated_invoice

            connections = invoice.connections()
            form = InvoiceForm(instance=invoice)

            context = {
                'form': form,
                'invoice': invoice,
                'connections': connections
            }

        if 'title' in request.GET:
            invoices = Invoice.objects.filter(title=request.GET['title'])
            income, commissions = calc_split(invoices)

            context.update(title=request.GET['title'],
                           income=income,
                           commissions=commissions,
                           total=income - commissions,
                           split=.25 * (income - commissions),
                           invoices=invoices)

        return self.render_to_response(context)
示例#7
0
def invoice():
    form = InvoiceForm()
    if form.validate_on_submit():
        return redirect(url_for('pdf_template'))
    return render_template('invoice_form2.html', title='SF online', form=form)
示例#8
0
def index():
    form = InvoiceForm()
    return render_template("index.html", form=form)
示例#9
0
def invoice_add(request):
    if request.method == 'POST':
        invoice_items = []
        errors = []
        form = InvoiceForm(request.POST)
        client = ""

        # validate submitted items and prepare invoice draft in user's session
        for k, v in request.POST.iteritems():
            if k.startswith('item_id_'):
                try:
                    iid = k.replace('item_id_', '')
                    pkey = int(v)
                    bit = ItemsBucket.objects.get(pk=pkey)

                    t = InvoiceItem()
                    t.ordinal = iid
                    t.id = str(pkey)
                    t.count = str(int(request.POST.get('item_amount_' + iid)))
                    t.name = bit.item.name
                    t.sell_price = str(bit.sell_price)
                    t.tax = str(bit.item.tax_rate)
                    invoice_items.append(t)
                except DoesNotExist:
                    errors.append('Incorrect item id ' + pkey)

        invoice_items.sort(key=lambda InvoiceItem: InvoiceItem.ordinal,
                           reverse=False)

        for item in invoice_items:
            db_item = ItemsBucket.objects.get(pk=item.id)
            if int(item.count) > int(db_item.count):
                errors.append('To many items of ' + db_item.item.name)

        if "client_id" in request.POST and request.POST["client_id"]:
            try:
                client = Client.objects.get(pk=request.POST.get('client_id'))
            except DoesNotExist:
                errors.append('Incorrect client id')

        if "invoice_number" in request.POST and request.POST["invoice_number"]:
            ex = InvoiceDocument.objects.filter(
                number=request.POST.get('invoice_number') + '/2012')
            if ex.count() > 0:
                errors.append('Invoice with number ' +
                              request.POST.get('invoice_number') +
                              '/2012 already exists')

        if not errors and form.is_valid():
            # no errors, save invoice and push changes
            doc = InvoiceDocument()
            doc.number = form.cleaned_data['invoice_number'] + '/2012'
            doc.date = datetime.now()
            doc.client = client
            doc.save()
            for item in invoice_items:
                db_item = ItemsBucket.objects.get(pk=item.id)
                t = InvoiceDocumentEntry()
                t.item = db_item.item
                t.count = item.count
                price = db_item.sell_price
                tax = db_item.item.tax_rate.percentage
                net_price = float(price - (price / 100) * tax)
                t.net_price = net_price
                t.gross_price = item.sell_price
                t.tax = tax
                db_item.count -= int(item.count)
                db_item.save()
                t.document = doc
                t.save()
            return redirect('/documents/invoice')
        else:
            # errors occured, redisplay the form with errors
            items = ItemsBucket.objects.filter(count__gt=0)
            clients = Client.objects.order_by('name')
            currencies = Currency.objects.all()
            return render_to_response('storage/invoice_add.html', {
                'invoice_active': 'active',
                'clients': clients,
                'client': client,
                'items': items,
                'form': form,
                'invoice_items': invoice_items,
                'currency': currencies[0]
            },
                                      context_instance=RequestContext(request))
    else:
        clients = Client.objects.order_by('name')
        items = ItemsBucket.objects.filter(count__gt=0)
        form = InvoiceForm(initial={'invoice_number': '', 'client_id': ''})
        currencies = Currency.objects.all()
        return render_to_response('storage/invoice_add.html', {
            'invoice_active': 'active',
            'clients': clients,
            'items': items,
            'form': form,
            'currency': currencies[0]
        },
                                  context_instance=RequestContext(request))
示例#10
0
def invoice_add(request):
	if request.method == 'POST':
		invoice_items = []
		errors = []
		form = InvoiceForm(request.POST)
		client = ""

		# validate submitted items and prepare invoice draft in user's session
		for k,v in request.POST.iteritems():
			if k.startswith('item_id_'):
				try:
					iid = k.replace('item_id_', '')
					pkey = int(v)
					bit = ItemsBucket.objects.get(pk = pkey)

					t = InvoiceItem()
					t.ordinal = iid
					t.id = str(pkey)
					t.count = str(int(request.POST.get('item_amount_' + iid)))
					t.name = bit.item.name
					t.sell_price = str(bit.sell_price)
					t.tax = str(bit.item.tax_rate)
					invoice_items.append(t)
				except DoesNotExist:
					errors.append('Incorrect item id ' + pkey)

		invoice_items.sort(key=lambda InvoiceItem: InvoiceItem.ordinal, reverse=False)

		for item in invoice_items:
			db_item = ItemsBucket.objects.get(pk = item.id)
			if int(item.count) > int(db_item.count):
				errors.append('To many items of ' + db_item.item.name)

		if "client_id" in request.POST and request.POST["client_id"]:
			try:
				client = Client.objects.get(pk = request.POST.get('client_id'))
			except DoesNotExist:
				errors.append('Incorrect client id')

		if "invoice_number" in request.POST and request.POST["invoice_number"]:
			ex = InvoiceDocument.objects.filter(number = request.POST.get('invoice_number') + '/2012')
			if ex.count() > 0:
				errors.append('Invoice with number ' + request.POST.get('invoice_number') + '/2012 already exists')

		if not errors and form.is_valid():
			# no errors, save invoice and push changes
			doc = InvoiceDocument()
			doc.number = form.cleaned_data['invoice_number'] + '/2012'
			doc.date = datetime.now()
			doc.client = client
			doc.save()
			for item in invoice_items:
				db_item = ItemsBucket.objects.get(pk = item.id)
				t = InvoiceDocumentEntry()
				t.item = db_item.item
				t.count = item.count
				price = db_item.sell_price
				tax = db_item.item.tax_rate.percentage
				net_price = float(price - (price / 100) * tax)
				t.net_price = net_price
				t.gross_price = item.sell_price
				t.tax = tax
				db_item.count -= int(item.count)
				db_item.save()
				t.document = doc
				t.save()
			return redirect ('/documents/invoice')
		else:
			# errors occured, redisplay the form with errors
			items = ItemsBucket.objects.filter(count__gt=0)
			clients = Client.objects.order_by('name')
			currencies = Currency.objects.all()
			return render_to_response('storage/invoice_add.html', 
					{'invoice_active':'active', 
					'clients': clients,
					'client': client,
					'items': items,
					'form' : form,
					'invoice_items': invoice_items,
					'currency': currencies[0]},
					context_instance = RequestContext(request))
	else:
		clients = Client.objects.order_by('name')
		items = ItemsBucket.objects.filter(count__gt=0)
		form = InvoiceForm(initial={'invoice_number': '','client_id': ''})
		currencies = Currency.objects.all()
		return render_to_response('storage/invoice_add.html', 
			{'invoice_active':'active', 
			'clients': clients,
			'items': items,
			'form' : form,
			'currency': currencies[0]},
			context_instance = RequestContext(request))