Example #1
0
def setava_01(self, stock_taking):
    comp = list(self.mdb.stock.find().sort([("category", 1), ("_id", 1)]))
    autori = stock_taking['author'].strip().split(',')
    datum = str(stock_taking['closed'].date())
    filename = "{}_{}.pdf".format(stock_taking['_id'],
                                  ''.join(stock_taking['name'].split()))

    print("Generovani prehledu inventury")
    print("Od:", autori)
    print("Kdy:", datum)
    print("Soubor,", filename)

    page = 1
    money_sum = 0
    Err = []

    pdf = FPDF('P', 'mm', format='A4')
    pdf.set_auto_page_break(False)

    pdf.add_font('pt_sans',
                 '',
                 'static/pt_sans/PT_Sans-Web-Regular.ttf',
                 uni=True)
    pdf.add_font('pt_sans-bold',
                 '',
                 'static/pt_sans/PT_Sans-Web-Bold.ttf',
                 uni=True)
    pdf.set_font('pt_sans', '', 12)
    pdf.add_page()

    pdf.set_xy(0, 40)
    pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
    pdf.set_xy(0, 46)
    pdf.cell(pdf.w,
             0,
             'Universal Scientific Technologies s.r.o.',
             align='C',
             ln=2)

    pdf.set_xy(20, 200)
    pdf.cell(1, 0, 'Inventuru provedli:', ln=2)
    for x in autori:
        pdf.cell(1, 20, x, ln=2)

    pdf.set_font('pt_sans', '', 8)
    pdf.set_xy(120, 288)
    pdf.cell(
        10, 0, "Vytvořeno %s, strana %s z %s" %
        (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"), page,
         pdf.alias_nb_pages()))

    pdf.add_page()

    data = self.mdb.stock.aggregate([{
        '$addFields': {
            'count': {
                '$sum': '$history.bilance'
            }
        }
    }])

    query = [
        {
            "$group": {
                '_id': '$pid',
                'operations': {
                    "$push": "$$ROOT"
                }
            }
        },
        {
            "$addFields": {
                "packet_count": {
                    "$sum": "$operations.count"
                },
                "packet_reserv": {
                    "$sum": "$operations.reserv"
                },
                "packet_ordered": {
                    "$sum": "$operations.ordered"
                },
                "packet_price": {
                    "$function": {
                        "body": '''function(prices, counts) {
                         let total_counts = Array.sum(counts);
                         var tmp_count = total_counts;
                         var total_price = 0;

                         var c = counts.reverse();
                         var p = prices.reverse();

                         for(i in c){
                             if(c[i] > 0){
                                 if(c[i] < tmp_count){
                                     total_price += (c[i]*p[i]);
                                     tmp_count -= c[i]
                                  }
                                  else{
                                     total_price += (tmp_count*p[i]);
                                     tmp_count = 0;
                                  }
                            }

                         }
                         return total_price;
                        }''',
                        "args":
                        ["$operations.unit_price", "$operations.count"],
                        "lang": "js"
                    }
                }
            }
        },
        #{"$addFields": {"comp": "$pid"}},
        {
            "$lookup": {
                "from":
                "stock",
                "let": {
                    "pid": "$_id"
                },
                "pipeline": [
                    {
                        "$match": {
                            "$expr": {
                                "$in": ["$$pid", "$packets._id"]
                            }
                        }
                    },
                    {
                        "$unwind": "$packets"
                    },
                    {
                        "$match": {
                            "$expr": {
                                "$eq": ["$packets._id", "$$pid"]
                            }
                        }
                    },
                ],
                "as":
                "component"
            }
        },
        {
            "$set": {
                "component": {
                    "$first": "$component"
                }
            }
        },
        {
            "$lookup": {
                "from": "store_positions_complete",
                "localField": "component.packets.position",
                "foreignField": "_id",
                "as": "position_info",
            }
        },
        {
            "$set": {
                "position_info": {
                    "$first": "$position_info"
                }
            }
        },
        {
            "$group": {
                '_id': '$component._id',
                'packets': {
                    "$push": "$$ROOT"
                },
                #'component': { "$push": "$component" }
            }
        },
        {
            "$sort": {
                "_id": 1
            }
        }

        #{ "$sort": {"position_info.warehouse.code": 1, "position_info.path_string": 1, "position_info.name": 1, "component.name":1}},

        #{ "$project": { "packet_count": 1, "packet_reserv": 1, "packet_price": 1, "packet_ordered": 1, "_id": 0} },
        # { "$group": {
        #     '_id': 'null',
        #     'count': {"$sum": '$packet_count'},
        #     'price': {"$sum": '$packet_price'},
        #     'reserv': {"$sum": '$packet_reserv'},
        #     'ordered': {"$sum": '$packet_ordered'},
        #     }
        # }
    ]
    data = self.mdb.stock_operation.aggregate(query)

    gen_time = datetime.datetime(2018, 10, 1)
    lastOid = ObjectId.from_datetime(gen_time)

    number_components = 0
    number_packets = 0

    for i, component in enumerate(data):
        print(" ")
        number_components += 1
        # print(component['_id'], component)
        component['packets_count'] = []
        component['packets_prices'] = []
        try:
            ## Pokud je konec stránky
            if pdf.get_y() > pdf.h - 20:
                pdf.line(10, pdf.get_y() + 0.5, pdf.w - 10, pdf.get_y() + 0.5)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(150, pdf.get_y() + 1)
                pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                pdf.add_page()

            ## Pokud je nová strana
            if page != pdf.page_no():
                pdf.set_font('pt_sans', '', 8)
                page = pdf.page_no()
                pdf.set_xy(120, 288)
                pdf.cell(
                    10, 0, "Vytvořeno %s, strana %s z %s" %
                    (datetime.datetime.now().strftime("%d. %m. %Y, %H:%M:%S"),
                     page, pdf.alias_nb_pages()))

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(10, 10)
                pdf.cell(100, 5, 'Skladová položka')
                pdf.set_x(105)
                pdf.cell(10, 5, "Počet kusů", align='R')
                #pdf.set_x(120)
                #pdf.cell(10, 5, "Cena za 1ks", align='R')
                pdf.set_x(180)
                pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                pdf.line(10, 15, pdf.w - 10, 15)
                pdf.set_y(18)
                page_sum = 0

            pdf.set_font('pt_sans', '', 10)

            count = 0
            price = 0
            packets = ""
            for j, packet in enumerate(component['packets']):
                number_packets += 1
                pcount = packet['packet_count']
                pprice = round(packet['packet_price'], 2)

                component['packets_count'].append(pcount)
                component['packets_prices'].append(pprice)

                count += pcount
                price += pprice
                packets += " {},".format(pprice)

                #pac_info = get_packet_count(self.mdb, packet['_id'])
                #print("C: {}, {}, ".format(pcount-pac_info['packet_count'], pprice-pac_info['packet_price']))
            price_ks = 0
            first_price = 0

            inventura = False

            if count > 0:

                money_sum += price
                page_sum += price

                if price == 0.0:  # and x.get('count', 0) > 0:
                    Err.append(
                        'Polozka >%s< nulová cena, nenulový počet (%s)' %
                        (component['_id'], component.get('name', '---')))

                pdf.set_x(10)
                pdf.cell(
                    100, 5,
                    "{:5.0f}  {} ({})".format(i, packet['component']['name'],
                                              len(component['packets'])))

                pdf.set_font('pt_sans', '', 10)
                pdf.set_x(105)
                pdf.cell(10, 5, "{} j".format(count), align='R')

                # pdf.set_x(107)
                # pdf.cell(10, 5, repr(component['packets_count']) + " " +repr(component['packets_prices']), align='L')

                pdf.set_font('pt_sans-bold', '', 10)
                pdf.set_x(180)
                pdf.cell(10, 5, "%6.2f Kč" % (price), align='R')

        except Exception as e:
            Err.append('Err' + repr(e) + repr(component['_id']))
            print(e)

        if count > 0:
            pdf.set_y(pdf.get_y() + 4)

    pdf.line(10, pdf.get_y(), pdf.w - 10, pdf.get_y())
    pdf.set_font('pt_sans', '', 8)
    pdf.set_x(180)
    pdf.cell(10, 5, "Konec souhrnu", align='R')

    print("Celková cena", money_sum)
    print("Probematicke", len(Err))
    print("Polozek:", number_components)
    print("Pocet sacku:", number_packets)

    pdf.page = 1
    pdf.set_xy(20, 175)
    pdf.set_font('pt_sans', '', 12)
    pdf.cell(
        20, 20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %
        (datum, money_sum))
    if len(Err) > 0:
        pdf.set_xy(30, 80)
        pdf.cell(1, 6, "Pozor, chyby ve skladu:", ln=2)
        pdf.set_x(32)
        for ch in Err:
            pdf.cell(1, 5, ch, ln=2)
    pdf.page = page

    pdf.output("static/tmp/sestava.pdf")
    year = datum[:4]

    filename = "{}.pdf".format(''.join(stock_taking['name'].split(' ')))
    foldername = os.path.join(tornado.options.options.owncloud_root,
                              'accounting', year, 'stocktaking', filename)
    foldername = save_file(self.mdb, foldername)
    return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
Example #2
0
    def get(self, data = None):
        out_type = self.get_argument('type', 'html')
        components = []
        components = self.get_query_arguments('action[]', [])
        multiply = int(self.get_argument('multiply', 5))
        layout = self.get_argument('template', '70x40_simple')
        skip = int(self.get_argument('skip', 0))
        #print("Soucastky..",components)
        if len(components) > 0:
            comp = list(self.mdb.stock.find({'_id' : {'$in' : components}}))
        else:
            comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)]))
        page = 0
        #print("Budeme tisknout:", comp)

        if layout == 'souhrn_01':
            autori = self.get_query_argument('autor', None)
            if not autori: autori = ['autory vlozite pridanim autoru do adresy s parametrem "autor"', 'autoru muze byt vice, pouzijte vice parametru', 'Například pridanim tohoto na konec adresy: &autor=Tester První']
            datum = self.get_argument('datum', ">>pro specifikovani pridejte parametr 'datum' do GET parametru<<")
            page = 1
            money_sum = 0
            Err = []

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')
            pdf.set_auto_page_break(False)

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans', '', 12)
            pdf.add_page()

            pdf.set_xy(0, 40)
            pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
            pdf.set_xy(0, 46)
            pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2)

            pdf.set_xy(20, 200)
            pdf.cell(1,0, 'Inventuru provedli:', ln=2)
            for x in autori:
                pdf.cell(1,20, x, ln=2)

            pdf.set_font('pt_sans', '', 8)
            pdf.set_xy(120, 288)
            pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

            pdf.add_page()


            data = self.mdb.stock.aggregate([
                    {'$addFields': {'count': {'$sum': '$history.bilance'}}}
                ])


            gen_time = datetime.datetime(2018, 10, 1)
            lastOid = ObjectId.from_datetime(gen_time)


            for i, component in enumerate(data):
            #for i, component in enumerate(list(data)[:30]):
                print(i, "=============================")
                print(component['_id'])
                try:
                    ## Pokud je konec stránky
                    if pdf.get_y() > pdf.h-20:
                        pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5)

                        pdf.set_font('pt_sans', '', 10)
                        pdf.set_xy(150, pdf.get_y()+1)
                        pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                        pdf.add_page()

                    ## Pokud je nová strana
                    if page != pdf.page_no():
                        pdf.set_font('pt_sans', '', 8)
                        page = pdf.page_no()
                        pdf.set_xy(120, 288)
                        pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

                        pdf.set_font('pt_sans', '', 11)
                        pdf.set_xy(10, 10)
                        pdf.cell(100, 5, 'Skladová položka')
                        pdf.set_x(95)
                        pdf.cell(10, 5, "Počet kusů", align='R')
                        pdf.set_x(120)
                        pdf.cell(10, 5, "Cena za 1ks", align='R')
                        pdf.set_x(180)
                        pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                        pdf.line(10, 15, pdf.w-10, 15)
                        pdf.set_y(18)
                        page_sum = 0

                    pdf.set_font('pt_sans', '', 10)

                    count = component['count']

                    if count >0:
                        price = 0
                        price_ks = 0
                        first_price = 0


                        pdf.set_x(10)
                        pdf.cell(100, 5, component['_id'])

                        pdf.set_x(95)
                        pdf.cell(10, 5, "%5.d" %(count), align='R')

                    pdf.set_x(10)
                    pdf.cell(100, 5, "{:5.0f}  {}".format(i, component['_id']))


                    inventura = False
                    for x in reversed(component.get('history', [])):
                        if x.get('operation', None) == 'inventory':
                            print("inventura", x)
                            if x['_id'].generation_time > lastOid.generation_time:
                                print("#############")
                                inventura = True
                                count = x['absolute']

                                pdf.set_x(110)
                                pdf.cell(1, 5, "i")
                                break;

                    pdf.set_font('pt_sans', '', 10)
                    pdf.set_x(95)
                    pdf.cell(10, 5, "{} j".format(count), align='R')

                    rest = count

                    for x in reversed(component.get('history', [])):

                        if x.get('price', 0) > 0:
                            if first_price == 0:
                                first_price = x['price']
                            if x['bilance'] > 0:
                                if x['bilance'] <= rest:
                                    price += x['price']*x['bilance']
                                    rest -= x['bilance']
                                else:
                                    price += x['price']*rest
                                    rest = 0

                    print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price)
                    if(count-rest): price += rest*first_price
                    money_sum += price
                    page_sum +=price

                    if price == 0.0 and x.get('count', 0) > 0:
                        Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id']))

                    pdf.set_x(120)
                    if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R')
                    else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R')

                    pdf.set_font('pt_sans-bold', '', 10)
                    pdf.set_x(180)
                    pdf.cell(10, 5, "%6.2f Kč" %(price), align='R')


                except Exception as e:
                    Err.append('Err' + repr(e) + component['_id'])
                    print(e)

                pdf.set_y(pdf.get_y()+4)

            pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y())
            pdf.set_font('pt_sans', '', 8)
            pdf.set_x(180)
            pdf.cell(10, 5, "Konec souhrnu", align='R')

            pdf.set_font('pt_sans', '', 10)
            pdf.set_xy(150, pdf.get_y()+3)
            pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

            pdf.page = 1
            pdf.set_xy(20,175)
            pdf.set_font('pt_sans', '', 12)
            pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum))
            if len(Err) > 0:
                pdf.set_xy(30,80)
                pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2)
                pdf.set_x(32)
                for ch in Err:
                    pdf.cell(1,5,ch,ln=2)
            pdf.page = page

            print(autori)



        if layout == '105x74_simple':
            page = 0
            page_cols = 2
            page_rows = 4
            page_cells = page_cols * page_rows
            cell_w = 105
            cell_h = 75

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+5, cell_y+23)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        if layout == '70x42-3_simple':
            page = 0
            page_cols = 3
            page_rows = 7
            page_cells = page_cols * page_rows
            cell_w = 210/page_cols
            cell_h = 297/page_rows


            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['name'].strip().replace('/', '_')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                pdf.set_xy(cell_x+5, cell_y+6.75)
                if len(component['name'])<23:
                    pdf.set_font('pt_sans-bold', '', 14)
                else:
                    pdf.set_font('pt_sans-bold', '', 10)
                pdf.cell(cell_w-10, 0, component['name'][:35])
                pdf.set_xy(cell_x+2.5, cell_y+9)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w-5, h=7)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+4, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-8, 4, component['description'][:185])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-7)
                pdf.set_xy(cell_x+5, cell_y+13)
                pdf.set_font('pt_sans', '', 7.5)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + " |" + str(datetime.date.today()) + "| " + component['_id'])



        if layout == '105x48_simple':
            page = 0
            page_cols = 2
            page_rows = 6
            page_cells = page_cols * page_rows
            #cell_w = 105
            #cell_h = 48
            cell_w = 210/page_cols
            cell_h = 297/page_rows

            print ("pozadovany format je:", layout)
            pdf = FPDF('P', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+10)
                pdf.image('static/barcode/%s.png'%(id), w = cell_w, h=10)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(cell_x+5, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 4, component['description'][:275])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 4, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-10)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")


        elif layout == '105x48_panorama':
            page = 0
            page_cols = 6
            page_rows = 2
            page_cells = page_cols * page_rows
            cell_w = 48
            cell_h = 105

            print ("pozadovany format je:", layout)
            pdf = FPDF('L', 'mm', format='A4')

            pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
            pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
            pdf.set_font('pt_sans-bold', '', 12)

            pdf.set_auto_page_break(False)
            pdf.add_page()

            for i, component in enumerate(comp):
                i += skip
                id = component['_id'].strip().replace('/', '')
                code128.image(component['_id']).save("static/barcode/%s.png"%(id))

                if i != 0 and i%(page_cells) == 0:
                    page += 1
                    pdf.add_page()
                    print("New PAGE --- ", i, i%page_cells)

                row = int(i/page_cols)-page*page_rows
                column = i%page_cols
                cell_x = column*cell_w
                cell_y = row*cell_h

                print(component)
                pdf.set_font('pt_sans-bold', '', 14)
                pdf.set_xy(cell_x+5, cell_y+5)
                pdf.cell(cell_w-10, 0, component['_id'])
                pdf.set_xy(cell_x, cell_y+cell_h)
                pdf.rotate(90)
                pdf.image('static/barcode/%s.png'%(id), w = cell_h-5, h=10)
                pdf.rotate(0)

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(cell_x+8, cell_y+20)
                try:
                    pdf.multi_cell(cell_w-10, 5, component['description'])
                except Exception as e:
                    pdf.multi_cell(cell_w-10, 5, "ERR" + repr(e))


                pdf.set_xy(cell_x+5, cell_y+cell_h-15)
                pdf.set_font('pt_sans', '', 8)
                pdf.cell(cell_w-10, 10, ', '.join(component['category']) + "  |  " + str(datetime.datetime.now()) + "  |  " + "UST")



        pdf.output("static/tmp/sestava.pdf")
        with open('static/tmp/sestava.pdf', 'rb') as f:
            self.set_header("Content-Type", 'application/pdf; charset="utf-8"')
            self.set_header("Content-Disposition", "inline; filename=UST_tiskova_sestava.pdf")
            self.write(f.read())
        f.close()
Example #3
0
def setava_01(self, stock_taking):
    comp = list(self.mdb.stock.find().sort([("category", 1), ("_id",1)]))
    autori = stock_taking['author'].strip().split(',')
    datum = str(stock_taking['closed'].date())
    filename = "{}_{}.pdf".format(stock_taking['_id'], ''.join(stock_taking['name'].split()))

    page = 1
    money_sum = 0
    Err = []

    pdf = FPDF('P', 'mm', format='A4')
    pdf.set_auto_page_break(False)

    pdf.add_font('pt_sans', '', 'static/pt_sans/PT_Sans-Web-Regular.ttf', uni=True)
    pdf.add_font('pt_sans-bold', '', 'static/pt_sans/PT_Sans-Web-Bold.ttf', uni=True)
    pdf.set_font('pt_sans', '', 12)
    pdf.add_page()

    pdf.set_xy(0, 40)
    pdf.cell(pdf.w, 0, 'Celkový přehled skladu', align='C', ln=2)
    pdf.set_xy(0, 46)
    pdf.cell(pdf.w, 0, 'Universal Scientific Technologies s.r.o.', align='C', ln=2)

    pdf.set_xy(20, 200)
    pdf.cell(1,0, 'Inventuru provedli:', ln=2)
    for x in autori:
        pdf.cell(1,20, x, ln=2)

    pdf.set_font('pt_sans', '', 8)
    pdf.set_xy(120, 288)
    pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

    pdf.add_page()

    ref = self.get_argument('ref')
    value = self.get_argument('value')
    c_name = self.get_argument('name')
    package = self.get_argument('package')
    ust_id = self.get_argument('ust_id')
    price_predicted = self.get_argument('price_predicted', 0.0)
    price_store = self.get_argument('price_store', 0.0)
    price_final = self.get_argument('price_final', 0.0)
    description = self.get_argument('description', '')
    print(ref.split(','))

    data = self.mdb.stock.aggregate([
            {'$addFields': {'count': {'$sum': '$history.bilance'}}}
        ])

    if exist.count() > 0:
        update = self.mdb.production.update(
            {
                '_id': bson.ObjectId(name),
                "components.Ref": c
            },{
                "$set": {
                "components.$.Ref": c,
                "components.$.Value": value,
                "components.$.Package": package,
                "components.$.UST_ID": ust_id,
                "components.$.price_predicted": price_predicted,
                "components.$.price_store": price_store,
                "components.$.price_final": price_final,
                "components.$.Note": description,
            }
        }, upsert = True)
    else:
        print("NOVA POLOZKA")
        update = self.mdb.production.update(
            {
                '_id': bson.ObjectId(name)
            },{
                "$push": {'components': {
                    "Ref": c,
                    "Package": package,
                    "Value": value,
                    "UST_ID": ust_id,
                    "price_predicted": price_predicted,
                    "price_store": price_store,
                    "price_final": price_final,
                    "Note": description
                    }
                }
            })

    gen_time = datetime.datetime(2018, 10, 1)
    lastOid = ObjectId.from_datetime(gen_time)


    for i, component in enumerate(data):
    #for i, component in enumerate(list(data)[:30]):
        #print(i, "=============================")
        print(component['_id'])
        try:
            ## Pokud je konec stránky
            if pdf.get_y() > pdf.h-20:
                pdf.line(10, pdf.get_y()+0.5, pdf.w-10, pdf.get_y()+0.5)

                pdf.set_font('pt_sans', '', 10)
                pdf.set_xy(150, pdf.get_y()+1)
                pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

                pdf.add_page()

            ## Pokud je nová strana
            if page != pdf.page_no():
                pdf.set_font('pt_sans', '', 8)
                page = pdf.page_no()
                pdf.set_xy(120, 288)
                pdf.cell(10, 0, "Generováno %s, strana %s z %s" %(datetime.datetime.now(), page, pdf.alias_nb_pages()) )

                pdf.set_font('pt_sans', '', 11)
                pdf.set_xy(10, 10)
                pdf.cell(100, 5, 'Skladová položka')
                pdf.set_x(95)
                pdf.cell(10, 5, "Počet kusů", align='R')
                #pdf.set_x(120)
                #pdf.cell(10, 5, "Cena za 1ks", align='R')
                pdf.set_x(180)
                pdf.cell(10, 5, "Cena položky (bez DPH)", align='R', ln=2)
                pdf.line(10, 15, pdf.w-10, 15)
                pdf.set_y(18)
                page_sum = 0

            pdf.set_font('pt_sans', '', 10)

            count = component['count']
            price = 0
            price_ks = 0
            first_price = 0

            ref = self.get_argument('Ref')
            val = self.get_argument('Val')
            package = self.get_argument('Package')
            posx = self.get_argument('PosX')
            posy = self.get_argument('PosY')
            rot = self.get_argument('Rot')
            side = self.get_argument('Side')
            tstep = self.get_argument('Tstep')

            inventura = False
            for x in reversed(component.get('history', [])):
                if x.get('operation', None) == 'inventory':
                    #TODO: tady porovnávat, jesti to patri do stejne kampane. Ne na zaklade casu ale ID
                    if x['_id'].generation_time > lastOid.generation_time:
                        inventura = True
                        count = x['absolute']
                        #pdf.set_x(110)
                        #pdf.cell(1, 5, "i")
                        break;

            if count > 0:
                rest = count

                for x in reversed(component.get('history', [])):

                    if x.get('price', 0) > 0:
                        if first_price == 0: 
                            first_price = x['price']
                        if x['bilance'] > 0:
                            if x['bilance'] <= rest:
                                price += x['price']*x['bilance']
                                rest -= x['bilance']
                            else:
                                price += x['price']*rest
                                rest = 0
                
                print("Zbývá", rest, "ks, secteno", count-rest, "za cenu", price)
                if(count-rest): price += rest*first_price
                money_sum += price
                page_sum +=price

                if price == 0.0 and x.get('count', 0) > 0:
                    Err.append('Polozka >%s< nulová cena, nenulový počet' %(component['_id']))


                #pdf.set_x(120)
                #if count > 0: pdf.cell(10, 5, "%6.2f Kč" %(price/count), align='R')
                #else: pdf.cell(10, 5, "%6.2f Kč" %(0), align='R')

                pdf.set_font('pt_sans', '', 10)
                pdf.set_x(95)
                pdf.cell(10, 5, "{} j".format(count), align='R')

                pdf.set_x(10)
                pdf.cell(100, 5, "{:5.0f}  {}".format(i, component['_id']))

                pdf.set_font('pt_sans-bold', '', 10)
                pdf.set_x(180)
                pdf.cell(10, 5, "%6.2f Kč" %(price), align='R')


        except Exception as e:
            Err.append('Err' + repr(e) + component['_id'])
            print(e)

        if count > 0:
            pdf.set_y(pdf.get_y()+4)

    pdf.line(10, pdf.get_y(), pdf.w-10, pdf.get_y())
    pdf.set_font('pt_sans', '', 8)
    pdf.set_x(180)
    pdf.cell(10, 5, "Konec souhrnu", align='R')

    #pdf.set_font('pt_sans', '', 10)
    #pdf.set_xy(150, pdf.get_y()+3)
    #pdf.cell(100, 5, 'Součet strany: {:6.2f} Kč'.format(page_sum))

    pdf.page = 1
    pdf.set_xy(20,175)
    pdf.set_font('pt_sans', '', 12)
    pdf.cell(20,20, "Cena skladových zásob k %s je %0.2f Kč (bez DPH)" %(datum, money_sum))
    if len(Err) > 0:
        pdf.set_xy(30,80)
        pdf.cell(1,6,"Pozor, chyby ve skladu:", ln=2)
        pdf.set_x(32)
        for ch in Err:
            pdf.cell(1,5,ch,ln=2)
    pdf.page = page

    pdf.output("static/tmp/sestava.pdf")
    year = datum[:4]

    filename = "{}.pdf".format(''.join(stock_taking['name'].split(' ')))
    foldername = os.path.join(tornado.options.options.owncloud_root, 'accounting', year, 'stocktaking', filename)
    foldername = save_file(self.mdb, foldername)
    return upload_file(self.oc, 'static/tmp/sestava.pdf', foldername)
Example #4
0
    def create_pdf(self):
        pdf = FPDF(orientation='P')  # start PDF, set to portrait, add page
        pdf.add_page()
        x, y = (5.0, 5.0)
        pdf.set_xy(x, y)  # set x and y coordinates for printing

        # Set up variables based on layout chosen by user
        layout = self.file_settings_widget.ids.pdflayout.text

        # Default values for option: "Default (5x4)"
        w = 50; h = 50  # set width and height
        x_change = 50  # set x distance between this code and next
        y_change = 50  # set y distance between this code and next
        max_in_row = 3  # set the max # codes in row - 1
        max_in_pg = 20  # set the max # codes in pg

        if layout == "4x1":
            w = 60; h = 60  # set same vars as above but for diff layout
            x_change = 60; y_change = 60
            max_in_row = 0; max_in_pg = 4
        elif layout == "4x2":
            w = 70; h = 70
            x_change = 65; y_change = 65
            max_in_row = 1; max_in_pg = 8
        elif layout == "4x3":
            w = 70; h = 70
            x_change = 65; y_change = 65
            max_in_row = 2; max_in_pg = 12
        elif layout == "4x4":
            w = 50; h = 55
            x_change = 50; y_change = 55
            max_in_row = 3; max_in_pg = 16
        elif layout == "3x2":
            w = 90; h = 90
            x_change = 90; y_change = 90
            max_in_row = 1; max_in_pg = 6
        elif layout == "3x3":
            w = 70; h = 70
            x_change = 70; y_change = 70
            max_in_row = 2; max_in_pg = 9
        elif layout == "2x2":
            w = 100; h = 100
            x_change = 100; y_change = 100
            max_in_row = 1; max_in_pg = 4
        elif layout == "1x2 and 5/8":
            w = 35; h = 92.20
            x_change = 33; y_change = 88
            max_in_row = 5; max_in_pg = 18
        elif layout == "Landscape Text":
            w = 35; h = 35
            x_change = 33; y_change = 88
            max_in_row = 5; max_in_pg = 18

        """ Printing of codes usually results in first page being mostly blank, so this method is a 
        work around to that issue, by printing a first page and then reprinting that first page correctly, 
        since the 2nd page onward works fine """
        # This first part is just to get rid of the blank page at the beginning by printing a pg of codes arbitrarily
        if layout == "Landscape Text":
            row_num = 0  # used to track # of rows for the Landscape Text layout
            num_in_row = 0  # used to measure how many will fit in a row
            num_in_page = 0  # used to measure how many will fit in a pg
            i = 0  # used to get the label for each code
            num_codes_to_arbitrarily_print = len(self.array_of_codes)
            if num_codes_to_arbitrarily_print > 18:
                num_codes_to_arbitrarily_print = 18  # if the num codes greater than 18, keep it to 18 as that's all I need
            for j in range(num_codes_to_arbitrarily_print):  # print qr codes to pdf file
                code = self.array_of_codes[j]
                pdf.image(code, w=w, h=h)  # print qr code to pdf

                pdf.set_xy(5.0,
                           5.0)  # the farthest point you can go here is (275, -195) (really 280, -200 but the starting x,y points are also to be taken into account
                pdf.rotate(-90)  # rotate so labels printed sideways
                pdf.set_font('Arial', '', 14)  # set font family, style, and size
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row), txt=self.code_labels_array[i])
                pdf.rotate(0)  # undo rotation

                num_in_page += 1
                x += x_change  # adjust values of vars for the next code so it is printed correctly
                if num_in_row == max_in_row: x = 5.0; y += y_change; num_in_row = -1; row_num += 1  # when maxnum codes are printed in a row, move to next row
                if num_in_page == max_in_pg: y = 5.0; pdf.add_page(); num_in_page = 0; row_num = 0  # when max codes in page are printed in pg, move to nxt pg
                pdf.set_xy(x, y)
                num_in_row += 1
                i += 1

            if i != 18:  # if 18 codes not reached, add a page so that this method/work around still works
                pdf.add_page()  # this page would have been added otherwise, as seen above in code
                x = 5.0; y = 5.0
                pdf.set_xy(x, y)

        # Then we print the actual codes that will be on the PDF
        row_num = 0  # used to track # of rows for the Landscape Text layout
        num_in_row = 0  # used to measure how many will fit in a row
        num_in_page = 0  # used to measure how many will fit in a pg
        i = 0  # index used to keep track of array_of_codes position for labels
        for code in self.array_of_codes:  # print qr codes to pdf file
            pdf.image(code, w=w, h=h)  # print code to pdf

            if layout == "Landscape Text":
                pdf.set_xy(5.0,
                           5.0)  # the farthest point you can go here is (275, -195) (really 280, -200 but the starting x,y points are also to be taken into account
                pdf.rotate(-90)  # rotate so labels printed sideways
                pdf.set_font('Arial', '', 14)  # set font family, style, and size
                text_to_print1 = self.code_labels_array[i][:20]
                text_to_print2 = self.code_labels_array[i][20:40]  # split up texts so label fits and doesn't get cut off
                text_to_print3 = self.code_labels_array[i][40:60]
                text_to_print4 = self.code_labels_array[i][60:80]
                text_to_print5 = self.code_labels_array[i][80:100]
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row), txt=text_to_print1)
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row) + 5, txt=text_to_print2)
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row) + 10, txt=text_to_print3)
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row) + 15, txt=text_to_print4)
                pdf.text((h + 3) + y_change * row_num, -1 * (w - 15) - (33 * num_in_row) + 20, txt=text_to_print5)
                pdf.rotate(0)  # undo rotation

            num_in_page += 1
            x += x_change  # update vars so next code printed correctly
            if num_in_row == max_in_row: x = 5.0; y += y_change; num_in_row = -1; row_num += 1  # when maxnum codes are printed in a row, move to next row
            if num_in_page == max_in_pg:  # when max codes in page are printed in pg, move to nxt pg
                y = 5.0; num_in_page = 0; row_num = 0
                if i + 1 < len(self.array_of_codes): pdf.add_page()  # but only if there are more codes to print
            pdf.set_xy(x, y)
            num_in_row += 1
            i += 1

        # Then we remove the first page by moving the values of the array down one and then decrementing total #pgs
        if layout == "Landscape Text":  # only do this if using landscape text
            for i in range(pdf.page - 1):
                pdf.pages[i + 1] = pdf.pages[i + 2]
            pdf.page = pdf.page - 1

        if not self.ids.individualcodes.active:  # if Individual QR Codes checkbox not checked
            for code in self.array_of_codes:  # Then delete qrcodes
                try: os.remove(code)
                except: continue
        self.array_of_codes = []  # empty the array_of_codes array for the next create

        t = datetime.now()
        file_name = f"SQUIRELOutput-{t.year}-{t.month}-{t.day}-{t.hour}_{t.minute}_{t.second}.pdf"
        if self.save_folder_path is not None and self.save_folder_path is not "":
            file_name = f"{self.save_folder_path}/{file_name}"
        pdf.output(file_name, 'F').encode('latin-1')  # output final PDF file