def test_xml_generation(sample_invoice_xml): invoice = Invoice() invoice_xml = _xml_to_string(invoice.to_xml()) sample_xml = _xml_to_string(sample_invoice_xml) assert invoice_xml == sample_xml
def save_invoice(r): date = datetime.datetime.strptime(r['date'],'%d-%b-%Y') try: inv_num = int(r['reference'].split("-")[-1]) except: inv_num = r['inv_num'] i = Invoice( # Invoice type = InvoiceType.objects.get(pk=3),#r['itype']), date = date, #r['date'], contact = Contact.objects.get(pk=r['contact_id']), inv = inv_num, #re.sub(r'[^0-9.]','',inv_num), ref = r['reference'], nett = str(re.sub(r'[^0-9.]','',r['inv_nett'])), gst = str(re.sub(r'[^0-9.]','',r['inv_gst'])), total = str(re.sub(r'[^0-9.]','',r['inv_total'])) ) try: ipk = Invoice.objects.get(ref=r['reference']) i.pk = ipk.pk except: pass i.save() return i
def create_invoices(startDate, endDate): startdatetime = datetime(startDate.year, startDate.month, startDate.day) enddatetime = datetime(endDate.year, endDate.month, endDate.day) # because sql will check on 0:00 am on end date, if shipdate was 7pm on enddate, it will not be included enddatetime = enddatetime + timedelta(days=1) # startdatetime = datetime.combine(startDate, datetime.min.time()) # enddatetime = datetime.combine(endDate, datetime.max.time()) shipped_orders = Order.objects.filter(shipDate__range=(startdatetime, enddatetime)).filter(orderStatus="Shipped").order_by('orderNo') invoice_amounts = {} orderNoList = [] if len(shipped_orders) == 0: logger.exception( ' admin or system tried generated invoice for ' + str(startDate) + ' to ' + str(endDate) + ', But no shipped order during these days.') return 0 for order in shipped_orders: try: invoiceno = "SFMINV-" + startDate.strftime("%m%d") + "-" + endDate.strftime("%m%d") \ + "-" + order.store.storeCode if invoiceno not in list(invoice_amounts.keys()): print('adding invoice for store', order.storeName) # invoicenote = "invoice from SFM" # check if the invoice already exists, if so delete the invoice and create new Invoice.objects.filter(invoiceNo=invoiceno).delete() invoice = Invoice(startDate=startDate, endDate=endDate, storeName=order.storeName, store=order.store, invoiceNo=invoiceno, status="Unpaid", notes="", subTotal=0, discount=0, taxrate=0) invoice.save() invoice_amounts[invoiceno] = 0 # print(order.saleDate) orderdate = order.saleDate if order.saleDate is not None else order.shipDate.date() invoice = Invoice.objects.get(invoiceNo=invoiceno) if order.customerPaidShipping is not None and order.customerPaidShipping > 0 and order.orderNo not in orderNoList: invoiceshipitem = InvoiceItems(invoice=invoice, shipDate=order.shipDate.date(), orderDate=orderdate, orderNo=order.orderNo, customer=order.recipientName, description='Shipping', amount=order.customerPaidShipping) invoiceshipitem.save() invoice_amounts[invoiceno] += order.customerPaidShipping orderNoList.append(order.orderNo) product = Product.objects.get(sfmId=order.sfmId) amt = product.price desc = order.sfmId + '-' + order.design invoiceitem = InvoiceItems(invoice=invoice, shipDate=order.shipDate.date(), orderDate=orderdate, orderNo=order.orderNo, customer=order.recipientName, description=desc, amount=amt) invoiceitem.save() invoice_amounts[invoiceno] += amt except Exception as err: print('error ----', str(err)) logger.exception('Error in invoice ' + invoiceno + ', item for order ' + order.sfmId + ', Aborting... details: ' + str(err)) raise Exception('Error generating invoice') logger.info(' admin or system generated invoice for ' + str(startDate) + ' to ' + str(endDate) + ' , count: ' + str(len(invoice_amounts))) updateInvoices(invoice_amounts) return len(invoice_amounts)
def forms_valid(self, form, formset): user = self.request.user invoice = Invoice( recipient=user, status='new', compound=True, date=timezone.now(), invoiced_entity=form.cleaned_data['invoiced_entity'], billing_address=form.cleaned_data['billing_address'], ) invoice.save() for i, form in enumerate(formset.forms): if not hasattr(form, 'invoice'): continue child_invoice = form.invoice InvoiceLine( invoice_id=invoice.id, line_order=i, reference='INV#{}'.format(child_invoice.reference_number), description='DebConf attendance for {}'.format( child_invoice.recipient.userprofile.display_name()), unit_price=child_invoice.total, quantity=1, ).save() self.reference_number = invoice.reference_number return super().forms_valid(form, formset)
def process_packings(queryset): """ Given a Packing and Packing Items that have been completed, process and generate Invoices """ packings = queryset packing_count = 0 for packing in packings: packing_items = PackingItem.objects.filter(packing=packing) invoice_kwargs = { 'packing': packing, 'signed_off_at': timezone.now(), } invoice = Invoice(**invoice_kwargs) invoice.save() try: print u'%s' % invoice except: pass packing_item_count = 0 for packing_item in packing_items: if packing_item.fulfilled: invoice_item_kwargs = { 'invoice': invoice, 'packing_item': packing_item, 'invoice_weight': packing_item.fulfilment_weight, 'invoice_quantity': packing_item.fulfilment_quantity, 'invoice_unit_weight': packing_item.fulfilment_unit_weight, 'invoice_weight_price': packing_item.fulfilment_weight_price, 'invoice_unit_price': packing_item.fulfilment_unit_price, 'notes': packing_item.notes, } invoice_item = InvoiceItem(**invoice_item_kwargs) try: invoice_item.full_clean() except ValidationError, e: print e else: invoice_item.save() packing_item_count += 1 try: print u' %s' % invoice_item except: pass else: break if len(packing_items) == packing_item_count: packing_count += 1
def save(self, invoice, invoice_items, company): with transaction.atomic(): instance = Invoice(**invoice) instance.company = company print(instance.released_at) instance.save() for item in invoice_items: entry = InvoiceItem(**item) entry.invoice = instance entry.save()
def process_recurring_invoice(self, template): new = Invoice(contractor=template.contractor, subscriber=template.subscriber, direction=template.direction, paymentWay=template.paymentWay, currency=template.currency) new.save() for i in template.items.all(): newi = Item(name=i.name, count=i.count, price=i.price) new.items.add(newi) return new
def on_new_credit(sender, companyInfo, amount, currency, **kwargs): """ Creates invoice with credit """ from invoices.models import Invoice, Item if companyInfo.id == settings.OUR_COMPANY_ID: return # do not generate invoice to ourself invoice = Invoice(subscriber=companyInfo, paid=True) invoice.save() itemTitle = '%s (%i)' % (ugettext('Phone services credit'), companyInfo.phone) invoice.items.add(Item(price=amount, name=itemTitle)) invoice.send()
def save_receipt(self, customer, subscription): invoice = Invoice( customer=customer, date=timezone.now(), name=customer.name, description=_("Upgrade/downgrade to {subscription}").format( subscription=subscription.name), amount=subscription.price, method=Invoice.LIPA_NA_MPESA, upgrade_to=subscription) invoice.save() receipt, created = MPESAReceipt.objects.get_or_create( receipt=self.cleaned_data['receipt'], customer=customer, invoice=invoice)
def save_payment(self, customer): invoice = Invoice( customer=customer, date=timezone.now(), name=customer.name, description=_("{subscription} subscription payment").format( subscription=customer.customersubscription.subscription), amount=customer.customersubscription.subscription.price, method=Invoice.LIPA_NA_MPESA, ) invoice.save() receipt, created = MPESAReceipt.objects.get_or_create( receipt=self.cleaned_data['receipt'], customer=customer, invoice=invoice)
def save_payment(self, customer): invoice = Invoice( customer=customer, date=timezone.now(), name=customer.name, description=_("{subscription} subscription payment").format( subscription=customer.customersubscription.subscription), amount=customer.customersubscription.subscription.price, method=Invoice.LIPA_NA_MPESA, ) invoice.save() receipt, created = MPESAReceipt.objects.get_or_create( receipt=self.cleaned_data['receipt'], customer=customer, invoice=invoice )
def save_receipt(self, customer, subscription): invoice = Invoice( customer=customer, date=timezone.now(), name=customer.name, description=_( "Upgrade/downgrade to {subscription}").format(subscription=subscription.name), amount=subscription.price, method=Invoice.LIPA_NA_MPESA, upgrade_to=subscription ) invoice.save() receipt, created = MPESAReceipt.objects.get_or_create( receipt=self.cleaned_data['receipt'], customer=customer, invoice=invoice )
def generate_invoice(cls, character, ref, amount, message): # generate an invoice and return it due = timezone.now() + timedelta(days=14) return Invoice(character=character, amount=round(amount, -6), invoice_ref=ref, note=message, due_date=due)
def pay_overview(request): """ Shows a list of all payable expenses and lets user pay them. """ return render(request, 'admin/pay/overview.html', { 'expenses': json.dumps([expense.to_dict() for expense in Expense.payable()], default=json_serial), 'invoices': json.dumps([invoice.to_dict() for invoice in Invoice.payable()], default=json_serial), 'accounts': json.dumps([s.name for s in BankAccount.objects.all().order_by('name')]) })
def account_overview(request): return render(request, 'admin/account/overview.html', { 'expenses': json.dumps( [expense.to_dict() for expense in Expense.accountable(request.user.profile.may_account())], default=json_serial), 'invoices': json.dumps( [invoice.to_dict() for invoice in Invoice.accountable(request.user.profile.may_account())], default=json_serial) })
def verifyPayment(request): request_body = json.loads(request.body.decode('utf-8')) print(request_body) params = {} try: params['razorpay_payment_id'] = request_body['payment_id'] params['razorpay_signature'] = request_body['signature'] except KeyError: return Response({'message': 'Provide both payment_id and signature'}) try: params['razorpay_order_id'] = orders[request.user.email]['id'] except KeyError: return Response({'message': 'No order found for this user'}) env = environ.Env( DEBUG=(bool, False) ) environ.Env.read_env() RAZORPAY_ID = env('RAZORPAY_ID') RAZORPAY_SECRET_KEY = env('RAZORPAY_SECRET_KEY') client = razorpay.Client(auth=(RAZORPAY_ID, RAZORPAY_SECRET_KEY)) result = 1 try: client.utility.verify_payment_signature(params) except razorpay.errors.SignatureVerificationError: result = 0 if result == 1: order = client.order.fetch(params['razorpay_order_id']) invoice = Invoice(type='bill', order_id=order['id']) invoice.save() payment = Payment(buyer=request.user, invoice=invoice, amount=order['amount'] / 100) payment.save() bill = Bill.objects.get(id=order['notes']['bill_id']) bill.is_paid = True bill.save() return Response({'success': result})
def create(request): next_page = 'invoices/create.html' clients = Client.objects.all() if request.method == 'POST': client = Client.objects.get(pk=request.POST['input_client']) reference_name = request.POST['input_reference_name'] reference_number = -1 if 'input_reference_number' not in request.POST or request.POST['input_reference_number'] == '' else request.POST.get('input_reference_number', -1) items_description = request.POST.getlist('input_description') items_price = request.POST.getlist('input_price') if len(items_description) == 0 or len(items_price) == 0: message = 'Debe especificar al menos un item' level = 'danger' return render(request,'invoices/create.html',{'message': message,'message_level':level}) input_date = request.POST['input_date_created'] if input_date == '': message = 'Debe especificar la fecha' level = 'danger' return render(request,'invoices/create.html',{'clients':clients,'message': message,'message_level':level}) else: date_formated = datetime.datetime.strptime(input_date,'%d/%M/%Y').strftime('%Y-%M-%d') i = Invoice( sub_total = request.POST['input_subtotal'], iva = request.POST['input_iva'], total = request.POST['input_total'], date_created = date_formated, reference_number = reference_number, reference_name = reference_name, client = client ) i.save() print items_description for index in xrange(0,len(items_description)): item = Item(description = items_description[index], price = items_price[index], invoice = i) item.save() return HttpResponseRedirect('/invoices/%s/'%i.id) else: selected_client = request.GET.get('client_id','') t = loader.get_template(next_page) c = RequestContext(request,{'clients':clients, 'selected_client':selected_client}) return HttpResponse(t.render(c))
def create_consumption_and_invoice(measurer, measure): with transaction.atomic(): consumption_history = ConsumptionHistory.objects.create( from_date = measurer.last_visit, consumption = measurer.calculate_consumption(measure), measurer = measurer ) measurer.register_visit(measure) invoice = Invoice( detail = consumption_history, client = measurer.house.familyboss, place = measurer.house ) invoice.save() return { 'consumption' : consumption_history.consumption, 'amount' : invoice.amount, 'house' : measurer.house.house_id }
def attest_overview(request): """ Displays the attest overview list. """ return render(request, 'admin/attest/overview.html', { 'expenses': json.dumps( [expense.to_dict() for expense in Expense.attestable(request.user.profile.may_attest(), request.user)], default=json_serial), 'invoices': json.dumps( [invoice.to_dict() for invoice in Invoice.attestable(request.user.profile.may_attest(), request.user)], default=json_serial) })
def sample_invoice(sender, sample_items, client_address) -> Invoice: invoice = Invoice( is_business=True, sender=sender, invoice_number="00001A", invoice_type="TD01", invoice_currency="EUR", invoice_date=date(2019, 6, 16), invoice_deadline=date(2019, 5, 2), invoice_tax_rate=22.00, invoice_amount=2.00, invoice_tax_amount=2.00, causal=("A" * 200 + "B" * 200), transmission_format="FPR12", payment_condition="TP02", payment_method="MP08", recipient_code="ABCDEFG", recipient_tax_code="AAABBB12B34Z123D", recipient_first_name="Patrick", recipient_last_name="A", recipient_address=client_address, ) invoice.save() for item in sample_items: item.save() invoice.items.add(item) invoice.save() return invoice
def process_packings(queryset): """ Given a Packing and Packing Items that have been completed, process and generate Invoices """ packings = queryset for packing in packings: packing_items = PackingItem.objects.filter(packing=packing) invoice_kwargs = { 'packing': packing, } invoice = Invoice(**invoice_kwargs) invoice.save() print u'%s' % invoice for packing_item in packing_items: invoice_item_kwargs = { 'invoice': invoice, 'packing_item': packing_item, 'invoice_weight': packing_item.fulfilment_weight, 'invoice_quantity': packing_item.fulfilment_quantity, 'invoice_unit_weight': packing_item.fulfilment_unit_weight, 'invoice_weight_price': packing_item.fulfilment_weight_price, 'invoice_unit_price': packing_item.fulfilment_unit_price, 'notes': packing_item.notes, } invoice_item = InvoiceItem(**invoice_item_kwargs) try: invoice_item.full_clean() except ValidationError, e: print e else: invoice_item.save() print u' %s' % invoice_item
def send_daily_invoice_notification(): today = datetime.datetime.today() #today = datetime.datetime(2010, 7, 15) gw = BraintreeGateway(settings.MERCHANT_ID, settings.PUBLIC_KEY, settings.PRIVATE_KEY) transactions = gw.get_daily_transactions(today) logging.info("%s transactions were found today %s" % (len(transactions), today)) for transaction in transactions: if transaction.subscription_id is not None: invoice = Invoice() invoice.cc_mask = '*'*12 + transaction.credit_card_details.masked_number[12:] invoice.cc_type = transaction.credit_card_details.card_type invoice.charge = decimal.Decimal(transaction.amount) invoice.currency = transaction.currency_iso_code invoice.transaction_status_response = transaction.processor_response_text invoice.transaction_type = transaction.type.lower() invoice.transaction_id = transaction.id invoice.customer_name = "%s %s" % (transaction.customer_details.first_name, transaction.customer_details.last_name) invoice.customer_email = transaction.customer_details.email invoice.customer_id = transaction.customer_details.id invoice.shop_dns = "<Unspecified Shop>" if transaction.customer_details.website is None else transaction.customer_details.website try: shop_id = None if transaction.vault_customer.custom_fields is '' else transaction.vault_customer.custom_fields.get("shop_id", None) if shop_id is not None: try: shop = Shop.objects.get(id=shop_id) invoice.shop = shop invoice.market_place = shop.marketplace.name except Shop.DoesNotExist: logging.error("Shop ID = %s not exist for user %s" % (shop_id, invoice.customer_name)) pass else: logging.error("User %s has not setted shop_id property in braintree" % invoice.customer_name) except Exception, e: logging.error(e) pass invoice.subscription_id = transaction.subscription_id subscription = gw.get_subscription_details(invoice.subscription_id) invoice.plan_id = subscription.plan_id invoice.valid_from = subscription.billing_period_start_date invoice.valid_up_to = subscription.billing_period_end_date invoice.next_billing_date = subscription.next_billing_date invoice.save() msg = invoice.to_text() logging.info("Sending email to %s. tx=%s, charge=%s, " % (invoice.customer_name, invoice.transaction_id, invoice.charge)) mail = EmailMessage(subject='%s | Notification Invoice' % invoice.market_place, body=msg, from_email=settings.EMAIL_FROM, to=[invoice.customer_email]+[mail for name, mail in settings.STAFF], headers={'X-SMTPAPI': '{\"category\": \"Notification Invoice\"}'}) mail.send(fail_silently=True)
def test_sales_pending_without_invoice(self): """ Should return this sale if not have Invoice to cover""" sale = SaleFactory(total_value=100) self.assertCountEqual(Invoice.sales_pending().all(), [sale])
def job_set_inv_payment(user, job, pricing): if get_setting('module', 'jobs', 'jobsrequirespayment'): if not job.invoice: inv = Invoice() inv.object_type = ContentType.objects.get(app_label=job._meta.app_label, model=job._meta.module_name) inv.object_id = job.id inv.title = "Job Add Invoice" inv.bill_to = job.contact_name first_name = '' last_name = '' if job.contact_name: name_list = job.contact_name.split(' ') if len(name_list) >= 2: first_name = name_list[0] last_name = ' '.join(name_list[1:]) inv.bill_to_first_name = first_name inv.bill_to_last_name = last_name inv.bill_to_company = job.contact_company inv.bill_to_address = job.contact_address inv.bill_to_city = job.contact_city inv.bill_to_state = job.contact_state inv.bill_to_zip_code = job.contact_zip_code inv.bill_to_country = job.contact_country inv.bill_to_phone = job.contact_phone inv.bill_to_fax = job.contact_fax inv.bill_to_email = job.contact_email inv.ship_to = job.contact_name inv.ship_to_first_name = first_name inv.ship_to_last_name = last_name inv.ship_to_company = job.contact_company inv.ship_to_address = job.contact_address inv.ship_to_city = job.contact_city inv.ship_to_state = job.contact_state inv.ship_to_zip_code = job.contact_zip_code inv.ship_to_country = job.contact_country inv.ship_to_phone = job.contact_phone inv.ship_to_fax = job.contact_fax inv.ship_to_email =job.contact_email inv.terms = "Due on Receipt" inv.due_date = datetime.now() inv.ship_date = datetime.now() inv.message = 'Thank You.' inv.status = True inv.total = get_job_price(user, job, pricing) inv.subtotal = inv.total inv.balance = inv.total inv.estimate = 1 inv.status_detail = 'estimate' inv.save(user) # update job job.invoice = inv job.save() if is_admin(user): if job.payment_method in ['paid - cc', 'paid - check', 'paid - wire transfer']: boo_inv = inv.tender(user) # payment payment = Payment() boo = payment.payments_pop_by_invoice_user(user, inv, inv.guid) payment.mark_as_paid() payment.method = job.payment_method payment.save(user) # this will make accounting entry inv.make_payment(user, payment.amount)
def corp_memb_inv_add(user, corp_memb, **kwargs): """ Add an invoice for this corporate membership """ renewal = kwargs.get('renewal', False) renewal_total = kwargs.get('renewal_total', 0) renew_entry = kwargs.get('renew_entry', None) if not corp_memb.invoice or renewal: inv = Invoice() if renew_entry: inv.object_type = ContentType.objects.get(app_label=renew_entry._meta.app_label, model=renew_entry._meta.module_name) inv.object_id = renew_entry.id else: inv.object_type = ContentType.objects.get(app_label=corp_memb._meta.app_label, model=corp_memb._meta.module_name) inv.object_id = corp_memb.id inv.title = "Corporate Membership Invoice" inv.bill_to = corp_memb.name inv.bill_to_company = corp_memb.name inv.bill_to_address = corp_memb.address inv.bill_to_city = corp_memb.city inv.bill_to_state = corp_memb.state inv.bill_to_zip_code = corp_memb.zip inv.bill_to_country = corp_memb.country inv.bill_to_phone = corp_memb.phone inv.bill_to_email = corp_memb.email inv.ship_to = corp_memb.name inv.ship_to_company = corp_memb.name inv.ship_to_address = corp_memb.address inv.ship_to_city = corp_memb.city inv.ship_to_state = corp_memb.state inv.ship_to_zip_code = corp_memb.zip inv.ship_to_country = corp_memb.country inv.ship_to_phone = corp_memb.phone inv.ship_to_email =corp_memb.email inv.terms = "Due on Receipt" inv.due_date = datetime.now() inv.ship_date = datetime.now() inv.message = 'Thank You.' inv.status = True if not renewal: inv.total = corp_memb.corporate_membership_type.price else: inv.total = renewal_total inv.subtotal = inv.total inv.balance = inv.total inv.estimate = 1 inv.status_detail = 'estimate' inv.save(user) if is_admin(user): # if offline payment method if not corp_memb.get_payment_method().is_online: inv.tender(user) # tendered the invoice for admin if offline # mark payment as made payment = Payment() payment.payments_pop_by_invoice_user(user, inv, inv.guid) payment.mark_as_paid() payment.method = corp_memb.get_payment_method() payment.save(user) # this will make accounting entry inv.make_payment(user, payment.amount) return inv return None
def _insertInvoice(self, what): s = CompanyInfo.objects.all().order_by('?')[0] invoice = Invoice(subscriber=s) invoice.save() invoice.items.add(Item(name=what, count=2, price=13)) return invoice
def make_invoice_for_entry(entry, **kwargs): """ Create an invoice for a Form Entry. """ price = entry.pricing.price or kwargs.get('custom_price') price = unicode(price) now = datetime.now() inv = Invoice() inv.title = "%s Invoice" % (entry.form.title) inv.object_type = ContentType.objects.get(app_label=entry._meta.app_label, model=entry._meta.module_name) inv.object_id = entry.id inv.subtotal = price inv.total = price inv.balance = price inv.due_date = now inv.ship_date = now inv.save() return inv
def save_invoice(self, *args, **kwargs): status_detail = kwargs.get('status_detail', 'tendered') admin_notes = kwargs.get('admin_notes', None) object_type = ContentType.objects.get(app_label=self._meta.app_label, model=self._meta.module_name) try: # get invoice invoice = Invoice.objects.get( object_type = object_type, object_id = self.pk, ) except ObjectDoesNotExist: # else; create invoice # cannot use get_or_create method # because too many fields are required invoice = Invoice() invoice.object_type = object_type invoice.object_id = self.pk # update invoice with details invoice.title = "Registration %s for Event: %s" % (self.pk, self.event.title) invoice.estimate = True invoice.status_detail = status_detail invoice.subtotal = self.amount_paid invoice.total = self.amount_paid invoice.balance = invoice.total invoice.tender_date = datetime.now() invoice.due_date = datetime.now() invoice.ship_date = datetime.now() invoice.admin_notes = admin_notes invoice.save() self.invoice = invoice self.save() return invoice
def test_sales_pending_with_invoice_not_all_value(self): """ Should return this sale if has invoices for not all total_value""" sale = SaleFactory(total_value=1000) InvoiceFactory(sale=sale, total_value=50) InvoiceFactory(sale=sale, total_value=50) self.assertCountEqual(Invoice.sales_pending().all(), [sale])
def send_daily_invoice_notification(): today = datetime.datetime.today() #today = datetime.datetime(2010, 7, 15) gw = BraintreeGateway(settings.MERCHANT_ID, settings.PUBLIC_KEY, settings.PRIVATE_KEY) transactions = gw.get_daily_transactions(today) logging.info("%s transactions were found today %s" % (len(transactions), today)) for transaction in transactions: if transaction.subscription_id is not None: invoice = Invoice() invoice.cc_mask = '*' * 12 + transaction.credit_card_details.masked_number[ 12:] invoice.cc_type = transaction.credit_card_details.card_type invoice.charge = decimal.Decimal(transaction.amount) invoice.currency = transaction.currency_iso_code invoice.transaction_status_response = transaction.processor_response_text invoice.transaction_type = transaction.type.lower() invoice.transaction_id = transaction.id invoice.customer_name = "%s %s" % ( transaction.customer_details.first_name, transaction.customer_details.last_name) invoice.customer_email = transaction.customer_details.email invoice.customer_id = transaction.customer_details.id invoice.shop_dns = "<Unspecified Shop>" if transaction.customer_details.website is None else transaction.customer_details.website try: shop_id = None if transaction.vault_customer.custom_fields is '' else transaction.vault_customer.custom_fields.get( "shop_id", None) if shop_id is not None: try: shop = Shop.objects.get(id=shop_id) invoice.shop = shop invoice.market_place = shop.marketplace.name except Shop.DoesNotExist: logging.error("Shop ID = %s not exist for user %s" % (shop_id, invoice.customer_name)) pass else: logging.error( "User %s has not setted shop_id property in braintree" % invoice.customer_name) except Exception, e: logging.error(e) pass invoice.subscription_id = transaction.subscription_id subscription = gw.get_subscription_details(invoice.subscription_id) invoice.plan_id = subscription.plan_id invoice.valid_from = subscription.billing_period_start_date invoice.valid_up_to = subscription.billing_period_end_date invoice.next_billing_date = subscription.next_billing_date invoice.save() msg = invoice.to_text() logging.info("Sending email to %s. tx=%s, charge=%s, " % (invoice.customer_name, invoice.transaction_id, invoice.charge)) mail = EmailMessage(subject='%s | Notification Invoice' % invoice.market_place, body=msg, from_email=settings.EMAIL_FROM, to=[invoice.customer_email] + [mail for name, mail in settings.STAFF], headers={ 'X-SMTPAPI': '{\"category\": \"Notification Invoice\"}' }) mail.send(fail_silently=True)
def test_sales_pending_with_invoice_for_most_all_value(self): """ Should return not sale if has invoices for all total_value""" sale = SaleFactory(total_value=1000) InvoiceFactory(sale=sale, total_value=1500) InvoiceFactory(sale=sale, total_value=500) self.assertEqual(Invoice.sales_pending().count(), 0)
def load_invoice(request): variables = {} if request.POST: invoice = Invoice() detail_invoice = [] xmlfile = request.FILES['xmlfile'] tree = ET.parse(xmlfile) root = tree.getroot() emision = int(root.attrib['emision']) emision = datetime.utcfromtimestamp(emision).strftime('%Y-%m-%d') invoice.date = emision tipo = root.attrib['tipo'] invoice.type = tipo folio = root.attrib['folio'] invoice.folio = int(folio) rut_emisor = root[0].attrib['rut'] invoice.issuing_rut = str(rut_emisor) nombre_emisor = root[0].attrib['razonSocial'] invoice.issuing_name = nombre_emisor rut_receptor = root[1].attrib['rut'] invoice.receiver_rut = str(rut_receptor) nombre_receptor = root[1].attrib['razonSocial'] invoice.receiver_name = nombre_receptor detail = [] for r in root[2]: dic = { 'monto': r.attrib['monto'], 'iva': r.attrib['iva'], 'detalle': r.text } detail.append(dic) invoice.detail = str(detail) try: invoice.save() variables['mensaje'] = "guardado correctamente" print("se guardo") except: variables['mensaje'] = "error al guardar" print("no se guardo") return render(request, 'invoices/load_invoice.html', variables)
class SaleListPendingInvoice(SaleListView): queryset = Invoice.sales_pending()\ .select_related('customer').order_by('-id') template_name = 'sales/pending_invoice.html'
def test_xml_header_generation(sender, client_address, sample_summary): invoice = Invoice( sender=sender, invoice_number="00001A", invoice_type="TD01", invoice_currency="EUR", invoice_summary=sample_summary, invoice_date=date(2019, 6, 16), transmission_format="FPR12", recipient_code="ABCDEFG", recipient_tax_code="AAABBB12B34Z123D", recipient_first_name="Patrick", recipient_last_name="A", recipient_address=client_address, ) xml = invoice.to_xml() assert xml is not None header = xml.xpath( "/p:FatturaElettronica/FatturaElettronicaHeader", namespaces={ "p": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" }, )[0] t_data = header.xpath("DatiTrasmissione")[0] assert t_data.xpath("IdTrasmittente/IdPaese")[0].text == "IT" assert t_data.xpath("IdTrasmittente/IdCodice")[0].text == "PIABCDE" assert t_data.xpath("ProgressivoInvio")[0].text == "00001A" assert t_data.xpath("FormatoTrasmissione")[0].text == "FPR12" # TODO: test PEC address assert t_data.xpath("CodiceDestinatario")[0].text == "ABCDEFG" # TODO: might need to add this to the invoice, in order to be able to # TODO: use different party for invoices (if ever needed) # Supplier data s_data = header.xpath("CedentePrestatore/DatiAnagrafici")[0] assert s_data.xpath("IdFiscaleIVA/IdPaese")[0].text == "IT" # TODO: add this to the model if it is the P. IVA # assert s_data.xpath("IdFiscaleIVA/IdCodice")[0].text == "IT" assert s_data.xpath("RegimeFiscale")[0].text == "RF01" assert (s_data.xpath("Anagrafica/Denominazione")[0].text == "Python Italia APS") a_data = header.xpath("CedentePrestatore/Sede")[0] assert a_data.xpath("Indirizzo")[0].text == "Via Mugellese 1/A" assert a_data.xpath("CAP")[0].text == "50013" assert a_data.xpath("Comune")[0].text == "Campi Bisenzio" assert a_data.xpath("Provincia")[0].text == "FI" assert a_data.xpath("Nazione")[0].text == "IT" # Client data c_data = header.xpath("CessionarioCommittente/DatiAnagrafici")[0] assert c_data.xpath("CodiceFiscale")[0].text == "AAABBB12B34Z123D" assert c_data.xpath("Anagrafica/Nome")[0].text == "Patrick" assert c_data.xpath("Anagrafica/Cognome")[0].text == "A" ca_data = header.xpath("CessionarioCommittente/Sede")[0] assert ca_data.xpath("Indirizzo")[0].text == "Via Roma 1" assert ca_data.xpath("CAP")[0].text == "83100" assert ca_data.xpath("Comune")[0].text == "Avellino" assert ca_data.xpath("Provincia")[0].text == "AV" assert ca_data.xpath("Nazione")[0].text == "IT"
def test_xml_body_generation(sender, client_address, sample_summary): invoice = Invoice( sender=sender, invoice_number="00001A", invoice_type="TD01", invoice_currency="EUR", invoice_date=date(2019, 6, 16), invoice_summary=sample_summary, invoice_tax_rate=22.00, invoice_amount=2.00, invoice_tax_amount=2.00, causal=("A" * 200 + "B" * 200), transmission_format="FPR12", recipient_code="ABCDEFG", recipient_tax_code="AAABBB12B34Z123D", recipient_first_name="Patrick", recipient_last_name="A", recipient_address=client_address, ) xml = invoice.to_xml() assert xml is not None body = xml.xpath( "/p:FatturaElettronica/FatturaElettronicaBody", namespaces={ "p": "http://ivaservizi.agenziaentrate.gov.it/docs/xsd/fatture/v1.2" }, )[0] general_data = body.xpath("DatiGenerali/DatiGeneraliDocumento")[0] assert general_data.xpath("TipoDocumento")[0].text == "TD01" assert general_data.xpath("Data")[0].text == "2019-06-16" assert general_data.xpath("Divisa")[0].text == "EUR" assert general_data.xpath("Numero")[0].text == "00001A" # make sure the limit for the causal is respected (200 chars) assert len(general_data.xpath("Causale")) == 2 assert general_data.xpath("Causale")[0].text == "A" * 200 assert general_data.xpath("Causale")[1].text == "B" * 200 # Invoice summary summary = body.xpath("DatiBeniServizi")[0] assert len(summary.xpath("DettaglioLinee")) == 2 first_item = summary.xpath("DettaglioLinee")[0] second_item = summary.xpath("DettaglioLinee")[1] assert first_item.xpath("NumeroLinea")[0].text == "1" assert first_item.xpath("Descrizione")[0].text == "item 1" assert first_item.xpath("Quantita")[0].text == "1.00" assert first_item.xpath("PrezzoUnitario")[0].text == "1.00" assert first_item.xpath("PrezzoTotale")[0].text == "1.00" assert first_item.xpath("AliquotaIVA")[0].text == "0.00" assert second_item.xpath("NumeroLinea")[0].text == "2" assert second_item.xpath("Descrizione")[0].text == "item 2" assert second_item.xpath("Quantita")[0].text == "2.00" assert second_item.xpath("PrezzoUnitario")[0].text == "2.00" assert second_item.xpath("PrezzoTotale")[0].text == "2.00" assert second_item.xpath("AliquotaIVA")[0].text == "0.00" # TODO: this needs to be formatted to have two decimal places assert summary.xpath("DatiRiepilogo/AliquotaIVA")[0].text == "22.0" assert summary.xpath("DatiRiepilogo/ImponibileImporto")[0].text == "2.0" assert summary.xpath("DatiRiepilogo/Imposta")[0].text == "2.0"
def make_payment_inv_add(user, make_payment, **kwargs): inv = Invoice() # field to be populated to invoice inv.title = "Make Payment Invoice" inv.bill_to = make_payment.first_name + ' ' + make_payment.last_name inv.bill_to_first_name = make_payment.first_name inv.bill_to_last_name = make_payment.last_name inv.bill_to_company = make_payment.company inv.bill_to_address = make_payment.address inv.bill_to_city = make_payment.city inv.bill_to_state = make_payment.state inv.bill_to_zip_code = make_payment.zip_code inv.bill_to_country = make_payment.country inv.bill_to_phone = make_payment.phone inv.bill_to_email = make_payment.email inv.ship_to = make_payment.first_name + ' ' + make_payment.last_name inv.ship_to_first_name = make_payment.first_name inv.ship_to_last_name = make_payment.last_name inv.ship_to_company = make_payment.company inv.ship_to_address = make_payment.address inv.ship_to_city = make_payment.city inv.ship_to_state = make_payment.state inv.ship_to_zip_code = make_payment.zip_code inv.ship_to_country = make_payment.country inv.ship_to_phone = make_payment.phone inv.ship_to_email = make_payment.email inv.terms = "Due on Receipt" inv.due_date = datetime.now() inv.ship_date = datetime.now() inv.message = 'Thank You.' inv.status = True inv.estimate = True inv.status_detail = 'estimate' inv.object_type = ContentType.objects.get(app_label=make_payment._meta.app_label, model=make_payment._meta.module_name) inv.object_id = make_payment.id inv.subtotal = make_payment.payment_amount inv.total = make_payment.payment_amount inv.balance = make_payment.payment_amount inv.save(user) make_payment.invoice_id = inv.id return inv
def directory_set_inv_payment(user, directory, **kwargs): if get_setting('module', 'directories', 'directoriesrequirespayment'): if not directory.invoice: inv = Invoice() inv.object_type = ContentType.objects.get(app_label=directory._meta.app_label, model=directory._meta.module_name) inv.object_id = directory.id profile = user.get_profile() inv.title = "Directory Add Invoice" inv.bill_to = '%s %s' % (user.first_name, user.last_name) inv.bill_to_first_name = user.first_name inv.bill_to_last_name = user.last_name inv.bill_to_company = profile.company inv.bill_to_address = profile.address inv.bill_to_city = profile.city inv.bill_to_state = profile.state inv.bill_to_zip_code = profile.zipcode inv.bill_to_country = profile.country inv.bill_to_phone = profile.phone inv.bill_to_fax = profile.fax inv.bill_to_email = profile.email inv.ship_to = inv.bill_to inv.ship_to_first_name = user.first_name inv.ship_to_last_name = user.last_name inv.ship_to_company = profile.company inv.ship_to_address = profile.address inv.ship_to_city = profile.city inv.ship_to_state = profile.state inv.ship_to_zip_code = profile.zipcode inv.ship_to_country = profile.country inv.ship_to_phone = profile.phone inv.ship_to_fax = profile.fax inv.ship_to_email = profile.email inv.terms = "Due on Receipt" inv.due_date = datetime.now() inv.ship_date = datetime.now() inv.message = 'Thank You.' inv.status = True inv.total = get_directory_price(user, directory) inv.subtotal = inv.total inv.balance = inv.total inv.estimate = 1 inv.status_detail = 'estimate' inv.save(user) # update job directory.invoice = inv directory.save() if is_admin(user): if directory.payment_method in ['paid - cc', 'paid - check', 'paid - wire transfer']: boo_inv = inv.tender(user) # payment payment = Payment() boo = payment.payments_pop_by_invoice_user(user, inv, inv.guid) payment.mark_as_paid() payment.method = directory.payment_method payment.save(user) # this will make accounting entry inv.make_payment(user, payment.amount)
def invoice_user(user, force=False, save=False): from bursary.models import Bursary attendee = user.attendee try: bursary = user.bursary except Bursary.DoesNotExist: bursary = Bursary() lines = [] fee_info = FEE_INVOICE_INFO.get(attendee.fee) if fee_info: fee_info['quantity'] = 1 lines.append(InvoiceLine(**fee_info)) try: accomm = attendee.accomm except ObjectDoesNotExist: accomm = None if accomm and not bursary.potential_bursary('accommodation'): for line in invoice_accomm(accomm): lines.append(InvoiceLine(**line)) try: food = attendee.food except ObjectDoesNotExist: food = None if food and not bursary.potential_bursary('food'): for line in invoice_food(food): lines.append(InvoiceLine(**line)) for paid_invoice in user.invoices.filter(status='paid', compound=False): lines.append( InvoiceLine( reference='INV#{}'.format(paid_invoice.reference_number), description='Previous Payment Received', unit_price=-paid_invoice.total, quantity=1, )) invoice = Invoice(recipient=user, status='new', date=timezone.now(), invoiced_entity=attendee.invoiced_entity, billing_address=attendee.billing_address) # Only save invoices if non empty if save and lines: invoice.save() total = 0 for i, line in enumerate(lines): line.line_order = i total += line.total if save: line.invoice_id = invoice.id line.save() return { 'invoice': invoice, 'lines': lines, 'total': total, 'total_twd': total * TWD_EXCHANGE_RATE, }