Beispiel #1
0
def process_invoice(form, form_items):
    pk = None
    if form.is_valid() and form_items.is_valid():
        instance = form.save()
        existing_pks = []

        with transaction.atomic():
            for form in form_items:
                item_pk = form.cleaned_data['id']
                del form.cleaned_data['DELETE']
                del form.cleaned_data['id']
                form.cleaned_data['invoice'] = instance

                if item_pk:
                    InvoiceItem.objects.filter(pk=item_pk).update(
                        **form.cleaned_data)
                    existing_pks.append(item_pk)
                else:
                    obj = InvoiceItem(**form.cleaned_data)
                    obj.save()
                    existing_pks.append(obj.pk)

            deleted_pks = set(instance.invoiceitem_set.all().values_list(
                'pk', flat=True)).difference(set(existing_pks))
            instance.invoiceitem_set.filter(pk__in=deleted_pks).delete()

        return True, instance.pk
    return False, pk
Beispiel #2
0
def add_invoice_items(r,i):
    d = {}
    # create dict of items
    for k,v in r.iteritems():
        if re.match('^\d',k):           # InvoiceItem  
            new_k = int(k.split('|')[0])
            new_dict_items = {k: v}
            if not d.has_key(new_k): 
                d[new_k] = {'item_total':'','item_p':'','item_qty':'','item_each':'','item_total':'','item_gst':'','item':''}
            d[new_k][k.split('|')[1]]=v

    for z,x in d.iteritems():
        t = ''
        t = InvoiceItem(
            invoice	= i,
            order	= z,
            meta    = MetaItem.objects.get(pk=1)
        )
        try: t.title = x['item_h2']
        except: pass
        try: t.item  = x['item_p']
        except: pass 
        try: t.qty   = x['item_qty']
        except: pass 
        try: t.each  = x['item_each']
        except: pass 
        try: t.nett  = x['item_total']
        except: pass 
        try: t.gst   = x['item_gst']
        except: pass 
        try: t.total = x['item']
        except: pass 
        t.save()
    return t
Beispiel #3
0
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
Beispiel #4
0
    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()
Beispiel #5
0
    def validate(self, data):
        instance_id = None
        if self.instance is not None:
            instance_id = self.instance.id
        messages = InvoiceItem.validate(instance_id, data)
        if messages:
            raise serializers.ValidationError(messages)

        return data
Beispiel #6
0
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
Beispiel #7
0
def previous_months_invoices_september(modeladmin, request, queryset):
    
    #response = HttpResponse(content_type='text')
    
    previous_month_patients = Patient.objects.raw("select p.id, p.name, p.first_name "+  
        "from public.invoices_patient p, public.invoices_prestation prest "+
        "where p.id = prest.patient_id "+
        "and prest.date between '2014-09-01'::DATE and '2014-10-01'::DATE "+ 
        "and p.private_patient = 'f' "+
        "and (select count(inv.id) from public.invoices_invoiceitem inv "+
        "where inv.invoice_date between '2014-09-01'::DATE and '2014-10-01'::DATE "+ 
        "and inv.patient_id = p.id) = 0" + 
        "group by p.id "+
        "order by p.name")
    invoice_counters = 0
    for p in previous_month_patients:
        invoiceitem = InvoiceItem(patient=p,
                                  invoice_date=datetime.datetime(2014, 9, 30),
                                  invoice_sent=False,
                                  invoice_paid=False)
        invoiceitem.clean()
        invoiceitem.save()
        invoice_counters  = invoice_counters + 1 
Beispiel #8
0
def create_invoice_for_health_insurance(modeladmin, request, queryset):
    # response = HttpResponse(content_type='text')

    from collections import defaultdict

    prestations_to_invoice = defaultdict (list)
    invoices_created = []
    invpks = []
    # for p in queryset:
    #     if PrivateInvoiceItem.objects.filter (prestations__id=p.pk).count () == 0 and InvoiceItem.objects.filter (
    #             prestations__id=p.pk).count () == 0:
    #         prestations_to_invoice[p.patient].append (p)

    _private_patient_flag = False
    for k, v in prestations_to_invoice.iteritems ():
        if (k.private_patient):
            # invoiceitem = PrivateInvoiceItem (private_patient=k,
            #                                   invoice_date=datetime.datetime.now (),
            #                                   invoice_sent=False,
            #                                   invoice_paid=False)
            _private_patient_flag = True
        else:
            invoiceitem = InvoiceItem (patient=k,
                                       invoice_date=datetime.datetime.now (),
                                       invoice_sent=False,
                                       invoice_paid=False)
            _private_patient_flag = False
            invoices_created.append (invoiceitem)
            invpks.append(invoiceitem.pk)
        invoiceitem.save()
        for prestav in v:
            invoiceitem.prestations.add (prestav)

    # return HttpResponseRedirect("/admin/invoices/invoiceitem/?ct=%s&ids=%s" % (invoiceitem.pk, ",".join(invpks)))
    if not _private_patient_flag:
        return HttpResponseRedirect ("/admin/invoices/invoiceitem/")
Beispiel #9
0
def previous_months_invoices_feb(modeladmin, request, queryset):
    # response = HttpResponse(content_type='text')

        # response = HttpResponse(content_type='text')
    previous_month_patients = Patient.objects.raw ("SELECT "
                                                       + "    pat.id, "
                                                       + "    pat.name, "
                                                       + "    pat.first_name,"
                                                       + "    pat.code_sn "
                                                       + "FROM "
                                                       + "    invoices_prestation out, "
                                                       + "    invoices_patient pat, "
                                                       + "    invoices_carecode cod "
                                                       + "WHERE "
                                                       + "    out.date > '2017-01-31' "
                                                       + "    AND out.date < '2017-03-01' "
                                                       + "    AND pat.id = out.patient_id "
                                                       + "    AND pat.is_private = 'f' "
                                                       + "    AND cod.id = out.carecode_id "
                                                       + "    AND cod.reimbursed = TRUE "
                                                       + "    AND out.id NOT IN( "
                                                       + "        SELECT "
                                                       + "            prest.id "
                                                       + "        FROM "
                                                       + "            public.invoices_invoiceitem_prestations rel, "
                                                       + "            invoices_prestation prest "
                                                       + "        WHERE "
                                                       + "            prest.date > '2017-01-31' "
                                                       + "            AND prest.date < '2017-03-01' "
                                                       + "            AND rel.prestation_id = prest.id "
                                                       + "    ) GROUP BY pat.id")

    invoice_counters = 0
    for p in previous_month_patients:
        currInvoices = InvoiceItem.objects.filter (patient__code_sn=p.code_sn).filter (invoice_date__range=["2017-02-01", "2017-02-28"])
        if currInvoices.exists ():
            currInvoices[0].clean ()
            currInvoices[0].save ()
        else:
             invoiceitem = InvoiceItem (patient=p,
                                        invoice_date=datetime.datetime (2017, 2, 28),
                                        invoice_sent=False,
                                        invoice_paid=False)
             invoiceitem.clean ()
             invoiceitem.save ()
             invoice_counters += 1