def blendticks(g1, g2): cnum = g1.split('_')[0] if len(cnum) == 11: base = cnum else: base = 'blendtemp' gfile1 = addpath(f'tmp/{scac}/data/vinterchange/{g1}') print(gfile1) reader1 = PdfFileReader(open(gfile1, 'rb')) p1 = reader1.getPage(0) gfile2 = addpath(f'tmp/{scac}/data/vinterchange/{g2}') reader2 = PdfFileReader(open(gfile2, 'rb')) p2 = reader2.getPage(0) #offset_x = p2.mediaBox[2] offset_x = 500 offset_y = 0 # add second page to first one p2.mergeTranslatedPage(p1, offset_x, offset_y, expand=True) p2.cropBox.lowerLeft = (50, 525) p2.cropBox.upperRight = (1050, 800) outfile = addpath(f'tmp/{scac}/data/vinterchange/{base}_BLEND.pdf') with open(outfile, "wb") as out_f: writer3 = PdfFileWriter() writer3.addPage(p2) writer3.write(out_f) return outfile
def pagemerger(filelist, cache): lfs = len(filelist) - 1 print('lfs has value:', lfs) for j in range(lfs): if j == 0: firstfile = filelist[0] else: firstfile = addpath(f'tmp/{scac}/data/vreport/temp' + str(j - 1) + '.pdf') reader = PdfFileReader(open(firstfile, 'rb')) first_page = reader.getPage(0) sup_reader = PdfFileReader(open(filelist[j + 1], 'rb')) sup_page = sup_reader.getPage( 0) # This is the first page, can pick any page of document #translated_page = PageObject.createBlankPage(None, sup_page.mediaBox.getWidth(), sup_page.mediaBox.getHeight()) # translated_page.mergeScaledTranslatedPage(sup_page, 1, 0, 0) # -400 is approximate mid-page # translated_page.mergePage(invoice_page) sup_page.mergePage(first_page) writer = PdfFileWriter() # writer.addPage(translated_page) writer.addPage(sup_page) if j == lfs - 1: outfile = addpath(f'tmp/{scac}/data/vreport/report' + str(cache) + '.pdf') else: outfile = addpath(f'tmp/{scac}/data/vreport/temp' + str(j) + '.pdf') print('lfs and j are:', j, lfs) print('firstfile=', firstfile) print('supfile=', filelist[j + 1]) print('outfile=', outfile) with open(outfile, 'wb') as f: writer.write(f) f.close() docref = f'tmp/{scac}/data/vreport/report' + str(cache) + '.pdf' killfile = addpath(f'tmp/{scac}/data/vreport/report' + str(cache - 1) + '.pdf') try: os.remove(killfile) except: print('Could not remove previous file') cache = cache + 1 if cache == 999: cache = 0 print('The value of cache is:', cache) return cache, docref
def pay_init(bill, err, modlink): success = 1 myb = Bills.query.get(bill) status = myb.Status if status == 'Paid': success = 0 err.append( 'Bill has been paid in full. Use unpay to restart payment process' ) if success == 1: myb.pDate = today myb.pAmount = myb.bAmount pacct = myb.pAccount if pacct is None: pacct = get_def_bank(myb) elif len(pacct) < 4: pacct = get_def_bank(myb) myb.pAccount = pacct myb.Status = 'Paying' db.session.commit() modlink = 11 err.append(f'Paying Bill {myb.Jo}') docref = f'tmp/{scac}/data/vbills/{myb.Original}' if os.path.isfile(addpath(docref)): leftscreen = 0 else: leftscreen = 1 err.append('Bill has no source document') else: err.append('Could not complete billpay') modlink = 0 leftscreen = 1 return err, modlink, leftscreen, docref
def main(invo, order, docref, emailin): import smtplib import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText import shutil import os from CCC_system_setup import addpath, emailvals emails, passwds, ourserver = emailvals() absdocref = addpath(docref) letter = invo[1] if letter == 'O': word = 'Booking' else: word = 'Order' emailfrom = emails[2] emailto = emailin #emailto = "*****@*****.**" emailcc = emails[0] fileToSend = absdocref username = emails[2] password = passwds[0] msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Cc"] = emailcc msg["Subject"] = 'First Eagle Logistics Invoice: ' + invo + ' for ' + word + ': ' + order body = 'Dear Customer:\n\nYour invoice is attached. Please remit payment at your earliest convenience.\n\nThank you for your business- we appreciate it very much.\n\nSincerely,\n\nFIRST EAGLE LOGISTICS,INC.\n\n\nNorma Ghanem\nFirst Eagle Logistics, Inc.\n505 Hampton Park Blvd Unit O\nCapitol Heights,MD 20743\n301 516 3000' msg.attach(MIMEText(body, 'plain')) attachment = open(fileToSend, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % fileToSend) msg.attach(part) server = smtplib.SMTP(ourserver) #server.starttls() server.login(username, password) emailto = [emailto, emailcc] server.sendmail(emailfrom, emailto, msg.as_string()) server.quit()
def repackage(npages, file6, docref): import numpy as np import subprocess import fnmatch import os import json import shutil from collections import Counter import datetime from PyPDF2 import PdfFileReader newpages = [] for f in range(1, npages + 1): newpages.append(addpath(f'tmp/{scac}/data/vreport/' + str(f) + '.pdf')) pdfcommand = ['pdfunite'] for page in newpages: pdfcommand.append(page) pdfcommand.append(file6) tes = subprocess.check_output(pdfcommand) os.rename(file6, addpath(docref))
def isoMautoscanner(): if request.method == 'POST': # ____________________________________________________________________________________________________________________B.FormVariables.General from viewfuncs import parseline, popjo, jovec, newjo, timedata, nonone, nononef from viewfuncs import numcheck, numcheckv, viewbuttons, get_ints, numcheckvec #Zero and blank items for default username = session['username'].capitalize() today = datetime.date.today() now = datetime.datetime.now().strftime('%I:%M %p') vinlist='' try: os.remove('/home/oslm/oslrun/tmp/data/processing/vins.txt') except IOError: print('File already removed') vins = request.values.get('vinlist') if vins is not None: vinlist=vins.split() txt_file=addpath(f'tmp/{scac}/data/processing/vins.txt') with open(txt_file,'a+') as f: for vin in vinlist: vin=vin.strip() f.write(vin+'\n') f.close() thisip = os.environ['PUBLICIP'] vinlist = vinlist + ['Sent to', thisip] tout = subprocess.check_output(['scp', '/home/oslm/oslrun/tmp/data/processing/vins.txt', 'mark@'+thisip+':/home/mark/flask/crontasks/incoming/vins.txt']) #os.system('scp tmp/data/processing/vins.txt [email protected]:/home/mark/flask/crontasks/incoming/vins.txt') #p = subprocess.Popen(["scp", "tmp/data/processing/vins.txt", "[email protected]:/home/mark/flask/crontasks/incoming/vins.txt"]) #sts = os.waitpid(p.pid, 0) # ____________________________________________________________________________________________________________________E.Delete.General else: from viewfuncs import popjo, jovec, timedata, nonone, nononef today = datetime.date.today() #today = datetime.datetime.today().strftime('%Y-%m-%d') now = datetime.datetime.now().strftime('%I:%M %p') err=['All is well', ' ', ' ', ' ', ' '] vinlist='' return vinlist
def install_pay_init(bill, err, modlink): success = 1 modata = Bills.query.get(bill) status = modata.Status if status == 'Paid': success = 0 leftscreen, docref, prevpayvec = 1, 0, 0 err.append( 'Bill has been paid in full. Use unpay to restart payment process' ) else: prevpayvec = [] pmtlist = json.loads(modata.PmtList) paclist = json.loads(modata.PacctList) reflist = json.loads(modata.RefList) pmethods = json.loads(modata.MethList) memolist = json.loads(modata.MemoList) pdatelist = json.loads(modata.PdateList) checklist = json.loads(modata.CheckList) total = 0.00 for ix, pmt in enumerate(pmtlist): prevpayvec.append([ pmtlist[ix], paclist[ix], pmethods[ix], reflist[ix], memolist[ix], pdatelist[ix] ]) total = total + float(pmt) bamtf = float(modata.bAmount) diff = bamtf - total modata.pDate = today modata.pAmount = d2s(diff) pacct = modata.pAccount if pacct is None: pacct = get_def_bank(modata) elif len(pacct) < 4: pacct = get_def_bank(modata) modata.pAccount = pacct db.session.commit() modlink = 12 err.append(f'Paying Part of Bill {modata.Jo}') docref = f'tmp/{scac}/data/vbills/{modata.Original}' if os.path.isfile(addpath(docref)): leftscreen = 0 else: leftscreen = 1 err.append('Bill has no source document') return err, modlink, leftscreen, docref, prevpayvec
def huntparse(): s = addpath('originals_bin/pdf/hunt/') t = addpath('processing/pdf_bin/hunt/') u = addpath('originals_processed/pdf') for file in os.listdir(s): if fnmatch.fnmatch(file, '*.pdf'): shutil.copy(s + file, u) shutil.move(s + file, t + file) data = addpath('processing/pdf_bin/hunt') done = addpath('processing/pdforder/') viewloc = addpath('tmp/data/vorders/') #Using new format here the left item is what we are looking for (keyword) and right side is the Label hitems = ['Total Rate:Amount', 'Commodity:commodity'] # These items we look to see if there are load and delivery points to add to database vadditems = ['Pickup', 'Shipper', 'Consignee', 'Delivery'] today = datetime.datetime.today() todaydate = today.date() todaynow = today.time() todaystr = datetime.datetime.today().strftime('%Y-%m-%d') year = str(today.year) day = str(today.day) month = str(today.month) #print(month,day,year) datestr = 'label:' + month + '/' + day + '/' + year pyr = year[2] + year[3] date_p1 = re.compile( r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|June|July|August|September|October|November|December)\s?\d{1,2},?\s?\d{4}' ) date_y2 = re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2}') date_y4 = re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{4}') date_p3 = re.compile( r'\d{1,2}\s?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s?\d{4}' ) date_p4 = re.compile(r'\s' + pyr + '(?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])') time_p24 = re.compile( r'(?:[1-9]|0[0-9]|1[0-9]|2[01234])[:](?:0[0-9]|[12345][0-9])') container_p = re.compile(r'[A-Z,a-z]{4}\s?[Ool0123456789]{7}') amount_p = re.compile( r'\$(?:[0-9]|[0-9]{2}|[0-9]{3}|[1-9],[0-9]{3})\.[0-9]{2}') fcount = 0 for file2 in os.listdir(addpath('processing/pdf_bin/hunt')): if fnmatch.fnmatch(file2, '*.pdf'): fcount = fcount + 1 base = os.path.splitext(file2)[0] #print(base) load = base.replace('Tender_', '') print('Load=', load) if not load: load = '000000' #print(file2,base,load) print('Running file: ', file2) print( subprocess.check_output([ 'pdf2txt.py', '-o', done + load + '.txt', addpath('processing/pdf_bin/hunt/' + file2) ])) #See if the order exists already: o = Orders.query.filter(Orders.Original == file2).first() if o is None: jtype = 'T' nextjo = newjo(jtype, todaystr) #add some default values here for database: input = Orders(Status='A0', Jo=nextjo, Load=load, Order=load, Company=None, Location=None, Booking=None, BOL=None, Container=None, Date=None, Driver=None, Company2=None, Time=None, Date2=None, Time2=None, Seal=None, Pickup=None, Delivery=None, Amount=None, Path=None, Original=file2, Description='Load Broker Line Haul', Chassis=None, Detention='0', Storage='0', Release=0, Shipper='JB Hunt', Type=None, Time3=None, Bid=0, Lid=0, Did=0, Label=None, Dropblock1=None, Dropblock2=None, Commodity=None, Packing=None, Links=None, Hstat=-1, Istat=-1, Proof=None, Invoice=None, Gate=None, Package=None, Manifest=None, Scache=0, Pcache=0, Icache=0, Mcache=0, Pkcache=0, QBi=0, InvoTotal=None) db.session.add(input) db.session.commit() o = Orders.query.filter(Orders.Jo == nextjo).first() # Find and add load and delivery points to database for j, item in enumerate(vadditems): with open(done + load + '.txt') as openfile: for line in openfile: if len(line) > 3: linelist = line.split() word1 = linelist[0] if item == word1: line1 = line line2 = next(openfile) line3 = next(openfile) line4 = next(openfile) line5 = next(openfile) if j == 0: pickupdate = line2 print('pickupdate', pickupdate) linelist2 = line2.split() print('DATE', linelist2[0], flush=True) try: date1 = datetime.datetime.strptime( linelist2[0], '%Y-%m-%d') except: print('Could not convert:', date1, flush=True) date1 = todaydate try: time1 = datetime.datetime.strptime( linelist2[1], '%H:%M').time() except: time1 = todaynow o.Date = date1 o.Time = time1 db.session.commit() if j == 1: shipperlines = line2 + line3 + line4 + line5 print('shipperlines: ', shipperlines) o.Dropblock1 = shipperlines company = dropupdate(shipperlines) addr1 = line3.strip() cdat = Drops.query.filter( (Drops.Entity == company) & (Drops.Addr1 == addr1)).first() if cdat is not None: lid = cdat.id else: lid = 0 o.Company = company o.Lid = lid db.session.commit() if j == 2: consigneelines = line2 + line3 + line4 + line5 print('consigneelines: ', consigneelines) o.Dropblock2 = consigneelines company2 = dropupdate(consigneelines) addr1 = line3.strip() cdat = Drops.query.filter( (Drops.Entity == company2) & (Drops.Addr1 == addr1)).first() if cdat is not None: did = cdat.id else: did = 0 o.Company2 = company2 o.Did = did db.session.commit() if j == 3: deliverydate = line2 print('deliverydate', deliverydate) linelist2 = line2.split() #print('DATE',linelist2[0]) date2 = datetime.datetime.strptime( linelist2[0], '%Y-%m-%d') print(date1) time2 = datetime.datetime.strptime( linelist2[1], '%H:%M').time() o.Date2 = date2 o.Time2 = time2 db.session.commit() for item in hitems: list = [] label = item.split(':', 1)[1] item = item.split(':', 1)[0] with open(done + load + '.txt') as openfile: for line in openfile: if item.lower() in line.lower(): rest = line.lower().split(item.lower(), 1)[1] rest = line[-len(rest):] if ':' in rest: rest = rest.split(':', 1)[1] elif '#' in rest: rest = rest.split('#', 1)[1] elif 'NUMBER' in rest: rest = rest.split('NUMBER', 1)[1] rest = rest.replace('#', '') rest = rest.replace(':', '') rest = rest.replace('-', '') rest = rest.strip() #Could have multiple space inside words which we do not want to store in database: pieces = rest.split() phrase = '' for piece in pieces: piece = piece.strip() phrase = phrase + ' ' + piece rest = phrase.strip() #print('item=',item,'rest=',rest,'line=',line) lofrest = len(rest) if lofrest > 0: numbers = sum(c.isdigit() for c in rest) keyratio = float(numbers) / float(lofrest) else: keyratio = 0.0 if keyratio > .4: list.append(rest) if len(list) > 0: best = max(list, key=list.count) else: best = None if label == 'Amount': o.Amount = best db.session.commit() if label == 'commodity': o.Location = best db.session.commit() pdat = People.query.filter(People.Company == 'JB Hunt').first() if pdat is not None: bid = pdat.id else: bid = 0 book = 'JBHunt ' + load o.Booking = book o.Bid = bid o.Type = '53 Dry Van' db.session.commit() os.rename( addpath('processing/pdf_bin/hunt/') + file2, viewloc + file2) print('File ', fcount) return
def invoiceM(oder, payment): myo = Moving.query.get(oder) today = datetime.datetime.today() # Check to see if we have the required data to make an invoice: pdata1 = People.query.filter((People.Company == myo.Shipper) & (People.Ptype == 'Moving')).first() if pdata1 is not None: invo = 1 leftsize = 8 cache = myo.Cache + 1 # These are the services we wish to add to the invoice sdata = Services.query.order_by(Services.Price.desc()).all() total = 0 for data in sdata: testone = request.values.get('serv' + str(data.id)) if testone: servid = int(testone) mys = Services.query.get(servid) qty = 1 total = total + mys.Price input = Invoices(Jo=myo.Jo, SubJo=None, Pid=0, Service=mys.Service, Description=' ', Ea=mys.Price, Qty=qty, Amount=myo.Amount, Total=myo.Amount, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() idat = Invoices.query.filter(Invoices.Jo == myo.Jo).first() if idat is None: descript = 'Job Order ' + myo.Jo + ' Moving from ' + myo.Drop1 + ' to ' + myo.Drop2 total = myo.Amount input = Invoices(Jo=myo.Jo, SubJo=None, Pid=0, Service='Moving Services', Description=descript, Ea=myo.Amount, Qty=1, Amount=myo.Amount, Total=myo.Amount, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() ldat = Invoices.query.filter(Invoices.Jo == myo.Jo).first() if ldat is None: invo = 0 leftsize = 10 err = [ ' ', ' ', 'No services on invoice yet and none selected', ' ', ' ' ] else: invo = 1 leftsize = 8 invodate = ldat.Date dt = ldat.Date err = [' ', ' ', 'Created invoice for JO= ' + myo.Jo, ' ', ' '] ldata = Invoices.query.filter(Invoices.Jo == myo.Jo).order_by( Invoices.Ea.desc()).all() pdata1 = People.query.filter(People.Company == myo.Shipper).first() joborder = myo.Jo file1 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c0.pdf') file2 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c' + str(cache) + '.pdf') file3 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c' + str(cache - 1) + '.pdf') today = datetime.datetime.today().strftime('%m/%d/%Y') type = joborder[1] if invodate is None or invodate == 0: invodate = today else: invodate = invodate.strftime('%m/%d/%Y') date1 = myo.Date.strftime('%m/%d/%Y') date2 = myo.Date2.strftime('%m/%d/%Y') if payment != 0: try: paydate = payment[2].strftime('%m/%d/%Y') except: paydate = payment[2] billto = list(range(5)) if pdata1 is not None: billto[0] = comporname( pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) billto[4] = nononestr(pdata1.Email) else: for i in range(5): billto[i] = ' ' loadat = [' '] * 5 p2 = myo.Dropblock1 p2 = p2.splitlines() for j, p in enumerate(p2): if j < 5: loadat[j] = p.title() shipto = [' '] * 5 p2 = myo.Dropblock2 p2 = p2.splitlines() for j, p in enumerate(p2): if j < 5: shipto[j] = p.title() us = list(range(4)) us[0] = 'FIRST EAGLE LOGISTICS INC' us[1] = '505 HAMPTON PARK BLVD UNIT O' us[2] = 'CAPITOL HEIGHTS MD 20743' us[3] = '301-516-3000 [email protected]' line1 = [ 'No. Stops', 'Terms', 'Job Start', 'Job Finish', 'Bill of Lading', 'Container No.' ] line2 = [ 'Quantity', 'Item Code', 'Description', 'Price Each', 'Amount' ] due = 'Due Upon Receipt' bol = myo.BOL if len(bol) < 2: bol = myo.Jo line3 = [myo.Booking, due, date1, date2, bol, myo.Container] note, bank = bankdata('FC') lab1 = 'Balance Due' lab2 = 'Add $39.00 for all international wires' ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 m1 = hls - dl m2 = hls - 2 * dl m3 = hls - 3 * dl m4 = hls - 4 * dl m5 = hls - 18 * dl m6 = hls - 23 * dl m7 = hls - 27 * dl fulllinesat = [m1, m2, m3, m4, m5, m6, m7] p1 = ltm + 87 p2 = ltm + 180 p3 = ctrall p4 = rtm - 180 p5 = rtm - 100 sds1 = [p1, p2, p3, p4, p5] n1 = ltm + 58 n2 = ltm + 128 n3 = rtm - 140 n4 = rtm - 70 sds2 = [n1, n2, n3, n4] q1 = ltm + 180 q2 = rtm - 180 sds3 = [q1, q2] bump = 2.5 tb = bump * 2 c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) logo = addpath("tmp/pics/logo3.jpg") c.drawImage(logo, 185, 680, mask='auto') # Date and JO boxes dateline = m1 + 8.2 * dl c.rect(rtm - 150, m1 + 7 * dl, 150, 2 * dl, stroke=1, fill=0) c.line(rtm - 150, dateline, rtm, dateline) c.line(rtm - 75, m1 + 7 * dl, rtm - 75, m1 + 9 * dl) # Address boxes ctm = 218 c.rect(ltm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(ctm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(rtm - 175, m1 + dl, 175, 5 * dl, stroke=1, fill=0) level1 = m1 + 5 * dl c.line(ltm, level1, ltm + 175, level1) c.line(ctm, level1, ctm + 175, level1) c.line(rtm - 175, level1, rtm, level1) for i in fulllinesat: c.line(ltm, i, rtm, i) for k in sds1: c.line(k, m1, k, m3) for l in sds2: c.line(l, m3, l, m5) for m in sds3: c.line(m, m6, m, m7) c.line(ltm, m1, ltm, m7) c.line(rtm, m1, rtm, m7) h1 = avg(m6, m7) - 3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm - 75, dateline + 1.5 * dl, 'Invoice') c.setFont('Helvetica', 11, leading=None) c.drawCentredString(rtm - 112.5, dateline + bump, 'Date') c.drawCentredString(rtm - 37.7, dateline + bump, 'Invoice #') c.drawString(ltm + bump * 3, m1 + 5 * dl + bump * 2, 'Bill To') c.drawString(ctm + bump * 3, m1 + 5 * dl + bump * 2, 'Load At') c.drawString(rtm - 170 + bump * 2, m1 + 5 * dl + bump * 2, 'Delv To') ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] for j, i in enumerate(line1): c.drawCentredString(ctr[j], m2 + tb, i) ctr = [ avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm) ] for j, i in enumerate(line2): c.drawCentredString(ctr[j], m4 + tb, i) dh = 12 ct = 305 top = m6 - 1.5 * dh for i in bank: c.drawCentredString(ct, top, i) top = top - dh top = m1 + 9 * dl - 5 for i in us: c.drawString(ltm + bump, top, i) top = top - dh bottomline = m6 - 23 c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2 + tb, bottomline, 'Balance Due:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m7 + 12, 'Add $39.00 for all international wires') c.setFont('Times-Roman', 9, leading=None) j = 0 dh = 9.95 top = m5 - dh for i in note: c.drawString(ltm + tb, top, note[j]) j = j + 1 top = top - dh # _______________________________________________________________________ # Insert data here # _______________________________________________________________________ c.setFont('Helvetica', 12, leading=None) dh = 13 top = level1 - dh lft = ltm + bump * 3 for i in billto: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = ctm + bump * 3 for i in loadat: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = rtm - 175 + bump * 3 for i in shipto: c.drawString(lft, top, i) top = top - dh x = avg(rtm - 75, rtm) y = dateline - dh - bump c.drawCentredString(x, y, joborder) x = avg(rtm - 75, rtm - 150) c.drawCentredString(x, y, invodate) c.setFont('Helvetica', 9, leading=None) j = 0 for i in line3: ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] c.drawCentredString(ctr[j], m3 + tb, i) j = j + 1 total = 0 top = m4 - dh for data in ldata: qty = float(data.Qty) each = float(data.Ea) subtotal = qty * each total = total + subtotal line4 = [str(qty), data.Service] line5 = nononestr(data.Description) line5lines = line5.splitlines() line6 = [each, subtotal] j = 0 for i in line4: ctr = [avg(ltm, n1), avg(n1, n2)] c.drawCentredString(ctr[j], top, i) j = j + 1 j = 0 for i in line6: ctr = [n4 - tb * 2, rtm - tb * 2] c.drawRightString(ctr[j], top, dollar(i)) j = j + 1 for line in line5lines: c.drawString(n2 + tb, top, line) top = top - dh #top = top-dh if payment != 0: c.setFont('Helvetica-Bold', 18, leading=None) c.drawCentredString(ct, top - 2 * dh, 'Payment Received') if payment != 0: c.setFont('Helvetica-Bold', 12, leading=None) try: thispay = nononef(payment[0]) except: thispay = 0.00 top = top - 4 * dh try: c.drawString( n2 + bump, top, 'Your payment of ' + payment[0] + ', Ref No. ' + payment[1]) except: c.drawString(ct, top, 'There is no payment data as of yet') try: c.drawString(n2 + bump, top - dh, 'was applied on ' + paydate) except: c.drawString(ct, top - dh, 'There is a problem with the date') else: thispay = 0.00 total = total - thispay c.drawRightString(rtm - tb * 2, bottomline, dollar(total)) c.showPage() c.save() # try: # Now make a cache copy shutil.copy(file1, file2) except: print('Could not find', file1, file2) # Remove old cache company try: shutil.move(file3, file1) except: print('Could not find', file3, file1) if cache > 1: docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + 'c' + str( cache) + '.pdf' # Store for future use else: docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + 'c0.pdf' if payment == 0: for ldatl in ldata: ldatl.Pid = pdata1.id ldatl.Original = docref db.session.commit() myo.Path = docref myo.Cache = cache db.session.commit() return invo, err, docref, leftsize, dt
def isoC(): if request.method == 'POST': # ____________________________________________________________________________________________________________________B.FormVariables.Compliance from viewfuncs import parseline, popjo, jovec, newjo, timedata, nonone, nononef from viewfuncs import numcheck, numcheckv, viewbuttons, get_ints, numcheckvec #Zero and blank items for default username = session['username'].capitalize() cache = 0 modata = 0 modlink = 0 fdata = 0 filesel = '' docref = '' doctxt = '' longs = '' today = datetime.date.today() now = datetime.datetime.now().strftime('%I:%M %p') leftsize = 10 match = request.values.get('Match') modify = request.values.get('Modify') vmod = request.values.get('Vmod') viewo = request.values.get('ViewO') print = request.values.get('Print') returnhit = request.values.get('Return') deletehit = request.values.get('Delete') delfile = request.values.get('DELF') # hidden values update = request.values.get('Update') newjob = request.values.get('NewJ') thisjob = request.values.get('ThisJob') oder = request.values.get('oder') modlink = request.values.get('modlink') longs = request.values.get(longs) searchfind = request.values.get('mastersearch') assemble = request.values.get('Assemble') oder = nonone(oder) modlink = nonone(modlink) actype = request.values.get('actype') leftscreen = 1 err = ['All is well', ' ', ' ', ' ', ' '] if returnhit is not None: modlink = 0 actype = 'Choose Compliance Subject' if searchfind is not None: modlink = 20 # ____________________________________________________________________________________________________________________E.FormVariables.Compliance # ____________________________________________________________________________________________________________________B.DataUpdates.Compliance if update is not None and modlink == 1: if oder > 0: modata = Compliance.query.get(oder) vals = [ 'subject', 'category', 'longs', 'item', 'date1', 'date2' ] a = list(range(len(vals))) for i, v in enumerate(vals): a[i] = request.values.get(v) datedue = a[4] datefiled = a[5] if datedue == '': newdate1 = None else: newdate1 = datedue if datefiled == '': newdate2 = None else: newdate2 = datedue modata.Subject = a[0] modata.Category = a[1] modata.Textinfo = a[2] modata.Item = a[3] modata.Date1 = newdate1 modata.Date2 = newdate2 db.session.commit() err[3] = 'Modification to Compliance id ' + str( modata.id) + ' completed.' modlink = 0 # ____________________________________________________________________________________________________________________B.GetData.Compliance if actype == 'Choose Compliance Subject' or actype is None: odata = Compliance.query.all() else: odata = Compliance.query.filter(Compliance.Subject == actype).all() if assemble is not None: avec = numcheckvec(odata, 'oder') scommand = ['pdfunite'] if len(avec) > 0: for a in avec: gdat = Compliance.query.get(a) dot = gdat.File1 docref = f'tmp/{scac}/data/vcompliance/' + dot scommand.append(docref) scommand.append( f'tmp/{scac}/data/vunknown/assembledoutput.pdf') tes = subprocess.check_output(scommand) # ____________________________________________________________________________________________________________________B.Search.Compliance if (newjob is None and modlink < 10) or modlink == 20: oder, numchecked = numcheck(1, odata, 0, 0, 0, 0, ['oder']) # ____________________________________________________________________________________________________________________E.Search.Compliance # ____________________________________________________________________________________________________________________B.Views.Compliance if viewo is not None and numchecked == 1: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if oder > 0: modata = Compliance.query.get(oder) if modata.File1 is not None: dot = modata.File1 txt = dot.split('.', 1)[0] + '.txt' docref = f'tmp/{scac}/data/vcompliance/' + dot doctxt = docref.replace('.pdf', '.txt').replace( '.jpg', '.txt').replace('.jpeg', '.txt') leftscreen = 0 leftsize = 10 modlink = 0 err = [' ', ' ', 'Viewing document ' + docref, ' ', ' '] if (viewo is not None) and numchecked != 1: err = [ 'Must check exactly one box to use this option', ' ', ' ', ' ', ' ' ] # ____________________________________________________________________________________________________________________E.Views.Compliance # ____________________________________________________________________________________________________________________B.Modify.Compliance if (modify is not None or vmod is not None) and numchecked == 1: modlink = 1 leftsize = 8 if oder > 0: modata = Compliance.query.get(oder) if vmod is not None: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if modata.File1 is not None: dot = modata.File1 docref = f'tmp/{scac}/data/vcompliance/' + dot doctxt = docref.replace('.pdf', '.txt').replace( '.jpg', '.txt').replace('.jpeg', '.txt') leftscreen = 0 err = ['All is well', ' ', ' ', ' ', ' '] if (modify is not None or vmod is not None) and numchecked != 1: modlink = 0 err[0] = ' ' err[2] = 'Must check exactly one box to use this option' # ____________________________________________________________________________________________________________________E.Modify.Compliance # ____________________________________________________________________________________________________________________B.Delete.Compliance if deletehit is not None and numchecked == 1: if oder > 0: #This section is to determine if we can delete the source file along with the data. If other data is pointing to this #file then we need to keep it. modata = Compliance.query.get(oder) if modata.File1 is not None: dot = modata.File1 docref = f'tmp/{scac}/data/vcompliance/' + dot othdoc = Compliance.query.filter((Compliance.File1 == dot) & ( Compliance.File1 != modata.id)).first() if othdoc is None: try: os.remove(addpath(docref)) os.remove(addtxt(docref)) except: err[0] = 'File already removed' Compliance.query.filter(Compliance.id == oder).delete() db.session.commit() odata = Compliance.query.all() if deletehit is not None and numchecked != 1: err = [ ' ', ' ', 'Must have exactly one item checked to use this option', ' ', ' ' ] # ____________________________________________________________________________________________________________________E.Delete.Compliance # ____________________________________________________________________________________________________________________B.Newjob.Compliance if newjob is not None: err = ['Select Source Document from List'] fdata = myoslist(f'tmp/{scac}/data/vunknown') fdata.sort() modlink = 10 leftsize = 8 leftscreen = 0 docref = f'tmp/{scac}/data/vunknown/NewJob.pdf' if newjob is None and update is None and modlink == 10: filesel = request.values.get('FileSel') filetxt = filesel.replace('.pdf', '.txt').replace('.jpg', '.txt').replace( '.jpeg', '.txt') fdata = myoslist(f'tmp/{scac}/data/vunknown') fdata.sort() leftsize = 8 leftscreen = 0 docref = f'tmp/{scac}/data/vunknown/' + filesel doctxt = f'tmp/{scac}/data/vunknown/' + filetxt try: longs = open(addpath(doctxt)).read() longs = longs[0:999] except: doctxt = '' longs = '' if delfile is not None and modlink == 10: modlink = 0 filesel = request.values.get('FileSel') if filesel != '1': dockill1 = f'tmp/{scac}/data/vunknown/' + filesel try: os.remove(addpath(dockill1)) except: err[1] = 'Could not delete ...' try: os.remove(addtxt(dockill1)) except: err[2] = 'Could not delete txt' if update is not None and modlink == 10: modlink = 0 #Create the new database entry for the source document filesel = request.values.get('FileSel') if filesel != '1': docold = f'tmp/{scac}/data/vunknown/' + filesel docref = f'tmp/{scac}/data/vcompliance/' + filesel try: shutil.move(addpath(docold), addpath(docref)) except: err[4] = 'File has been moved already' try: shutil.move(addtxt(docold), addtxt(docref)) except: err[4] = 'File has been moved already' else: docref = '' doctxt = '' subject = request.values.get('subject') category = request.values.get('category') item = request.values.get('item') longs = request.values.get('longs') datedue = request.values.get('date1') datefiled = request.values.get('date2') docsave = ntpath.basename(docref) if datedue == '': newdate1 = None else: newdate1 = datedue if datefiled == '': newdate2 = None else: newdate2 = datedue input = Compliance(Subject=subject, Category=category, Item=item, Textinfo=longs, File1=docsave, File2=None, File3=None, Date1=newdate1, Date2=newdate2) db.session.add(input) db.session.commit() db.session.close() odata = Compliance.query.all() modlink = 0 leftscreen = 1 oder = 0 leftsize = 10 err = ['All is well', ' ', ' ', ' ', ' '] # ____________________________________________________________________________________________________________________E.Newjob.Compliance if modlink == 20: odata = Compliance.query.filter( (Compliance.Textinfo.contains(searchfind)) | (Compliance.Subject.contains(searchfind)) | (Compliance.Category.contains(searchfind))).all() #This is the else for 1st time through (not posting data from overseas.html) else: from viewfuncs import popjo, jovec, timedata, nonone, nononef, init_truck_zero today = datetime.date.today() #today = datetime.datetime.today().strftime('%Y-%m-%d') now = datetime.datetime.now().strftime('%I:%M %p') oder = 0 cache = 0 modata = 0 modlink = 0 fdata = 0 filesel = '' docref = '' doctxt = '' longs = '' odata = Compliance.query.all() leftscreen = 1 leftsize = 10 err = ['All is well', ' ', ' ', ' ', ' '] actype = '' fdata = myoslist('data/vunknown') fdata.sort() doctxt = os.path.splitext(docref)[0] + '.txt' leftsize = 8 acdata = [] for adat in db.session.query(Compliance.Subject).distinct(): acdata.append(adat.Subject) return odata, oder, err, modata, modlink, leftscreen, docref, leftsize, fdata, filesel, today, now, doctxt, longs, acdata, actype
def knight_parse(): #Move all files in the originals_bin/pdf to the processing/pdf_bin #We have to move and preserve the original file to rename it based on order and load s=addpath('originals_bin/pdf/knight/') t=addpath('processing/pdf_bin/knight/') u=addpath('originals_processed/pdf') for file in os.listdir(s): if fnmatch.fnmatch(file, '*.pdf'): shutil.copy(s+file,u) shutil.move(s+file,t+file) data=addpath('processing/pdf_bin/knight') done=addpath('processing/pdforder/') viewloc=addpath(f'tmp/{scac}/data/vorders/') #Using new format here the left item is what we are looking for (keyword) and right side is the Label hitems=['Order:Order', 'BOL:BOL', 'Booking:Booking', 'Pick Up:Pickup', 'Delivery:Delivery'] # These items we look to see if there are load and delivery points to add to database vadditems=['Load At:Load at', 'Deliver To:Deliver to'] today = datetime.datetime.today() year= str(today.year) day=str(today.day) month=str(today.month) #print(month,day,year) datestr='label:'+month+'/'+day+'/'+year pyr=year[2]+year[3] date_p1=re.compile(r'(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|June|July|August|September|October|November|December)\s?\d{1,2},?\s?\d{4}') date_y2=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2}') date_y4=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{4}') date_p3=re.compile(r'\d{1,2}\s?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s?\d{4}') date_p4=re.compile(r'\s'+pyr+'(?:0[1-9]|1[012])(?:0[1-9]|[12][0-9]|3[01])') time_p24=re.compile(r'(?:[1-9]|0[0-9]|1[0-9]|2[01234])[:](?:0[0-9]|[12345][0-9])') container_p = re.compile(r'[A-Z,a-z]{4}\s?[Ool0123456789]{7}') amount_p = re.compile(r'\$(?:[0-9]|[0-9]{2}|[0-9]{3}|[1-9],[0-9]{3})\.[0-9]{2}') orderdata = [] fcount=0 for file2 in os.listdir(addpath('processing/pdf_bin/knight')): if fnmatch.fnmatch(file2, '*.pdf'): fcount=fcount+1 base=os.path.splitext(file2)[0] #print(base) load=re.findall('\d+', base)[0] #print('Load=',load) if not load: load='000000' mysetlist={'Load':load} #print(file2,base,load) print ('Running file: ',file2) print (subprocess.check_output(['pdf2txt.py', '-o', done+load+'.txt', addpath('processing/pdf_bin/knight/'+file2)])) #add some default values here for database: mysetlist.update({'Status':'A0'}) mysetlist.update({'Description':'Load Broker Line Haul'}) mysetlist.update({'Chassis': 'NFO'}) mysetlist.update({'Detention': 0}) mysetlist.update({'Storage': 0}) mysetlist.update({'Release': 0}) mysetlist.update({'Container': 'NFO'}) mysetlist.update({'BOL': 'NFO'}) mysetlist.update({'Driver': 'NFO'}) mysetlist.update({'Company2': 'NFO'}) mysetlist.update({'Seal': 'NFO'}) mysetlist.update({'Shipper': 'Knight Logistics LLC'}) mysetlist.update({'Type': 'NFO'}) mysetlist.update({'Order': '000000'}) companyfound='' locationfound='' # Find and add load and delivery points to database for item in vadditems: subitem = item.split(':',1)[1] item = item.split(':',1)[0] label=item with open(done+load+'.txt') as openfile: for line in openfile: if re.search(item, line, re.IGNORECASE) or re.search(subitem, line, re.IGNORECASE): if re.search(item, line, re.IGNORECASE): test=item else: test=subitem rest=line.lower().split(test.lower(),1)[0] line1=line line2=next(openfile) line3=next(openfile) line4=next(openfile) l1=len(rest) st=max(0,l1-15) en=st+40 capture1=line2[st:en] capture2=line3[st:en] capture3=line4[st:en] capture1=capture1.strip() capture2=capture2.strip() capture3=capture3.strip() capture4=capture3.split(' ',1)[0] capture4=capture4.replace(',','') capture4=capture4.strip() #print(capture1) #print(capture2) #print(capture3) #print(capture4) if 'load' in line1.lower(): type='Load' if 'deliver' in line1.lower(): type='Deliver' #print(type) # Update Database company1=dropupdate(capture1+'\n'+capture2+'\n'+capture3+'\n'+capture4) if 'load' in line1.lower(): mysetlist.update({'Company' : company1}) if 'deliver' in line1.lower(): mysetlist.update({'Company2' : company1}) date=None date2=None time=None time2=None time3=None with open(done+load+'.txt') as openfile: for line in openfile: if 'earliest' in line.lower() and not date: datep=date_y2.findall(line) if datep: date=datetime.datetime.strptime(datep[0], '%m/%d/%y').strftime('%Y/%m/%d') datep=date_y4.findall(line) if datep: date=datetime.datetime.strptime(datep[0], '%m/%d/%Y').strftime('%Y/%m/%d') time=time_p24.findall(line) if time: time=time[0] else: time=None #print(line) #print(date) #print(time) mysetlist.update({'Date' : date}) mysetlist.update({'Time' : time}) date_p2=re.compile(r'\d{1,2}[/-]\d{1,2}[/-]\d{2,4}') if 'earliest' in line.lower() and not date2: datep=date_y2.findall(line) if datep: date2=datetime.datetime.strptime(datep[0], '%m/%d/%y').strftime('%Y/%m/%d') datep=date_y4.findall(line) if datep: date2=datetime.datetime.strptime(datep[0], '%m/%d/%Y').strftime('%Y/%m/%d') time2=time_p24.findall(line) if time2: time2=time2[0] else: time2=None mysetlist.update({'Date2' : date2}) mysetlist.update({'Time2' : time2}) mysetlist.update({'Time3' : time3}) container=container_p.findall(line) if container: mysetlist.update({'Container' : container[0]}) for item in hitems: list=[] label = item.split(':',1)[1] item = item.split(':',1)[0] with open(done+load+'.txt') as openfile: for line in openfile: if item.lower() in line.lower(): rest=line.lower().split(item.lower(),1)[1] rest=line[-len(rest):] if ':' in rest: rest=rest.split(':',1)[1] elif '#' in rest: rest=rest.split('#',1)[1] elif 'NUMBER' in rest: rest=rest.split('NUMBER',1)[1] rest=rest.replace('#', '') rest=rest.replace(':', '') rest=rest.replace('-', '') rest=rest.strip() #Could have multiple space inside words which we do not want to store in database: pieces=rest.split() phrase='' for piece in pieces: piece=piece.strip() phrase=phrase + ' ' + piece rest=phrase.strip() #print('item=',item,'rest=',rest,'line=',line) lofrest=len(rest) if lofrest > 0: numbers = sum(c.isdigit() for c in rest) keyratio = float(numbers)/float(lofrest) else: keyratio = 0.0 if keyratio > .4: list.append(rest) if len(list)>0: best=max(list,key=list.count) else: best=None mysetlist.update({label : best}) print('This is what I got on each iteration', list) #Looking for amount in whole file: longs = open(done+load+'.txt').read() amount=amount_p.findall(longs) if amount: amount = [w.replace('$','') for w in amount] amount = [w.replace(',','') for w in amount] amt=[float(i) for i in amount] newamount="{:.2f}".format(max(amt)) mysetlist.update({'Amount': newamount}) #Little cheat, the future name of the document after signing #Need it here to save in database order=mysetlist["Order"] print(mysetlist) print(load) print(order) forig='load'+load+'_order' + order + '.pdf' try: os.remove(viewloc+forig) except: print('File does not yet exist: '+viewloc+forig) os.rename(addpath('processing/pdf_bin/knight/'+file2),viewloc+forig) mysetlist.update({'Original': forig}) # fsig='load'+load+'_order' + mysetlist["Order"] + '_sig.pdf' # mysetlist.update({'Orders_Signed': fsig}) orderdata.append(mysetlist) print('File ',fcount,flush=True) print(mysetlist) if 1==1: # Get the next Job Order number print('Now entering the parsed data into database...',flush=True) lv=JO.query.get(1) nextid=lv.nextid eval=str(nextid%100).zfill(2) day2="{0:0=2d}".format(int(day)) if month=='10': month='X' if month=='11': month='Y' if month=='12': month='Z' # The type and company can be changed depending on who is calling jtype='T' jcompany='F' nextjo=jcompany+jtype+month+day2+year[3]+eval #print(nextjo, today) for index in range(len(orderdata)): obj=orderdata[index] Order=obj.get("Order") Order=Order.strip() tDate=obj.get("Date") #print('tDate=',tDate) if tDate is not None and tDate != '': Date=datetime.datetime.strptime(tDate, '%Y/%m/%d') else: Date=today tDate=obj.get("Date2") if tDate is not None and tDate != '': Date2=datetime.datetime.strptime(tDate, '%Y/%m/%d') else: Date2=today loadcompany=obj.get("Company") pdata=People.query.filter(People.Company==loadcompany).first() if pdata is None: lid=None else: lid=pdata.id delivercompany=obj.get("Company2") pdata=People.query.filter(People.Company==delivercompany).first() if pdata is None: did=None else: did=pdata.id # Check to see if this order file is in database already: odata = Orders.query.filter(Orders.Order == Order).first() if odata is None: input = Orders(Status=obj.get("Status"), Jo=nextjo, Load=obj.get("Load"),Order=obj.get("Order"), Company=obj.get("Company"), Location=obj.get("Location"),Booking=obj.get("Booking"), BOL=obj.get("BOL"),Container=obj.get("Container"), Date=Date,Driver=obj.get("Driver"),Company2=obj.get("Company2"), Time=obj.get("Time"), Date2=Date2, Time2=obj.get("Time2"), Seal=obj.get("Seal"), Pickup=obj.get("Pickup"), Delivery=obj.get("Delivery"), Amount=obj.get('Amount'), Path=None, Original=obj.get('Original'), Description=obj.get("Description"), Chassis=obj.get('Chassis'), Detention=obj.get('Detention'), Storage=obj.get('Storage'), Release=obj.get('Release'), Shipper=obj.get('Shipper'), Type=obj.get('Type'), Time3=None, Bid=None, Lid=lid, Did=did, Label='', Dropblock1='',Dropblock2='', Commodity=None, Packing=None, Links=None, Hstat=-1, Istat=-1, Proof=None, Invoice=None, Gate=None, Package=None, Manifest=None, Scache=0, Pcache=0, Icache=0, Mcache=0, Pkcache=0, QBi=0, InvoTotal=obj.get('Amount')) print ('Data part ', index+1, ' of ', len(orderdata), 'is being added to database: Orders') db.session.add(input) input2 = JO(jo=nextjo, nextid=0, date=today, status=1) db.session.add(input2) nextid=nextid+1 lv.nextid=nextid eval=str(nextid%100).zfill(2) nextjo=jcompany+jtype+month+day2+year[3]+eval else: # The order already exists so we merge the new with the old if have no values print ('The data for dataset ', index+1, ' of ', len(orderdata), 'is already in the database: table Orders has been updated') odata.Date=Date odata.Time=obj.get("Time") odata.Date2=Date2 odata.Time2=obj.get("Time2") odata.Original=obj.get('Original') if odata.Pickup=='NFO' or odata.Pickup=='None' or odata.Pickup is None: odata.Pickup=obj.get("Pickup") if odata.Location=='NFO': odata.Location=Location if odata.Company=='NFO': odata.Company=obj.get("Company") if odata.Driver=='NFO': odata.Driver=obj.get("Driver") if odata.Booking=='NFO' or odata.Booking=='None' or odata.Booking is None: odata.Booking=obj.get("Booking") if odata.BOL=='NFO': odata.BOL=obj.get("BOL") if odata.Container=='NFO' or odata.Container=='None' or odata.Container is None: odata.Container=obj.get("Container") if odata.Delivery=='NFO': odata.Delivery=obj.get("Delivery") odata.Amount=obj.get('Amount') if odata.Company2=='NFO': odata.Company2=obj.get('Company2') if odata.Seal=='NFO': odata.Seal=obj.get('Seal') if odata.Shipper=='NFO': odata.Shipper=obj.get('Shipper') if odata.Type=='NFO': odata.Type=obj.get('Type') db.session.commit() print('Total # pdf files found: ', fcount)
def plcontents(file4, itemlist, blist, cache): details = request.values.get('dt3') indent1 = 50 lastexp = 'D' today = datetime.datetime.today().strftime('%m/%d/%Y') invodate = datetime.date.today().strftime('%m/%d/%Y') sdate = request.values.get('start') fdate = request.values.get('finish') try: start = datetime.datetime.strptime(sdate, '%Y-%m-%d') end = datetime.datetime.strptime(fdate, '%Y-%m-%d') except: start = today end = today ltm, rtm, bump, tb, ctrall, left_ctr, right_ctr, dl, dh, tdl, hls, m1, m2, m3, m4, m5, m6, m7, n1, n2, n3 = reportsettings( 1) pages = [file4] page = 1 c = canvas.Canvas(file4, pagesize=letter) c.setLineWidth(1) bottomy = n3 mtop = n1 p1 = ltm + 55 p15 = ltm + 65 p2 = ltm + 140 p3 = ltm + 200 p4 = ltm + 270 p5 = rtm - 150 p6 = rtm - 50 # p7=rtm-40 #Set the Building Propration for Items shared between FEL and Other Fbp = .80 prorate = [1.0, 1.0] inctotals = [0.0, 0.0, 0.0, 0.0] optype = ['Trucking', 'Overseas', 'Storage', 'Moving'] keyval = ['Order', 'Booking', 'JO', 'JO'] exptotals = [0.0, 0.0] i_categories = [ 'BldRent', 'BldRepMaint', 'Utilities', 'Adv-Mark', 'BankFees', 'Taxes', 'OfficeSupp', 'Insurance', 'ProfFees', 'Other' ] d_categories = [ 'Container', 'Towing', 'Fuel', 'Payroll', 'Rentals', 'Other' ] catbp = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, Fbp, Fbp, Fbp, 1.0, 1.0, 1.0, Fbp, 1.0, 1.0, 1.0 ] extype = [] exptotals = [] for cat in d_categories: extype.append('D:' + cat) exptotals.append(0.0) for cat in i_categories: extype.append('I:' + cat) exptotals.append(0.0) #___________Income_____________________________ for kval in range(4): complete = 0 while complete == 0 and page < 20: c, page, pages, mtop = newpagecheck(c, mtop, bottomy + 20, page, file4, pages) if details == 'on': hvec = [ltm, p1, p15, p2, p3, p4, p5, p6, rtm] headerlist = [ 'InvoDate', 'L', 'Service', optype[kval], 'Container', 'From', 'To', 'Invoiced' ] justify = ['c', 'c', 'l', 'l', 'l', 'l', 'l', 'r'] mtop = stripheader(c, 10, mtop, hvec, headerlist) elif mtop == n1: hvec = [ltm, rtm] headerlist = ['INCOME ALL SOURCES'] justify = ['r'] mtop = stripheader(c, 12, mtop, hvec, headerlist) mtop = mtop - dh * 1.5 mtop, inctotals, rlist = pl_orderlisting(c, 9, mtop, hvec, itemlist, justify, inctotals, bottomy, kval, optype, details) if mtop > 0: complete = 1 else: c, page, pages, mtop = newpagecheck(c, mtop, bottomy + 20, page, file4, pages) itemlist = rlist if details == 'on': mtop = mtop - dh indent = 0 else: indent = indent1 c.setFont('Helvetica-Bold', 11, leading=None) if kval == 0: c.drawString(ltm + indent, mtop, 'Income from:') c.drawRightString(rtm - bump - indent * 3, mtop, optype[kval] + ' Operations:') c.drawRightString(rtm - bump - indent, mtop, dollar(inctotals[kval])) mtop = mtop - dh * 1.2 inctotal = 0.0 for i in inctotals: inctotal = inctotal + i c.setFont('Helvetica-Bold', 11, leading=None) #mtop=mtop-dh c.drawRightString(rtm - bump - indent * 2, mtop, 'Total for All Sources of Income:') c.drawRightString(rtm - bump, mtop, dollar(inctotal)) mtop = mtop - dh p1 = ltm + 55 p2 = ltm + 120 p3 = ltm + 240 p4 = ltm + 410 p5 = rtm - 120 p6 = rtm - 50 #___________Expenses_____________________________ for kval, exp in enumerate(extype): #blist.append([d1.strftime('%m/%d/%Y'),'COGS',company,desc,acct,nodollar(bamount)]) complete = 0 count = 0 while complete == 0 and page < 20 and count < 5000: count += 1 c, page, pages, mtop = newpagecheck(c, mtop, bottomy + 20, page, file4, pages) if details == 'on': hvec = [ltm, p1, p2, p3, p5, p6, rtm] headerlist = [ 'BillDate', 'ExpType', 'Vendor', 'Description', 'Account', 'Expense' ] justify = ['c', 'c', 'l', 'l', 'l', 'r'] mtop = stripheader(c, 10, mtop, hvec, headerlist) elif mtop == n1 or kval == 0: hvec = [ltm, rtm] headerlist = ['COSTS and EXPENSES'] justify = ['r'] mtop = stripheader(c, 12, mtop, hvec, headerlist) mtop = mtop - dh * 1.5 mtop, exptotals, rlist = pl_explisting(c, 9, mtop, hvec, blist, justify, exptotals, bottomy, kval, exp, details, catbp) if mtop > 0: complete = 1 else: c, page, pages, mtop = newpagecheck(c, mtop, bottomy + 20, page, file4, pages) blist = rlist if details == 'on': mtop = mtop - dh indent = 0 else: indent = indent1 c.setFont('Helvetica-Bold', 11, leading=None) thisexp = extype[kval][0] if thisexp != lastexp: dtotals = exptotals[0:kval] print(kval, dtotals) dtotal = 0.0 for tot in dtotals: dtotal = dtotal + tot mtop = mtop - dh * .5 c.drawRightString(rtm - bump, mtop, dollar(dtotal)) mtop = mtop - 2 * dh lastexp = thisexp c.drawString(ltm + indent, mtop, 'Indirect Costs (Overhead):') if kval == 0: c.drawString(ltm + indent, mtop, 'Direct Costs:') catname = extype[kval].replace('D:', '').replace('I:', '') c.drawRightString(rtm - bump - indent * 3, mtop, catname + ':') c.drawRightString(rtm - bump - indent, mtop, dollar(exptotals[kval])) mtop = mtop - dh if kval == len(extype) - 1: lastones = len(exptotals) - len(dtotals) itotals = exptotals[-lastones:] itotal = 0.0 for tot in itotals: itotal = itotal + tot try: gapct = itotal / inctotal * 100 except: gapct = 0.00 mtop = mtop - dh * .5 c.drawString(ltm + indent * 2, mtop, 'Overhead Rate: ' + d2s(gapct) + '%') c.drawRightString(rtm - bump, mtop, dollar(itotal)) mtop = mtop - 2 * dh exptotal = 0.0 for i in exptotals: exptotal = exptotal + i c.setFont('Helvetica-Bold', 11, leading=None) c.drawRightString(rtm - bump, mtop, 'Total for All Expenses: ' + dollar(exptotal)) mtop = mtop - 2 * dh c.showPage() c.save() if len(pages) > 1: pdfcommand = ['pdfunite'] for page in pages: pdfcommand.append(page) multioutput = addpath(f'tmp/{scac}/data/vreport/multioutput' + str(cache) + '.pdf') pdfcommand.append(multioutput) tes = subprocess.check_output(pdfcommand) else: multioutput = '' return pages, multioutput
def depositcontents(file4, itemlist, cache, nextjo, acctin, stamp): today = datetime.datetime.today().strftime('%m/%d/%Y') invodate = datetime.date.today().strftime('%m/%d/%Y') adat = Accounts.query.filter(Accounts.Name == acctin).first() if adat is not None: rt = adat.Routing an = adat.AcctNumber else: rt = 'Unknown' an = 'Unknow' ltm, rtm, bump, tb, ctrall, left_ctr, right_ctr, dl, dh, tdl, hls, m1, m2, m3, m4, m5, m6, m7, n1, n2, n3 = reportsettings( 1) pages = [file4] page = 1 c = canvas.Canvas(file4, pagesize=letter) c.setLineWidth(1) place = [ltm + 10, ltm + 90, ltm + 270, ltm + 450, ltm + 500, rtm - 80] ctr = [] for j, p in enumerate(place): if j < len(place) - 1: ctr.append(avg(p, place[j + 1])) #Main Items Listing c.setFont('Helvetica-Bold', 14, leading=None) c.drawString(45, 550, 'Deposit Ticket ' + nextjo) c.drawString(45, 530, 'Bank Account: ' + acctin) c.drawString(305, 550, 'Account Number: ' + an) c.drawString(305, 530, 'Bank Routing: ' + rt) c.setFont('Helvetica-Bold', 12, leading=None) top = n2 + dh - 50 c.drawString(place[0], top, 'Checks Deposited: Details by Job Order') top = top - dl for j, i in enumerate( ['Job Order', 'Customer', 'Remit/Check Ref #', 'Amount']): if j == 3: c.drawRightString(place[j], top, i) else: c.drawString(place[j], top, i) c.setFont('Helvetica', 12, leading=None) top = top - dh total = 0.00 checks = [] cktotals = [] complist = [] l1 = len(itemlist) for k in range(l1): newlist = itemlist[k] for j, i in enumerate(newlist): if j == 2: if i not in checks: checks.append(i) complist.append(newlist[1]) if j == 3: c.drawRightString(place[j], top, i) amt = float(i) total = total + amt else: c.drawString(place[j], top, i) top = top - dl if top < n3: c.showPage() c.save() page = page + 1 base = file4.replace('.pdf', '') newfile = base + 'page' + str(page) + '.pdf' top = n2 - dh c = canvas.Canvas(newfile, pagesize=letter) pages.append(newfile) totals = d2s(total) c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(place[2], top, 'Total:') c.drawRightString(place[3], top, totals) for ch in checks: subtotal = 0.00 for items in itemlist: if items[2] == ch: amt = float(items[3]) subtotal = subtotal + amt cktotals.append(subtotal) #Main Items Listing c.setFont('Helvetica-Bold', 12, leading=None) top = top - 2 * dh c.drawString(place[0], top, 'Checks Deposited: Summary by Check') top = top - dl for j, i in enumerate(['Check#', 'Customer', '', 'Amount']): if j == 3: c.drawRightString(place[j], top, i) else: c.drawString(place[j], top, i) c.setFont('Helvetica', 12, leading=None) top = top - dh total = 0.00 for j, ch in enumerate(checks): c.drawString(place[0], top, ch) c.drawString(place[1], top, complist[j]) c.drawRightString(place[3], top, d2s(cktotals[j])) top = top - dh c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(place[2], top, 'Total:') c.drawRightString(place[3], top, totals) if stamp == 1: c.setFont('Helvetica-Bold', 14, leading=None) top = top - 3 * dh depstamp = addpath(f"tmp/{scac}/pics/deposited.png") c.drawImage(depstamp, 135, 50, mask='auto') c.drawCentredString(307, 65, today) jdat = JO.query.filter(JO.jo == nextjo).first() jdat.dinc = d2s(totals) db.session.commit() c.showPage() c.save() if len(pages) > 1: pdfcommand = ['pdfunite'] for page in pages: pdfcommand.append(page) multioutput = addpath(f'tmp/{scac}/data/vreport/multioutput' + str(cache) + '.pdf') pdfcommand.append(multioutput) tes = subprocess.check_output(pdfcommand) else: multioutput = '' return pages, multioutput
def T_invoice(odata, ldata, pdata1, pdata2, pdata3, cache, invodate, payment): # pdata1:Bid (Bill To) # pdata2:Lid (Load At) # pdata3:Did (Delv To) # All dates must begin in datetime format and will be converted to strings as required joborder = odata.Jo file1 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + '.pdf') file2 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c' + str(cache) + '.pdf') today = datetime.datetime.today().strftime('%m/%d/%Y') type = joborder[1] if invodate is None or invodate == 0: invodate = today else: invodate = invodate.strftime('%m/%d/%Y') date1 = odata.Date.strftime('%m/%d/%Y') date2 = odata.Date2.strftime('%m/%d/%Y') if payment != 0: try: paydate = payment[2].strftime('%m/%d/%Y') except: paydate = payment[2] billto = list(range(5)) if pdata1 is not None: billto[0] = comporname( pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) # billto[4]=nononestr(pdata1.Email) billto[4] = ' ' else: for i in range(5): billto[i] = ' ' loadat = list(range(5)) if pdata2 is not None: loadat[0] = pdata2.Entity.title() loadat[1] = nononestr(pdata2.Addr1).title() loadat[2] = nononestr(pdata2.Addr2).title() loadat[3] = '' loadat[4] = '' else: for i in range(5): loadat[i] = ' ' shipto = list(range(5)) if pdata3 is not None: shipto[0] = pdata3.Entity.title() shipto[1] = nononestr(pdata3.Addr1).title() shipto[2] = nononestr(pdata3.Addr2).title() shipto[3] = '' shipto[4] = '' else: for i in range(5): shipto[i] = ' ' if type == 'T': line1 = [ 'Order #', 'Booking #', 'Job Start', 'Job Finish', 'Bill of Lading', 'Container No.' ] line2 = ['Quantity', 'Item Code', 'Description', 'Price Each', 'Amount'] if type == 'T': chassis = ' ' try: line3 = [ odata.Order, odata.Booking, date1, date2, odata.BOL, odata.Container ] except: line3 = [odata.Order, odata.Booking, date1, date2, ' ', ' '] qnote, note, bank, us, lab, logoi = bankdata('FC') lab1 = lab[0] lab2 = lab[1] # ___________________________________________________________ ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 m1 = hls - dl m2 = hls - 2 * dl m3 = hls - 3 * dl m4 = hls - 4 * dl m5 = hls - 18 * dl m6 = hls - 23 * dl m7 = hls - 27 * dl fulllinesat = [m1, m2, m3, m4, m5, m6, m7] p1 = ltm + 87 p2 = ltm + 180 p3 = ctrall p4 = rtm - 180 p5 = rtm - 100 sds1 = [p1, p2, p3, p4, p5] n1 = ltm + 58 n2 = ltm + 128 n3 = rtm - 140 n4 = rtm - 70 sds2 = [n1, n2, n3, n4] q1 = ltm + 180 q2 = rtm - 180 sds3 = [q1, q2] bump = 2.5 tb = bump * 2 c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) c.drawImage(logoi, 180, 670, mask='auto') # Date and JO boxes dateline = m1 + 8.2 * dl c.rect(rtm - 150, m1 + 7 * dl, 150, 2 * dl, stroke=1, fill=0) c.line(rtm - 150, dateline, rtm, dateline) c.line(rtm - 75, m1 + 7 * dl, rtm - 75, m1 + 9 * dl) if type == 'T': # Address boxes ctm = 218 c.rect(ltm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(ctm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(rtm - 175, m1 + dl, 175, 5 * dl, stroke=1, fill=0) level1 = m1 + 5 * dl c.line(ltm, level1, ltm + 175, level1) c.line(ctm, level1, ctm + 175, level1) c.line(rtm - 175, level1, rtm, level1) for i in fulllinesat: c.line(ltm, i, rtm, i) for k in sds1: c.line(k, m1, k, m3) for l in sds2: c.line(l, m3, l, m5) for m in sds3: c.line(m, m6, m, m7) c.line(ltm, m1, ltm, m7) c.line(rtm, m1, rtm, m7) h1 = avg(m6, m7) - 3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm - 75, dateline + 1.5 * dl, 'Invoice') c.setFont('Helvetica', 11, leading=None) c.drawCentredString(rtm - 112.5, dateline + bump, 'Date') c.drawCentredString(rtm - 37.7, dateline + bump, 'Invoice #') c.drawString(ltm + bump * 3, m1 + 5 * dl + bump * 2, 'Bill To') c.drawString(ctm + bump * 3, m1 + 5 * dl + bump * 2, 'Load At') c.drawString(rtm - 170 + bump * 2, m1 + 5 * dl + bump * 2, 'Deliver To') ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] for j, i in enumerate(line1): c.drawCentredString(ctr[j], m2 + tb, i) ctr = [avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm)] for j, i in enumerate(line2): c.drawCentredString(ctr[j], m4 + tb, i) dh = 12 ct = 305 top = m6 - 1.5 * dh for i in bank: c.drawCentredString(ct, top, i) top = top - dh top = m1 + 9 * dl - 5 for i in us: c.drawString(ltm + bump, top, i) top = top - dh bottomline = m6 - 23 c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2 + tb, bottomline, 'Balance Due:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m7 + 12, 'Add $39.00 for all international wires') c.setFont('Times-Roman', 9, leading=None) j = 0 dh = 9.95 top = m5 - dh for i in note: c.drawString(ltm + tb, top, note[j]) j = j + 1 top = top - dh # _______________________________________________________________________ # Insert data here # _______________________________________________________________________ c.setFont('Helvetica', 10, leading=None) if type == 'T': dh = 13 top = level1 - dh lft = ltm + bump * 3 for i in billto: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = ctm + bump * 3 for i in loadat: c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = rtm - 175 + bump * 3 for i in shipto: c.drawString(lft, top, i) top = top - dh x = avg(rtm - 75, rtm) y = dateline - dh - bump c.drawCentredString(x, y, joborder) x = avg(rtm - 75, rtm - 150) c.drawCentredString(x, y, invodate) c.setFont('Helvetica', 9, leading=None) j = 0 for i in line3: ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] i = nononestr(i) c.drawCentredString(ctr[j], m3 + tb, i) j = j + 1 total = 0 top = m4 - dh for data in ldata: qty = float(float(data.Qty)) each = float(float(data.Ea)) subtotal = qty * each total = total + subtotal line4 = [str(qty), data.Service] line5 = nononestr(data.Description) line6 = [each, subtotal] j = 0 for i in line4: ctr = [avg(ltm, n1), avg(n1, n2)] c.drawCentredString(ctr[j], top, i) j = j + 1 c.drawString(n2 + tb, top, line5) j = 0 for i in line6: ctr = [n4 - tb * 2, rtm - tb * 2] c.drawRightString(ctr[j], top, dollar(i)) j = j + 1 top = top - dh if payment != 0: c.setFont('Helvetica-Bold', 18, leading=None) c.drawCentredString(ct, top - 2 * dh, 'Payment Received') if payment != 0: c.setFont('Helvetica-Bold', 12, leading=None) try: thispay = float(payment[0]) except: thispay = 0.00 top = top - 4 * dh try: c.drawString( n2 + bump, top, 'Your payment of ' + payment[0] + ', Ref No. ' + payment[1]) except: c.drawString(ct, top, 'There is no payment data as of yet') try: c.drawString(n2 + bump, top - dh, 'was applied on ' + paydate) except: c.drawString(ct, top - dh, 'There is a problem with the date') else: thispay = 0.00 total = total - thispay c.drawRightString(rtm - tb * 2, bottomline, dollar(total)) c.showPage() c.save() # # Now make a cache copy shutil.copy(file1, file2) return file2
def main(order, docref, emailin, monsel, inco, company): import smtplib import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText from CCC_system_setup import addpath import ntpath import shutil import os emails, passwds, ourserver = emailvals() newfile = ntpath.basename(docref) shutil.copy(addpath(docref), newfile) emailfrom = emails[2] emailto = emailin emailcc = emails[0] fileToSend = newfile username = emails[0] password = passwds[0] monvec = [ 'All', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] month = monvec[monsel] msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Cc"] = emailcc if inco == 0: msg["Subject"] = 'Invoice ' + order + ' for ' + company + ' (Storage for the Month of ' + month + ' 2018)' body = 'Dear Customer:\n\nYour invoice for storage services is attached. Please remit payment at your earliest convenience.\n\nThank you for your business- we appreciate it very much.\n\nSincerely,\n\nFIRST EAGLE LOGISTICS,INC.\n\n\nNorma Ghanem\nFirst Eagle Logistics, Inc.\n505 Hampton Park Blvd Unit O\nCapitol Heights,MD 20743\n301 516 3000' else: msg["Subject"] = 'Payment Received for Invoice ' + order body = 'Dear Customer:\n\nYour payment receipt for storage services is attached. Your payment has been applied for the month of ' + month + ' 2018.\n\nThank you for your business- we appreciate it very much.\n\nSincerely,\n\nFIRST EAGLE LOGISTICS,INC.\n\n\nNorma Ghanem\nFirst Eagle Logistics, Inc.\n505 Hampton Park Blvd Unit O\nCapitol Heights,MD 20743\n301 516 3000' msg.attach(MIMEText(body, 'plain')) attachment = open(fileToSend, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % fileToSend) msg.attach(part) server = smtplib.SMTP(ourserver) #server.starttls() server.login(username, password) emailto = [emailto, emailcc] server.sendmail(emailfrom, emailto, msg.as_string()) server.quit() os.remove(newfile)
def pagemergermp(filelist, cache, pages, multioutput): lfs = len(filelist) - 1 print('lfs has value:', lfs) for j in range(lfs): if j == 0: firstfile = filelist[0] else: firstfile = addpath(f'tmp/{scac}/data/vreport/temp' + str(j - 1) + '.pdf') reader = PdfFileReader(open(firstfile, 'rb')) first_page = reader.getPage(0) sup_reader = PdfFileReader(open(filelist[j + 1], 'rb')) sup_page = sup_reader.getPage( 0) # This is the first page, can pick any page of document #translated_page = PageObject.createBlankPage(None, sup_page.mediaBox.getWidth(), sup_page.mediaBox.getHeight()) # translated_page.mergeScaledTranslatedPage(sup_page, 1, 0, 0) # -400 is approximate mid-page # translated_page.mergePage(invoice_page) sup_page.mergePage(first_page) writer = PdfFileWriter() # writer.addPage(translated_page) writer.addPage(sup_page) if j == lfs - 1: outfile = addpath(f'tmp/{scac}/data/vreport/report' + str(cache) + '.pdf') else: outfile = addpath(f'tmp/{scac}/data/vreport/temp' + str(j) + '.pdf') print('lfs and j are:', j, lfs) print('firstfile=', firstfile) print('supfile=', filelist[j + 1]) print('outfile=', outfile) with open(outfile, 'wb') as f: writer.write(f) f.close() # This gives us the merges backdrop pdf file on which we will place the contents. # Now place the mulitpage content on this file for each page and assemble newpages = [] for j, page in enumerate(pages): reader = PdfFileReader(open(outfile, 'rb')) first_page = reader.getPage(0) sup_reader = PdfFileReader(open(multioutput, 'rb')) sup_page = sup_reader.getPage(j) sup_page.mergePage(first_page) writer = PdfFileWriter() writer.addPage(sup_page) newoutfile = addpath2('multipage' + str(j) + '.pdf') with open(newoutfile, 'wb') as f: writer.write(f) f.close() newpages.append(newoutfile) pdfcommand = ['pdfunite'] for page in newpages: pdfcommand.append(page) newmultioutput = addpath(f'tmp/{scac}/data/vreport/newmultioutput' + str(cache) + '.pdf') pdfcommand.append(newmultioutput) tes = subprocess.check_output(pdfcommand) docref = f'tmp/{scac}/data/vreport/report' + str(cache) + '.pdf' shutil.move(newmultioutput, addpath(docref)) killfile = addpath(f'tmp/{scac}/data/vreport/report' + str(cache - 1) + '.pdf') try: os.remove(killfile) except: print('Could not remove previous file') cache = cache + 1 if cache == 999: cache = 0 print('The value of cache is:', cache) return cache, docref
def isoS(): if request.method == 'POST': monsel, oder, peep, serv, invo, inco, cache, modata, modlink, fdata, invooder = init_storage_zero( ) invojo, filesel, docref, search11, search12, search21, search31 = init_storage_blank( ) leftscreen = 1 docref = ' ' err = ['All is well', ' ', ' ', ' ', ' '] ldata = None #today = datetime.datetime.today().strftime('%Y-%m-%d') today = datetime.date.today() invodate = datetime.date.today() leftsize = 10 monvec = [ 'Month', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] monlvec = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] match = request.values.get('Match') modify = request.values.get('Modify') vmod = request.values.get('Vmod') minvo = request.values.get('MakeI') mpack = request.values.get('MakeP') viewo = request.values.get('ViewO') viewi = request.values.get('ViewI') viewp = request.values.get('ViewP') analyze = request.values.get('Analyze') print = request.values.get('Print') addE = request.values.get('addentity') addS = request.values.get('addservice') recpay = request.values.get('RecPay') hispay = request.values.get('HisPay') monsel = request.values.get('monsel') returnhit = request.values.get('Return') deletehit = request.values.get('Delete') # hidden values update = request.values.get('Update') invoupdate = request.values.get('invoUpdate') recupdate = request.values.get('recUpdate') modlink = request.values.get('passmodlink') emailnow = request.values.get('emailnow') emailinvo = request.values.get('emailInvo') newjob = request.values.get('NewJ') thisjob = request.values.get('ThisJob') oder = request.values.get('oder') invo = request.values.get('invo') invooder = request.values.get('invooder') cache = request.values.get('cache') peep = request.values.get('peep') serv = request.values.get('serv') inco = request.values.get('inco') modlink = nonone(modlink) oder = nonone(oder) invo = nonone(invo) invooder = nonone(invooder) peep = nonone(peep) serv = nonone(serv) monsel = nonone(monsel) inco = nonone(inco) modal = 0 if returnhit is not None: modlink = 0 invo = 0 invooder = 0 inco = 0 # ____________________________________________________________________________________________________________________B.UpdateDatabases.Storage if update is not None and modlink == 1: if oder > 0: modata = Storage.query.get(oder) desc = request.values.get('desc') amount = request.values.get('amount') thiscomp = request.values.get('thiscomp') dstart = request.values.get('dstart') balfwd = request.values.get('pybal') modata.Description = desc modata.Amount = amount modata.Date = dstart modata.BalFwd = balfwd ldat = People.query.filter(People.Company == thiscomp).first() if ldat is not None: acomp = ldat.Company aid = ldat.id else: acomp = None aid = None modata.Company = acomp modata.Pid = aid modata.Label = modata.Jo + ' ' + thiscomp + ' ' + amount db.session.commit() err[3] = 'Modification to Storage JO ' + modata.Jo + ' completed.' modlink = 0 if peep > 0: modata = People.query.get(peep) modata.Ptype = 'Storage' vals = [ 'company', 'fname', 'mnames', 'lname', 'addr1', 'addr2', 'addr3', 'idtype', 'tid', 'tel', 'email', 'assoc1', 'assoc2', 'date1' ] a = list(range(len(vals))) i = 0 for v in vals: a[i] = request.values.get(v) i = i + 1 modata.Company = a[0] modata.First = a[1] modata.Middle = a[2] modata.Last = a[3] modata.Addr1 = a[4] modata.Addr2 = a[5] modata.Addr3 = a[6] modata.Idtype = a[7] modata.Idnumber = a[8] modata.Telephone = a[9] modata.Email = a[10] modata.Associate1 = a[11] modata.Associate2 = a[12] modata.Date1 = a[13] db.session.commit() err = [ ' ', ' ', 'Modification to Entity ID ' + str(modata.id) + ' completed.', ' ', ' ' ] modlink = 0 # And now update the crossover to Storage in case the Company info changed: cross = Storage.query.filter(Storage.Pid == peep) for cros in cross: cros.Company = a[0] db.session.commit() if serv > 0: modata = Services.query.get(serv) vals = ['service', 'price'] a = list(range(len(vals))) i = 0 for v in vals: a[i] = request.values.get(v) i = i + 1 modata.Service = a[0] modata.Price = a[1] db.session.commit() err = [ ' ', ' ', 'Modification to Services Data with ID ' + str(modata.id) + ' completed.', ' ', ' ' ] modlink = 0 if inco > 0: modata = Income.query.get(inco) vals = ['desc', 'recamount', 'custref', 'recdate'] i = 0 for v in vals: a[i] = request.values.get(v) i = i + 1 modata.Description = a[0] modata.Amount = a[1] modata.Ref = a[2] modata.Date = a[3] db.session.commit() err = [ ' ', ' ', 'Modification to Income Data with ID ' + str(modata.id) + ' completed.', ' ', ' ' ] # ____________________________________________________________________________________________________________________E.UpdateDatabases.Storage # ____________________________________________________________________________________________________________________B.UpdateInvoice.Storage if invoupdate is not None and monsel != 0: leftsize = 8 odata1 = Storage.query.get(invooder) invojo = popjo(invooder, monsel) ldata = Invoices.query.filter(Invoices.SubJo == invojo).all() invodate = request.values.get('invodate') total = 0 for data in ldata: iqty = request.values.get('qty' + str(data.id)) iqty = nononef(iqty) data.Description = request.values.get('desc' + str(data.id)) deach = request.values.get('cost' + str(data.id)) if deach is not None: deach = "{:.2f}".format(float(deach)) amount = iqty * float(deach) else: deach = "{:.2f}".format(0.00) amount = 0.00 total = total + amount amount = "{:.2f}".format(amount) data.Qty = iqty data.Ea = deach data.Amount = amount data.Total = 0.00 data.Date = invodate db.session.commit() if total > 0 and ldata is not None: for data in ldata: data.Total = "%0.2f" % total db.session.commit() odata1.Amount = "%0.2f" % total db.session.commit() #Remove zeros from invoice in case a zero was the mod Invoices.query.filter(Invoices.Qty == 0).delete() db.session.commit() #Create invoice code for order err = [ ' ', ' ', 'Invoice created for Storage JO: ' + invojo, ' ', ' ' ] ldata = Invoices.query.filter(Invoices.SubJo == invojo).all() # ____________________________________________________________________________________________________________________E.UpdateInvoice.Storage odata = Storage.query.order_by(Storage.Jo).all() cdata = People.query.filter(People.Ptype == 'Storage').order_by( People.Company).all() sdata = Services.query.all() oder, peep, serv, numchecked = numcheck(3, odata, cdata, sdata, 0, 0, ['oder', 'peep', 'serv']) # ____________________________________________________________________________________________________________________E.SearchFilters.Storage # ____________________________________________________________________________________________________________________B.EmailInvoice.Storage if emailinvo is not None: leftsize = 10 leftscreen = 1 modlink = 0 modata = Storage.query.get(invooder) invojo = popjo(invooder, monsel) ldata = Invoices.query.filter(Invoices.SubJo == invojo).order_by( Invoices.Ea.desc()).all() pdata1 = People.query.filter(People.id == modata.Pid).first() ldat = Invoices.query.filter(Invoices.SubJo == invojo).first() if pdata1 is None: err = [ ' ', ' ', 'There is no Billing information for this selection', ' ', ' ' ] else: email = pdata1.Email company = pdata1.Company docref = ldat.Original if 'vinvoice' not in docref: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] else: if email is not None: import invoice_mimemail_S invoice_mimemail_S.main(invojo, docref, email, monsel, inco, company) if inco == 0: for data in ldata: data.Status = "E" db.session.commit() else: for data in ldata: data.Status = "P" db.session.commit() invooder = 0 invo = 0 inco = 0 # ____________________________________________________________________________________________________________________E.EmailInvoice.Storage # ____________________________________________________________________________________________________________________B.Viewers.Storage if viewo is not None and numchecked == 1: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if oder > 0: modata = Storage.query.get(oder) if modata.Original is not None: if len(modata.Original) > 5: docref = modata.Original leftscreen = 0 leftsize = 8 modlink = 0 err = [ ' ', ' ', 'Viewing document ' + docref, ' ', ' ' ] if (viewo is not None or viewi is not None or viewp is not None) and numchecked != 1: err = [ 'Must check exactly one box to use this option', ' ', ' ', ' ', ' ' ] if viewi is not None and numchecked == 1: err = [ 'There is no document available for this selection', ' ', ' ', ' ', ' ' ] if monsel == 0: err[1] = 'Need to select the month' if oder > 0 and monsel > 0: invooder = oder modata = Storage.query.get(oder) invojo = popjo(oder, monsel) ldat = Invoices.query.filter(Invoices.SubJo == invojo).first() if ldat.Original is not None: docref = ldat.Original leftscreen = 0 leftsize = 8 modlink = 5 err = [' ', ' ', 'Viewing document ' + docref, ' ', ' '] # ____________________________________________________________________________________________________________________E.Viewers.Storage # ____________________________________________________________________________________________________________________B.ModifyEntries.Storage if (modify is not None or vmod is not None) and numchecked == 1: modlink = 1 leftsize = 8 if oder > 0: modata = Storage.query.get(oder) if vmod is not None: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if modata.Original is not None: if len(modata.Original) > 5: leftscreen = 0 docref = modata.Original err = ['All is well', ' ', ' ', ' ', ' '] if serv > 0: modata = Services.query.get(serv) if vmod is not None: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if peep > 0: modata = People.query.get(peep) if vmod is not None: err = [ ' ', ' ', 'There is no document available for this selection', ' ', ' ' ] if (modify is not None or vmod is not None) and numchecked != 1: modlink = 0 err[0] = ' ' err[2] = 'Must check exactly one box to use this option' # ____________________________________________________________________________________________________________________E.ModifyEntries.Storage # ____________________________________________________________________________________________________________________B.AddEntries.Storage if addS is not None and serv > 0 and numchecked == 1: leftsize = 8 modlink = 2 modata = Services.query.get(serv) if addS is not None and numchecked == 0: leftsize = 8 modlink = 1 #We will create a blank line and simply modify that by updating: input = Services(Service='New', Price=0.00) db.session.add(input) db.session.commit() modata = Services.query.filter(Services.Service == 'New').first() serv = modata.id err = [' ', ' ', 'Enter Data for New Service', ' ', ' '] if addS is not None and numchecked > 1: modlink = 0 err[0] = ' ' err[2] = 'Must check exactly one box to use this option' if addE is not None and peep > 0 and numchecked == 1: leftsize = 8 modlink = 3 modata = People.query.get(peep) if addE is not None and numchecked == 0: leftsize = 8 modlink = 1 #We will create a blank line and simply modify that by updating: input = People(Company='New', First='', Middle='', Last='', Addr1='', Addr2='', Addr3='', Idtype='', Idnumber='', Telephone='', Email='', Associate1='', Associate2='', Date1=today, Date2=None, Original=None, Ptype='Storage', Temp1=None, Temp2=None) db.session.add(input) db.session.commit() modata = People.query.filter((People.Company == 'New') & (People.Ptype == 'Storage')).first() peep = modata.id modata.Company = '' db.session.commit() modata = People.query.get(peep) err = [' ', ' ', 'Enter Data for New Company', ' ', ' '] if addE is not None and numchecked > 1: modlink = 0 err[0] = ' ' err[2] = 'Must check exactly one box to use this option' # ____________________________________________________________________________________________________________________E.AddEntries.Storage # ____________________________________________________________________________________________________________________B.ReceivePayment.Storage if (recpay is not None and oder > 0 and numchecked == 1 and monsel > 0) or recupdate is not None: leftsize = 8 if recpay is not None: invooder = oder odat = Storage.query.get(invooder) invojo = popjo(invooder, monsel) ldat = Invoices.query.filter(Invoices.SubJo == invojo).first() err = ['Have no Invoice to Receive Against', ' ', ' ', ' ', ' '] if ldat is not None: invodate = ldat.Date if ldat.Original is not None: docref = ldat.Original leftscreen = 0 leftsize = 8 incdat = Income.query.filter(Income.SubJo == invojo).first() if incdat is None: err = ['Creating New Payment on SubJo', ' ', ' ', ' ', ' '] paydesc = 'Received payment on Invoice ' + invojo + ' for month of ' + monvec[ monsel] recamount = str(ldat.Amount) custref = 'ChkNo' recdate = datetime.date(today.year, monsel, 28) input = Income(Jo=odat.Jo, SubJo=invojo, Pid=odat.Pid, Description=paydesc, Amount=recamount, Ref=custref, Date=recdate, Original=None) db.session.add(input) payment = 0 else: recamount = request.values.get('recamount') custref = request.values.get('custref') desc = request.values.get('desc') recdate = request.values.get('recdate') incdat.Amount = recamount incdat.Ref = custref incdat.Description = desc incdat.Date = recdate db.session.commit() payment = [recamount, custref, recdate] modata = Income.query.filter(Income.SubJo == invojo).first() inco = modata.id err = [' ', ' ', 'Amend Payment for Invoice', ' ', ' '] ldata = Invoices.query.filter( Invoices.SubJo == invojo).order_by( Invoices.Ea.desc()).all() pdata1 = People.query.filter(People.id == odat.Pid).first() cache = nonone(odat.Cache) + 1 basejo = odat.Jo involine, paidline, refline, balline = money12(basejo) balduenow = balline[monsel] try: balduenow = float[balduenow] except: balduenow = 0.00 if balduenow < .001: for data in ldata: data.Status = "P" db.session.commit() import make_S_invoice make_S_invoice.main(odat, ldata, pdata1, invojo, involine, paidline, refline, balline, invodate, cache, payment) if cache > 1: docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + 'c' + str( cache) + '.pdf' # Store for future use else: docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + '.pdf' odat.Cache = cache idat = Invoices.query.filter(Invoices.SubJo == invojo).first() idat.Original = docref db.session.commit() leftscreen = 0 err[4] = 'Viewing ' + docref if recpay is not None and (oder == 0 or numchecked != 1 or monsel == 0): err = ['Invalid selections:', '', '', '', ''] if oder == 0: err[1] = 'Must select a Storage Job' if numchecked != 1: err[2] = 'Must select exactly one Storage Job' if monsel == 0: err[3] = 'Must select a month to apply payment' # ____________________________________________________________________________________________________________________E.ReceivePayment.Storage # ____________________________________________________________________________________________________________________B.PaymentHistory.Storage if hispay is not None or modlink == 7: if oder == 0 and invooder == 0: err[1] = 'Must select a Storage Job' else: if oder != 0: invooder = oder modata = Storage.query.get(invooder) ldata = Invoices.query.filter( Invoices.Jo == modata.Jo).order_by(Invoices.SubJo).all() fdata = Income.query.filter(Income.Jo == modata.Jo).order_by( Income.SubJo).all() #Check to see if we need to delete anything from history killthis = request.values.get('killthis') if killthis is not None and modlink == 7: for data in ldata: testone = request.values.get('bill' + str(data.id)) if testone: kill = int(testone) Invoices.query.filter(Invoices.id == kill).delete() db.session.commit() for data in fdata: testone = request.values.get('pay' + str(data.id)) if testone: kill = int(testone) Income.query.filter(Income.id == kill).delete() db.session.commit() ldata = Invoices.query.filter( Invoices.Jo == modata.Jo).order_by( Invoices.SubJo).all() fdata = Income.query.filter( Income.Jo == modata.Jo).order_by(Income.SubJo).all() leftsize = 8 modlink = 7 # ____________________________________________________________________________________________________________________E.PaymentHistory.Storage # ____________________________________________________________________________________________________________________B.Delete.Storage if deletehit is not None and numchecked == 1: if oder > 0: Storage.query.filter(Storage.id == oder).delete() odata = Storage.query.all() if peep > 0: People.query.filter(People.id == peep).delete() cdata = People.query.filter( People.Ptype == 'Storage').order_by(People.Company).all() if serv > 0: Services.query.filter(Services.id == serv).delete() sdata = Services.query.all() db.session.commit() if deletehit is not None and numchecked != 1: err = [ ' ', ' ', 'Must have exactly one item checked to use this option', ' ', ' ' ] # ____________________________________________________________________________________________________________________E.Delete.Storage # ____________________________________________________________________________________________________________________B.Invoicing.Storage if ((minvo is not None and oder > 0) or invoupdate is not None) and monsel > 0: err = ['Could not create invoice', ' ', ' ', ' ', ' '] # First time through: have an order to invoice if oder > 0: invooder = oder myo = Storage.query.get(invooder) fee = myo.Amount #Check to see if we have the required data to make an invoice: invojo = popjo(invooder, monsel) thismonth = calendar.month_name[monsel] invodate = request.values.get('invodate') invo = 1 leftsize = 8 cache = nonone(myo.Cache) + 1 mys = Services.query.get(serv) if mys is not None: addserv = mys.Service price = mys.Price qty = 1 d = datetime.date(today.year, monsel, 1) descript = 'Monthly Storage Fee for Month of ' + thismonth input = Invoices(Jo=myo.Jo, SubJo=invojo, Pid=myo.Pid, Service=addserv, Description=descript, Ea=price, Qty=qty, Amount=price, Total=price, Date=d, Original=None, Status='New') db.session.add(input) db.session.commit() ldata = Invoices.query.filter(Invoices.SubJo == invojo).first() if ldata is None: invodate = datetime.date(today.year, monsel, 1) #See if there is an invoice from previous month to copy from try: invojoprev = popjo(invooder, monsel - 1) invodate = datetime.date(today.year, monsel, 1) ldata2 = Invoices.query.filter( Invoices.SubJo == invojoprev).all() for data in ldata2: mydescript = data.Description newdescript = data.Description for i in range(12): if monlvec[i] in newdescript: j = i + 1 if j == 12: j = 0 mydescript = newdescript.replace( monlvec[i], monlvec[j]) input = Invoices(Jo=myo.Jo, SubJo=invojo, Pid=myo.Pid, Service=data.Service, Description=mydescript, Ea=data.Ea, Qty=data.Qty, Amount=data.Amount, Date=invodate, Total=data.Total, Original=None, Status='New') db.session.add(input) db.session.commit() except: if mys is None: addserv = 'Monthly Storage' price = fee else: addserv = mys.Service price = mys.Price qty = 1 invodate = datetime.date(today.year, monsel, 1) descript = 'Monthly Storage Fee for Month of ' + thismonth input = Invoices(Jo=myo.Jo, SubJo=invojo, Pid=myo.Pid, Service=addserv, Description=descript, Ea=price, Qty=qty, Amount=price, Date=invodate, Total=price, Original=None, Status='New') db.session.add(input) db.session.commit() else: ldat = Invoices.query.filter( Invoices.SubJo == invojo).first() if ldat is None: if mys is None: addserv = 'Monthly Storage' price = fee else: addserv = mys.Service price = mys.Price qty = 1 invodate = datetime.date(today.year, monsel, 1) descript = 'Monthly Storage Fee for Month of ' + thismonth input = Invoices(Jo=myo.Jo, SubJo=invojo, Pid=myo.Pid, Service=addserv, Description=descript, Ea=price, Qty=qty, Amount=price, Date=invodate, Total=price, Original=None, Status='New') db.session.add(input) db.session.commit() ldat = Invoices.query.filter( Invoices.SubJo == invojo).first() invodate = ldat.Date # If have ldata: err = [' ', ' ', 'Created invoice for JO= ' + invojo, ' ', ' '] ldata = Invoices.query.filter(Invoices.SubJo == invojo).order_by( Invoices.Ea.desc()).all() pdata1 = People.query.filter(People.id == myo.Pid).first() odat = Storage.query.get(invooder) basejo = odat.Jo involine, paidline, refline, balline = money12(basejo) import make_S_invoice make_S_invoice.main(odat, ldata, pdata1, invojo, involine, paidline, refline, balline, invodate, cache, 0) if cache > 1: docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + 'c' + str( cache) + '.pdf' # Store for future use else: docref = f'tmp/{scac}/data/vinvoice/INV' + invojo + '.pdf' odat.Path = docref odat.Cache = cache idat = Invoices.query.filter(Invoices.SubJo == invojo).first() idat.Original = docref db.session.commit() leftscreen = 0 err[4] = 'Viewing ' + docref modata = Storage.query.get(invooder) elif minvo is not None and monsel == 0: err = [' ', ' ', 'Choose a Month for the Invoice', ' ', ' '] elif minvo is not None: err = [ ' ', ' ', 'Must select at least 1 Job for this selection', ' ', ' ' ] # ____________________________________________________________________________________________________________________E.Invoicing.Storage # ____________________________________________________________________________________________________________________B.NewJob.Storage if newjob is not None: err = ['Select Source Document from List'] fdata = myoslist(f'tmp/{scac}/data/vunknown') modlink = 4 leftsize = 8 leftscreen = 0 docref = f'tmp/{scac}/data/vunknown/NewJob.pdf' if newjob is None and modlink == 4: filesel = request.values.get('FileSel') if filesel != '1': fdata = myoslist(f'tmp/{scac}/data/vunknown') leftsize = 8 leftscreen = 0 docref = f'tmp/{scac}/data/vunknown/' + filesel if thisjob is not None: modlink = 0 #Create the new database entry for the source document filesel = request.values.get('FileSel') if filesel != '1': docold = f'tmp/{scac}/data/vunknown/' + filesel docref = f'tmp/{scac}/data/vorders/' + filesel shutil.move(addpath(docold), addpath(docref)) else: docref = '' sdate = request.values.get('dstart') if sdate is None: sdate = today jtype = 'S' nextjo = newjo(jtype, sdate) thisdesc = request.values.get('thisdesc') thisamt = request.values.get('thisamt') thiscomp = request.values.get('thiscomp') pybal = request.values.get('pybal') ldat = People.query.filter(People.Company == thiscomp).first() if ldat is not None: acomp = ldat.Company aid = ldat.id else: acomp = None aid = None label = nextjo + ' ' + thiscomp + ' ' + thisamt input = Storage(Jo=nextjo, Description=thisdesc, BalFwd=pybal, Amount=thisamt, Status='New', Cache=1, Original=docref, Path=None, Pid=aid, Company=thiscomp, Date=sdate, Label=label) db.session.add(input) db.session.commit() modata = Storage.query.filter(Storage.Jo == nextjo).first() csize = People.query.filter(People.Ptype == 'Storage').order_by( People.Company).all() oder = modata.id leftscreen = 1 err = ['All is well', ' ', ' ', ' ', ' '] odata = Storage.query.all() # ____________________________________________________________________________________________________________________E.New Job.Storage # ____________________________________________________________________________________________________________________B.Matching.Storage if match is not None: if oder > 0 and peep > 0 and numchecked == 2: myo = Storage.query.get(oder) myp = People.query.get(peep) myo.Pid = peep myo.Company = myp.Company db.session.commit() if numchecked != 2: err[1] = 'Must select exactly 2 boxes to use this option.' err[0] = ' ' # ____________________________________________________________________________________________________________________E.Matching.Storage # Create the time oriented data for the columns bm, cm = timedata(odata) #This is the else for 1st time through else: # ____________________________________________________________________________________________________________________B.STORAGEnotPost odata = Storage.query.order_by(Storage.Jo).all() cdata = People.query.filter(People.Ptype == 'Storage').order_by( People.Company).all() sdata = Services.query.all() ldata = None today = datetime.datetime.today().strftime('%Y-%m-%d') invodate = today monsel, oder, peep, serv, invo, inco, cache, modata, modlink, fdata, invooder = init_storage_zero( ) invojo, filesel, docref, search11, search12, search21, search31 = init_storage_blank( ) monvec = [ 'All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] leftscreen = 1 leftsize = 10 docref = ' ' err = ['All is well', ' ', ' ', ' ', ' '] bm, cm = timedata(odata) docref = docref.replace('tmp/vinvoice', f'tmp/{scac}/data/vinvoice') return odata, cdata, sdata, oder, peep, serv, err, modata, modlink, fdata, today, inco, leftscreen, docref, leftsize, ldata, monsel, monvec, invo, invooder, invojo, cache, filesel, bm, cm, invodate
def invoice_mimemail(order,docref,eprof): ourserver = websites['mailserver'] emailin1=request.values.get('edat2') emailin2=request.values.get('edat3') emailcc1=request.values.get('edat4') emailcc2=request.values.get('edat5') etitle=request.values.get('edat0') ebody=request.values.get('edat1') newfile = request.values.get('edat6') order=order.strip() lastpath = 'vpackages' if 'INV' in docref: lastpath = 'vinvoice' elif 'Proof' in docref: lastpath = 'vproofs' elif 'Manifest' in docref: lastpath = 'vmanifest' if newfile != 'none': cfrom = addpath(f'tmp/{scac}/data/{lastpath}/{docref}') print(cfrom,newfile) shutil.copy(cfrom,newfile) #emailto = "*****@*****.**" emailfrom = em['invo'] username = em['invo'] password = passwords['invo'] msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailin1 emailto=[emailin1] if emailin2 is not None: msg["To"] = emailin2 emailto.append(emailin2) if emailcc1 is not None: msg["CC"] = emailcc1 emailto.append(emailcc1) if emailcc2 is not None: msg["Cc"] = emailcc2 emailto.append(emailcc2) #msg["Subject"] = 'First Eagle Logistics Invoice: '+ invo + ' for Order: '+ order msg["Subject"] = etitle #body = 'Dear Customer:\n\nYour invoice is attached. Please remit payment at your earliest convenience.\n\nThank you for your business- we appreciate it very much.\n\nSincerely,\n\nFIRST EAGLE LOGISTICS,INC.\n\n\nNorma Ghanem\nFirst Eagle Logistics, Inc.\n505 Hampton Park Blvd Unit O\nCapitol Heights,MD 20743\n301 516 3000' msg.attach(MIMEText(ebody, 'plain')) if newfile != 'none': attachment = open(newfile, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % newfile) msg.attach(part) attachment.close() os.remove(newfile) server = smtplib.SMTP(ourserver) print('username=',username,password,ourserver) #server.connect(ourserver, 465) #server.ehlo() server.starttls() #server.starttls() server.login(username,password) #emailto = [emailin1, emailin2, emailcc1, emailcc2] server.sendmail(emailfrom, emailto, msg.as_string()) server.quit() return emailin1
def maerskparser(): #Move all files in the originals_bin/pdf to the processing/pdf_bin s = addpath('originals_bin/pdf/maersk/') t = addpath('processing/pdf_bin/') u = addpath('originals_processed/pdf') for file in os.listdir(s): if fnmatch.fnmatch(file, '*.pdf'): shutil.copy(s + file, u) shutil.move(s + file, t + file) wk = addpath('processing/tmp/') data = addpath('processing/pdf_bin/') viewloc = addpath('tmp/data/vbookings/') hitems = [ 'booking:Booking', 'reference:ExportRef', 'vessel:Vessel', 'cy/cy:LoadPort', 'total:Amount' ] date_y4 = re.compile( r'\d{4}[-](?:0[1-9]|1[012])[-](?:0[1-9]|[12][0-9]|3[01])') date_y42 = re.compile( r'(?:0[1-9]|1[012])[-](?:0[1-9]|[12][0-9]|3[01])[-]\d{4}') amount_p = re.compile( r'(?:[0-9]|[0-9]{2}|[0-9]{3}|[1-9],[0-9]{3}|[0-9]{4})\.[0-9]{2}') dictdata = [] fcount = 0 for file2 in os.listdir(data): if fnmatch.fnmatch(file2, '*.pdf'): fcount = fcount + 1 base = os.path.splitext(file2)[0] base = base.replace('-', '') base = base.replace(' ', '') file1 = file2.replace('-', '') file1 = file1.replace(' ', '') #shutil.copy(data+file2,viewloc+file1) #print (subprocess.check_output(['pdf2txt.py', '-o', done+base+'.txt', wk+file2])) tj = subprocess.check_output( ['pdf2txt.py', '-o', wk + base + '.txt', data + file2]) mysetlist = {'Jo': 'NAY'} mysetlist.update({'Booking': ''}) mysetlist.update({'ExportRef': ''}) mysetlist.update({'Vessel': ''}) mysetlist.update({'Line': 'Maersk'}) mysetlist.update({'PortCut': ''}) mysetlist.update({'DocCut': ''}) mysetlist.update({'SailDate': ''}) mysetlist.update({'EstArr': ''}) mysetlist.update({'AES': 'NAY'}) mysetlist.update({'Original': file1}) mysetlist.update({'Amount': ''}) mysetlist.update({'LoadPort': ''}) mysetlist.update({'Dest': ''}) mysetlist.update({'Status': 'Unmatched'}) datecut = None datesail = None datearr = None with open(wk + base + '.txt') as openfile: for line in openfile: if 'latest' in line.lower(): datep = date_y42.findall(line) if datep: datecut = datetime.datetime.strptime( datep[0], '%m-%d-%Y').strftime('%Y/%m/%d') if 'etd' in line.lower(): testline = line + next(openfile) datep = date_y4.findall(testline) if datep: datesail = datetime.datetime.strptime( datep[0], '%Y-%m-%d').strftime('%Y/%m/%d') if 'eta' in line.lower(): testline = line + next(openfile) datep = date_y4.findall(testline) if datep: datearr = datetime.datetime.strptime( datep[0], '%Y-%m-%d').strftime('%Y/%m/%d') mysetlist.update({'PortCut': datecut}) mysetlist.update({'DocCut': datecut}) mysetlist.update({'SailDate': datesail}) mysetlist.update({'EstArr': datearr}) for item in hitems: list = [] label = item.split(':', 1)[1] item = item.split(':', 1)[0] with open(wk + base + '.txt') as openfile: for line in openfile: if item.lower() in line.lower(): if (item in 'vesselcy/cy'): line = line + next(openfile) rest = line.lower().split(item.lower(), 1)[1] rest = line[-len(rest):] if ':' in rest: rest = rest.split(':', 1)[1] rest = rest.replace('#', '') rest = rest.replace(':', '') rest = rest.replace('-', '') rest = rest.strip() #Could have multiple space inside words which we do not want to store in database: pieces = rest.split() phrase = '' for piece in pieces: piece = piece.strip() phrase = phrase + ' ' + piece phrase = phrase.strip() if item in 'booking': if len(phrase) > 0: nratio = len(re.sub("\D", "", phrase)) / len(phrase) if nratio > .6: list.append(phrase) elif item in 'vessel': if 'MAERSK' in phrase: if len(phrase) > 50: phrase = phrase[0:49] list.append(phrase) elif item in 'cy/cy': list.append(phrase) nextphrase = next(openfile).strip() mysetlist.update({'Dest': nextphrase}) else: if len(phrase) > 25: phrase = phrase[0:24] list.append(phrase) if len(list) > 0: best = max(list, key=list.count) else: best = '' mysetlist.update({label: best}) longs = open(wk + base + '.txt').read() amount = amount_p.findall(longs) if amount: amount = [w.replace('$', '') for w in amount] amount = [w.replace(',', '') for w in amount] #amt=[float(i) for i in amount] #newamount="{:.2f}".format(max(amt)) mysetlist.update({'Amount': amount[0]}) print(mysetlist) dictdata.append(mysetlist) shutil.move(data + file2, viewloc + file1) if dictdata: for index in range(len(dictdata)): obj = dictdata[index] Booking = obj.get("Booking") #Convert all dates to Database Storage format: portcut = obj.get("PortCut") doccut = obj.get("DocCut") saildate = obj.get("SailDate") estarr = obj.get("EstArr") if portcut is not None: portcut = datetime.datetime.strptime(portcut, '%Y/%m/%d') if doccut is not None: doccut = datetime.datetime.strptime(doccut, '%Y/%m/%d') if saildate is not None: saildate = datetime.datetime.strptime(saildate, '%Y/%m/%d') if estarr is not None: estarr = datetime.datetime.strptime(estarr, '%Y/%m/%d') bdata = Bookings.query.filter(Bookings.Booking == Booking).first() if bdata is None: input = Bookings(Jo=None, Booking=Booking, ExportRef=obj.get("ExportRef"), Line=obj.get("Line"), Vessel=obj.get("Vessel"), PortCut=portcut, DocCut=doccut, SailDate=saildate, EstArr=estarr, RelType=None, AES=None, Original=obj.get("Original"), Amount=obj.get("Amount"), LoadPort=obj.get("LoadPort"), Dest=obj.get("Dest"), Status="Unmatched") print('Data part ', index + 1, ' of ', len(dictdata), 'is being added to database: Bookings') db.session.add(input) else: # The data already exists for the Booking. Update select parameters inside it. if bdata.Status != "Locked": bdata.ExportRef = obj.get("ExportRef") bdata.Line = obj.get("Line") bdata.Vessel = obj.get("Vessel") bdata.PortCut = portcut bdata.DocCut = doccut bdata.SailDate = saildate bdata.EstArr = estarr bdata.Original = obj.get("Original") bdata.Amount = obj.get("Amount") bdata.LoadPort = obj.get("LoadPort") bdata.Dest = obj.get("Dest") db.session.commit() print('Total # pdf files found: ', fcount)
def incomecontents(file4, itemlist, cache): today = datetime.datetime.today().strftime('%m/%d/%Y') invodate = datetime.date.today().strftime('%m/%d/%Y') sdate = request.values.get('start') fdate = request.values.get('finish') try: start = datetime.datetime.strptime(sdate, '%Y-%m-%d') end = datetime.datetime.strptime(fdate, '%Y-%m-%d') except: start = today end = today ltm, rtm, bump, tb, ctrall, left_ctr, right_ctr, dl, dh, tdl, hls, m1, m2, m3, m4, m5, m6, m7, n1, n2, n3 = reportsettings( 1) pages = [file4] page = 1 c = canvas.Canvas(file4, pagesize=letter) c.setLineWidth(1) place = [ltm + 10, ltm + 80, ltm + 140, ltm + 280, ltm + 410, rtm - 80] ctr = [] for j, p in enumerate(place): if j < len(place) - 1: ctr.append(avg(p, place[j + 1])) #Main Items Listing c.setFont('Helvetica', 12, leading=None) l1 = len(itemlist) top = n2 - dh for k in range(l1): newlist = itemlist[k] for j, i in enumerate(newlist): if j == 5: c.drawRightString(rtm - 10, top, i) else: c.drawString(place[j], top, i) top = top - dl if top < n3: c.showPage() c.save() page = page + 1 base = file4.replace('.pdf', '') newfile = base + 'page' + str(page) + '.pdf' top = n2 - dh c = canvas.Canvas(newfile, pagesize=letter) pages.append(newfile) c.showPage() c.save() if len(pages) > 1: pdfcommand = ['pdfunite'] for page in pages: pdfcommand.append(page) multioutput = addpath(f'tmp/{scac}/data/vreport/multioutput' + str(cache) + '.pdf') pdfcommand.append(multioutput) tes = subprocess.check_output(pdfcommand) else: multioutput = '' return pages, multioutput
def jaycontents(file4, paiditems, servicelist, itemlist, bitemlist, total, btotal, nettotal, cache): ltm, rtm, bump, tb, ctrall, left_ctr, right_ctr, dl, dh, tdl, hls, m1, m2, m3, m4, m5, m6, m7, n1, n2, n3 = reportsettings( 1) pages = [file4] page = 1 c = canvas.Canvas(file4, pagesize=letter) c.setLineWidth(1) bottomy = n3 badd = 30 p1 = ltm + 50 p2 = p1 + 50 p3 = p2 + 80 p4 = p3 + 70 p5 = rtm - 132 p7 = rtm - 100 p8 = rtm - 70 p9 = rtm - 40 total = 0.00 hvec = [ltm, rtm] headerlist = ['Credits'] mtop = stripheader(c, 12, n1, hvec, headerlist) hvec = [ltm, rtm] headerlist = ['Payments Made'] mtop = stripheader(c, 11, mtop, hvec, headerlist) hvec = [ltm, p1, p2, p3, p4, p8, rtm] headerlist = [ 'Start', 'Finish', 'Booking', 'Container', 'Summary', 'Paid Amount' ] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, total, rlist = paymentlisting(c, 9, mtop, hvec, paiditems, total, bottomy) hvec = [ltm, rtm] headerlist = ['Work Performed'] mtop = stripheader(c, 11, mtop, hvec, headerlist) hvec = [ltm, p1, p2, p3, p4, p5, p7, p8, p9, rtm] headerlist = [ 'Start', 'Finish', 'Booking', 'Container', 'Summary', 'Gross', 'Days', 'Fees', 'NetP' ] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, total, rlist = itemlisting(c, 9, mtop, hvec, itemlist, total, bottomy) #See if we bottomed out on page: if mtop == 0: c.showPage() c.save() page = page + 1 base = file4.replace('.pdf', '') newfile = base + 'page' + str(page) + '.pdf' c = canvas.Canvas(newfile, pagesize=letter) pages.append(newfile) hvec = [ltm, rtm] headerlist = ['Credits (continued)'] mtop = stripheader(c, 12, n1, hvec, headerlist) hvec = [ltm, rtm] headerlist = ['Work Performed (continued)'] mtop = stripheader(c, 11, mtop, hvec, headerlist) hvec = [ltm, p1, p2, p3, p4, p5, p7, p8, p9, rtm] headerlist = [ 'Start', 'Finish', 'Booking', 'Container', 'Summary', 'Gross', 'Days', 'Fees', 'NetP' ] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, total, rlist = itemlisting(c, 9, mtop, hvec, rlist, total, bottomy) mtop = mtop - dh * 1.2 c.setFont('Helvetica-Bold', 12, leading=None) c.drawRightString(p8, mtop + bump, 'Credits Total:') c.drawRightString(rtm - bump, mtop + bump, dollar(total)) credit_total = total mtop = mtop - dh c.line(ltm, mtop, rtm, mtop) mtop = mtop - .2 * dh c.line(ltm, mtop, rtm, mtop) debit_total = 0.0 hvec = [ltm, rtm] headerlist = ['Debits'] mtop = stripheader(c, 12, mtop, hvec, headerlist) c, page, pages, mtop = newpagecheck(c, mtop, bottomy + badd, page, file4, pages) hvec = [ltm, rtm] headerlist = ['Services Used'] mtop = stripheader(c, 11, mtop, hvec, headerlist) c, page, pages, mtop = newpagecheck(c, mtop, bottomy + badd, page, file4, pages) hvec = [ltm, p1, p2, p3, p4, p8, rtm] headerlist = [ 'Start', 'Finish', 'Booking', 'Container', 'Summary', 'Amount Due' ] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, debit_total, rlist = paymentlisting(c, 9, mtop, hvec, paiditems, debit_total, bottomy) #See if we bottomed out on page: if mtop == 0: c.showPage() c.save() page = page + 1 base = file4.replace('.pdf', '') newfile = base + 'page' + str(page) + '.pdf' c = canvas.Canvas(newfile, pagesize=letter) pages.append(newfile) hvec = [ltm, rtm] headerlist = ['Debits (continued)'] mtop = stripheader(c, 12, n1, hvec, headerlist) hvec = [ltm, rtm] headerlist = ['Services Used (continued)'] mtop = stripheader(c, 11, mtop, hvec, headerlist) hvec = [ltm, p1, p2, p3, p4, p8, rtm] headerlist = [ 'Start', 'Finish', 'Booking', 'Container', 'Summary', 'Amount Due' ] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, debit_total, rlist = paymentlisting(c, 9, mtop, hvec, rlist, debit_total, bottomy) c, page, pages, mtop = newpagecheck(c, mtop, bottomy + badd, page, file4, pages) hvec = [ltm, rtm] headerlist = ['Bills to Jays Auto Account'] mtop = stripheader(c, 11, mtop, hvec, headerlist) c, page, pages, mtop = newpagecheck(c, mtop, bottomy + badd, page, file4, pages) hvec = [ltm, p3, p7, rtm] headerlist = ['Date', 'Bill Summary', 'Amount'] mtop = stripheader(c, 10, mtop, hvec, headerlist) c, page, pages, mtop = newpagecheck(c, mtop, bottomy + badd, page, file4, pages) mtop, debit_total, rlist = billitemlisting(c, 9, mtop, hvec, bitemlist, debit_total, bottomy) #See if we bottomed out on page: if mtop == 0: c.showPage() c.save() page = page + 1 base = file4.replace('.pdf', '') newfile = base + 'page' + str(page) + '.pdf' c = canvas.Canvas(newfile, pagesize=letter) pages.append(newfile) hvec = [ltm, rtm] headerlist = ['Debits (continued)'] mtop = stripheader(c, 12, n1, hvec, headerlist) hvec = [ltm, rtm] headerlist = ['Bills to Jays Auto Account (continued)'] mtop = stripheader(c, 11, mtop, hvec, headerlist) hvec = [ltm, p3, p7, rtm] headerlist = ['Date', 'Bill Summary', 'Amount'] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, debit_total, rlist = billitemlisting(c, 9, mtop, hvec, rlist, debit_total, bottomy) mtop = mtop - dh * 1.2 c.setFont('Helvetica-Bold', 12, leading=None) c.drawRightString(p8, mtop + bump, 'Debits Total:') c.drawRightString(rtm - bump, mtop + bump, dollar(debit_total)) net = credit_total - debit_total bottomline = n3 + bump c.setFont('Helvetica-Bold', 12, leading=None) c.drawRightString(300, bottomline, 'Balance Due:') c.drawString(300 + bump, bottomline, dollar(net)) c.showPage() c.save() if len(pages) > 1: pdfcommand = ['pdfunite'] for page in pages: pdfcommand.append(page) multioutput = addpath(f'tmp/{scac}/data/vreport/multioutput' + str(cache) + '.pdf') pdfcommand.append(multioutput) tes = subprocess.check_output(pdfcommand) else: multioutput = '' return pages, multioutput
def main(odata, ldata, pdata1, invojo, involine, paidline, refline, balline, invodate, cache, payment): # pdata1:Bid (Bill To) # pdata2:Lid (Load At) # pdata3:Did (Delv To) from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib.pagesizes import landscape from reportlab.platypus import Image from reportlab.lib.units import inch import csv import math import datetime import shutil from viewfuncs import sdiff, sadd, dollar, nodollar, nononef from CCC_system_setup import myoslist, addpath, bankdata, scac joborder = invojo file1 = addpath(f'tmp/{scac}/data/vinvoice/INV'+joborder+'.pdf') file2 = addpath(f'tmp/{scac}/data/vinvoice/INV'+joborder+'c'+str(cache)+'.pdf') type = joborder[1] #today = datetime.datetime.today().strftime('%m/%d/%Y') # if invodate is None or invodate==0: # invodate=today # else: try: invodate = invodate.strftime('%m/%d/%Y') except: err = 'ivodate already a string' billhistory = involine payhistory = paidline openbalance = balline custref = refline pyopenbal = odata.BalFwd pyopenbal = nononef(pyopenbal) pyopenbal = nodollar(pyopenbal) a = pyopenbal for j, i in enumerate(openbalance): if billhistory[j] != '' or payhistory[j] != '': openbalance[j] = sadd(a, i) a = openbalance[j] if j > 0: b = openbalance[j-1] else: b = pyopenbal # 'a' is the last open balance and should be added to the bill try: prevbal = float(b) except: prevbal = 0.00 def avg(in1, in2): out = (in1+in2)/2 return out def comporname(company, name): if company is None or company == '': nameout = name else: if len(company) < 4: nameout = name else: nameout = company return nameout def fullname(first, middle, last): if first is not None: nameout = first else: nameout = '' if middle is not None: nameout = nameout+' '+middle if last is not None: nameout = nameout+' '+last if len(nameout) > 55: nameout = first + ' ' + last return nameout def address(addr1, addr2, addr3): street = addr1 if addr3 is None or addr3 == '': cityst = addr2 else: if len(addr3) < 5: cityst = addr2 if addr2 is None or addr2 == '': cityst = addr3 if len(addr2) < 3: cityst = addr3 if addr2 and addr3: if len(addr2) > 3 and len(addr3) > 3: street = addr1 + ' ' + addr2 cityst = addr3 return street, cityst def nononestr(input): if input is None or input == 'None': input = '' return input def nonone(input): if input is None: input = 0 return input billto = list(range(5)) if pdata1 is not None: billto[0] = comporname(pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) billto[4] = nononestr(pdata1.Email) else: for i in range(5): billto[i] = ' ' us = list(range(4)) us[0] = 'FIRST EAGLE LOGISTICS INC' us[1] = '505 HAMPTON PARK BLVD UNIT O' us[2] = 'CAPITOL HEIGHTS MD 20743' us[3] = '301-516-3000 [email protected]' line1 = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] line2 = ['Quantity', 'Item Code', 'Description', 'Price Each', 'Amount'] line3 = billhistory line41 = payhistory line42 = custref line5 = openbalance note = list(range(3)) note[0] = '*All invoices that are 15 days past due will incurr a $35.00 late fee.' note[1] = '*After 60 days an additional late fee will be assessed in the amount of $100.00.' note[2] = '*If your account reaches 90 days past due it will be submitted for collection.' lab1 = 'Balance Due' lab2 = 'Add $39.00 for all international wires' nonote, bank = bankdata('FC') # ___________________________________________________________ ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl*2 hls = 530 m1 = hls-dl m2 = hls-2*dl m3 = hls-3*dl m4 = hls-4*dl m5 = hls-5*dl m61 = hls-6*dl m62 = hls-7*dl m63 = hls-8*dl m7 = hls-20*dl m8 = hls-23*dl m9 = hls-27*dl fulllinesat = [m1, m2, m3, m4, m5, m61, m62, m63, m7, m8, m9] p = [0]*13 p[0] = ltm+87 for i in range(1, 13): p[i] = p[i-1]+37.7 n1 = ltm+58 n2 = ltm+128 n3 = rtm-140 n4 = rtm-70 sds2 = [n1, n2, n3, n4] q1 = ltm+180 q2 = rtm-180 sds3 = [q1, q2] bump = 2.5 tb = bump*2 c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) logo = addpath("tmp/felpics/logo3.jpg") c.drawImage(logo, 185, 680, mask='auto') # Date and JO boxes dateline = m1+8.2*dl c.rect(rtm-150, m1+7*dl, 150, 2*dl, stroke=1, fill=0) c.line(rtm-150, dateline, rtm, dateline) c.line(rtm-75, m1+7*dl, rtm-75, m1+9*dl) if type == 'S': # Address boxes ctm = 218 c.rect(ltm, m1+dl, 175, 5*dl, stroke=1, fill=0) #c.rect(ctm, m1+dl,175,5*dl, stroke=1, fill=0) #c.rect(rtm-175, m1+dl,175,5*dl, stroke=1, fill=0) level1 = m1+5*dl c.line(ltm, level1, ltm+175, level1) # c.line(ctm,level1,ctm+175,level1) # c.line(rtm-175,level1,rtm,level1) for i in fulllinesat: c.line(ltm, i, rtm, i) for k in p[0:12]: c.line(k, m1, k, m61) for l in sds2: c.line(l, m62, l, m7) for m in sds3: c.line(m, m8, m, m9) c.line(ltm, m1, ltm, m9) c.line(rtm, m1, rtm, m9) h1 = avg(m8, m9)-3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm-75, dateline+1.5*dl, 'Invoice') if payment != 0: c.setFont('Helvetica-Bold', 18, leading=None) c.drawCentredString(rtm-75, dateline-50, 'Payment Received') c.setFont('Helvetica', 12, leading=None) c.drawCentredString(rtm-112.5, dateline+bump, 'Date') c.drawCentredString(rtm-37.7, dateline+bump, 'Invoice #') c.drawString(ltm+bump*3, m1+5*dl+bump*2, 'Bill To') # c.drawString(ctm+bump*3,m1+5*dl+bump*2,'Load At') # c.drawString(rtm-170+bump*2,m1+5*dl+bump*2,'Delv To') dh = 12 ct = 305 if payment != 0: try: thispay = float(payment[0]) except: thispay = 0.00 top = m1+4*dl-5 try: c.drawString(ct, top, 'Your payment of '+payment[0]+', Ref No. '+payment[1]) c.drawString(ct, top-dh, 'was applied on '+payment[2]) except: c.drawString(ct, top, 'There is no payment data as of yet') else: thispay = 0.00 c.drawString(ct, m1+dl, 'Balance Fwd from 2018: $'+pyopenbal) j = 0 ctr = [avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm)] for i in line2: c.drawCentredString(ctr[j], m63+tb, i) j = j+1 top = m8-1.5*dh for i in bank: c.drawCentredString(ct, top, i) top = top-dh top = m1+9*dl-5 for i in us: c.drawString(ltm+bump, top, i) top = top-dh bottomline = m8-23 c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2+tb, bottomline, 'Balance Due:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m9+12, 'Add $39.00 for all international wires') c.setFont('Times-Roman', 9, leading=None) j = 0 dh = 9.95 top = m7-dh for i in note: c.drawString(ltm+tb, top, note[j]) j = j+1 top = top-dh # _______________________________________________________________________ # Insert data here # _______________________________________________________________________ c.setFont('Helvetica', 12, leading=None) dh = 13 top = level1-dh lft = ltm+bump*3 for i in billto: c.drawString(lft, top, i) top = top-dh x = avg(rtm-75, rtm) y = dateline-dh-bump c.drawCentredString(x, y, joborder) x = avg(rtm-75, rtm-150) try: c.drawCentredString(x, y, invodate) except: err = 'Date not set yet' c.setFont('Helvetica', 9, leading=None) c.drawCentredString(avg(ltm, p[0]), m2+tb, '2019 by Month:') c.drawCentredString(avg(ltm, p[0]), m3+tb, 'Bill History') c.drawCentredString(avg(ltm, p[0]), m4+tb, 'Pay History') c.drawCentredString(avg(ltm, p[0]), m5+tb, 'Cust Ref No.') c.drawCentredString(avg(ltm, p[0]), m61+tb, 'Open Balances') for j, i in enumerate(line1): ctr = avg(p[j], p[j+1]) c.drawCentredString(ctr, m2+tb, i) c.drawCentredString(ctr, m3+tb, line3[j]) c.drawCentredString(ctr, m4+tb, line41[j]) c.drawCentredString(ctr, m5+tb, line42[j]) c.drawCentredString(ctr, m61+tb, line5[j]) total = 0 top = m63-dh for data in ldata: qty = int(nonone(data.Qty)) each = float(nonone(data.Ea)) subtotal = qty*each total = total+subtotal line4 = [str(qty), data.Service] line5 = nononestr(data.Description) line6 = [each, subtotal] ctr = [avg(ltm, n1), avg(n1, n2)] for j, i in enumerate(line4): c.drawCentredString(ctr[j], top, i) ctr = [n4-tb*2, rtm-tb*2] for j, i in enumerate(line6): c.drawRightString(ctr[j], top, dollar(i)) line5a = line5.splitlines() for line in line5a: c.drawString(n2+tb, top, line) top = top-dh top = top-dh if prevbal > 0: c.drawString(n2+tb, top, 'Open balance from previous month') c.drawRightString(rtm-tb*2, top, dollar(prevbal)) total = total+prevbal-thispay c.drawRightString(rtm-tb*2, bottomline, dollar(total)) c.showPage() c.save() # # Now make a cache copy shutil.copy(file1, file2)
def custcontents(file4, itemlist, headerlist, pstops, cache): today = datetime.datetime.today().strftime('%m/%d/%Y') invodate = datetime.date.today().strftime('%m/%d/%Y') sdate = request.values.get('start') fdate = request.values.get('finish') openbalrequest = request.values.get('dc6') print('itemlist=', itemlist) try: start = datetime.datetime.strptime(sdate, '%Y-%m-%d') end = datetime.datetime.strptime(fdate, '%Y-%m-%d') except: start = today end = today ltm, rtm, bump, tb, ctrall, left_ctr, right_ctr, dl, dh, tdl, hls, m1, m2, m3, m4, m5, m6, m7, n1, n2, n3 = reportsettings( 1) mtop = n1 pages = [file4] page = 1 c = canvas.Canvas(file4, pagesize=letter) c.setLineWidth(1) bottomy = n3 complete = 0 ptot = 0.0 for p in pstops: ptot = ptot + p tofromavail = 220 - (ptot - 140) tfeach = tofromavail / 2.0 pvec = [55] + pstops + [tfeach, tfeach, 40, 40] hvec = [ltm] base = ltm for p in pvec: base = base + p hvec.append(base) hvec.append(rtm) p1 = ltm + 55 p2 = ltm + 120 p3 = ltm + 190 p4 = ltm + 300 p5 = rtm - 120 p6 = rtm - 80 p7 = rtm - 40 totals = [0.0, 0.0] while complete == 0 and page < 20: #hvec=[ltm,p1,p2,p3,p4,p5,p6,p7,rtm] #headerlist=['InvoDate', 'Order','Container','From','To','Invoiced','Paid','Open'] keylen = 5 - (11 - len(headerlist)) justify = ['c'] + ['l'] * keylen + ['l', 'l', 'r', 'r', 'r'] mtop = stripheader(c, 10, mtop, hvec, headerlist) mtop, totals, rlist = orderlisting(c, 9, mtop, hvec, itemlist, justify, totals, bottomy) if mtop > 0: complete = 1 else: c, page, pages, mtop = newpagecheck(c, mtop, bottomy + 20, page, file4, pages) itemlist = rlist if openbalrequest != 'on': c.setFont('Helvetica-Bold', 12, leading=None) c.drawRightString(rtm - bump, bottomy + dl * 1.2 + bump, 'Income Total: ' + dollar(totals[0])) c.setFont('Helvetica-Bold', 12, leading=None) c.drawRightString(rtm - bump, bottomy + bump, 'Open Balance Total: ' + dollar(totals[1])) c.showPage() c.save() if len(pages) > 1: pdfcommand = ['pdfunite'] for page in pages: pdfcommand.append(page) multioutput = addpath(f'tmp/{scac}/data/vreport/multioutput' + str(cache) + '.pdf') pdfcommand.append(multioutput) tes = subprocess.check_output(pdfcommand) else: multioutput = '' return pages, multioutput
def reportmaker(type,thiscomp): cache = request.values.get('cache') cache=nonone(cache) file2=addpath(f'tmp/{scac}/data/vreport/background.pdf') file3=addpath(f'tmp/{scac}/data/vreport/headers.pdf') file4=addpath(f'tmp/{scac}/data/vreport/contents.pdf') qnote, note, bank, us, lab, logoi = bankdata('FC') file1=addpath(f'tmp/{scac}/data/vreport/pagestart.pdf') c=canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) #logo = addpath("tmp/pics/logo3.jpg") c.drawImage(logoi, 185, 680, mask='auto') c.showPage() c.save() if type=='mtick': ticketbackground(file2) ticketheaders(file3) itemlist=ticketcalcs() ticketcontents(file4,itemlist) cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='jay': invobackground(file2) jayheaders(file3) paiditems,servicelist,itemlist,bitemlist,total,btotal,nettotal=jaycalcs() pages,multioutput=jaycontents(file4,paiditems,servicelist,itemlist,bitemlist,total,btotal,nettotal,cache) if len(pages)>1: cache,docref=pagemergermp([file1,file2,file3],cache,pages,multioutput) else: cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='income': ticketbackground(file2) ticketheaders(file3) itemlist=incomecalcs() pages,multioutput=incomecontents(file4,itemlist,cache) if len(pages)>1: cache,docref=pagemergermp([file1,file2,file3],cache,pages,multioutput) else: cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='expenses': ticketbackground(file2) ticketheaders(file3) itemlist=incomecalcs() pages,multioutput=incomecontents(file4,itemlist,cache) if len(pages)>1: cache,docref=pagemergermp([file1,file2,file3],cache,pages,multioutput) else: cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='customer': custbackground(file2) custheaders(file3,thiscomp) print('thiscompany=',thiscomp) itemlist,headerlist,pstops=custcalcs(thiscomp) pages,multioutput=custcontents(file4,itemlist,headerlist,pstops,cache) if len(pages)>1: cache,docref=pagemergermp([file1,file2,file3],cache,pages,multioutput) else: cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='pl': custbackground(file2) plheaders(file3) itemlist,blist=plcalcs() pages,multioutput=plcontents(file4,itemlist,blist,cache) if len(pages)>1: cache,docref=pagemergermp([file1,file2,file3],cache,pages,multioutput) else: cache,docref=pagemerger([file1,file2,file3,file4],cache) if type=='deposit' or type=='recdeposit': if type=='recdeposit': stamp=1 else: stamp=0 file2=addpath(f'tmp/{scac}/data/vreport/depositslip.pdf') print('thiscomp=',thiscomp) itemlist=depositcalcs(thiscomp) # We are creating a deposit for review so get the account to deposit into depojo = request.values.get('depojo') acdeposit = request.values.get('acdeposit') print(itemlist,depojo) pages,multioutput=depositcontents(file4,itemlist,cache,depojo,acdeposit,stamp) cache,docref=pagemerger([file4,file2,file1],cache) if stamp == 1: savefile = addpath(f'tmp/{scac}/data/vdeposits/' + depojo + '.pdf') shutil.copyfile(addpath(docref), savefile) return cache,docref
def writechecks(bdat, pdat, file1, sbdata, links, style): today = datetime.datetime.today().strftime('%m/%d/%Y') nbills = 1 file1 = addpath(file1) if links == 0: amt = bdat.pAmount amt = amt.replace(',', '') amount = float(amt) else: amt = bdat.pMulti amt = amt.replace(',', '') amount = float(amt) #billno = 'Bk:'+bdat.bCat billno = bdat.Jo # Create the Check Date: billdate = bdat.pDate print(billdate) try: datestr = billdate.strftime('%m/%d/%Y') except: datestr = datetime.datetime.today().strftime('%m/%d/%Y') if bdat.Memo is None: memo = ' ' else: memo = bdat.Memo if bdat.Description is None: desc = ' ' else: desc = bdat.Description payref = bdat.Ref # Check to see if we have the required data to make an invoice: company = pdat.Company addr1 = pdat.Addr1 addr2 = pdat.Addr2 email = pdat.Email phone = pdat.Telephone payee = company amount_num = "{:.2f}".format(amount) # amount_num=145.23 bank = bdat.pAccount type = bdat.bType if links != 0: memo = '' nbills = 0 for sb in sbdata: nbills = nbills + 1 if len(memo) > 45: memo = memo + '\n' memo = memo + sb.Memo + ', ' lm = len(memo) memo = memo[0:lm - 2] one = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine' ] tenp = [ 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen' ] tenp2 = [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' ] def avg(in1, in2): out = (in1 + in2) / 2 return out def once(num): one = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine' ] word = '' word = one[int(num)] word = word.strip() return word def ten(num): tenp = [ 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen' ] tenp2 = [ '', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety' ] word = '' if num[0] == '1': word = tenp[int(num[1])] else: text = once(num[1]) word = tenp2[int(num[0])] word = word + "-" + text word = word.strip() return word def hundred(num): one = [ '', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine' ] word = '' text = ten(num[1:]) word = one[int(num[0])] if num[0] != '0': word = word + "-Hundred " word = word + text word = word.strip() return word def thousand(num): word = '' pref = '' text = '' length = len(num) if length == 6: text = hundred(num[3:]) pref = hundred(num[:3]) if length == 5: text = hundred(num[2:]) pref = ten(num[:2]) if length == 4: text = hundred(num[1:]) word = one[int(num[0])] if num[0] != '0' or num[1] != '0' or num[2] != '0': word = word + "-Thousand " word = word + text if length == 6 or length == 5: word = pref + word word = word.strip() return word def million(num): word = '' pref = '' text = '' length = len(num) if length == 9: text = thousand(num[3:]) pref = hundred(num[:3]) if length == 8: text = thousand(num[2:]) pref = ten(num[:2]) if length == 7: text = thousand(num[1:]) word = one[int(num[0])] if num[0] != '0' or num[1] != '0' or num[2] != '0': word = word + " Million " word = word + text if length == 9 or length == 8: word = pref + word word = word.strip() return word val1 = float(amount_num) val2 = math.floor(val1) print(val2) val3 = val1 - val2 val3 = round(val3 * 100) print(val3) a = str(val2) leng = len(a) if leng == 1: if a == '0': num = 'Zero' else: num = once(a) if leng == 2: num = ten(a) if leng == 3: num = hundred(a) if leng > 3 and leng < 7: num = thousand(a) if leng > 6 and leng < 10: num = million(a) lnum = len(num) # print(num[lnum-1]) if num[lnum - 1] == '-': num = num[0:lnum - 1] tval3 = "{0:0=2d}".format(val3) amount_text = num + ' and ' + tval3 + '/100 ' # print(amount_text) # We need to add '*******' to back of this enough to fill up the rest of the block atlen = len(amount_text) # Guess that we need 120 chars total atremain = 90 - atlen b = '*' for i in range(atremain): b = b + '*' # print(atlen,atremain,b) amount_text = amount_text + b # print(amount_text) c = canvas.Canvas(file1, pagesize=letter) c.setFont('Helvetica', 12, leading=None) c.drawString(515, 720, datestr) c.drawString(70, 685, payee) # ____________________________________________________________________________ c.drawString(500, 686, amount_num) c.drawString(30, 660, amount_text) image = addpath(f'tmp/{scac}/pics/ck_sigfile.png') c.drawImage(image, 374, 587, width=200, height=40) c.setFont('Helvetica', 12, leading=None) ltm = 15 rtm = 590 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 m1 = 510 m2 = m1 - dl m3 = m2 - dl m4 = m3 - 10 m5 = m4 - dl m6 = m5 - dl m7 = 265 m8 = m7 - dl m9 = m8 - dl m10 = m9 - 10 m11 = m10 - dl m12 = m11 - dl n1 = ltm + 90 n2 = n1 + 150 n3 = n2 + 80 n4 = n3 + 80 n5 = rtm - 90 bump = 3 btype = bdat.bType bcat = bdat.bCat bsubcat = bdat.bSubcat item11 = [ 'Date', 'Ck No.| Pay Ref', 'Type', 'Category', 'Subcategory', 'Amount Paid' ] item12 = [datestr, payref, btype, bcat, bsubcat, amount_num] item21 = ['BillNo', 'Check Made Out To', 'From Acct'] item22 = [billno, payee, bank] item3 = 'Memo on Check:' item41 = ['Address of Company:'] if style == 1: fulllinesat = [m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12] for i in fulllinesat: c.line(ltm, i, rtm, i) vlines1at = [ltm, n1, n2 - 40, n3 - 40, n4 - 40, n5, rtm] for i in vlines1at: c.line(i, m1, i, m3) c.line(i, m7, i, m9) p1 = n1 p2 = n5 - 60 vlines2at = [ltm, n1, p2 - 20, rtm] for i in vlines2at: c.line(i, m4, i, m6) c.line(i, m10, i, m12) else: fulllinesat = [m7, m8, m9, m10, m11, m12] for i in fulllinesat: c.line(ltm, i, rtm, i) vlines1at = [ltm, n1, n2 - 40, n3 - 40, n4 - 40, n5, rtm] for i in vlines1at: c.line(i, m7, i, m9) p1 = n1 p2 = n5 - 60 vlines2at = [ltm, n1, p2 - 20, rtm] for i in vlines2at: c.line(i, m10, i, m12) dx = 80 xoff = 18 stretch = [0, -5, 15, 10, 10, 0] if style == 1: for i in range(6): x = avg(vlines1at[i], vlines1at[i + 1]) c.drawCentredString(x, m2 + bump, item11[i]) c.drawCentredString(x, m3 + bump, str(item12[i])) c.drawCentredString(x, m8 + bump, item11[i]) c.drawCentredString(x, m9 + bump, str(item12[i])) for i in range(3): x = avg(vlines2at[i], vlines2at[i + 1]) c.drawCentredString(x, m5 + bump, item21[i]) c.drawCentredString(x, m6 + bump, str(item22[i])) c.drawCentredString(x, m11 + bump, item21[i]) c.drawCentredString(x, m12 + bump, str(item22[i])) else: for i in range(6): x = avg(vlines1at[i], vlines1at[i + 1]) c.drawCentredString(x, m8 + bump, item11[i]) c.drawCentredString(x, m9 + bump, str(item12[i])) for i in range(3): x = avg(vlines2at[i], vlines2at[i + 1]) c.drawCentredString(x, m11 + bump, item21[i]) c.drawCentredString(x, m12 + bump, str(item22[i])) mlev11 = m6 - dl mlev12 = mlev11 - dl mlev13 = mlev12 - dl * 1.5 mlev14 = mlev13 - dl mlev15 = mlev14 - dl mlev21 = m12 - dl mlev22 = mlev21 - dl mlev23 = mlev22 - dl * 1.5 mlev24 = mlev23 - dl mlev25 = mlev24 - dl c.setFont('Helvetica', 10, leading=None) if links != 0: memo2 = memo.splitlines() nlines = len(memo2) memoline = 592 + 13 * (nlines - 1) memoline2 = mlev12 memoline3 = mlev22 for line in memo2: c.setFont('Helvetica', 12, leading=None) c.drawString(52, memoline, line) memoline = memoline - 13 c.setFont('Helvetica', 10, leading=None) if style == 1: c.drawString(ltm + 20, memoline2, line) memoline2 = memoline2 - 10 c.drawString(ltm + 20, memoline3, line) memoline3 = memoline3 - 10 else: c.drawString(52, 592, memo) c.setFont('Helvetica', 12, leading=None) if style == 1: c.drawString(ltm + 20, mlev11, item3) c.drawString(ltm + 20, mlev21, item3) c.setFont('Helvetica', 10, leading=None) if links == 0: if style == 1: c.drawString(ltm + 20, mlev12, memo) c.drawString(ltm + 20, mlev22, memo) memoline2 = mlev12 memoline3 = mlev22 try: pufrom = 'Pickup: ' + bdat.Link except: pufrom = 'Pickup: Unknown' c.setFont('Helvetica', 12, leading=None) if style == 1: c.drawString(ltm + 20, memoline2 - dl, 'Payee Address:') c.drawString(ltm + 20, memoline3 - dl, 'Payee Address:') c.setFont('Helvetica', 10, leading=None) if addr1 is None: addr1 = '' if addr2 is None: addr2 = '' if pufrom is None: pufrom = '' if style == 1: c.drawString(ltm + 20, memoline2 - dl * 2, company) c.drawString(ltm + 20, memoline2 - dl * 2 - 11, addr1) c.drawString(ltm + 20, memoline2 - dl * 2 - 22, addr2) c.drawString(ltm + 20, memoline2 - dl * 2 - 44, pufrom) else: cdata = companydata() c.setFont('Helvetica', 12, leading=None) offup = 5 c.drawString(50, m2 + offup, cdata[2]) c.drawString(50, m2 + offup - 14, cdata[5]) c.drawString(50, m2 + offup - 28, cdata[6]) memoline2 = memoline2 + 1 c.drawString(ltm + 70, memoline2, company) c.drawString(ltm + 70, memoline2 - 14, addr1) c.drawString(ltm + 70, memoline2 - 28, addr2) zip = getzip(addr2) print('myzipcode is', zip) if zip != 0: barcode_usps = usps.POSTNET(zip) barcode_usps.drawOn(c, ltm + 70, memoline2 - 42) c.setFont('Helvetica', 10, leading=None) c.drawString(ltm + 20, memoline3 - dl * 2, company) c.drawString(ltm + 20, memoline3 - dl * 2 - 11, addr1) c.drawString(ltm + 20, memoline3 - dl * 2 - 22, addr2) c.drawString(ltm + 20, memoline3 - dl * 2 - 44, pufrom) acct = bdat.bAccount comp = bdat.Co if acct is None: acct = ' ' if comp is None: comp = ' ' if nbills == 0: if btype == 'Expense': if style == 1: c.drawString( ltm + 230, mlev11, 'Expensed Account Name: ' + acct + ' (' + comp + ')') c.drawString(ltm + 230, mlev21, 'Expensed Account Name: ' + acct + ' (' + comp + ')') mlev21 = mlev21 - 2 * dl mlev11 = mlev11 - 2 * dl if style == 1: c.drawString(ltm + 230, mlev11, 'Full Description:') c.drawString(ltm + 230, mlev21, 'Full Description:') for i, line in enumerate(desc.splitlines()): mlev21 = mlev21 - dl mlev11 = mlev11 - dl if style == 1: c.drawString(ltm + 230, mlev11, line) c.drawString(ltm + 230, mlev21, line) if nbills > 1: dl = .9 * dl if nbills > 5: dl = .9 * dl mlevtop = mlev14 + 80 - dl - dl mlevbot = mlev24 + 80 - dl - dl if links != 0: s1 = ltm + 200 s2 = ltm + 240 s3 = ltm + 310 s4 = ltm + 480 if btype == 'Expense': if style == 1: c.drawString( ltm + 230, mlev11, 'Expensed Account Name: ' + acct + ' (' + comp + ')') c.drawString(ltm + 230, mlev21, 'Expensed Account Name: ' + acct + ' (' + comp + ')') mlevtop = mlev11 - 2 * dl mlevbot = mlev21 - 2 * dl c.setFont('Helvetica-Bold', 10, leading=None) if style == 1: c.drawString(s1, mlevtop, 'ID') c.drawString(s2, mlevtop, 'Bill No') c.drawString(s3, mlevtop, 'Reference/BkNo.') c.drawString(s4, mlevtop, 'Amount') c.drawString(s1, mlevbot, 'ID') c.drawString(s2, mlevbot, 'Bill No') c.drawString(s3, mlevbot, 'Reference/BkNo.') c.drawString(s4, mlevbot, 'Amount') c.setFont('Helvetica', 10, leading=None) for data in sbdata: mlevtop = mlevtop - dl mlevbot = mlevbot - dl id = str(data.id) billno = data.Jo ref = data.Memo # if memo long ref = ref.replace('For booking ', '') amt = dollar(float(data.pAmount)) if style == 1: c.drawString(s1, mlevtop, id) c.drawString(s1, mlevbot, id) try: if style == 1: c.drawString(s2, mlevtop, billno) c.drawString(s2, mlevbot, billno) except: err = '1' if style == 1: c.drawString(s3, mlevtop, ref) if style == 1: c.drawString(s4, mlevtop, amt) c.drawString(s3, mlevbot, ref) c.drawString(s4, mlevbot, amt) c.showPage() c.save() return
def multi_inv(odata, odervec, chas, newchas): # First create all the invoices for these specific jobs for oder in odervec: myo = Orders.query.get(oder) con = myo.Container qty, d1, d2 = chassismatch(myo) myo.Links = json.dumps(odervec) Invoices.query.filter(Invoices.Jo == myo.Jo).delete() myo.Istat = 1 db.session.commit() for oder in odervec: myo = Orders.query.get(oder) qty, d1, d2 = chassismatch(myo) shipper = myo.Shipper jo = myo.Jo bid = myo.Bid chassis = myo.Chassis if chassis is None: chassis = 'NoNum' myo.Chassis = chassis db.session.commit() if 'GBL' in chassis: chas = 0 lid = myo.Lid if lid is None or lid == 0: expimp = getexpimp(con) if expimp == 'Export': lid = dropupdate2(bid) if expimp == 'Import': lid = dropupdate3('BAL') if lid is None or lid == 0: myo.lid = 0 myo.Company = 'NAY' else: print('lid=',lid) ddat = Drops.query.get(lid) myo.Lid = lid myo.Company = ddat.Entity db.session.commit() myo = Orders.query.get(oder) did = myo.Did if did is None or did == 0: expimp = getexpimp(con) if expimp == 'Export': did = dropupdate3('BAL') if expimp == 'Import': did = dropupdate2(bid) if did is None or did == 0: myo.did = 0 myo.Company2 = 'NAY' else: ddat = Drops.query.get(did) myo.Did = did myo.Company2 = ddat.Entity db.session.commit() myo = Orders.query.get(oder) cache = myo.Icache c1, c2 = myo.Company, myo.Company2 c1, c2 = stripper(c1), stripper(c2) if chas != 1: # Make sure all invoices have the required parts total = float(myo.Amount) descript = 'From ' + c1 + ' to ' + c2 input = Invoices(Jo=myo.Jo, SubJo=None, Pid=bid, Service='Line Haul', Description=descript, Ea=myo.Amount, Qty=1, Amount=total, Total=total, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() # If chassis to be added then we have to add those fees in: if chas == 1: mys = Services.query.filter(Services.Service == 'Chassis Fees').first() descript = 'Days of Chassis' if newchas == 0: price = float(mys.Price) else: price = float(newchas) chassis_amount = price*qty haul_amount = float(myo.Amount) total = haul_amount+chassis_amount input = Invoices(Jo=myo.Jo, SubJo=None, Pid=bid, Service=mys.Service, Description=descript, Ea=d2s(price), Qty=qty, Amount=chassis_amount, Total=total, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() descript = 'From ' + c1 + ' to ' + c2 input = Invoices(Jo=myo.Jo, SubJo=None, Pid=bid, Service='Line Haul', Description=descript, Ea=myo.Amount, Qty=1, Amount=haul_amount, Total=total, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() # Now write out the invoice ldata = Invoices.query.filter(Invoices.Jo == myo.Jo).order_by(Invoices.Ea.desc()).all() pdata1 = People.query.filter(People.id == myo.Bid).first() pdata2 = Drops.query.filter(Drops.id == myo.Lid).first() pdata3 = Drops.query.filter(Drops.id == myo.Did).first() from make_T_invoice import T_invoice T_invoice(myo, ldata, pdata1, pdata2, pdata3, cache, today, 0) docref = f'tmp/{scac}/data/vinvoice/INV'+myo.Jo+'c'+str(cache)+'.pdf' for ldatl in ldata: ldatl.Pid = pdata1.id ldatl.Original = docref db.session.commit() myo.Invoice = os.path.basename(docref) myo.Icache = cache+1 db.session.commit() # Now all the invoices are created. Next pack them up and create a single master invoice. keydata = [0]*len(odervec) grandtotal = 0 for jx, ix in enumerate(odervec): odat = Orders.query.get(ix) print(f'Working {oder} {odat.Jo} ') if jx == 0: pdata1 = People.query.filter(People.id == odat.Bid).first() date1 = odat.Date order = odat.Order date2 = odat.Date2 dtest1 = odat.Date dtest2 = odat.Date2 if dtest1 < date1: date1 = dtest1 if dtest2 > date2: date2 = dtest2 idat = Invoices.query.filter(Invoices.Jo == odat.Jo).order_by(Invoices.Ea.desc()).first() c1, c2 = odat.Company, odat.Company2 c1, c2 = stripper(c1), stripper(c2) descr = 'From ' + c1 + ' to ' + c2 keydata[jx] = [odat.Jo, odat.Booking, odat.Container, idat.Total, descr] grandtotal = grandtotal+float(idat.Total) print(keydata[jx]) # put together the file paperwork file1 = f'tmp/{scac}/data/vpackages/P_' + 'test.pdf' cache2 = int(odat.Pkcache) docref = f'tmp/{scac}/data/vpackages/P_c'+str(cache2)+'_' + order + '.pdf' odat.Pkcache = cache2 + 1 for jx, ix in enumerate(odervec): odat = Orders.query.get(ix) odat.Package = os.path.basename(docref) db.session.commit() import make_TP_invoice make_TP_invoice.main(file1, keydata, grandtotal, pdata1, date1, date2) filegather = ['pdfunite', addpath(file1)] for ix in odervec: odat = Orders.query.get(ix) filegather.append(addpath(f'tmp/{scac}/data/vinvoice/{odat.Invoice}')) filegather.append(addpath(docref)) tes = subprocess.check_output(filegather) return docref
def isoB(indat): if request.method == 'POST': from viewfuncs import nonone, numcheck, newjo from viewfuncs import calendar7_weeks, txtfile, numcheckvec, d2s, erud, dataget_B, hv_capture, docuploader, get_def_bank from gledger_write import gledger_write, gledger_app_write # Initialize variables used in the python code that require a value username, bill, peep, cache, modata, modlink, fdata, adata, cdat, pb, passdata, vdata, caldays, daylist,\ weeksum, nweeks, filesel, docref, doctxt, bType, bClass, expdata, addjobselect, jobdata, modal, viewck, acceptthese,\ assdata, monlvec = var_start() divdat = Divisions.query.all() todaydt = datetime.datetime.today() today = todaydt.strftime('%Y-%m-%d') docref = ' ' doctxt = ' ' if indat == 'stay' or indat == 0: indat = '0' # Get all the variables appearing on the html page including button pushes match, vmod, modify2, viewo, addE, addE2, paybill, paybill2, unpay, printck, returnhit, deletehit, \ update, modlink, newbill, thisbill, newxfer, thisxfer, calendar, calupdate, incoming, datatable1, \ datatable2, copy, copy12, qpay, bill, cache, peep, uploadS, thismuch, vendmuch, thisbox0, thisbox1, thisbox2, \ thisbox3, thisbox4, thisbox5, thisbox6 = var_request() modlink, bill, peep = nonone(modlink), nonone(bill), nonone(peep) dlist = [datatable1, datatable2] leftscreen = 0 oid = 0 # Get varibles that may be selected from the selection boxes and dont override the button pushes hv, newbill, addE, copy, copy12, UploadS, newxfer, vmod, match, acceptthese, qpay, paybill, paybill2, printck, \ viewo, viewbill, viewck, deletehit, unpay, lbox, holdvec, err \ = get_selections(thismuch, vendmuch, thisbox0, thisbox1, thisbox2, thisbox3, thisbox4, thisbox5, thisbox6, newbill, vmod, paybill, printck) #Key variables may need to be altered based on the type of selection container in modlink: #modlink = 1 initial selection of an item to modify with update #modlink = 4 part of sequence in creating a new bill #modlink = 8 creating a new vendor during new bill process #modlink = 6 paying multiple bills with one check #modlink = 14 paying one bill with one check #after modification is started, if it is a bill and selection boxes are updated with onchange: #modlink = 7 modification to a bill for continuous modification until update button is used #modlink = 11 paying a bill #modlink = 12 quickpay (pay using default values) #modlink = 70 controls process of document uploading to establish a bill leftscreen = alterations(modlink, leftscreen) if returnhit is not None: modlink, leftscreen, indat = cleanup() # ____________________________________________________________________________________________________________________B.QuickBillPayTowing if incoming is not None: incoming_setup() # ____________________________________________________________________________________________________________________E.QuickBillPayTowing # ____________________________________________________________________________________________________________________B.Uploading if modlink == 4 and (newbill is None and thisbill is None and update is None): modlink, err, bill, docref = uploadsource(modlink, err, oid, docref, username) if modlink == 70: err, oid = docuploader('bill') modlink = 0 # ____________________________________________________________________________________________________________________E.Uploading # ____________________________________________________________________________________________________________________B.UpdateDatabasesSection if ( update is not None and modlink == 1 ) or modlink == 8 or modlink == 7 or modlink == 6 or modlink == 11 or modlink == 12 or modlink == 14: success = 1 if bill > 0: modata = Bills.query.get(bill) # if paying a bill there could be multiple link items to capture if modlink == 6: try: links = json.loads(modata.Link) except: links = 0 if links != 0: bill = links[0] modata = Bills.query.get(bill) #Modifying only the billing information (but getting the billing information if paying the bill if modlink == 7: err, docref, expdata, assdata, leftscreen, modlink, hv = modbill( bill, update, err, docref, expdata, assdata, leftscreen, modlink, hv) cdat = People.query.filter( People.Company == modata.Company).first() if cdat is not None: if cdat.Ptype == 'TowCo': hv[3] = '2' ifxfer = modata.bType if ifxfer == 'XFER': run_xfer(update, err) if modlink == 11 or modlink == 12 or modlink == 14: err, hv, docref, modlink = run_paybill( bill, update, err, hv, docref, username, modlink) if modal == 1: calendar = 1 modlink = 0 # create return status if update is not None and modlink != 6 and success: modlink = 0 leftscreen = 1 indat = '0' if modlink == 9 or modlink == 8: err, expdata, modlink, peep = modpeeps(peep, update, err, modlink, expdata) modata = People.query.get(peep) print(modata.Company) # _____________________________________________________________________________________________________________B.UpdateDatabasesSection bdata, cdata = dataget_B(hv[1], hv[0], hv[3]) # ____________________________________________________________________________________________________________________B.SearchFilters if acceptthese == 1: print('acceptthese', acceptthese) modlink = 0 # Check to see if these are all new jobs ready to be updated to ready status odervec = numcheckvec(bdata, 'bill') print(odervec) if len(odervec) > 0: for ix in odervec: bdat = Bills.query.get(ix) bdat.Temp2 = None db.session.commit() else: err.append('Must check at least one box to use this option') if modlink < 5: bill, peep, numchecked = numcheck(2, bdata, cdata, 0, 0, 0, ['bill', 'peep']) else: numchecked = 0 if uploadS is not None: print('Using uploadS') if bill > 0 and numchecked == 1: bdat = Bills.query.get(bill) jo = bdat.Jo cache = bdat.Cache filename2 = f'Source_{jo}_c{str(cache)}.pdf' err.append(f'File uploaded as {filename2}') #Provide a file name for the upload and store message: edat = LastMessage.query.filter( LastMessage.User == username).first() if edat is not None: edat.Err = json.dumps(err) db.session.commit() else: input = LastMessage(User=username, Err=json.dumps(err)) db.session.add(input) db.session.commit() modlink = 70 leftscreen = 1 mm3 = 0 else: err.append('No Bill Selected for Source Upload') err.append('Select One Box') # ____________________________________________________________________________________________________________________E.SearchFilters # ____________________________________________________________________________________________________________________B.Viewers if viewo == 1 and numchecked == 1: if bill > 0: modata = Bills.query.get(bill) viewtype = 'source' hv[2] = viewtype if modata.Original is not None: if len(modata.Original) > 5: docref = f'tmp/{scac}/data/vbills/{modata.Original}' leftscreen = 0 leftsize = 8 modlink = 0 err.append('Viewing document ' + docref) if viewo == 1 and numchecked != 1: err.append('Must check exactly one box to view source file') if viewck == 1 and numchecked == 1: if bill > 0: modata = Bills.query.get(bill) viewtype = 'check' hv[2] = viewtype if modata.Code1 is not None: if len(modata.Code1) > 5: docref = f'tmp/{scac}/data/vchecks/{modata.Code1}' leftscreen = 0 leftsize = 8 modlink = 0 err.append('Viewing check ' + docref) if viewck == 1 and numchecked != 1: err.append('Must check exactly one box to view checks') # ____________________________________________________________________________________________________________________E.Viewers # ____________________________________________________________________________________________________________________B.Modify Entries if vmod is not None and numchecked == 1: modlink, leftscreen, docref, expdata, modata = mod_init( err, bill, peep) # Modification coming from calendar if modify2 is not None: bill = nonone(modify2) modata = Bills.query.get(bill) modlink = 7 leftsize = 8 # ____________________________________________________________________________________________________________________E.Modify Entries # ____________________________________________________________________________________________________________________B.Add Entries if addE is not None: leftsize = 8 modlink = 9 # Remove any new starts that were not completed People.query.filter(People.Ptype == 'NewVendor').delete() # We will create a blank line and simply modify that by updating: input = People(Company='', First=None, Middle=None, Last=None, Addr1='', Addr2='', Addr3='', Idtype=None, Idnumber='', Telephone='', Email='', Associate1=None, Associate2=None, Date1=today, Date2=None, Original=None, Ptype='NewVendor', Temp1=None, Temp2=None, Accountid=None) db.session.add(input) db.session.commit() modata = People.query.filter(People.Ptype == 'NewVendor').first() peep = modata.id err.append('Enter Data for New Entity') expdata = Accounts.query.filter( Accounts.Type == 'Expense').order_by(Accounts.Name).all() if addE2 is not None: leftsize = 8 modlink = 8 # We will create a blank line and simply modify that by updating: hlist = hv_capture([ 'thiscomp', 'ctype', 'billacct', 'bamt', 'bdate', 'ddate', 'bdesc' ]) hv = hv[0:2] + hlist print(hv) # We will create a blank line and simply modify that by updating: input = People(Company='', First=None, Middle=None, Last=None, Addr1='', Addr2='', Addr3='', Idtype=None, Idnumber='', Telephone='', Email='', Associate1=None, Associate2=None, Date1=today, Date2=None, Original=None, Ptype='NewVendor', Temp1=None, Temp2=None, Accountid=None) db.session.add(input) db.session.commit() modata = People.query.filter(People.Ptype == 'NewVendor').first() peep = modata.id err.append('Enter Data for New Entity') expdata = Accounts.query.filter( Accounts.Type == 'Expense').order_by(Accounts.Name).all() # ____________________________________________________________________________________________________________________E.Add Entries # ____________________________________________________________________________________________________________________B.Delete an Entry if deletehit is not None and numchecked >= 1: if bill > 0: bdat = Bills.query.get(bill) try: orderid = nonone(bdat.Temp2) adat = Autos.query.get(orderid) if adat is not None: adata = Autos.query.filter( Autos.Orderid == adat.Orderid).all() for dat in adata: dat.Status = 'Novo' except: err.append('Delete problem') jo = bdat.Jo Gledger.query.filter(Gledger.Tcode == jo).delete() Bills.query.filter(Bills.id == bill).delete() db.session.commit() if peep > 0: peepvec = numcheckvec(cdata, 'peep') for peep in peepvec: People.query.filter(People.id == peep).delete() db.session.commit() bdata = Bills.query.order_by(Bills.bDate).all() cdata = People.query.filter((People.Ptype == 'Vendor') | (People.Ptype == 'TowCo')).order_by( People.Company).all() if deletehit is not None and numchecked == 0: err.append( 'Must have at least one item checked to use this option') # ____________________________________________________________________________________________________________________E.Delete an Entry # ____________________________________________________________________________________________________________________B.NewXfer.Billing if newxfer == 1: modlink = 3 err.append('Select Source Document from List') leftscreen = 0 expdata = Accounts.query.filter( (Accounts.Type != 'Expense') & (Accounts.Type != 'Income') & (~Accounts.Type.contains('Accounts'))).order_by( Accounts.Name).all() vdata = [today, today, '', ''] if newxfer is None and modlink == 3: leftscreen = 0 bdate = request.values.get('bdate') ddate = request.values.get('bdate') xamt = request.values.get('xamt') new_desc = request.values.get('desc') xferfrom = request.values.get('fromacct') xferto = request.values.get('toacct') if xamt is None: xamt = '0.00' vdata = [bdate, ddate, xamt, new_desc, xferfrom, xferto] print(vdata) expdata = Accounts.query.filter( (Accounts.Type != 'Expense') & (Accounts.Type != 'Income') & (~Accounts.Type.contains('Accounts'))).order_by( Accounts.Name).all() if thisxfer is not None: modlink = 0 sdate = request.values.get('bdate') if sdate is None or sdate == '': sdate = today fromacct = request.values.get('fromacct') toacct = request.values.get('toacct') adat = Accounts.query.filter(Accounts.Name == toacct).first() if adat is not None: cat = adat.Category sub = adat.Subcategory else: cat = None sub = None xamt = request.values.get('xamt') xamt = d2s(xamt) xdesc = request.values.get('xdesc') btype = 'XFER' nextjo = newjo(billxfrcode, today) co = nextjo[0] input = Bills(Jo=nextjo, Pid=0, Company=toacct, Memo=None, Description=xdesc, bAmount=xamt, Status='Paid', Cache=0, Original=None, Ref=None, bDate=sdate, pDate=sdate, pAmount=xamt, pMulti=None, pAccount=fromacct, bAccount=toacct, bType=btype, bCat=cat, bSubcat=sub, Link=None, User=username, Co=co, Temp1=None, Temp2=None, Recurring=0, dDate=today, pAmount2='0.00', pDate2=None, Code1=None, Code2=None, CkCache=0, QBi=0, iflag=0, PmtList=None, PacctList=None, RefList=None, MemoList=None, PdateList=None, CheckList=None, MethList=None) db.session.add(input) db.session.commit() modata = Bills.query.filter(Bills.Jo == nextjo).first() err = gledger_write('xfer', nextjo, toacct, fromacct) bill = modata.id leftscreen = 1 err.append('All is well') bdata = Bills.query.order_by(Bills.bDate).all() # ____________________________________________________________________________________________________________________E.NewXfer.Billing if copy == 1: if bill > 0 and numchecked == 1: # sdate=today.strftime('%Y-%m-%d') bdat = Bills.query.get(bill) thisdate = bdat.bDate nextdate = thisdate + datetime.timedelta(days=30) nextjo = newjo(billexpcode, today) input = Bills(Jo=nextjo, Pid=bdat.Pid, Company=bdat.Company, Memo=bdat.Memo, Description=bdat.Description, bAmount=bdat.bAmount, Status=bdat.Status, Cache=0, Original=bdat.Original, Ref=bdat.Ref, bDate=nextdate, pDate=None, pAmount='0.00', pMulti=None, pAccount=bdat.pAccount, bAccount=bdat.bAccount, bType=bdat.bType, bCat=bdat.bCat, bSubcat=bdat.bSubcat, Link=None, User=username, Co=bdat.Co, Temp1=None, Temp2='Copy', Recurring=0, dDate=today, pAmount2='0.00', pDate2=None, Code1=None, Code2=None, CkCache=0, QBi=0, iflag=0, PmtList=None, PacctList=None, RefList=None, MemoList=None, PdateList=None, CheckList=None, MethList=None) db.session.add(input) db.session.commit() err = gledger_write('newbill', nextjo, bdat.bAccount, bdat.pAccount) elif peep > 0 and numchecked == 1: # sdate=today.strftime('%Y-%m-%d') pdat = People.query.get(peep) input = People(Company=pdat.Company, First=pdat.First, Middle='Copy', Last=None, Addr1=pdat.Addr1, Addr2=pdat.Addr2, Addr3=pdat.Addr3, Idtype=pdat.Idtype, Idnumber=pdat.Idnumber, Telephone=pdat.Telephone, Email=pdat.Email, Associate1=pdat.Associate1, Associate2=pdat.Associate2, Date1=today, Date2=None, Original=None, Ptype='Vendor', Temp1=pdat.Temp1, Temp2=pdat.Temp2, Accountid=pdat.Accountid) db.session.add(input) db.session.commit() else: err.append('Must select one item to use this function') if copy12 is not None: if bill > 0 and numchecked == 1: # sdate=today.strftime('%Y-%m-%d') bdat = Bills.query.get(bill) thisdate = bdat.bDate year = thisdate.year month = thisdate.month day = thisdate.day while month < 12: month = month + 1 nextdate = datetime.datetime(year, month, day) nextjo = newjo(billexptype, today) input = Bills(Jo=nextjo, Pid=bdat.Pid, Company=bdat.Company, Memo=bdat.Memo, Description=bdat.Description, bAmount=bdat.bAmount, Status=bdat.Status, Cache=0, Original=bdat.Original, Ref=bdat.Ref, bDate=nextdate, pDate=None, pAmount='0.00', pMulti=None, pAccount=bdat.pAccount, bAccount=bdat.bAccount, bType=bdat.bType, bCat=bdat.bCat, bSubcat=bdat.bSubcat, Link=None, User=username, Co=bdat.Co, Temp1=None, Temp2='Copy', Recurring=0, dDate=today, pAmount2='0.00', pDate2=None, Code1=None, Code2=None, CkCache=0, QBi=0, iflag=0, PmtList=None, PacctList=None, RefList=None, MemoList=None, PdateList=None, CheckList=None, MethList=None) db.session.add(input) db.session.commit() err = gledger_write('newbill', nextjo, bdat.bAccount, bdat.pAccount) if qpay is not None: if bill > 0 and numchecked == 1: print('qpay entered!!') bdat = Bills.query.get(bill) bdat.pDate = bdat.bDate bdat.pAmount = bdat.bAmount bdat.Temp2 = '' bdat.Status = 'Paid' pacct = bdat.pAccount if pacct is None: pacct = get_def_bank(bdat) elif pacct == '0' or pacct == '1' or pacct == 0 or pacct == 1: pacct = get_def_bank(bdat) bdat.pAccount = pacct db.session.commit() # ____________________________________________________________________________________________________________________B.NewJob if newbill is not None: err, modlink, leftscreen, hv, expdata, vdata = newbill_init( err, hv) if newbill is None and modlink == 4: err, modlink, leftscreen, hv, expdata, vdata, assdata = newbill_passthru( err, hv, modlink) if thisbill is not None: err, modlink, leftscreen, bill = newbill_update( err, hv, modlink, username) bdata = Bills.query.order_by(Bills.bDate).all() # ____________________________________________________________________________________________________________________E.New Bill if unpay == 1: if numchecked == 1 and bill > 0: myb = Bills.query.get(bill) iflag = myb.iflag if iflag is None: iflag = 0 if iflag > 0: undolastpayment(bill) err.append( f'Unpaid Last Payment on Bill {myb.Jo} and removed from register' ) else: myb.Status = 'Unpaid' myb.pAmount = '0.00' db.session.commit() Gledger.query.filter((Gledger.Tcode == myb.Jo) & (Gledger.Type == 'PD')).delete() Gledger.query.filter((Gledger.Tcode == myb.Jo) & (Gledger.Type == 'PC')).delete() Gledger.query.filter((Gledger.Tcode == myb.Jo) & (Gledger.Type == 'XD')).delete() Gledger.query.filter((Gledger.Tcode == myb.Jo) & (Gledger.Type == 'XC')).delete() db.session.commit() err.append(f'Unpay Bill {myb.Jo} and remove from register') else: err.append('Must select one Bill to Unpay') if paybill is not None or paybill2 is not None or viewbill == 1: print('paybill', numchecked, modlink, bill) if numchecked == 1 and bill > 0: myb = Bills.query.get(bill) if viewbill == 1 and myb.Status == 'Paid': modlink = 15 if myb.iflag is None: myb.iflag = 0 if myb.iflag > 0: err, modlink, leftscreen, docref, prevpayvec = install_pay_init( bill, err, modlink) hv[19] = prevpayvec else: err, modlink, leftscreen, docref = pay_init( bill, err, modlink) modata = Bills.query.get(bill) if numchecked > 1 and bill > 0: err, modlink, lefscreen, docref = multi_pay_init( bill, err, modlink) modata = Bills.query.get(bill) if numchecked == 0 or bill == 0: err.append('Must check at least one bill for this selection') err.append(f'Numchecked = {numchecked}') bdata = Bills.query.order_by(Bills.bDate).all() if printck is not None or modlink == 6 or modlink == 14 or indat != '0': from viewfuncs import check_prep def multi_prep(bill): if bdat.Status == 'Paid-M': linkcode = bdat.Link sbdata = Bills.query.filter(Bills.Link == linkcode) link = linkcode.replace('Link+', '') items = link.split('+') links = [] [links.append(int(item)) for item in items] else: links = 0 sbdata = 0 if printck is not None and numchecked == 1: modlink = 14 elif printck is not None and numchecked > 1: modlink = 6 if indat != '0': bdat = Bills.query.filter(Bills.Jo == indat).first() bill = bdat.id modlink = 6 if numchecked == 1: modlink = 14 if (numchecked >= 1 and bill > 0 ) or modlink == 6 or modlink == 12 or modlink == 14: if modlink == 6 or modlink == 12 or modlink == 14: bdat = Bills.query.get(bill) try: bill_list = json.loads(bdat.Link) except: bill_list = [bill] billready, err, linkcode = check_prep(bill_list) else: bill_list = numcheckvec(bdata, 'bill') billready, err, linkcode = check_prep(bill_list) if billready == 1: from viewfuncs import check_inputs sbdata = Bills.query.filter(Bills.Link == linkcode).all() links = json.loads(linkcode) bdat = Bills.query.get(links[0]) pdat = People.query.get(bdat.Pid) ckcache = bdat.CkCache if ckcache is None or ckcache == 0: ckcache = 1 last_ckfile = f'Check_{bdat.Jo}_{bdat.Ref}_c{str(ckcache-1)}.pdf' ckfile = f'Check_{bdat.Jo}_{bdat.Ref}_c{str(ckcache)}.pdf' docref = f'tmp/{scac}/data/vchecks/{ckfile}' bdat.Code1 = ckfile ckcache = ckcache + 1 bdat.CkCache = ckcache pamount = bdat.pAmount if pamount == '0.00': bdat.pAmount = bdat.bAmount db.session.commit() ckstyle = request.values.get('ckstyle') if ckstyle is not None: hv[21] = ckstyle ckstyle = nonone(ckstyle) else: ckstyle = 1 err = check_inputs(bill_list) co = bdat.Co expdata = Accounts.query.filter(( (Accounts.Type == 'Expense') & (Accounts.Co == co)) | ( (Accounts.Type == 'Credit Card') & (Accounts.Co == co))).order_by( Accounts.Name).all() #modlink = 6 leftscreen = 0 modata = Bills.query.get(links[0]) pb = 1 if err[0] != 'All is Well': err.append( 'Check will not be displayed until above input items input or corrected' ) else: from writechecks import writechecks if pdat is not None: writechecks(bdat, pdat, docref, sbdata, links, ckstyle) ck_check = bdat.bType db.session.commit() pacct = bdat.pAccount #Only write to the ledger on update if update is not None: if pacct is not None and pacct != '0': print('check is', ck_check) if ck_check == 'Credit Card' or ck_check == 'XFER': print('Doing the Transfer') err = err = gledger_write( 'xfer', bdat.Jo, bdat.bAccount, bdat.pAccount) err.append( f'Ledger xfer for {bdat.Jo} to {bdat.bAccount} from {bdat.pAccount}' ) else: print('Paying the Bill') err = gledger_write( 'paybill', bdat.Jo, bdat.bAccount, bdat.pAccount) err.append( f'Ledger paid {bdat.Jo} to {bdat.bAccount} from {bdat.pAccount}' ) else: err.append( 'No Account for Fund Withdrawal') #Attempt to remove the previous cache copy: try: last_file = addpath( f'tmp/{scac}/data/vchecks/{last_ckfile}') os.remove(last_file) except: print(f'Could nor remove {last_file}') else: err.append( 'Must select exactly 1 Bill box to use this option.') # ____________________________________________________________________________________________________________________B.Matching if match is not None: if bill > 0 and peep > 0 and numchecked == 2: myo = Bills.query.get(bill) myp = People.query.get(peep) myo.Pid = peep myo.Company = myp.Company myo.Description = myp.Associate1 db.session.commit() if numchecked != 2: err.append('Must select exactly 2 boxes to use this option.') # ____________________________________________________________________________________________________________________E.Matching # ____________________________________________________________________________________________________________________B.Calendar.Billing if calendar is not None or calupdate is not None: leftscreen = 2 if calupdate is not None: waft = request.values.get('waft') wbef = request.values.get('wbef') waft = nonone(waft) wbef = nonone(wbef) nweeks = [wbef, waft] else: nweeks = [2, 2] caldays, daylist, weeksum = calendar7_weeks('Billing', nweeks) if calupdate is not None: for j in range(len(daylist)): ilist = daylist[j] if ilist: tid = ilist[0] fnum = 'note' + str(tid) fput = request.values.get(fnum) if len(fput) > 3: billno = f'{scac}_Bill_{str(tid)}' input = ChalkBoard(Jo=billno, creator=username, comments=fput, status=1) db.session.add(input) db.session.commit() caldays, daylist, weeksum = calendar7_weeks('Billing', nweeks) # ____________________________________________________________________________________________________________________E.Calendar.Billing if (modlink > 0 and bill > 0) or (modlink > 0 and peep > 0) or leftscreen == 0: leftsize = 8 elif leftscreen == 2: leftsize = 10 else: leftsize = 10 else: username, bill, peep, cache, modata, modlink, fdata, adata, cdat, pb, passdata, vdata, caldays, daylist,\ weeksum, nweeks, filesel, docref, doctxt, bType, bClass, expdata, addjobselect, jobdata, modal, viewck, acceptthese,\ assdata, monlvec = var_start() err = [] hv = [0] * 25 hv[0] = 'X' hv[1] = '1' from viewfuncs import nonone, erud, dataget_B leftscreen = 1 leftsize = 10 addjobselect = 0 dlist = ['on'] * 2 dlist[1] = 'off' jobdata = 0 modal = 0 expdata = 0 assdata = [0] divdat = Divisions.query.all() err.append('All is well') leftsize = 8 rightsize = 12 - leftsize today = datetime.date.today() critday = datetime.date.today() + datetime.timedelta(days=7) bdata, cdata = dataget_B(hv[1], hv[0], hv[3]) hv[23] = assdata acdata = Accounts.query.filter( (Accounts.Type == 'Bank') | (Accounts.Type == 'Credit Card') | (Accounts.Type == 'Current Liability')).order_by( Accounts.Name).all() err = erud(err) if expdata == 0: expdata = Accounts.query.filter(Accounts.Type == 'Expense').order_by( Accounts.Name).all() return username, divdat, hv, bdata, cdata, bill, peep, err, modata, adata, acdata, expdata, modlink, caldays, daylist, weeksum, nweeks, addjobselect, jobdata, modal, dlist, fdata, today, cdat, pb, critday, vdata, leftscreen, docref, doctxt, leftsize, cache, filesel
def main(odata, cdata1, cdata2, tdata): import smtplib import mimetypes from email.mime.multipart import MIMEMultipart from email import encoders from email.message import Message from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.text import MIMEText import ntpath import shutil import os import numpy as np import subprocess import fnmatch from collections import Counter import datetime from PyPDF2 import PdfFileReader from CCC_system_setup import addpath, emailvals, scac prefix = 'processing/to_email/' done = 'originals_processed/emailed/' wk = f'tmp/{scac}/data/vmanifest/' jo = str(odata.Jo) order = str(odata.Order) driver = str(odata.Driver) drv_email = str(tdata.Email) mfile = wk + 'Manifest' + jo + '.pdf' mfile = addpath(mfile) emails, passwds, ourserver = emailvals() #newfile= ntpath.basename(mfile) #shutil.copy(mfile,newfile) emailfrom = emails[2] emailto = drv_email emailcc = emails[0] fileToSend = mfile username = emails[2] password = passwds[0] msg = MIMEMultipart() msg["From"] = emailfrom msg["To"] = emailto msg["Cc"] = emailcc msg["Subject"] = 'Manifest for Order ' + order body = 'Hello ' + driver + ',\n\nThe attached file is a manifest for a load to which you are the primary driver.\n\nPlease review and let us know if any corrections are required.\n\nSincerely,\n\nFIRST EAGLE LOGISTICS DISPATCH\n\n\n' msg.attach(MIMEText(body, 'plain')) attachment = open(fileToSend, "rb") part = MIMEBase('application', 'octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % fileToSend) msg.attach(part) server = smtplib.SMTP(ourserver) #server.starttls() server.login(username, password) emailto = [emailto, emailcc] server.sendmail(emailfrom, emailto, msg.as_string()) server.quit()
def main(file1, keydata, grandtotal, pdata1, date1, date2): # pdata1:Bid (Bill To) # pdata2:Lid (Load At) # pdata3:Did (Delv To) from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.lib.pagesizes import landscape from reportlab.platypus import Image from reportlab.lib.units import inch import csv import math import datetime import shutil from viewfuncs import parseline from CCC_system_setup import addpath, bankdata file1 = addpath(file1) print(file1) date1 = date1.strftime('%m/%d/%Y') date2 = date2.strftime('%m/%d/%Y') # ___________________________________________________________ def dollar(infloat): outstr = '$' + "%0.2f" % infloat return outstr def avg(in1, in2): out = (in1 + in2) / 2 return out def comporname(company, name): if company is None or company == '': nameout = name else: if len(company) < 4: nameout = name else: nameout = company return nameout def fullname(first, middle, last): if first is not None: nameout = first else: nameout = '' if middle is not None: nameout = nameout + ' ' + middle if last is not None: nameout = nameout + ' ' + last if len(nameout) > 55: nameout = first + ' ' + last return nameout def address(addr1, addr2, addr3): street = addr1 if addr3 is None or addr3 == '': cityst = addr2 else: if len(addr3) < 5: cityst = addr2 if addr2 is None or addr2 == '': cityst = addr3 if len(addr2) < 3: cityst = addr3 if addr2 and addr3: if len(addr2) > 3 and len(addr3) > 3: street = addr1 + ' ' + addr2 cityst = addr3 return street, cityst def nononestr(input): if input is None or input == 'None': output = ' ' else: output = input return output def nonone(input): if input is None: input = 0 return input billto = list(range(5)) if pdata1 is not None: billto[0] = comporname( pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) billto[4] = nononestr(pdata1.Email) else: for i in range(5): billto[i] = ' ' line2 = ['Invoice', 'Booking', 'Container', 'Description', 'Amount'] qnote, note, bank, us, lab, logoi = bankdata('FC') ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 # m1=hls-dl # m2=hls-2*dl m3 = hls - dl m4 = hls - 2 * dl m5 = hls - 18 * dl m6 = hls - 23 * dl m7 = hls - 27 * dl fulllinesat = [m3, m4, m5, m6, m7] p1 = ltm + 87 p2 = ltm + 180 p3 = ctrall p4 = rtm - 180 p5 = rtm - 100 # sds1 =[p1,p2,p3,p4,p5] n1 = ltm + 60 n2 = ltm + 150 n3 = ltm + 240 n4 = rtm - 70 sds2 = [n1, n2, n3, n4] q1 = ltm + 180 q2 = rtm - 180 sds3 = [q1, q2] bump = 2.5 tb = bump * 2 bottomline = m6 - 23 print('file1 is', file1) c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) #logo = addpath("tmp/pics/onestop.png") c.drawImage(logoi, 185, 680, mask='auto') # Date and JO boxes dateline = m3 + 8.2 * dl c.rect(rtm - 150, m3 + 7 * dl, 150, 2 * dl, stroke=1, fill=0) c.line(rtm - 150, dateline, rtm, dateline) # c.line(rtm-75,m3+7*dl,rtm-75,m3+8*dl) c.drawCentredString(rtm - 75, dateline - 13 - bump, 'to') ctm = 218 c.rect(ltm, m3 + dl, 175, 5 * dl, stroke=1, fill=0) #c.rect(ctm, m3+dl,175,5*dl, stroke=1, fill=0) #c.rect(rtm-175, m3+dl,175,5*dl, stroke=1, fill=0) level1 = m3 + 5 * dl c.line(ltm, level1, ltm + 175, level1) # c.line(ctm,level1,ctm+175,level1) # c.line(rtm-175,level1,rtm,level1) # All full horizontal lines for i in fulllinesat: c.line(ltm, i, rtm, i) # for k in sds1: # c.line(k,m1,k,m3) for l in sds2: c.line(l, m3, l, m5) for m in sds3: c.line(m, m6, m, m7) c.line(ltm, m3, ltm, m7) c.line(rtm, m3, rtm, m7) h1 = m6 - 3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm - 75, dateline + 3 * dl, 'Invoice') c.drawCentredString(rtm - 75, dateline + 1.5 * dl, 'Summary') c.setFont('Helvetica', 12, leading=None) c.drawCentredString(rtm - 112.5, dateline + bump, 'Date') c.drawCentredString(rtm - 37.7, dateline + bump, 'Range') c.drawString(ltm + bump * 3, m3 + 5 * dl + bump * 2, 'Bill To') #c.drawString(ctm+bump*3,m1+5*dl+bump*2,'Load At') #c.drawString(rtm-170+bump*2,m1+5*dl+bump*2,'Delv To') dh = 13 top = level1 - dh lft = ltm + bump * 3 c.setFont('Helvetica', 10, leading=None) for i in billto: c.drawString(lft, top, i) top = top - dh c.setFont('Helvetica', 12, leading=None) x = avg(rtm - 75, rtm) + 3 y = dateline - dh - bump c.drawCentredString(x, y, date2) x = avg(rtm - 75, rtm - 150) - 3 c.drawCentredString(x, y, date1) c.drawRightString(rtm - tb * 2, bottomline, dollar(grandtotal)) ctr = [avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm)] for j, i in enumerate(line2): c.drawCentredString(ctr[j], m4 + tb, i) c.setFont('Helvetica', 10, leading=None) ctr = [avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n4, rtm), avg(n3, n4)] top = m4 - dl for k, data in enumerate(keydata): dataline = keydata[k] print(dataline) for j, i in enumerate(dataline): if j == 4: dlen = len(i) if dlen > 35: pline = parseline(i, 32) for myline in pline: if 'STORE' in myline: myline = 'WAREHOUSE STORAGE' if 'None' in myline: myline = '' if 'TBD' in myline: myline = '' c.drawString(n3 + 5, top, myline) top = top - .6 * dl else: c.drawString(n3 + 5, top, i) top = top - .6 * dl else: if 'None' in str(i): i = '' if 'TBD' in str(i): i = '' c.drawCentredString(ctr[j], top, str(i)) top = top - .6 * dl c.setFont('Helvetica', 12, leading=None) dh = 12 ct = 305 top = m6 - 1.5 * dh for i in bank: c.drawCentredString(ct, top, i) top = top - dh top = m3 + 9 * dl - 5 for i in us: c.drawString(ltm + bump, top, i) top = top - dh c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2 + tb, bottomline, 'Balance Due:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m7 + 12, 'Add $39.00 for all international wires') c.setFont('Times-Roman', 9, leading=None) dh = 9.95 top = m5 - dh for j, i in enumerate(note): c.drawString(ltm + tb, top, note[j]) top = top - dh c.showPage() c.save()
def invoiceO(ship, payment): today = datetime.datetime.today() myo = OverSeas.query.get(ship) # Check to see if we have the required data to make an invoice: pdat = People.query.get(myo.Pid) if pdat is not None: invo = 1 leftsize = 8 if myo.Cache is not None: cache = myo.Cache + 1 else: cache = 1 # if no invoice has been created add all the basics: idat = Invoices.query.filter(Invoices.Jo == myo.Jo).first() if idat is None: descript = 'Job ' + myo.Jo + ': ' + myo.Pol + ' to ' + myo.Pod try: total = myo.Charge.replace('$', '').replace(',', '') total = float(total) except: total = 0.00 input = Invoices(Jo=myo.Jo, SubJo=None, Pid=0, Service='Overseas Shipping', Description=descript, Ea=total, Qty=1, Amount=total, Total=total, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() # These are the services we wish to add to the invoice sdata = Services.query.order_by(Services.Price.desc()).all() total = 0 for data in sdata: testone = request.values.get('serv' + str(data.id)) if testone: servid = int(testone) mys = Services.query.get(servid) qty = 1 total = total + mys.Price input = Invoices(Jo=myo.Jo, SubJo=None, Pid=myo.Pid, Service=mys.Service, Description='', Ea=mys.Price, Qty=qty, Amount=mys.Price, Total=None, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() adata = Autos.query.filter(Autos.Jo == myo.Jo).all() for data in adata: ihave = Invoices.query.filter( Invoices.SubJo == str(data.id)).first() if ihave is None: qty = 1 towcost = data.TowCostEa if towcost is None: data.TowCostEa = '0.00' towcost = '0.00' towcharge = nononef(towcost) total = total + towcharge descript = data.Year + ' ' + data.Color + ' ' + data.Make + ' ' + data.Model + ' VIN:' + data.VIN input = Invoices(Jo=myo.Jo, SubJo=str(data.id), Pid=myo.Pid, Service='Towing', Description=descript, Ea=towcharge, Qty=qty, Amount=towcharge, Total=None, Date=today, Original=None, Status='New') db.session.add(input) db.session.commit() total = 0.0 ldata = Invoices.query.filter(Invoices.Jo == myo.Jo).all() for ldat in ldata: qty = float(ldat.Qty) each = float(ldat.Ea) amount = qty * each total = total + amount ldat.Amount = d2s(amount) db.session.commit() for ldat in ldata: ldat.Total = d2s(total) db.session.commit() ldat = Invoices.query.filter(Invoices.Jo == myo.Jo).first() if ldat is None: invo = 0 leftsize = 10 err = [ ' ', ' ', 'No services on invoice yet and none selected', ' ', ' ' ] else: invo = 1 leftsize = 8 dt = ldat.Date invodate = ldat.Date.strftime('%m/%d/%Y') err = [' ', ' ', 'Created invoice for JO= ' + myo.Jo, ' ', ' '] ldata = Invoices.query.filter(Invoices.Jo == myo.Jo).order_by( Invoices.Ea.desc()).all() pdata1 = People.query.get(myo.Pid) pdata2 = People.query.get(myo.ExportID) pdata3 = People.query.get(myo.ConsigID) pdata4 = People.query.get(myo.NotifyID) # _______________________________________________________________________________________________________________ joborder = myo.Jo file1 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + '.pdf') file2 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c' + str(cache) + '.pdf') file3 = addpath(f'tmp/{scac}/data/vinvoice/INV' + joborder + 'c' + str(cache - 1) + '.pdf') today = datetime.datetime.today().strftime('%m/%d/%Y') type = joborder[1] myb = Bookings.query.filter( myo.Booking == Bookings.Booking).first() if myb is not None: loadat1 = myo.Pol saildate = myb.SailDate.strftime('%m/%d/%Y') shipto1 = myo.Pod arrival = myb.EstArr.strftime('%m/%d/%Y') theline = myb.Line vessel = myb.Vessel else: loadat1 = myo.Pol saildate = 'TBD' shipto1 = myo.Pod arrival = 'TBD' theline = ' ' vessel = ' ' if payment != 0: try: paydate = payment[2].strftime('%m/%d/%Y') except: paydate = payment[2] billto = list(range(5)) if pdata1 is not None: billto[0] = comporname( pdata1.Company, fullname(pdata1.First, pdata1.Middle, pdata1.Last)) billto[1] = nononestr(pdata1.Addr1) billto[2] = nononestr(pdata1.Addr2) billto[3] = nononestr(pdata1.Telephone) billto[4] = nononestr(pdata1.Email) else: for i in range(5): billto[i] = ' ' loadat = list(range(5)) if pdata2 is not None: loadat[0] = parselinenoupper(loadat1, 34) loadat[1] = parselinenoupper('Depart Date: ' + saildate, 28) loadat[2] = ' ' loadat[3] = parselinenoupper(shipto1, 28) loadat[4] = parselinenoupper('Est. Arrival Date: ' + arrival, 28) else: for i in range(5): loadat[i] = ' ' shipto = list(range(5)) if pdata3 is not None: shipto[0] = comporname( pdata3.Company, fullname(pdata3.First, pdata3.Middle, pdata3.Last)) shipto[0] = shipto[0].title() shipto[1] = nononestr(pdata3.Addr1).title() shipto[2] = nononestr(pdata3.Addr2).title() shipto[3] = nononestr(pdata3.Telephone) shipto[4] = nononestr(pdata3.Email).lower() else: for i in range(5): shipto[i] = ' ' us = list(range(4)) us[0] = 'FIRST EAGLE LOGISTICS INC' us[1] = '505 HAMPTON PARK BLVD UNIT O' us[2] = 'CAPITOL HEIGHTS MD 20743' us[3] = '301-516-3000 [email protected]' line1 = [ 'Booking #', 'Container No.', 'Ship', 'Via', 'Vessel', 'Terms' ] line2 = [ 'Quantity', 'Item Code', 'Description', 'Price Each', 'Amount' ] line3 = [ myo.Booking, myo.Container, theline, myo.MoveType, vessel, 'Due Upon Receipt' ] note, bank = bankdata('FC') lab1 = 'Balance Due' lab2 = 'Add $39.00 for all international wires' ltm = 36 rtm = 575 ctrall = 310 left_ctr = 170 right_ctr = 480 dl = 17.6 tdl = dl * 2 hls = 530 m1 = hls - dl m2 = hls - 2 * dl m3 = hls - 3 * dl m4 = hls - 4 * dl m5 = hls - 18 * dl m6 = hls - 23 * dl m7 = hls - 27 * dl fulllinesat = [m1, m2, m3, m4, m5, m6, m7] p1 = ltm + 87 p2 = ltm + 168 p3 = ctrall - 25 p4 = rtm - 220 p5 = rtm - 120 sds1 = [p1, p2, p3, p4, p5] n1 = ltm + 50 n2 = ltm + 130 n3 = rtm - 140 n4 = rtm - 70 sds2 = [n1, n2, n3, n4] q1 = ltm + 180 q2 = rtm - 180 sds3 = [q1, q2] bump = 2.5 tb = bump * 2 c = canvas.Canvas(file1, pagesize=letter) c.setLineWidth(1) logo = addpath("tmp/pics/logo3.jpg") c.drawImage(logo, 185, 680, mask='auto') # Date and JO boxes dateline = m1 + 8.2 * dl c.rect(rtm - 150, m1 + 7 * dl, 150, 2 * dl, stroke=1, fill=0) c.line(rtm - 150, dateline, rtm, dateline) c.line(rtm - 75, m1 + 7 * dl, rtm - 75, m1 + 9 * dl) ctm = 218 c.rect(ltm, m1 + dl, 175, 5 * dl, stroke=1, fill=0) c.rect(ctm, m1 + dl, 150, 5 * dl, stroke=1, fill=0) c.rect(rtm - 200, m1 + dl, 200, 5 * dl, stroke=1, fill=0) level1 = m1 + 5 * dl c.line(ltm, level1, ltm + 175, level1) c.line(ctm, level1, ctm + 150, level1) c.line(rtm - 200, level1, rtm, level1) for i in fulllinesat: c.line(ltm, i, rtm, i) for k in sds1: c.line(k, m1, k, m3) for l in sds2: c.line(l, m3, l, m5) for m in sds3: c.line(m, m6, m, m7) c.line(ltm, m1, ltm, m7) c.line(rtm, m1, rtm, m7) h1 = avg(m6, m7) - 3 c.line(q2, h1, rtm, h1) c.setFont('Helvetica-Bold', 24, leading=None) c.drawCentredString(rtm - 75, dateline + 1.5 * dl, 'Invoice') c.setFont('Helvetica', 12, leading=None) c.drawCentredString(rtm - 112.5, dateline + bump, 'Date') c.drawCentredString(rtm - 37.7, dateline + bump, 'Invoice #') c.drawString(ltm + bump * 3, m1 + 5 * dl + bump * 2, 'Bill To') c.drawString(ctm + bump * 3, m1 + 5 * dl + bump * 2, 'Port to Port') c.drawString(rtm - 200 + bump * 2, m1 + 5 * dl + bump * 2, 'Customer/Consignee') ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] for j, i in enumerate(line1): c.drawCentredString(ctr[j], m2 + tb, i) ctr = [ avg(ltm, n1), avg(n1, n2), avg(n2, n3), avg(n3, n4), avg(n4, rtm) ] for j, i in enumerate(line2): c.drawCentredString(ctr[j], m4 + tb, i) dh = 12 ct = 305 top = m6 - 1.5 * dh for i in bank: c.drawCentredString(ct, top, i) top = top - dh top = m1 + 9 * dl - 5 for i in us: c.drawString(ltm + bump, top, i) top = top - dh bottomline = m6 - 23 c.setFont('Helvetica-Bold', 12, leading=None) c.drawString(q2 + tb, bottomline, 'Balance Due:') c.setFont('Helvetica', 10, leading=None) c.drawCentredString(avg(q2, rtm), m7 + 12, 'Add $39.00 for all international wires') c.setFont('Times-Roman', 9, leading=None) dh = 9.95 top = m5 - dh for j, i in enumerate(note): c.drawString(ltm + tb, top, note[j]) top = top - dh # _______________________________________________________________________ # Insert data here # _______________________________________________________________________ c.setFont('Helvetica', 10, leading=None) dh = 13 top = level1 - dh lft = ltm + bump * 3 for i in billto: i = i.title() c.drawString(lft, top, i) top = top - dh top = level1 - dh lft = ctm + bump * 3 for i in loadat: for k in i: c.drawString(lft, top, k) top = top - dh top = level1 - dh lft = rtm - 205 + bump * 3 for i in shipto: c.drawString(lft, top, i) top = top - dh x = avg(rtm - 75, rtm) y = dateline - dh - bump c.drawCentredString(x, y, joborder) x = avg(rtm - 75, rtm - 150) c.drawCentredString(x, y, invodate) c.setFont('Helvetica', 9, leading=None) ctr = [ avg(ltm, p1), avg(p1, p2), avg(p2, p3), avg(p3, p4), avg(p4, p5), avg(p5, rtm) ] for j, i in enumerate(line3): c.drawCentredString(ctr[j], m3 + tb, i) total = 0 top = m4 - dh for data in ldata: qty = data.Qty if qty != -1: qty = int(nonone(data.Qty)) each = float(nonone(data.Ea)) subtotal = qty * each if subtotal == 0: sqty = '' theservice = 'Included/NoTow' theeach = '' thesubtotal = '' else: sqty = str(qty) theservice = data.Service theeach = dollar(each) thesubtotal = dollar(subtotal) total = total + subtotal line4 = [sqty, theservice] line5 = nononestr(data.Description) line6 = [theeach, thesubtotal] ctr = [avg(ltm, n1), avg(n1, n2)] for j, i in enumerate(line4): c.drawCentredString(ctr[j], top, i) c.drawString(n2 + tb, top, line5) ctr = [n4 - tb * 2, rtm - tb * 2] for j, i in enumerate(line6): c.drawRightString(ctr[j], top, i) top = top - dh if payment != 0: c.setFont('Helvetica-Bold', 18, leading=None) c.drawCentredString(ct, top - 2 * dh, 'Payment Received') if payment != 0: c.setFont('Helvetica-Bold', 12, leading=None) try: thispay = dollar(float(payment[0])) except: thispay = '$0.00' # dollar(float(payment[0])) top = top - 4 * dh try: c.drawString( n2 + bump, top, 'Your payment of ' + thispay + ', Ref No. ' + payment[1]) except: c.drawString(ct, top, 'There is no payment data as of yet') try: c.drawString(n2 + bump, top - dh, 'was applied on ' + paydate) except: c.drawString(ct, top - dh, 'There is a problem with the date') thispay = nononef(thispay) else: thispay = 0.00 baldue = total - thispay c.drawRightString(rtm - tb * 2, bottomline, dollar(baldue)) c.showPage() c.save() # # Now make a cache copy shutil.copy(file1, file2) try: shutil.move(file3, file1) except: err = 'No file there' # _______________________________________________________________________________________________________________ if cache > 1: docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + 'c' + str( cache) + '.pdf' # Store for future use else: docref = f'tmp/{scac}/data/vinvoice/INV' + myo.Jo + '.pdf' if payment == 0: for ldatl in ldata: ldatl.Pid = pdata1.id ldatl.Original = docref db.session.commit() myo.Ipath = docref myo.Cache = cache db.session.commit() leftscreen = 0 #err[4]='Viewing '+docref return invo, err, leftscreen, leftsize, docref, dt