Example #1
0
 def setUpClass(cls):
     print("Setting up")
     conn = mongoengine.connect(db=DB_NAME, host=DB_HOST)
     for n in range(1, 11):
         invoice = Invoice(x=n, invoice_number=2)
         position = Position(**POSITION).save()
         #invoice.positions = [InvoiceItem(position_id=str(position.id))]
         invoice.positions = [InvoiceItem(position=position)]
         invoice.save()
Example #2
0
def previous_months_invoices_october(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-10-01'::DATE and '2014-10-31'::DATE " +
                                                  "and p.private_patient = 'f' " +
                                                  "and (select count(inv.id) from public.invoices_invoiceitem inv " +
                                                  "where inv.invoice_date between '2014-10-01'::DATE and '2014-10-31'::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, 10, 31),
                                  invoice_sent=False,
                                  invoice_paid=False)
        invoiceitem.clean()
        invoiceitem.save()
        invoice_counters = invoice_counters + 1
Example #3
0
    def post(self):
        new_invoice = Invoice(client_name=request.json['client_name'])
        db.session.add(new_invoice)

        for item in request.json['invoice_items']:
            new_invoice_item = InvoiceItem(
                units = item['units'],
                description = item['description'],
                amount = item['amount'],
                invoice = new_invoice
            )
            db.session.add(new_invoice_item)
        db.session.commit()
        return '', 204
def add_invoice():
    product = Product(name=f'Produkt testowy {random.randint(1, 1000)}')
    for _ in range(3):
        product.stocks.append(
            ProductStock(quantity=random.randint(1, 10), purchase_price=1))
    invoice = Invoice(account=random.choice(accounts),
                      invoice_amount=10,
                      invoice_number=str(
                          random.randint(1, 9) * 100 +
                          random.randint(0, 9) * 10 + random.randint(0, 9)),
                      invoice_date=datetime.datetime.today())

    for _ in range(5):
        invoice_item = InvoiceItem(product=product,
                                   name=product.name,
                                   quantity=1,
                                   price=2,
                                   discount=0)
        invoice.invoice_items.append(invoice_item)

    session.add(invoice)
    session.commit()
def add_invoice():
    account = session.query(Account).first()
    product = Product(name='Produkt testowy')
    for _ in range(3):
        product.stocks.append(
            ProductStock(quantity=random.randint(1, 10), purchase_price=1))

    invoice = Invoice(account=account,
                      invoice_amount=2,
                      invoice_number='123',
                      invoice_date=datetime.datetime.today())

    for _ in range(5):
        invoice_item = InvoiceItem(product=product,
                                   name='Zakup: ' + product.name,
                                   quantity=1,
                                   price=2,
                                   discount=0)
        invoice.invoice_items.append(invoice_item)

    session.add(invoice)
    session.commit()
Example #6
0
def write_invoice_xls(file_name, invoice):

    book = xlwt.Workbook(encoding='ascii')
    sheet = book.add_sheet(u"Facture %s" % Config.NAME_ORGA)
    sheet.col(1).width = 0x0d00 * 3
    sheet.col(4).width = 0x0d00 * 2
    rowx = 0
    sheet.write_merge(rowx, rowx + 1, 0, 3,
                      u"Facture de %s" % Config.NAME_ORGA, style_title)

    rowx += 3
    date = "Bko le %s" % invoice.date.strftime("%d/%m/%Y")
    sheet.write_merge(rowx, rowx, 2, 3, date)

    hheaders = [_(u"Quantité"), _(u"Désignation"), _(u"Prix Unitaire"),
                _(u"Montant")]
    rowx += 2
    for colx, val_center in enumerate(hheaders):
        sheet.write(rowx, colx, val_center, style_t_table)
    rowx += 1

    data = [(item.quantity, item.description.name, item.price,
             item.quantity * item.price)
            for item in InvoiceItem.filter(invoices=invoice)]

    for prod in data:
        col = 0
        for val_center in prod:
            if isinstance(val_center, str):
                style_ = style
            else:
                style_ = int_style
            sheet.write_merge(rowx, rowx, col, col, val_center, style_)
            col += 1
        rowx += 1
    book.save(file_name)

    openFile(file_name)
Example #7
0
def create_invoice(modeladmin, request, queryset):
    # response = HttpResponse(content_type='text')

    not_invoiced_prestas = Prestation.objects.raw(
        "select p.id,p.patient_id,p.carecode_id,p.date" +
        " from invoices_prestation p " +
        "left join invoices_invoiceitem_prestations ip on p.id = ip.prestation_id "
        + "where ip.prestation_id is NULL")
    from collections import defaultdict

    prestations_to_invoice = defaultdict(list)
    invoices_created = []
    invpks = []
    for p in queryset:
        if p in not_invoiced_prestas:
            prestations_to_invoice[p.patient].append(p)

    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)
        else:
            invoiceitem = InvoiceItem(patient=k,
                                      invoice_date=datetime.datetime.now(),
                                      invoice_sent=False,
                                      invoice_paid=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)))
    return HttpResponseRedirect("/admin/invoices/invoiceitem/")
Example #8
0
def previous_months_invoices_october(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-10-01'::DATE and '2014-10-31'::DATE " +
        "and p.private_patient = 'f' " +
        "and (select count(inv.id) from public.invoices_invoiceitem inv " +
        "where inv.invoice_date between '2014-10-01'::DATE and '2014-10-31'::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, 10, 31),
                                  invoice_sent=False,
                                  invoice_paid=False)
        invoiceitem.clean()
        invoiceitem.save()
        invoice_counters = invoice_counters + 1
Example #9
0
import sqlalchemy as sa
from sqlalchemy.orm import sessionmaker

from helpers import Timer
from models import Account, Invoice, Product, InvoiceItem, ProductStock

engine = sa.engine.create_engine('sqlite:///litedb', echo=False)
session = sessionmaker(bind=engine)()

session.query(Invoice).delete()
session.query(InvoiceItem).delete()
session.query(Product).delete()
session.query(ProductStock).delete()
session.commit()

account = session.query(Account).first()
with Timer('Insert big invoice'):
    invoice = Invoice(account=account, invoice_number='test')

    for _ in range(10000):
        product = Product(name=random.choice(string.ascii_uppercase) +
                          str(random.randint(1, 10000)))

        invoice_item = InvoiceItem(invoice=invoice,
                                   product=product,
                                   quantity=1,
                                   price=1)

    session.add(invoice)
    session.commit()
session.query(Invoice).delete()
session.query(InvoiceItem).delete()
session.query(Product).delete()
session.query(ProductStock).delete()
session.commit()

account = session.query(Account).first()
with Timer('Insert big invoice'):
    invoice = Invoice(account=account, invoice_number='test')
    session.add(invoice)
    session.flush()
    products = []
    items = []
    for _ in range(10000):
        product = Product(name=random.choice(string.ascii_uppercase) +
                          str(random.randint(1, 10000)))
        products.append(product)
    # session.bulk_save_objects(products)  # we need to fix it
    session.bulk_save_objects(products, return_defaults=True)
    session.flush()
    for row in products:
        invoice_item = InvoiceItem(invoice_id=invoice.id,
                                   product_id=row.id,
                                   quantity=1,
                                   price=1)
        items.append(invoice_item)

    session.bulk_save_objects(items)
    items = session.query(InvoiceItem)
    session.commit()
Example #11
0
def pdFview(filename, invoice):
    """
        cette views est cree pour la generation du PDF
    """

    if not filename:
        filename = get_temp_filename('pdf')
        print(filename)
    #on recupere les items de la facture
    items_invoice = InvoiceItem.filter(invoices=invoice)

    # Static source pdf to be overlayed
    PDFSOURCE = 'fact_source.pdf'
    TMP_FILE = 'tmp.pdf'
    DATE_FORMAT = u"%d/%m/%Y"

    DEFAULT_FONT_SIZE = 11
    FONT = 'Courier-Bold'
    # A simple function to return a leading 0 on any single digit int.

    def double_zero(value):
        try:
            return '%02d' % value
        except TypeError:
            return value

    # setup the empty canvas
    from io import FileIO as file
    # from Common.pyPdf import PdfFileWriter, PdfFileReader
    from PyPDF2 import PdfFileWriter, PdfFileReader

    # PDF en entrée
    input1 = PdfFileReader(file(PDFSOURCE, "rb"))

    # PDF en sortie
    output = PdfFileWriter()
    # Récupération du nombre de pages
    n_pages = input1.getNumPages()
    # Pour chaque page
    for i in range(n_pages):
        # Récupération de la page du doc initial (input1)
        page = input1.getPage(i)

        p = canvas.Canvas(TMP_FILE, pagesize=A4)
        # p.setFont(FONT, DEFAULT_FONT_SIZE)

        p.drawString(130, 683, str(invoice.number))
        p.drawString(98, 667, (invoice.client))

        p.drawString(460, 683, str(invoice.date.strftime(DATE_FORMAT)))

        # On ecrit les invoiceitem
        x, y = 40, 610
        for i in items_invoice:
            p.drawString(x, y, str(i.quantity).rjust(11, ' '))
            p.drawString(x + 75, y, str(i.description))
            p.drawString(x + 340, y, str(i.price).rjust(10, ' '))
            p.drawString(x + 430, y, str(i.price * i.quantity).rjust(10, ' '))
            y -= 20
        # on teste le type
        if invoice.type_ == "Facture":
            p.drawString(59, 80, "Pour acquit: ")
        else:
            p.drawString(59, 80, "Pour acceptation: ")

        p.drawString(435, 80, "Le fournisseur: ")
        #On calcul le montant total hors taxe et sa conversion en lettre
        ht = 0
        for i in items_invoice:
            montant = i.price * i.quantity
            ht += montant

        ht_en_lettre = cel(ht)

        p.drawString(470, 150, str(ht).rjust(10, ' '))
        ht_en_lettre1, ht_en_lettre2 = controle_caratere(ht_en_lettre +
                                                        " FCFA", 46, 40)
        p.drawString(258, 116, (ht_en_lettre  + " FCFA"))
        # p.drawString(258, 116, (ht_en_lettre1))
        # p.drawString(53, 100, (ht_en_lettre2))

        # legal_infos, legal_infos1 = controle_caratere(Config.BP, 55, 55)
        # p.drawString(90, 14, legal_infos)
        # p.drawString(90, 6, legal_infos1)
        p.showPage()
        # Sauvegarde de la page
        p.save()
        # Création du watermark
        watermark = PdfFileReader(file(TMP_FILE, "rb"))
        # Création page_initiale+watermark
        page.mergePage(watermark.getPage(0))
        # Création de la nouvelle page
        output.addPage(page)
    # Nouveau pdf
    file_dest = filename + ".pdf"
    outputStream = file(file_dest, u"wb")
    output.write(outputStream)
    outputStream.close()

    return file_dest
Example #12
0
    def save_b(self):
        ''' add operation '''
        # entete de la facture
        if not self.table_invoice.isvalid:
            return False
        try:
            num_invoice = int(self.num_invoice.text())
            self.num_invoice_error.setText(u"")
        except:
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="warning.png"))
            self.num_invoice.setStyleSheet("background-color:  rgb(255, 235, 235);")
            self.num_invoice_error.setToolTip(u"Le numero de facture est obligatoire.")
            self.num_invoice_error.setPixmap(self.pixmap)
        invoice_date = str(self.invoice_date.text())
        name_client = str(self.name_client.text())
        datetime_ = date_to_datetime(invoice_date)

        values_t = self.table_invoice.get_table_items()
        if name_client == "":
            self.name_client.setStyleSheet("background-color: rgb(255, 235, 235);")
            self.pixmap = QPixmap(u"{img_media}{img}".format(img_media=Config.img_media,
                                                      img="decline.png"))
            self.name_client_error.setToolTip(u"Nom du client est obligatoire.")
            self.name_client_error.setPixmap(self.pixmap)
            return False
        # if num_invoice > Config.credit:
        #     raise_error(("Avertisement"), u"<h2>Veuillez payer la reste de la licence</h2>")
        #     return False
        invoice = Invoice()
        try:
            invoice.owner = Owner.get(islog=True)
        except:
            if Config.DEBUG:
                invoice.owner = Owner.get(username='******')
            else:
                return False

        invoice.number = num_invoice
        invoice.date_ord = datetime_
        invoice.client = name_client.capitalize()
        invoice.location = "Bamako"
        invoice.type_ = "Facture"
        invoice.subject = ""
        invoice.tax = False
        invoice.otax_rate = 18
        try:
            invoice.save()
        except:
            raise_error("Erreur", u"Impossible d'enregistrer l'entête de la facture")
            return False

        # Save orderitems
        try:
            order = Invoice.get(number=num_invoice)
        except:
            return False
        for i in values_t:
            qty, name, price = i
            description = Product.filter(name=name).get()
            item = InvoiceItem()
            item.invoices = invoice.id
            item.quantity = int(i[0])
            item.description = description
            item.price = int(i[2])
            try:
                item.save()
                self.name_client.clear()
                self.num_invoice.clear()
            except Exception as e:
                print(e)
                invoice.delete_instance()
                raise_error("Erreur", u"Ce mouvement n'a pas pu etre "
                                      u"enregistré dans les rapports")
                return False

        self.change_main_context(ShowInvoiceViewWidget,
                                        invoice=invoice)
Example #13
0
            product=product,
            purchase_price=random.randint(1, 9)
        )
        session.add(product)
    session.commit()

    accounts = session.query(Account).all()
    products = session.query(Product).all()
    items = []
    for account in accounts:
        for _ in range(random.randint(1,5)):
            invoice = Invoice(
                account=account,
                invoice_number="".join(random.choices(string.ascii_uppercase, k=5)) + str(random.randint(0,9))
            )
            session.add(invoice)
            session.flush()
            for row in random.choices(products, k=random.randint(1,9)):
                invoice_item = InvoiceItem(
                    invoice_id=invoice.id,
                    product_id=row.id,
                    quantity=1,
                    name="Order: " + row.name,
                    price=row.price * 2
                )
                items.append(invoice_item)

    session.bulk_save_objects(items)
    session.commit()
    # session.rollback()
import os
from config import db
from models import Invoice, InvoiceItem

INVOICES = [
    {'client_name': 'Eastridge', 'invoice_items': [{'units': 5, 'description': 'Some cool product #1', 'amount': 19.99}, {'units': 10, 'description': 'Some cool product #2', 'amount': 29.99}]},
    {'client_name': 'Ilgor', 'invoice_items': [{'units': 20, 'description': 'Some cool product', 'amount': 39.99}]}
]

if os.path.exists("invoices.db"):
    os.remove("invoices.db")

db.create_all()

for invoice in INVOICES:
    i = Invoice(client_name=invoice['client_name'])
    for item in invoice['invoice_items']:
        ii = InvoiceItem(units=item['units'], description=item['description'], amount=item['amount'], invoice=i)
        db.session.add(ii)
    db.session.add(i)

db.session.commit()