def test_invoice_info(self): invoice_path = os.path.join(self.file_base_dir, 'invoice_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add invoice info invoice_info_data = invoice._invoice_info_data() self.assertEqual(invoice_info_data, []) invoice.invoice_info = InvoiceInfo(12) # After add invoice info invoice_info_data = invoice._invoice_info_data() self.assertEqual(len(invoice_info_data), 1) self.assertEqual(invoice_info_data[0][0], 'Invoice id:') self.assertEqual(invoice_info_data[0][1], 12) invoice.invoice_info = InvoiceInfo(12, invoice_datetime=datetime( 2015, 6, 1)) invoice_info_data = invoice._invoice_info_data() self.assertEqual(len(invoice_info_data), 2) self.assertEqual(invoice_info_data[1][0], 'Invoice date:') self.assertEqual(invoice_info_data[1][1], '2015-06-01 00:00') invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def createLineInvoice(line, current_user): invoiceNumber = str(line[0]) invoiceDueDate = line[6] unitCount = line[7] unitPrice = line[8] invoiceDesc = line[4] clientEmail = line[2] clientName = line[1] invoiceAmt = line[9] invoice = Invoice(invoiceNumber, clientName, clientEmail, current_user.id, unitCount, unitPrice, invoiceAmt, invoiceDueDate, datetime.today().strftime('%d-%m-%y'), invoiceDesc) db.session.add(invoice) db.session.commit() doc = SimpleInvoice('invoice' + str(invoice.id) + '.pdf') doc.invoice_info = InvoiceInfo(line[0], datetime.today(), invoiceDueDate) business = Business.query.filter_by(id=current_user.id).first() doc.service_provider_info = ServiceProviderInfo( name=business.name, street=business.street, city=business.city, state=business.state, ) doc.client_info = ClientInfo(email=clientEmail, name=clientName) doc.add_item(Item(invoiceDesc, line[5], unitCount, unitPrice)) doc.finish() return invoice
def test_invoice_info(self): invoice_path = os.path.join(self.file_base_dir, 'invoice_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add invoice info invoice_info_data = invoice._invoice_info_data() self.assertEqual(invoice_info_data, []) invoice.invoice_info = InvoiceInfo(12) # After add invoice info invoice_info_data = invoice._invoice_info_data() self.assertEqual(len(invoice_info_data), 1) self.assertEqual(invoice_info_data[0][0], 'Invoice id:') self.assertEqual(invoice_info_data[0][1], 12) invoice.invoice_info = InvoiceInfo(12, invoice_datetime=datetime(2015, 6, 1)) invoice_info_data = invoice._invoice_info_data() self.assertEqual(len(invoice_info_data), 2) self.assertEqual(invoice_info_data[1][0], 'Invoice date:') self.assertEqual(invoice_info_data[1][1], '2015-06-01 00:00') invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_transaction(self): invoice_path = os.path.join(self.file_base_dir, 'transaction.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) transaction_data = invoice._transactions_data() self.assertEqual(transaction_data, []) invoice.add_transaction(Transaction('A', 1, date.today(), 9.9)) invoice.add_transaction(Transaction('B', 3, date(2015, 6, 1), 3.3)) transaction_data = invoice._transactions_data() self.assertEqual(len(transaction_data), 3) self.assertEqual(transaction_data[0][0], 'Transaction id') self.assertEqual(transaction_data[1][3], 9.9) self.assertEqual(transaction_data[2][0], 3) self.assertEqual(transaction_data[2][2], '2015-06-01') self.assertEqual(transaction_data[2][3], 3.3) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_service_provider_info(self): invoice_path = os.path.join(self.file_base_dir, 'service_provider_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add service provider info info_data = invoice._service_provider_data() self.assertEqual(info_data, []) # Empty info invoice.service_provider_info = ServiceProviderInfo() info_data = invoice._service_provider_data() self.assertEqual(info_data, []) invoice.service_provider_info = ServiceProviderInfo( name='CiCiApp', street='Street xxx', city='City ccc', state='State sss', country='Country rrr', post_code='Post code ppp', vat_tax_number=666) # After add service provider info info_data = invoice._service_provider_data() self.assertEqual(len(info_data), 7) self.assertEqual(info_data[0][0], 'Name:') self.assertEqual(info_data[0][1], 'CiCiApp') self.assertEqual(info_data[4][0], 'Country:') self.assertEqual(info_data[4][1], 'Country rrr') self.assertEqual(info_data[6][0], 'Vat/Tax number:') self.assertEqual(info_data[6][1], 666) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_client_info(self): invoice_path = os.path.join(self.file_base_dir, 'client_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add client info info_data = invoice._client_info_data() self.assertEqual(info_data, []) # Empty info invoice.client_info = ClientInfo() info_data = invoice._client_info_data() self.assertEqual(info_data, []) invoice.client_info = ClientInfo(name='Client ccc', street='Street sss', city='City ccc', state='State sss', country='Country ccc', post_code='Post code ppp', email='*****@*****.**', client_id=3214) # After add client info info_data = invoice._client_info_data() self.assertEqual(len(info_data), 8) self.assertEqual(info_data[0][0], 'Name:') self.assertEqual(info_data[0][1], 'Client ccc') self.assertEqual(info_data[6][0], 'Email:') self.assertEqual(info_data[6][1], '*****@*****.**') self.assertEqual(info_data[7][0], 'Client id:') self.assertEqual(info_data[7][1], 3214) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_client_info(self): invoice_path = os.path.join(self.file_base_dir, 'client_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add client info info_data = invoice._client_info_data() self.assertEqual(info_data, []) # Empty info invoice.client_info = ClientInfo() info_data = invoice._client_info_data() self.assertEqual(info_data, []) invoice.client_info = ClientInfo( name='Client ccc', street='Street sss', city='City ccc', state='State sss', country='Country ccc', post_code='Post code ppp', email='*****@*****.**', client_id=3214 ) # After add client info info_data = invoice._client_info_data() self.assertEqual(len(info_data), 8) self.assertEqual(info_data[0][0], 'Name:') self.assertEqual(info_data[0][1], 'Client ccc') self.assertEqual(info_data[6][0], 'Email:') self.assertEqual(info_data[6][1], '*****@*****.**') self.assertEqual(info_data[7][0], 'Client id:') self.assertEqual(info_data[7][1], 3214) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_service_provider_info(self): invoice_path = os.path.join(self.file_base_dir, 'service_provider_info.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add service provider info info_data = invoice._service_provider_data() self.assertEqual(info_data, []) # Empty info invoice.service_provider_info = ServiceProviderInfo() info_data = invoice._service_provider_data() self.assertEqual(info_data, []) invoice.service_provider_info = ServiceProviderInfo( name='CiCiApp', street='Street xxx', city='City ccc', state='State sss', country='Country rrr', post_code='Post code ppp', vat_tax_number=666 ) # After add service provider info info_data = invoice._service_provider_data() self.assertEqual(len(info_data), 7) self.assertEqual(info_data[0][0], 'Name:') self.assertEqual(info_data[0][1], 'CiCiApp') self.assertEqual(info_data[4][0], 'Country:') self.assertEqual(info_data[4][1], 'Country rrr') self.assertEqual(info_data[6][0], 'Vat/Tax number:') self.assertEqual(info_data[6][1], 666) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_only_items_with_tax_rate(self): invoice_path = os.path.join(self.file_base_dir, 'only_items_with_tax.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add items item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(len(item_data), 0) self.assertEqual(item_subtotal, Decimal('0')) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 0) self.assertEqual(style, []) # Add items invoice.add_item(Item('Item1', 'Item desc', 1, 1.1)) invoice.add_item(Item('Item2', 'Item desc', 2, u'2.2')) invoice.add_item(Item(u'Item3', 'Item desc', 3, '3.3')) # set tax rate invoice.set_item_tax_rate(19) # After add items items = invoice.items self.assertEqual(len(items), 3) self.assertEqual(items[0].name, 'Item1') self.assertEqual(items[0].amount, Decimal('1.1')) self.assertEqual(items[1].amount, Decimal('4.4')) self.assertEqual(items[2].name, u'Item3') self.assertEqual(items[2].amount, Decimal('9.9')) item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(item_subtotal, Decimal('15.4')) self.assertEqual(len(item_data), 3) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 7) # header, subtotal, tax, total self.assertEqual(item_data[-3][-1], Decimal('15.4')) # subtotal self.assertEqual(item_data[-2][-1], Decimal('2.926')) # tax self.assertEqual(item_data[-1][-1], Decimal('18.326')) # total invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def test_simple(self): invoice_path = os.path.join(self.file_base_dir, 'simple.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) doc = SimpleInvoice(invoice_path) doc.is_paid = True doc.invoice_info = InvoiceInfo(1023, datetime.now(), datetime.now()) doc.service_provider_info = ServiceProviderInfo( name='PyInvoice', street='My Street', city='My City', state='My State', country='My Country', post_code='222222', vat_tax_number='Vat/Tax number') doc.client_info = ClientInfo(email='*****@*****.**') doc.add_item(Item('Item', 'Item desc', 1, '1.1')) doc.add_item(Item('Item', 'Item desc', 2, '2.2')) doc.add_item(Item('Item', 'Item desc', 3, '3.3')) items = doc.items self.assertEqual(len(items), 3) doc.set_item_tax_rate(20) # 20% doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) transactions = doc.transactions self.assertEqual(len(transactions), 2) doc.set_bottom_tip( "Email: [email protected]<br />Don't hesitate to contact us for any questions." ) doc.finish() self.assertTrue(os.path.exists(invoice_path))
def test_only_items_with_tax_rate(self): invoice_path = os.path.join(self.file_base_dir, 'only_items_with_tax.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add items item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(len(item_data), 0) self.assertEqual(item_subtotal, Decimal('0')) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 0) self.assertEqual(style, []) # Add items invoice.add_item(Item('Item1', 'Item desc', 1, 1.1)) invoice.add_item(Item('Item2', 'Item desc', 2, u'2.2')) invoice.add_item(Item(u'Item3', 'Item desc', 3, '3.3')) # set tax rate invoice.set_item_tax_rate(19) # After add items items = invoice.items self.assertEqual(len(items), 3) self.assertEqual(items[0].name, 'Item1') self.assertEqual(items[0].amount, Decimal('1.1')) self.assertEqual(items[1].amount, Decimal('4.4')) self.assertEqual(items[2].name, u'Item3') self.assertEqual(items[2].amount, Decimal('9.9')) item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(item_subtotal, Decimal('15.4')) self.assertEqual(len(item_data), 3) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 7) # header, subtotal, tax, total self.assertEqual(item_data[-3][-1], Decimal('15.4')) # subtotal self.assertEqual(item_data[-2][-1], Decimal('2.93')) # tax self.assertEqual(item_data[-1][-1], Decimal('18.33')) # total invoice.finish() self.assertTrue(os.path.exists(invoice_path))
def generate_pdf(self, order, user): invoice_doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional invoice_doc.is_paid = False invoice_doc.invoice_info = InvoiceInfo( order.id, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional invoice_doc.service_provider_info = ServiceProviderInfo( name='Azen Store', street='Somewhere in Guatemala', city='Guatemala', state='Guatemala', country='Guatemala', post_code='0100X', ) order_items = OrderItem.objects.filter(order=order).all() # Client info, optional invoice_doc.client_info = ClientInfo(client_id=user.id, name=user.username) for order_item in order_items: # Add Item invoice_doc.add_item( Item(order_item.product.name, 'Item', order_item.quantity, order_item.product.price)) # Tax rate, optional invoice_doc.set_item_tax_rate(0) # 0% # Optional invoice_doc.set_bottom_tip( "Email: [email protected]<br />Don't hesitate to contact us for any questions.<br />Coupons are applied in payments..." ) invoice_doc.finish()
def createInvoice(datafields): doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional doc.is_paid = True doc.invoice_info = InvoiceInfo( 1023, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name='pyInvoice', street='My Street', city='My City', state='My State', country='My Country', post_code='222222', vat_tax_number='Vat/Tax number') # Client info, optional doc.client_info = ClientInfo(email='*****@*****.**') # Add Item itemCount = 0 for item in range(len(datafields)): doc.add_item( Item(datafields[itemCount]['product'], 'Item Desc', int(datafields[itemCount]['quantity']), str(datafields[itemCount]['rate']))) itemCount += 1 # Tax rate, optional doc.set_item_tax_rate(int(datafields[0]['gstrate'])) # 20% # Transactions detail, optional doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) # Optional doc.set_bottom_tip( "Email: [email protected]<br />Don't hesitate to contact us for any questions." ) doc.finish()
def createInvoice(ID, job): doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional doc.is_paid = True doc.invoice_info = InvoiceInfo( 1023, datetime.now(), datetime.now()) # Invoice info, optional companyName = Company.getName(ID) companyAddress = Company.getAddress(ID) companyCity = Company.getCity(ID) companyPostcode = Company.getPostcode(ID) companyPhone = Company.getPhone(ID) companyAccNumber = Company.getAccNumber(ID) companySortCode = Company.getSort(ID) # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name=companyName, street=companyAddress, city=companyCity, post_code=companyPostcode, vat_tax_number='Vat/Tax number') clientName = Customers.getName(ID) clientAddress = Customers.getAddress(ID) clientCity = Customers.getCity(ID) clientPostcode = Customers.getPostcode(ID) # Client info, optional doc.client_info = ClientInfo(name=clientName, street=clientAddress, city=clientCity, post_code=clientPostcode, email='*****@*****.**') invoiceMaterials = JobMaterials.getInvoiceMaterials(job) for each in invoiceMaterials: materialName = each[0] pricePerUnit = each[1] desc = each[2] quantity = each[3] doc.add_item(Item(materialName, desc, quantity, pricePerUnit)) # Add Item #doc.add_item(Item('Item', 'Item desc', 1, '1.1')) #doc.add_item(Item('Item', 'Item desc', 2, '2.2')) #doc.add_item(Item('Item', 'Item desc', 3, '3.3')) # Tax rate, optional doc.set_item_tax_rate(20) # 20% ## Transactions detail, optional #doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) #doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) # Optional doc.set_bottom_tip( "Email: [email protected]<br />Don't hesitate to contact us for any questions." ) doc.finish()
def imaker(fName, id, duedate, clientId, clientName, clientMobileNumber, prods, discountNo): #fname: filename #id: invoice id, type: str or int or unicode #duedate: invoice duedate: str or int or unicode #clientId: passed in client_info. type: str or int or unicode #clientName: type is str ot unicode #clientMobileNumber. type: int or str or unicode #prods is a list which makes the item table #prods -> name, description price, quantity #discountNo: passes into the function which sets the discount rate. type: int doc = SimpleInvoice(fName) # Paid stamp, optional doc.is_paid = False doc.invoice_info = InvoiceInfo(id, datetime.now(), duedate) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo(name='Salman Wholeseller', mobileNumber='03362510211') # Client info, optional doc.client_info = ClientInfo( client_id=clientId, name=clientName, mobileNumber=clientMobileNumber, ) # Add Item for x in prods: doc.add_item(Item(x[0], x[1], x[2], x[3])) # Tax rate, optional doc.set_item_discount_rate(discountNo) # 20% doc.finish()
def generate_invoice(response, invoice_obj): customer = invoice_obj.customer doc = SimpleInvoice( response, pagesize="A4", provider_header=settings.COMPANY_NAME, client_header=customer.name, provider_address=settings.COMPANY_ADDRESS, client_address=customer.address.name, ) # Paid stamp, optional doc.is_paid = True doc.service_provider_info = ServiceProviderInfo() doc.invoice_info = InvoiceInfo(invoice_obj.id, invoice_obj.created_at) doc.client_info = ClientInfo( name=customer.name, street=customer.address.name, city=_get_customer_active_accounts(customer), ) # Add Item this_month = datetime.today().replace(day=15).date() accounts = invoice_obj.accounts.all() monthly_credit_count = 0 monthly_penalty_count = 0 total_credit = 0 total_penalty = 0 for account in accounts: for deposit in account.deposits.all(): if deposit.date == this_month: monthly_credit_count += 1 total_credit += deposit.principal total_penalty += deposit.penalty if deposit.penalty > 0: monthly_penalty_count += 1 total_loan_count = 0 total_loan_principal = 0 total_loan_interest = 0 total_loan_penalty = 0 total_penalty_count = 0 for loan in customer.loans.all(): for deposit in loan.deposits.all(): if deposit.date == this_month: total_loan_count += 1 total_loan_principal += deposit.principal total_loan_penalty += deposit.penalty total_loan_interest += deposit.interest if deposit.penalty > 0: total_penalty_count += 1 details = { "Account Credit": [monthly_credit_count, total_credit], "Account Penalty": [monthly_penalty_count, total_penalty], "Loan Principal": [total_loan_count, total_loan_principal], "Loan Interest": [total_loan_count, total_loan_interest], "Loan Penalty": [total_penalty_count, total_loan_penalty], } for key, value in details.items(): doc.add_item(Item(key, value[0], value[1])) doc.set_bottom_tip("Don't hesitate to contact us for any questions!") doc.finish() invoice_obj.detail = details invoice_obj.save()
def test_simple(self): invoice_path = os.path.join(self.file_base_dir, 'simple.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) doc = SimpleInvoice(invoice_path) doc.is_paid = True doc.invoice_info = InvoiceInfo(1023, datetime.now(), datetime.now()) doc.service_provider_info = ServiceProviderInfo( name='PyInvoice', street='My Street', city='My City', state='My State', country='My Country', post_code='222222', vat_tax_number='Vat/Tax number' ) doc.client_info = ClientInfo(email='*****@*****.**') doc.add_item(Item('Item', 'Item desc', 1, '1.1')) doc.add_item(Item('Item', 'Item desc', 2, '2.2')) doc.add_item(Item('Item', 'Item desc', 3, '3.3')) items = doc.items self.assertEqual(len(items), 3) doc.set_item_tax_rate(20) # 20% doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) transactions = doc.transactions self.assertEqual(len(transactions), 2) doc.set_bottom_tip("Email: [email protected]<br />Don't hesitate to contact us for any questions.") doc.finish() self.assertTrue(os.path.exists(invoice_path))
from datetime import datetime, date from pyinvoice.models import InvoiceInfo, ServiceProviderInfo, ClientInfo, Item, Transaction from pyinvoice.templates import SimpleInvoice #def createInvoice(): doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional #doc.is_paid = True doc.invoice_info = InvoiceInfo(1023, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name='PyInvoice', street='My Street', city='My City', state='My State', country='My Country', post_code='222222', vat_tax_number='Vat/Tax number' ) # Client info, optional doc.client_info = ClientInfo(email='*****@*****.**') itemList=[Item('Item', 'Item desc', 1, '1.1'),Item('Item', 'Item desc', 2, '2.2')] # Add Item doc.add_item(itemList[0]) doc.add_item(itemList[1]) #doc.add_item(Item('Item', 'Item desc', 1, '1.1')) #doc.add_item(Item('Item', 'Item desc', 2, '2.2')) doc.add_item(Item('Item', 'Item desc', 3, '3.3'))
def test_only_items(self): invoice_path = os.path.join(self.file_base_dir, 'only_items.pdf') if os.path.exists(invoice_path): os.remove(invoice_path) invoice = SimpleInvoice(invoice_path) # Before add items item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(len(item_data), 0) self.assertEqual(item_subtotal, Decimal('0')) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 0) self.assertEqual(style, []) # Add items invoice.add_item(Item('Item1', 'Item desc', 1, 1.1)) invoice.add_item(Item('Item2', 'Item desc', 2, u'2.2')) invoice.add_item(Item(u'Item3', 'Item desc', 3, '3.3')) # After add items items = invoice.items self.assertEqual(len(items), 3) self.assertEqual(items[0].name, 'Item1') self.assertEqual(items[0].amount, Decimal('1.1')) self.assertEqual(items[1].amount, Decimal('4.4')) self.assertEqual(items[2].name, u'Item3') self.assertEqual(items[2].amount, Decimal('9.9')) item_data, item_subtotal = invoice._item_raw_data_and_subtotal() self.assertEqual(item_subtotal, Decimal('15.4')) self.assertEqual(len(item_data), 3) item_data, style = invoice._item_data_and_style() self.assertEqual(len(item_data), 6) # header, subtotal, total self.assertEqual(item_data[-2][-1], Decimal('15.4')) # subtotal self.assertEqual(item_data[-1][-1], Decimal('15.4')) # total # test style # ## Subtotal self.assertEqual(style[-4], ('SPAN', (0, 4), (3, 4))) self.assertEqual(style[-3], ('ALIGN', (0, 4), (-2, -1), 'RIGHT')) # ## Total self.assertEqual(style[-2], ('SPAN', (0, 5), (3, 5))) self.assertEqual(style[-1], ('ALIGN', (0, 5), (-2, -1), 'RIGHT')) invoice.finish() self.assertTrue(os.path.exists(invoice_path))
from datetime import datetime, date from pyinvoice.models import InvoiceInfo, ServiceProviderInfo, ClientInfo, Item, Transaction from pyinvoice.templates import SimpleInvoice doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional doc.is_paid = True doc.invoice_info = InvoiceInfo(1023, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name='PyInvoice', street='My Street', city='My City', state='My State', country='My Country', post_code='222222', ) # Client info, optional doc.client_info = ClientInfo(email='*****@*****.**') # Add Item doc.add_item(Item('Item', 'Item desc', 1, '1.1')) doc.add_item(Item('Item', 'Item desc', 2, '2.2')) doc.add_item(Item('Item', 'Item desc', 3, '3.3')) # Tax rate, optional doc.set_item_tax_rate(0) # 0%
def create_pdf(invoice_file, input_dict): """ function for creating pdf :param invoice_file: :param input_dict: :return: """ from pyinvoice.models import InvoiceInfo, ServiceProviderInfo, ClientInfo, Item from pyinvoice.templates import SimpleInvoice d = input_dict print('generating pdf') doc = SimpleInvoice(invoice_file) doc.is_paid = d['paid'] doc.invoice_info = InvoiceInfo(d['invoice_id'], d['created_on'], d['expires_on'], f"{d['company_expiration_fee']} %") # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name=d['company_name'], street=d['company_address'], city=d['company_city'], post_code=d['company_zip_code'], vat_tax_number=d['company_vat']) doc.client_info = ClientInfo(name=d['customer_name'], client_id=d['customer_id'], street=d['customer_address'], city=d['customer_city'], post_code=d['customer_zip_code']) for item in d['item_list']: if item['tax_free']: item['name'] += ' momsfri' doc.add_item(Item(item['name'], '', item['quantity'], item['cost_per'])) # Tax rate, optional doc.set_item_tax_rate(d['tax_percantage']) # 25% # Optional doc.set_bottom_tip( f"Email: {d['company_email']}<br />Kontonummer: {d['company_account']}<br />Godkänd för F-skatt<br />Vid frågor kontakt på {d['company_phone_number']}.<br />{d['extra_info']}" ) doc.finish()
from django.db import models # Create your models here. from datetime import datetime, date from pyinvoice.models import InvoiceInfo, ServiceProviderInfo, ClientInfo, Item, Transaction from Customer.models import PhysicalCustomer from pyinvoice.templates import SimpleInvoice from Employee.models import AddEmployee from Service.models import Service doc = SimpleInvoice('invoice.pdf') c1 = PhysicalCustomer.objects.all()[:1] e1 = AddEmployee.objects.all()[:1] s1 = Service.objects.all()[:1] # Paid stamp, optional doc.is_paid = True #PhysicalCustomer s = new PhysicalCustomer(); doc.invoice_info = InvoiceInfo(1023, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo(name=s1[0].description) # Client info, optional doc.client_info = ClientInfo( name=c1[0].Cust_name, email=c1[0].Cust_email, ) # Add Item
def generate_invoice(token): language = get_language() invoice_name = 'invoice-' + language + '-' + str(token) + '.pdf' invoice_path = os.path.join(SENDFILE_ROOT, 'invoices', invoice_name) international_pyinvoice = { INVOICE_ID: _('Invoice id'), INVOICE_DATETIME: _('Invoice date'), INVOICE: _('Invoice'), DUE_DATE: _('Invoice due date'), NAME: _('Name'), STREET: _('Street'), CITY: _('City'), STATE: _('State'), COUNTRY: _('Country'), POST_CODE: _('Postal code'), VAT_TAX_NUMBER: _('Vat/Tax number'), MERCHANT: _('Merchant'), EMAIL: _('Email'), CLIENT_ID: _('Client id'), CLIENT: _('Client'), DETAIL: _('Detail'), DESCRIPTION: _('Description'), UNITS: _('Units'), UNIT_PRICE: _('Unit Price'), AMOUNT: _('Amount'), SUBTOTAL: _('Subtotal'), TAX: _('Vat/Tax'), TOTAL: _('Total'), TRANSACTION_ID: _('Transaction id'), GATEWAY: _('Gateway'), TRANSACTION_DATE: _('Transaction date'), TRANSACTION: _('Transaction'), PAID: _('PAID'), PROVIDER_ID: _('SIRET'), CAPITAL: _('Capital'), INVOICE_STATUS: _('Payment status') } doc = SimpleInvoice(invoice_path, constants=international_pyinvoice) # get the order and payment order = Order.objects.get(token=token) #payment = order.get_payment() payment = order.payment # set the invoice related data # if payment.status == 'confirmed' or payment.status == 'refunded': # doc.is_paid = True doc.invoice_info = InvoiceInfo(payment.invoice_date.strftime("%Y/%m-") + str(payment.invoice_nb), payment.invoice_date.strftime("%Y/%m/%d"), invoice_status=payment.get_status_display()) # set provider data doc.service_provider_info = eagal_provider # set the client related data client_address = order.billing_address doc.client_info = ClientInfo(email=order.user.email, name=client_address.billing_name, street=client_address.street_address_1 + client_address.street_address_2, city=client_address.city, post_code=client_address.postal_code, state=client_address.country_area, country=client_address.country, client_id=order.user.pk) # set product related data item = order.item price = order.price doc.add_item(Item(item.name, str(item), 1, price.net, price.currency)) doc.set_item_tax_rate(price.tax_percent) # translation to do doc.set_bottom_tip( _("Email: %(email)s <br/>Please contact us if you have any questions.") % {'email': '*****@*****.**'}) doc.finish() return doc, invoice_path
def build_invoice(invoice_config): net = invoice_config['agreement_info'].get('net', 30) invoice_number = get_invoice_number( invoice_config['client_info']['client_id']) doc = SimpleInvoice(PDF_PATH) doc.invoice_info = InvoiceInfo(invoice_number, datetime.now(), datetime.now() + timedelta(days=net)) doc.service_provider_info = ServiceProviderInfo( **invoice_config['service_provider_info']) doc.client_info = ClientInfo(**invoice_config['client_info']) for item in invoice_config['line_items']: doc.add_item(Item(**item)) doc.set_bottom_tip( "Thanks for your business!<br />Email: {}<br />Don't hesitate to contact us for any questions." .format(invoice_config['agreement_info']['provider_email'])) doc.finish()
def GenerateCustomerInvoice(self, invoicenumber, clientemail, reservationtype, quantity, amountInclVAT, amountExVAT, vatAmount, productname): #invoice number should be int #client email we need to receive #reservationtype = upfront reservation or instant reservation #quantity = numbers of units purchased #amountExVAT = amount paid excluding vat #VAT = Vat % (21) try: pathtoInvoice = self.INV_COMP_PATH + invoicenumber + ".pdf" doc = SimpleInvoice(pathtoInvoice, precision=self.INV_COMP_PRECISION) # Paid stamp, optional doc.is_paid = True doc.invoice_info = InvoiceInfo( invoicenumber, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name=self.INV_COMP_NAME, street=self.INV_COMP_STREET + " " + self.INV_COMP_NR, city=self.INV_COMP_CITY, state=self.INV_COMP_STATE, country=self.INV_COMP_COUNTRY, post_code=self.INV_COMP_POSTAL, vat_tax_number=self.INV_COMP_VATNR) # Client info, optional doc.client_info = ClientInfo(email=clientemail) # Add Item #doc.add_item(Item(productname, reservationtype, quantity, amountExVAT)) doc.add_item( Item(productname, reservationtype, quantity, amountInclVAT, amountExVAT, vatAmount)) #doc.add_item(Item('Item', 'Item desc', 2, '2.2')) #doc.add_item(Item('Item', 'Item desc', 3, '3.3')) # Tax rate, optional doc.set_item_tax_rate(self.INV_COMP_TAXRATE) # Transactions detail, optional # doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) # doc.add_transaction(Transaction('Strip', 222, date.today(), 2)) # Optional doc.set_bottom_tip(self.INV_COMP_FOOT) doc.finish() return pathtoInvoice except StandardError: print "Unexpected error" return "error"
def main(invoiceItemsDct=invoiceItemsDct, calendar=calendar, eventType=eventType, project=project, client_email=client_email, client_name=client_name, client_street=client_street, client_city=client_city, client_state=client_state, client_country=client_country, client_post_code=client_post_code, provider_email=provider_email, provider_name=provider_name, provider_street=provider_street, provider_city=provider_city, provider_state=provider_state, provider_country=provider_country, provider_post_code=provider_post_code, provider_tax_rate=provider_tax_rate, billing_rate=billing_rate, invoice_due_date=invoice_due_date, invoice_id=invoice_id, paid_status=False): """ """ doc = SimpleInvoice('invoice.pdf') # Paid stamp, optional doc.is_paid = paid_status # Invoice info, optional doc.invoice_info = InvoiceInfo( invoice_id, datetime.now(), datetime.now() + timedelta(days=invoice_due_date)) # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name=provider_name, street=provider_street, city=provider_city, state=provider_state, country=provider_country, post_code=provider_post_code, # vat_tax_number=vat_tax_number ) # Client info, optional doc.client_info = ClientInfo( email=client_email # name=client_name, # street=client_street, # city=client_city, # state=client_state, # country=client_country, # post_code=client_post_code, ) # Add Item for key1, value1 in invoiceItemsDct.items(): for key2, value2 in value1.items(): doc.add_item( Item(key1, value2['description'], value2['duration'], billing_rate)) # Tax rate, optional doc.set_item_tax_rate(provider_tax_rate) # 20% # Transactions detail, optional ''' doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) ''' # Optional doc.set_bottom_tip( "Email: " + provider_email + "<br />Don't hesitate to contact us for any questions.") doc.finish()
def genPD(self, sales_refno, number): amount = 0 try: doc = SimpleInvoice('invoice2.pdf') # Paid stamp, optional doc.is_paid = True mydb = mysql.connector.connect(host="localhost", user="******", passwd="admin", database="invoice") cursor2 = mydb.cursor() invoice_refno = list() r = random.randint(100, 1000) cursor2.execute("select invoice_refno from bill_info") check = cursor2.fetchall() for i in check: checklist = i if r not in invoice_refno or r not in checklist: invoice_refno.append(r) break invoiceNumber = r doc.invoice_info = InvoiceInfo( invoiceNumber, datetime.now(), datetime.now()) # Invoice info, optional # Service Provider Info, optional doc.service_provider_info = ServiceProviderInfo( name='Python shop', street='23, Bakers Street, Dehradun', city='Dehradun', state='Uttarakhand', country='India', post_code='248009', #vat_tax_number='Vat/Tax number' ) # Client info, optional doc.client_info = ClientInfo( email='*****@*****.**') cursor2.execute("select * from sales_desc where sales_refno = " + str(sales_refno)) details = cursor2.fetchall() #add items in pdf for iterate in details: if iterate[1] == "b01": name = "parle-g" desc = "glucose biscuit 50g" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) elif iterate[1] == "b02": name = "milk-bikis" desc = "glucose biscuit 50g" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) elif iterate[1] == "cr01": name = "ponds face cream" desc = "face cream 100g" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) elif iterate[1] == "hw01": name = "dettol hand wash" desc = "anti-bacterial hand wash" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) elif iterate[1] == "j01": name = "levis jeans" desc = "levis jeans indigo colour waist:- 38 height:- 40" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) elif iterate[1] == "ts01": name = "octave tshirts" desc = "pack of 3 tshirts(red/green/blue)" doc.add_item( Item(name, desc, iterate[2], str(iterate[3] / iterate[2]))) amount += int(iterate[3]) else: print("item will be added to database soon......") # Tax rate, optional doc.set_item_tax_rate(5.25) # 5.25% total_amount = (amount * (5.25 / 100)) + amount print(total_amount) #store bill info in database cursor2.execute("select cid from customer_detail where cmno = " + str(number)) getCustomerId = cursor2.fetchone() sql = "insert into bill_info(sales_refno,total_amount,cid,date,invoice_refno) values(%s,%s,%s,%s,%s)" val = (sales_refno, total_amount, getCustomerId[0], str(datetime.now()), invoiceNumber) cursor2.execute(sql, val) mydb.commit() #Transactions detail, optional doc.add_transaction(Transaction('Paypal', 111, datetime.now(), 1)) doc.add_transaction(Transaction('Stripe', 222, date.today(), 2)) # Optional doc.set_bottom_tip( "Email: [email protected]<br />Feel Free to contact us for any queries." ) except mysql.connector.Error as e: print("database not working......currently working on fix.....") print(e) #to display flash message set 1 finally: import requests url = "https://www.fast2sms.com/dev/bulk" querystring = { "authorization": "n0BJ1r8yP2hOapZUmHcNFEgbvAuxeQXiG5Y3CS7MI9qLdjfok4gRtoI36EPh97QXUm0x2L85dkrzVwnf", "sender_id": "FSTSMS", "message": "Bill Generated!", "language": "english", "route": "p", "numbers": number, "flash": "1" } headers = {'cache-control': "no-cache"} response = requests.request("GET", url, headers=headers, params=querystring) doc.finish() mydb.close() os._exit(0)
def InvoiceMaker(repair_id=None, customer_id=None): if repair_id is not None and customer_id is not None: # Declare dictionaries and arrays item = [] full = {} # Get repair infos rep = Repair.objects.get(id=repair_id) # Get Invoice No invoice = Invoice.objects.get(repair=rep) no_invoice = f"{invoice.period}-{invoice.id:03d}" # Get items for this repair for repair in CategoryItemPhoneRepair.objects.filter( repair__customer_id=customer_id, repair_id=repair_id): if repair.custom_price == 0: price = repair.category.normal_price else: price = repair.custom_price print(repair.category.normal_price) print(repair.custom_price) dt = { "sn": repair.item.sn, 'cat': repair.category.category, 'price': price, 'prix': repair.category.normal_price, 'caption': repair.category.detail } item.append(dt) full['usr'] = repair.repair.customer full['pcs'] = item # Create the invoice pdf doc = SimpleInvoice('app/static/Facture-' + no_invoice + '.pdf') try: address = Address.objects.get(customer=full['usr']) print(address) except Address.DoesNotExist: address = Address.objects address.no = "" address.street = "" address.city = "" address.cp = "" address.country = "" try: phone = PhoneNumber.objects.get(customer=full['usr']) phone = phone.no_phone except PhoneNumber.DoesNotExist: phone = "0000000000" # TODO Make invoice and quotation # if full['state'].short_state == "Q": # type = "Devis" # elif full['state'].short_state == "HF" or full['state'].short_state == "P": # type = "Facture" doc.invoice_info = InvoiceInfo( no_invoice, rep.date_repaired, datetime.now().date()) # Invoice info, optional if rep.status.short_state == 'P': doc.is_paid = True else: doc.is_paid = False # Company Info, optional doc.service_provider_info = ServiceProviderInfo( name='SARL Hinna', street='70 Rue de la coquillarde, Espace Eole, Hall A', phone='06 66 69 65 56', city='Puyricard', state='PACA', country='France', post_code='13540', vat_tax_number='FR 71 879062552', siren="879 062 552 R.C.S. Aix-en-Provence", capital="1 000,00 Euros", denomination="Société à responsabilité limitée (SARL)", formated_address= '70 Rue de la coquillarde,<br/> Espace Eole, Hall A, <br/>13540 Puyricard, France', email='*****@*****.**', ) # Client info, optional t = iter(phone) nophone = ' '.join(a + b for a, b in zip(t, t)) doc.client_info = ClientInfo( email=full['usr'].mail + 'ff', name=full['usr'].famillyname.capitalize() + " " + full['usr'].firstname.capitalize(), street=address.no + ' ' + address.street, city=address.city, country=address.country, post_code=address.cp, client_id=f"{full['usr'].id:03d}", phone=nophone) # Add Items for i in item: i['caption'] = "<br />".join(i['caption'].split("\n")) doc.add_item( pyinvoice.models.Item(1, i['caption'], i['sn'], i['prix'], i['prix'])) # TVA doc.set_item_tax_rate(20) # 20% # Payments details for p in RepairPayment.objects.filter(repair=rep): doc.add_transaction( Transaction(transaction_id=p.id_payment, gateway=p.method.method, transaction_datetime=p.date_paid, amount=p.amount)) # Footer doc.set_bottom_tip( '<para>' + doc.service_provider_info.name + '<br/>' + doc.service_provider_info.formated_address + '<br/>' + doc.service_provider_info.email + '<br/>TVA Intracommunautaire : ' + doc.service_provider_info.vat_tax_number + '<br/>' + doc.service_provider_info.denomination + ' Au capital de ' + doc.service_provider_info.capital + ' - ' + doc.service_provider_info.siren + '<br/> Le défaut de paiement total ou partiel à la date d\'échéance indiquée sur la facture fera courir de façon automatique des intérêts, dès le premier jour de retard, au taux d\'intérêt légal. La totalité des frais de recouvrement demeureront à la charge du client débiteur. Aucun escompte ne sera pratiqué en cas de paiement anticipé.' + '<br/>Facture éditée le ' + str(datetime.now().date()) + '</para>') doc.finish() return True
def generateInvoice(self): print(self.invoiceService) print(self.servicePrice) if str(self.invoiceService).find(","): servicesSplittedList = self.invoiceService.split(",") print(servicesSplittedList) else: servicesSplittedList = [self.invoiceService] if str(self.servicePrice).find(","): pricesSplittedList = str(self.servicePrice).split(",") print(pricesSplittedList) else: pricesSplittedList = [str(self.invoiceService)] doc = SimpleInvoice(self.invoiceName + ".pdf") #Paid stamp doc.is_paid = False doc.invoice_info = InvoiceInfo(self.invoiceNumber, self.invoiceDate, self.invoiceExpiringDate) #Service provider doc.service_provider_info = ServiceProviderInfo( name="R&M Tech", street="My street", city="My City", state="My State", country="Costa Rica", post_code="22222222", vat_tax_number="Vat/Tax number") #client info doc.client_info = ClientInfo(name=self.invoiceName, client_id=self.invoiceID, email=self.invoiceEmail, street=self.invoiceAddress) #add item for i in range(0, len(servicesSplittedList)): doc.add_item( Item(servicesSplittedList[i], "", 1, str(pricesSplittedList[i]))) #tax rate doc.set_item_tax_rate(0) payments = [ "PayPal", "MasterCard", "Visa", "Google Pay", "Apple Pay", "Cash", "Cash", "Cash", "Cash" ] #transactions detail doc.add_transaction( Transaction(random.choice(payments), self.invoiceID, self.invoiceDate, 1)) #Optional doc.set_bottom_tip( "Email: [email protected]<br />Don't hesitate to contact us for any questions." ) doc.finish() print("PDF Done")