сообщить об ошибке лаборатории при создании таблицы для счета - PullRequest
0 голосов
/ 09 июля 2020

Я посмотрел на другие вопросы, похожие на этот, но до сих пор не могу понять этого.

У меня есть файл basi c php, который отправляет переменную в python файл для создания счета

<?php
//$_POST['invoiceNo'] == "EUR2002"
if (isset($_POST['invoiceNo'])) {
    // $data = json_decode($_POST['invoiceNo']);
    // $command = exec('/var/www/invoice.py ' . $data );
    // echo 'done| ';
    // echo $command;
    $command = '/var/www/invoice.py ' .json_decode($_POST['configure_options']) ;

    $escaped_command = escapeshellcmd($command);

    system($escaped_command);
    echo $escaped_command;
}
?>

При успешном выполнении он вызывает python, который я сохранил на моем локальном хосте / var / www / папке. Теперь в моем python скрипте я хочу создать счет: мой python файл

\#!/usr/bin/env python3.8
from mysql.connector import Error
import mysql.connector
from collections import defaultdict
import textwrap
import locale
from datetime import date
from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.charts.piecharts import Pie
from reportlab.rl_config import defaultPageSize
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib import colors
from reportlab.platypus import Table, TableStyle, Paragraph, PageBreak
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.lib import pdfencrypt
import json
import datetime
import os
import sys
import subprocess
import reportlab
import cgitb
cgitb.enable()

try:
    connection = mysql.connector.connect(
        host='localhost', database='africalla_db', user='alex', password='Paula1234!')
    if connection.is_connected():
        db_Info = connection.get_server_info()
        print("Connected to MySQL Server version ", db_Info)
        cursor = connection.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You're connected to database: ", record)
except Error as e:
    print("Error while connecting to MySQL", e)

try:
    data = json.loads(sys.argv[1])
except:
    print("ERROR")
    sys.exit(1)


locale.setlocale(locale.LC_ALL, '')
enc = pdfencrypt.StandardEncryption(
    "rptlab", ownerPassword='deinvoice!', canPrint=1, canModify=0, canCopy=1, canAnnotate=0, strength=40)


def open_file(filename):
    if sys.platform == "win32":
        os.startfile(filename)
    else:
        opener = "open" if sys.platform == "darwin" else "xdg-open"
        subprocess.call([opener, filename])


class mainReport:
    def __init__(self):
        self.datetimeStamp = datetime.datetime.now()
        self.currentDate = self.datetimeStamp.date()
        reportlab.rl_config.TTFSearchPath.append('fonts')

        if sys.platform == "win32":
            pdfmetrics.registerFont(TTFont('Century-Gothic', 'GOTHIC.ttf'))
            pdfmetrics.registerFont(
                TTFont('Century-Gothic-Bold', 'GOTHICB.ttf'))
            pdfmetrics.registerFont(TTFont('Candara', 'Candara.ttf'))
            pdfmetrics.registerFont(TTFont('Candara-Bold', 'Candarab.ttf'))
            pdfmetrics.registerFont(TTFont('Calibri-Bold', 'Calibrib.ttf'))
            pdfmetrics.registerFont(TTFont('Calibri', 'calibri.ttf'))
            pdfmetrics.registerFont(TTFont('Tahoma-Bold', 'tahomabd.ttf'))
            pdfmetrics.registerFont(TTFont('Tahoma', 'tahoma.ttf'))
        else:
            pdfmetrics.registerFont(TTFont('Century-Gothic', 'GOTHIC.TTF'))
            pdfmetrics.registerFont(
                TTFont('Century-Gothic-Bold', 'GOTHICB.TTF'))
            pdfmetrics.registerFont(TTFont('Candara', 'Candara.ttf'))
            pdfmetrics.registerFont(TTFont('Candara-Bold', 'Candarab.ttf'))
            pdfmetrics.registerFont(TTFont('Calibri-Bold', 'calibri.ttf'))
            pdfmetrics.registerFont(TTFont('Calibri', 'calibri.ttf'))
            pdfmetrics.registerFont(TTFont('Tahoma-Bold', 'tahomabd.ttf'))
            pdfmetrics.registerFont(TTFont('Tahoma', 'tahoma.ttf'))

        self.PAGE_WIDTH = defaultPageSize[0]
        self.PAGE_HEIGHT = defaultPageSize[1]

        self.filename = ("invoice.pdf")
        self.reporting = canvas.Canvas(self.filename)  # ,encrypt=enc)
        self.objectPosition = self.PAGE_HEIGHT
        self.beginInvoice(document="Invoice")

    def setCursorPosition(self, height, test=False):
        if(test):
            if((self.objectPosition - height) < 0):
                self.endOfCurrentPage(forceHeight=height)
        else:
            self.objectPosition = self.objectPosition - height

    def drawImage(self, size=(100, 100), image=None, pos=None):
        self.setCursorPosition((size[1] + 20), test=True)
        if pos == "centre":
            self.reporting.drawImage(image, (self.PAGE_WIDTH - size[0])/2, (
                self.objectPosition - size[1]), width=size[0], height=size[1], mask='auto', preserveAspectRatio=True)

        elif pos == "rightcentre":
            self.reporting.drawImage(image, (self.PAGE_WIDTH - size[0])/4, (
                self.objectPosition - size[1]), width=size[0], height=size[1], mask='auto', preserveAspectRatio=True)
        else:
            self.reporting.drawImage(
                image, 10, (self.objectPosition - size[1]), width=size[0], height=size[1], mask='auto', preserveAspectRatio=True)
        self.setCursorPosition((size[1] + 20))

    def drawText(self, text=None, pos=None, font_name='Calibri', font_size=12):
        self.reporting.setFont(font_name, font_size)
        text_width = pdfmetrics.stringWidth(
            text, fontName=font_name, fontSize=font_size)
        if len(text) > 45:
            wrap_text = textwrap.wrap(text, width=(110*12/font_size))
            for words in wrap_text:
                self.setCursorPosition(font_size+2, test=True)
                text_width = pdfmetrics.stringWidth(
                    words, fontName=font_name, fontSize=font_size)
                if pos == "centre":
                    self.reporting.drawString(
                        (self.PAGE_WIDTH - text_width) / 2.0, self.objectPosition, words)
                else:
                    self.reporting.drawString(10, self.objectPosition, words)
                self.setCursorPosition(font_size+5)
        else:
            if pos == "centre":
                self.reporting.drawString(
                    (self.PAGE_WIDTH - text_width) / 2.0, self.objectPosition, text)
            elif type(pos) == type(10):
                self.reporting.drawString(pos, self.objectPosition, text)
            else:
                self.reporting.drawString(10, self.objectPosition, text)
        self.setCursorPosition(font_size+5)

    def drawTable(self, tableData, reduceFont=False, mergeColCellsBy=None, invoice_type=None):
        if():
            bgFont, smallFont = 10, 8
        else:
            bgFont, smallFont = 14, 12
        styles = getSampleStyleSheet()
        style = styles["BodyText"]
        style = styles["BodyText"]
        header = Paragraph(
            "<bold><font size=14>Africalla Report</font></bold>", style)

        noOfRows = len(tableData)
        data_length = len(tableData)
        t = Table(tableData)
        if invoice_type == "head":
            t = Table(tableData, colWidths=[100, 250])
            t.setStyle(TableStyle([("BOX", (0, 0), (-1, -1), 0.5, colors.black),
                                   ('ALIGNMENT', (0, 0), (0, -1), 'RIGHT'),
                                   ('INNERGRID', (0, 0), (-1, -1), 0.5, colors.black)]))
            for i in range(0, data_length):
                if(i == 0):
                    t.setStyle(TableStyle(
                        [('FONT', (0, i), (-1, i), 'Tahoma', 10)]))
                else:
                    t.setStyle(TableStyle(
                        [('FONT', (0, i), (-1, i), 'Tahoma', 10)]))
            aW = self.PAGE_WIDTH
            aH = self.objectPosition
            w, h = header.wrap(aW, aH)
            aH = aH - h
            w, h = t.wrap(aW, aH)
            setPositionWidth = (aW - w)/2
            t.drawOn(self.reporting, setPositionWidth, aH-h)
            self.objectPosition = (self.objectPosition - (h + 50))

        elif invoice_type == "cropOverview":
            t = Table(tableData, colWidths=[
                      120, 45, 45, 45, 45, 45, 45, 45, 45, 45])
            for i in range(0, data_length):
                if(i == 0):
                    t.setStyle(TableStyle(
                        [('FONT', (0, i), (-1, i), 'Candara', 8)]))
                    z = 0
                    while z < 7:
                        t.setStyle(TableStyle(
                            [('SPAN', (z, 0), (z, 1)), ('VALIGN',   (z, 0), (z, 1), 'MIDDLE')]))
                        z += 1
                else:
                    t.setStyle(TableStyle(
                        [('FONT', (0, i), (-1, i), 'Tahoma', 7)]))

            t.setStyle(TableStyle([("BOX", (0, 2), (-1, 5), 0.5, colors.black),
                                   ('INNERGRID', (0, 2), (-1, 5), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (0, 5), (7, 6), 0.5, colors.black),
                                   ('INNERGRID', (0, 5), (7, 6), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (1, 0), (6, 1), 0.5, colors.black),
                                   ('INNERGRID', (1, 0), (6, 1), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (6, 1), (7, 1), 0.5, colors.black),
                                   ('INNERGRID', (6, 1), (7, 1), 0.5, colors.black)]))
            aW = self.PAGE_WIDTH
            aH = self.objectPosition
            w, h = header.wrap(aW, aH)
            aH = aH - h
            w, h = t.wrap(aW, aH)
            setPositionWidth = (aW - w)/2
            t.drawOn(self.reporting, 30, aH-h)
            self.objectPosition = (self.objectPosition - (h + 50))

        elif invoice_type == "crops":
            t = Table(tableData, colWidths=[120, 45, 45, 45, 250])
            t.setStyle(TableStyle([("BOX", (0, 0), (-1, 5), 0.5, colors.black),
                                   ('INNERGRID', (0, 0), (-1, 5), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (0, 0), (7, 6), 0.5, colors.black),
                                   ('INNERGRID', (0, 0), (7, 6), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (1, 0), (6, 1), 0.5, colors.black),
                                   ('INNERGRID', (1, 0), (6, 1), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (6, 1), (7, 1), 0.5, colors.black),
                                   ('INNERGRID', (6, 1), (7, 1), 0.5, colors.black)]))

            aWidth = self.PAGE_WIDTH
            aHeight = self.objectPosition
            w, h = header.wrap(aWidth, aHeight)
            aHeight = aHeight - h
            w, h = t.wrap(aWidth, aHeight)
            setPositionWidth = (aWidth - w)/2
            t.drawOn(self.reporting, 30, aHeight-h)
            self.objectPosition = (self.objectPosition - (h + 50))

        elif invoice_type == "cropsDetails":
            t = Table(tableData, colWidths=[
                      30, 90, 28, 28, 27, 27, 27, 27, 27, 27, 27, 27, 27, 30])
            t.setStyle(TableStyle([("BOX", (0, 0), (-1, 5), 0.5, colors.black),
                                   ('INNERGRID', (0, 0), (-1, 5), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (0, 0), (7, 6), 0.5, colors.black),
                                   ('INNERGRID', (0, 0), (7, 6), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (1, 0), (6, 1), 0.5, colors.black),
                                   ('INNERGRID', (1, 0), (6, 1), 0.5, colors.black)]))

            t.setStyle(TableStyle([("BOX", (6, 1), (7, 1), 0.5, colors.black),
                                   ('INNERGRID', (6, 1), (7, 1), 0.5, colors.black)]))

            aWidth = self.PAGE_WIDTH
            aHeight = self.objectPosition
            w, h = header.wrap(aWidth, aHeight)
            aHeight = aHeight - h
            w, h = t.wrap(aWidth, aHeight)
            setPositionWidth = (aWidth - w)/2
            t.drawOn(self.reporting, 30, aHeight-h)
            self.objectPosition = (self.objectPosition - (h + 50))

    def endOfCurrentPage(self, forceHeight=0):
        self.reporting.showPage()
        if(forceHeight == 0):
            self.objectPosition = (self.PAGE_HEIGHT - 40)
        else:
            self.objectPosition = (self.PAGE_HEIGHT - forceHeight)

    def completGeneratingReport(self):
        f = []
        '''for (dirpath, dirnames, filenames) in os.walk("systemReports\\"):
            f.extend(filenames)
            break
        for file in f:
            if(file.find('report') == 0):
                try:
                    os.remove("systemReports\\"+file)
                except:
                    pass'''
        self.reporting.save()
        open_file(self.filename)

    def beginInvoice(self, document=None):
        # -------------------------------------------- First Page ----------------------------------------------
        self.objectPosition = self.PAGE_HEIGHT - 40
        self.drawImage(
            size=(120, 120), image="africalla.png", pos="rightcentre")
        self.objectPosition = self.PAGE_HEIGHT - 60
        self.drawText(text="Address of the company", font_name='Century-Gothic-Bold',
                      font_size=8, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="Africalla Kenya Ltd", font_name='Century-Gothic',
                      font_size=6, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="P.O. Box 709,00621", font_name='Century-Gothic',
                      font_size=6, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="Red Hill, Limuru, Kiambu County",
                      font_name='Century-Gothic', font_size=6, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="Village Market, Nairobi, Kenya",
                      font_name='Century-Gothic', font_size=6, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="Mobile (+257) 721-837968", font_name='Century-Gothic',
                      font_size=6, pos=int(self.PAGE_WIDTH/2.2))
        self.drawText(text="E-mail sales@africalla.com",
                      font_name='Century-Gothic', font_size=6, pos=int(self.PAGE_WIDTH/2.2))

        # Drawing invoice Details
        self.setCursorPosition(40)
        self.drawText(text=document, font_name='Candara-Bold',
                      font_size=18, pos="centre")

        sqlOrderQuery = 'SELECT * FROM sales_info LEFT JOIN currencies USING(currency_id) LEFT JOIN sales_info_sub_data USING(sale_id) LEFT JOIN client_info USING(client_id)LEFT JOIN crops USING(crop_id) WHERE invoice_no = %s' % data
        print(sqlOrderQuery)
        mysqlcursor = connection.cursor()
        mysqlcursor.execute(sqlOrderQuery)
        recordsorder = mysqlcursor.fetchall()
        for row in recordsorder:
            cropid = row[0]
            varietyId = row[14]
            crop = row[33]
            clientName = row[21]
            invoice_no = row[13]
            deliveryNo = row[5]
            poNumber = row[6]
            stems = row[16]
            currencyid = [3]
            rate = row[22]
            inco = row[27]
            today = date.today()
            agent = row[28]
            d2 = today.strftime(" %d %b %Y")

        # Here we will fetch Invoice Details from the database
            varietyquery = 'SELECT variety FROM varieties WHERE variety_id = %s'
            mycursor = connection.cursor()
            mycursor.execute(varietyquery, (varietyId,))
            recordsvariety = mycursor.fetchall()
            for ro in recordsvariety:
                crop = ro[0]

            cropquery = 'SELECT crop FROM crops WHERE crop_id = %s'
            mycursor = connection.cursor()
            mycursor.execute(cropquery, (cropid,))
            recordscrop = mycursor.fetchall()
            for row in recordscrop:
                crop = row[0]

            currencyQuery = 'SELECT CurrencyCode FROM currencies WHERE currency_id = %s'
            mycursor = connection.cursor()
            mycursor.execute(currencyQuery, currencyid)
            recordscrop = mycursor.fetchall()
            for row in recordscrop:
                currency = row[0]

            self.setCursorPosition(-29)
            invoiceDate = "Date:  %s" % (d2)
            invoiceNo = "Invoice No.: %s" % (invoice_no)
            invoiceAgent = "Freightwings Ltd."
            deliveryNumber = "Delivery No.: %s" % (deliveryNo)
            poNumbers = "P.O No.: %s" % (poNumber)
            tableData = [[invoiceDate, invoiceNo], ["", poNumbers],
                         ["", deliveryNumber], ["Agent:", agent]]
            self.drawTable(tableData, invoice_type="head")

            # We now load shipping details from here
            self.setCursorPosition(-15)

            self.drawText(text="Ship to:", font_name='Candara-Bold',
                          font_size=12, pos=int(self.PAGE_WIDTH/4.8))
            self.setCursorPosition(-5)
            self.drawText(text="clientName", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/4.8))
            self.setCursorPosition(-5)
            self.drawText(text="P.O. Box 37869", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/4.8))
            self.setCursorPosition(-5)
            self.drawText(text="T E L : 0 4 4 5 4 8 3 2 9", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/4.8))
            self.setCursorPosition(-5)
            self.drawText(text="Dubai", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/4.8))

            # Invoicing to details
            self.setCursorPosition(-57)
            self.drawText(text="Invoice to:", font_name='Candara-Bold',
                          font_size=12, pos=int(self.PAGE_WIDTH/1.8))
            self.setCursorPosition(-5)
            self.drawText(text="Fresh Exchange FZCO", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/1.8))
            self.setCursorPosition(-5)
            self.drawText(text="Dafza Building 6WA", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/1.8))
            self.setCursorPosition(-5)
            self.drawText(text="Office 218", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/1.8))
            self.setCursorPosition(-5)
            self.drawText(text="Dubai", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/1.8))
            self.setCursorPosition(-5)
            self.drawText(text="United Arab Emirates", font_name='Candara',
                          font_size=10, pos=int(self.PAGE_WIDTH/1.8))

            # Show overview of Crops Table
            crops = (textwrap.fill(crop, 10))
            varieties = (textwrap.fill(crop, 10))

            self.setCursorPosition(-17)
            tableData = [["", "", "", "", "", "", "", "", "", ""],
                         ["", "", "", "", "", "", "", "Total", "", ""],
                         ["Total Boxes", "7", "", "", "", "",
                          "", "7", "Total Value", rate],
                         ["Total Stems", stems, "", "", "", "",
                          "", "2,100", "Currency:", currency],
                         ["Total Value", "$273.00", "", "", "",
                          "", "", "", "Mode:", "BY AIR"],
                         ["Actual Weight (Kg.)", "47.00 Kgs", "", "", "",
                          "", "", "47.00 Kgs", "INCO Term", inco],
                         ["Volumetric Weight (Kg.)", "77.00 Kgs", "", "", "", "", "", "77.00 Kgs", "", ""]]
            self.drawTable(tableData, invoice_type="cropOverview")

            self.setCursorPosition(-30)
            tableData = [[crops, "Total\n Stems", "Prices \nStem", "Total\n Price", "Comments"],
                         ["Length 50 cm", stems, "$ 0.14", rate, ""]]
            self.drawTable(tableData, invoice_type="crops")

            self.setCursorPosition(-30)
            tableData = [["GH", "variety", "Box\nNo..", "Box", "20\n cm", "25\n cm", "30\n cm", "35\n cm", "40\n cm", "50\n cm", "60\n cm", "70\n cm", "80\n cm", "90\n cm", "100\n cm", "120\n cm", "Total"],
                         ["1", varieties, "1", "", "", "", "", "",
                          "", "", "", "", "", "", "", stems,  "300"],
                         ["Total", varieties, "", "", "", "", "", "", "", "", "", "", "", "", "", stems,  "300"]]
            self.drawTable(tableData, invoice_type="cropsDetails")

            self.completGeneratingReport()


if __name__ == "__main__":
    mainReport()

Мой журнал:

= RESTART: /home/alex/Documents/Projects/Lathyflora Projects/Africalla Sales/invoice_app/invoice.py
Connected to MySQL Server version  8.0.20-0ubuntu0.20.04.1
You're connected to database:  ('africalla_db',)
SELECT * FROM sales_info LEFT JOIN currencies USING(currency_id) LEFT JOIN sales_info_sub_data USING(sale_id) LEFT JOIN client_info USING(client_id)LEFT JOIN crops USING(crop_id) WHERE invoice_no = "EUR2002"
Traceback (most recent call last):
  File "/home/alex/Documents/Projects/Lathyflora Projects/Africalla Sales/invoice_app/invoice.py", line 428, in <module>
    mainReport()
  File "/home/alex/Documents/Projects/Lathyflora Projects/Africalla Sales/invoice_app/invoice.py", line 89, in __init__
    self.beginInvoice(document="Invoice")
  File "/home/alex/Documents/Projects/Lathyflora Projects/Africalla Sales/invoice_app/invoice.py", line 410, in beginInvoice
    self.drawTable(tableData, invoice_type="cropOverview")
  File "/home/alex/Documents/Projects/Lathyflora Projects/Africalla Sales/invoice_app/invoice.py", line 206, in drawTable
    t.drawOn(self.reporting, 30, aH-h)
  File "/home/alex/.local/lib/python3.8/site-packages/reportlab/platypus/flowables.py", line 114, in drawOn
    self._drawOn(canvas)
  File "/home/alex/.local/lib/python3.8/site-packages/reportlab/platypus/flowables.py", line 95, in _drawOn
    self.draw()#this is the bit you overload
  File "/home/alex/.local/lib/python3.8/site-packages/reportlab/platypus/tables.py", line 1476, in draw
    cellRect = self._spanRects[colNo, rowNo]
KeyError: (0, 3)
...