-
Notifications
You must be signed in to change notification settings - Fork 0
/
tartanFunctions.py
3123 lines (3011 loc) · 107 KB
/
tartanFunctions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SYNOPSIS
These are various functions used in TARTAN.
This file is part of Tartan Systems (TARTAN).
AUTHOR
Written by Paul Malherbe, <paul@tartan.co.za>
COPYING
Copyright (C) 2004-2023 Paul Malherbe.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
def importTkinter():
try:
import tkinter as tk
import tkinter.ttk as ttk
return tk, ttk
except:
return None, None
def unbindAllWidgets(widget):
binds = []
for bind in widget.winfo_toplevel().bind():
if "<Key-Alt_L>" in bind:
binds.append((bind, widget.winfo_toplevel().bind(bind)))
widget.winfo_toplevel().unbind(bind)
return binds
def getManager(widget):
# Window Manager
try:
children = widget.winfo_children()
if not children:
mgr = "pack"
else:
mgr = ""
for c in children:
if c.winfo_manager():
mgr = c.winfo_manager()
break
except:
mgr = "pack"
return mgr
def placeWindow(window, parent=None, place="C", size=None, expose=False):
# Window Placement
window.update_idletasks()
if window.winfo_class().lower() == "tk":
parent = None
if parent:
if parent.winfo_class() != "Toplevel":
parent = parent.winfo_toplevel()
parent.update_idletasks()
if size:
ww, wh = size
else:
ww = window.winfo_reqwidth()
wh = window.winfo_reqheight()
if parent:
try:
import tkinter as tk
w = tk.Toplevel()
w.geometry("1x1+0+0")
w.update()
bar = w.winfo_y()
w.destroy()
except:
bar = 24
wx = int(parent.winfo_x() + ((parent.winfo_width() - ww) / 2))
wy = int(parent.winfo_y() + ((parent.winfo_height() - wh) / 2)) - bar
else:
if place == "L":
wx = 0
elif place == "R":
wx = window.winfo_screenwidth() - ww
else:
wx = int((window.winfo_screenwidth() - ww) / 2)
if place == "M":
wy = int((window.winfo_screenheight() - wh) / 2)
else:
wy = 0
window.geometry("%dx%d+%d+%d" % (ww, wh, wx, wy))
if expose and window.state() == "withdrawn":
window.deiconify()
window.update_idletasks()
def cutpasteMenu(event):
# Cut, copy and paste menu
from TartanClasses import tk, tkfont
wid = event.widget
font = tkfont.Font(font=("Arial", 10))
wid.menu = tk.Menu(wid, tearoff=False, takefocus=0, font=font)
image = getImage("Cut", (20, 20))
wid.menu.add_command(label="Cut", image=image, compound="left",
accelerator="Ctl-X", font=font)
wid.menu.i1 = image
image = getImage("Copy", (20, 20))
wid.menu.add_command(label="Copy", image=image, compound="left",
accelerator="Ctl-C", font=font)
wid.menu.i2 = image
image = getImage("Paste", (20, 20))
wid.menu.add_command(label="Paste", image=image, compound="left",
accelerator="Ctl-V", font=font)
wid.menu.i3 = image
wid.menu.add_separator()
wid.menu.add_command(label="Select all")
wid.menu.entryconfigure("Cut", command=lambda:
wid.focus_force() or wid.event_generate("<<Cut>>"))
wid.menu.entryconfigure("Copy", command=lambda:
wid.focus_force() or wid.event_generate("<<Copy>>"))
wid.menu.entryconfigure("Paste", command=lambda:
wid.focus_force() or wid.event_generate("<<Paste>>"))
wid.menu.entryconfigure("Select all", command=wid.select_all)
wid.menu.tk_popup(event.x_root + 40, event.y_root + 10, entry="0")
return "break"
def getPrgPath():
import os, sys
epath = os.path.dirname(sys.executable)
if getattr(sys, "frozen", False):
return sys._MEIPASS, epath
else:
return os.path.dirname(os.path.abspath(__file__)), epath
def showDialog(screen, dtype, title, mess, butt=None, dflt=None):
try:
if screen == "text":
if dtype == "question":
answer = None
while answer not in ("yes", "no"):
answer = input("\n%s (yes/no): " % mess)
return answer
else:
print(mess)
else:
try:
from TartanClasses import MyMessageBox
mb = MyMessageBox(screen, dtype, title=title, mess=mess,
butt=butt, dflt=dflt)
return mb.answer
except:
raise Exception
except Exception as err:
print("%s\n%s" % (mess, err))
def askChoice(screen=None, head="", mess="", butt=None, default=""):
return showDialog(screen, "choice", head, mess, butt, default)
def showError(screen=None, head="", mess=""):
showDialog(screen, "error", head, mess)
def showInfo(screen=None, head="", mess=""):
showDialog(screen, "info", head, mess)
def askQuestion(screen=None, head="", mess="", default="no"):
return showDialog(screen, "question", head, mess, dflt=default)
def showWarning(screen=None, head="", mess=""):
showDialog(screen, "warning", head, mess)
def getFontSize(tk=None, width=None, height=None, font=10):
if not tk:
try:
import tkinter as tk
except:
return 800, 600, 10
plus = True
while True:
win = tk.Tk()
win.withdraw()
if not height:
height = int(round(win.winfo_screenheight() * .90, 0))
if not width:
width = int(round(height * 1.33333, 0))
for _ in range(28):
entry = tk.Entry(win, font=("Courier", font))
entry.pack()
win.update_idletasks()
rh = win.winfo_reqheight()
win.destroy()
if plus:
if rh < height:
font += 1
elif rh == height:
break
else:
plus = False
else:
if rh <= height:
break
font -= 1
return width, height, font - 1
def loadRcFile(rcfile=None, default=False):
"""
Function to load a tartanrc file and return a dictionary.
rcfile - The path of the file to load defaulting to tartanrc.
default - Whether to return default settings if no file.
"""
import os, sys
from pathlib import Path
from TartanClasses import FITZ
# Defaults
if FITZ:
vwr = [""]
else:
win = os.path.join(getPrgPath()[1], "uty", "SumatraPDF.exe")
vwr = ["/usr/bin/evince", win]
tardir = os.path.join(Path.home(), "Tartan")
if not os.path.isdir(tardir):
os.makedirs(tardir)
if sys.platform == "win32":
test1 = os.path.normpath("C:/tartanrc")
test2 = os.path.normpath("C:/Tartan/tartanrc")
test3 = os.path.join(tardir, "tartanrc")
else:
test1 = os.path.join(Path.home(), ".tartanrc")
test2 = None
test3 = os.path.join(tardir, ".tartanrc")
opts = {
"dbase": ["SQLite"],
"dbname": ["tartan"],
"dbdir": [os.path.join(tardir, "fle")],
"dbhost": [""],
"dbport": [""],
"dbuser": [""],
"dbpwd": [""],
"bupdir": [os.path.join(tardir, "bup")],
"wrkdir": [os.path.join(tardir, "wrk")],
"upgdir": [os.path.join(tardir, "upg")],
"vwr": vwr,
"prn": [""],
"exp": [""],
"geo": [0],
"plc": ["C"],
"img": ["Y"],
"cnf": ["Y"],
"acnf": ["L"],
"ttip": ["Y"],
"errs": ["Y"],
"wrkf": ["D"],
"wrka": ["N"],
"mft": ["DejaVu Sans", "Arial"],
"mfs": [0],
"dft": ["DejaVu Sans Mono", "Courier New"],
"dfs": [0],
"theme": ["clam"],
"lsc": ["R"],
"nfg": ["#ffffff"],
"nbg": ["#a40204"],
"bsc": ["R"],
"bfg": ["#ffffff"],
"bbg": ["#a40204"],
"ffg": ["#ffffff"],
"fbg": ["#044e1c"],
"dfg": ["#000000"],
"dbg": ["#ffffff"],
"qfg": ["#000000"],
"qbg": ["#ffc0cb"],
"cfg": ["#000000"],
"cbg": ["#add8e6"],
"sfg": ["#000000"],
"sbg": ["#90ee90"]}
pths = ("dbdir", "bupdir", "wrkdir", "upgdir")
# Read and load rcfile
if not rcfile:
rcfile = os.environ.get("TARTANRC")
if not rcfile:
if os.path.isfile(test1):
rcfile = test1
elif test2 is not None and os.path.isfile(test2):
rcfile = test2
else:
rcfile = test3
try:
rcdic = {"name": rcfile}
fle = open(rcfile, "r")
for l in fle:
if l[0] in ("#", ";"):
continue
l = l.strip()
l = l.replace("[", "").replace("]", "")
l = l.replace("'", "")
l = l.split(" = ")
if l[0].strip() not in opts:
if l[0].strip() == "dcs":
rcdic["lsc"] = l[1].strip()
rcdic["bsc"] = l[1].strip()
continue
if l[0].strip() and l[0].strip() in pths:
path = os.path.normpath(l[1].strip())
if path == ".":
rcdic[l[0].strip()] = ""
else:
rcdic[l[0].strip()] = os.path.normpath(l[1].strip())
else:
rcdic[l[0].strip()] = l[1].strip()
fle.close()
if "dbase" not in rcdic or "dbname" not in rcdic:
raise Exception
except:
if not default:
return "error"
but = False
for o in opts:
if o not in rcdic:
if o in ("bfg", "bbg"):
but = True
continue
if len(opts[o]) == 1 or sys.platform != "win32":
rcdic[o] = opts[o][0]
else:
rcdic[o] = opts[o][1]
if o in ("dfs", "mfs"):
rcdic[o] = int(rcdic[o])
if o == "acnf" and rcdic[o].lower() == "y":
rcdic["acnf"] = "L"
if o == "errs" and rcdic[o] == "M":
rcdic[o] = "Y"
if but:
rcdic["bfg"] = rcdic["nfg"]
rcdic["bbg"] = rcdic["nbg"]
if not rcdic["geo"] or rcdic["geo"] == "0":
try:
w, h, f = getFontSize()
except:
w, h, f = 800, 600, 10
m = f
else:
g = rcdic["geo"].split("x")
if not rcdic["dfs"]:
w, h, f = getFontSize(None, int(g[0]), int(g[1]))
m = f
else:
w, h = (int(g[0]), int(g[1]))
m = rcdic["mfs"]
f = rcdic["dfs"]
rcdic["geo"] = "%sx%s" % (w, h)
rcdic["mfs"] = m
rcdic["dfs"] = f
if not rcdic["theme"]:
rcdic["theme"] = "clam"
if os.path.exists(rcfile):
# Create missing directories
check = []
for pth in pths:
if pth and pth in rcdic and not os.path.isdir(rcdic[pth]):
if rcdic[pth] not in check:
check.append(rcdic[pth])
if check:
try:
for d in check:
if d:
os.makedirs(d)
except:
return "makedir (%s)" % d
return rcdic
def parsePrg(text):
a = b = 0
text = text.strip()
if " /" in text:
a = text.index(" /")
if " -" in text:
b = text.index(" -")
if a and b:
if b > a:
exe = text.split(" /")[0]
else:
exe = text.split(" -")[0]
elif a:
exe = text.split(" /")[0]
elif b:
exe = text.split(" -")[0]
else:
exe = text
cmd = [exe]
cmd.extend(text.replace(exe, "").strip().split())
return exe, cmd
def showException(scrn, path, mess, maxTB=None, xits=None, dbm=None):
"""
Display an exception
scrn = The Screen on which to Display the Exception or None to print
path = The place where the log file resides
mess = The First Line of the Message
maxTB = The maximum number of entries to display
xits = A command to be executed on exiting the exception frame
dbm = The database class
"""
import getpass, os, platform, sys, time, traceback
from TartanClasses import ScrollText
def doSaveExc():
t = time.localtime()
t = time.strftime("Date: %Y-%m-%d Time: %H:%M:%S", t)
host = platform.uname()[1]
try:
user = getpass.getuser()
except:
user = "Unknown"
onam = platform.platform()
fnam = os.path.join(path, "errors.txt")
if os.path.isfile(fnam):
flenam = open(fnam, "a")
else:
flenam = open(fnam, "w")
flenam.write(t + "\n\n" + onam + "\n\n")
flenam.write("Host: %s User: %s" % (host, user) + "\n\n")
flenam.write(mess + "\n")
flenam.write("*******************************" + "\n")
flenam.close()
if dbm:
if not dbm.dbopen:
opened = True
dbm.openDbase()
else:
opened = False
try:
dbm.cu.execute("Select ctm_name, sys_msvr, sys_mprt, "\
"sys_msec, sys_maut, sys_mnam, sys_mpwd, ctm_email, "\
"ver_version from ctlmst, ctlsys, verupd where "\
"ctm_cono = 1")
smtp = dbm.cu.fetchone()
if not smtp or not smtp[1]:
raise Exception
err = sendMail(smtp[1:7], smtp[7], ["errors@tartan.co.za"],
"Version: %s Company: %s Host: %s User: %s" % (smtp[8],
smtp[0], host, user), attach=[fnam], wrkdir=path)
if not err:
os.remove(fnam)
except:
pass
if opened:
dbm.closeDbase()
try:
title = str(sys.exc_info()[0])
except:
title = str(sys.exc_type)
cla, exc, trbk = sys.exc_info()
if type(cla) == str:
excName = cla
else:
excName = cla.__name__
if type(exc) == str or not exc.__dict__:
excArgs = exc
else:
try:
excArgs = exc.__dict__["args"]
except KeyError:
excArgs = "<no args>"
if maxTB:
excTb = traceback.format_tb(trbk, maxTB)
else:
excTb = traceback.format_tb(trbk)
excMess = ""
for ta in excTb:
excMess = excMess + ta + "\012"
mess = str(mess) + "\n\n%s\n%s\n%s" % (excMess, excName, excArgs)
if path:
doSaveExc()
if scrn:
try:
if scrn.winfo_toplevel().state() == "withdrawn":
scrn.winfo_toplevel().deiconify()
ScrollText(scrn=scrn, title=title, mess=mess)
except:
pass
else:
print(mess)
def makeArray(col, row, dth, typ="I"):
"""
A routine to generate an array of lists
col = Number of Columns
row = Number of Rows
dth = Number of Levels
typ = "D" for Float, "I" for Integer, "S" for String
"""
import copy
a = []
b = []
c = []
if typ == "S":
d = ""
elif typ == "D":
d = 0.0
else:
d = 0
for _ in range(col):
a.append(d)
for _ in range(row):
b.append(copy.copy(a))
if dth < 2:
c = b
else:
for x in range(dth):
c.append(copy.deepcopy(b))
return(c)
def getPeriods(mf, conum, period, check=False):
"""
A routine to extract a financial period's start and end date for a Company
mf = The MainFrame object
conum = The company number
period = The period number
check = Check if a Year End needs to be run
"""
from TartanClasses import CCD, SplashScreen, Sql
sql = Sql(mf.dbm, ["ctlynd", "gentrn"], prog=__name__)
p = sql.getRec("ctlynd", cols=["cye_start", "cye_end",
"cye_final"], where=[("cye_cono", "=", conum), ("cye_period",
"=", period)], limit=1)
if not p:
showError(mf.window, "Period Error",
"Invalid Financial Period %s for Company %s" % (period, conum))
return (None, None, None)
if period and check:
sp = SplashScreen(mf.window,
"Checking if Period is Up To Date,\n\nPlease Wait....")
chk1 = sql.getRec("ctlynd", cols=["cye_last"],
where=[("cye_cono", "=", conum), ("cye_period", "=",
(period - 1))], limit=1)
chk2 = sql.getRec("gentrn", cols=["max(glt_capdt)"],
where=[("glt_cono", "=", conum), ("glt_curdt", "<",
int(p[0] / 100))], limit=1)
sp.closeSplash()
if chk2[0] and chk2[0] > chk1[0]:
ok = askQuestion(mf.window, "Year End Error",
"""A Year End Must be Performed for Period %s as Transactions Have Been Captured After the last Year End Run for that Period!
If Not Performed, certain Reports and Queries could have Incorrect Balances!
Do You Want to Continue Anyway?""" % (period-1), default="no")
if ok == "no":
return (None, None, None)
s_date = CCD(p[0], "D1", 10.0)
e_date = CCD(p[1], "D1", 10.0)
return (s_date, e_date, p[2])
def getModName(pth, prg, key, ext=None, wait=0):
"""
A routine to return a name for a printer output file which is unique ??
pth = The path where the file is to be created
prg = The calling module name
key = The key of the report e.g. Company Number/Account Number
ext = The file extension e.g. pdf or None
wait = The number of seconds to pause before returning the name
"""
import os, time
if wait:
time.sleep(wait)
t = time.localtime()
tim = "%04i%02i%02i%02i%02i%02i" % (t[0], t[1], t[2], t[3], t[4], t[5])
key = str(key).replace("/", "-").replace("\\", "-").replace(" ", "_")
if not ext:
return os.path.join(pth, "%s_%s_%s" % (prg, key, tim))
if ext and type(ext) == str:
return os.path.join(pth, "%s_%s_%s.%s" % (prg, key, tim, ext))
nam = []
for e in ext:
nam.append(os.path.join(pth, "%s_%s_%s.%s" % (prg, key, tim, e)))
return nam
def doPrinter(mf=None, conum=None, pdfnam=None, splash=True, header=None, repprt=None, repeml=None, fromad=None, attach=None, skip=False):
"""
This module Views or Prints and/or Mails a Report
mf = MainFrame object
conum = Company Number
pdfnam = Report PDF File Name
splash = Display a Splash Screen
header = Heading Used as Subject of Mail
repprt = A list containing the following:
Y or N widget created
Output Report to (V)iew, (P)rinter or e(X)port
Printer Name, view, export or blank
repeml = A list containing the following:
Y or N widget created
Y or N to email the report
Email addresses in a comma delimited string or a list/tuple
Email message which can be:
A string i.e. a message
A List or Tuple which can be:
Subject and Message
Subject, Message and Attachment
Whether to print/view the emailed report
fromad = The from address if not the default system or company one.
attach = A list of attachments
skip = Skip mail errors
"""
import os, subprocess, time
from TartanClasses import Dbase, ViewPDF, SplashScreen, Sql
# Email Document
sp = None
if repeml and repeml[1] == "Y" and repeml[2]:
try:
dbm = Dbase(mf.rcdic)
if dbm.err:
raise Exception("Database Error")
dbm.openDbase()
sql = Sql(dbm, tables=["ctlsys", "ctlmst", "emllog"])
if not conum:
conum = 1
smtp = sql.getRec(tables=["ctlmst", "ctlsys"], cols=["sys_msvr",
"sys_mprt", "sys_msec", "sys_maut", "sys_mnam", "sys_mpwd",
"ctm_email"], where=[("ctm_cono", "=", conum)], limit=1)
if not fromad:
fromad = smtp[6]
if type(repeml[2]) == str:
toad = repeml[2].split(",")
else:
toad = repeml[2]
if repeml[3]:
if type(repeml[3]) in (list, tuple):
if repeml[3][0]:
subj = repeml[3][0]
else:
subj = ""
if repeml[3][1]:
mess = repeml[3][1]
else:
mess = ""
if len(repeml[3]) == 3 and repeml[2]:
if not attach:
attach = repeml[3][2].split(",")
else:
attach.extend(repeml[3][2])
else:
subj = ""
mess = repeml[3]
else:
subj = ""
mess = ""
if not subj:
if type(header) in (tuple, list):
if len(header) == 1:
subj = header[0]
elif len(header) == 2:
subj = "%s %s" % tuple(header)
elif len(header) == 3:
subj = "%s %s %s" % tuple(header)
elif header:
subj = header
else:
subj = "PDF Report"
if not attach or not attach[0]:
att = [pdfnam]
else:
att = [pdfnam] + copyList(attach)
for eml in toad:
ok = False
while not ok:
if splash:
sp = SplashScreen(mf.window.focus_displayof(),
"E-Mailing the Report to:\n\n%s\n\nPlease Wait.." %
eml)
err = sendMail(smtp[0:6], fromad, eml, subj, mess,
attach=att, wrkdir=mf.rcdic["wrkdir"])
if splash:
sp.closeSplash()
if err:
if skip:
ok = "SKIPPED"
break
else:
ok = askQuestion(mf.window.focus_displayof(),
"E-Mail Error", "Problem Delivering This "\
"Message.\n\nTo: %s\nSubject: %s\n\n%s\n\n"\
"Would You Like to Retry?" % (toad[0],
subj,err))
if ok == "yes":
ok = False
else:
ok = "FAILED"
else:
ok = "OK"
if ok:
try:
sql.insRec("emllog", data=[fromad.strip(), eml,
subj, "%04i-%02i-%02i %02i:%02i" %
time.localtime()[0:5], ok])
except:
pass
break
except Exception as err:
showException(mf.window.focus_displayof(), mf.rcdic["wrkdir"],
"E-Mail Error\n\n%s" % err)
try:
dbm.commitDbase()
dbm.closeDbase()
except:
pass
if repeml[4].lower() == "n":
return
if repprt is None:
return
elif repprt[1].lower() == "x" or repprt[2] == "export":
return
elif repprt[2] and repprt[2].lower() == "none":
return
try:
if repprt[1].lower() == "v" or repprt[2] == "view":
# View Document
chk = pdfnam.split(".")[-1]
if chk == "svg":
import webbrowser
webbrowser.open_new(pdfnam)
else:
ViewPDF(mf, pdfnam)
return
# Print Document
if splash:
sp = SplashScreen(mf.window,
"Printing the Report\n\nPlease Wait....")
if repprt[2] == "Default":
prt = getPrinters(donly=True)
if not prt:
raise Exception("No Default Printer")
else:
prt = repprt[2]
prn = mf.rcdic["prn"]
if prn:
exe, chk = parsePrg(prn)
if not os.path.exists(exe):
prn = None
if prn:
cmd = []
fle = False
for c in chk:
if "%p%" in c:
c = c.replace("%p%", prt)
if "%f%" in c:
fle = True
c = c.replace("%f%", pdfnam)
cmd.append(c)
if exe.lower().count("sumatra") and len(cmd) == 1:
cmd.extend(["-print-to", "%s" % prt, pdfnam])
elif exe.lower().count("foxit") and len(cmd) == 1:
cmd.extend(["/t", pdfnam, prt])
elif cmd[0].endswith("lp") and len(cmd) == 1:
cmd.extend(["-d", prt, "-o", "media=A4", pdfnam])
elif cmd[0].endswith("lpr") and len(cmd) == 1:
cmd.extend(["-P", prt, pdfnam])
elif not fle:
cmd.append(pdfnam)
subprocess.Popen(cmd, stdout=subprocess.PIPE)
else:
printPDF(prt, pdfnam)
if splash and sp:
sp.closeSplash()
except Exception as err:
if splash and sp:
sp.closeSplash()
showException(mf.window.focus_displayof(), mf.rcdic["wrkdir"],
"Output Error %s\n\nVwr: %s\nPrn: %s\n" % (err, mf.rcdic["vwr"],
mf.rcdic["prn"]))
def textFormat(text, width=30, blong=True):
"""
Format a text block
Arguments:
`text` -- the string to be reformatted
`width` -- the maximum width of formatted text
`blong` -- break long words
"""
if text:
import textwrap
return textwrap.wrap(text, width=width, break_long_words=blong)
else:
return [""]
def findFile(start=".", name=None, ftyp="f", case="n"):
"""
A routine used to find a file given the starting path, name and whether
name refers to a (f)ile or (d)irectory and whether case sensitive or not.
"""
import os
if type(start) == str:
start = [start]
name = os.path.basename(name)
for d in start:
for root, dirs, files in os.walk(d):
if ftyp == "d":
for pth in dirs:
if case == "y" and os.path.basename(pth) == name:
return os.path.join(root, pth)
elif os.path.basename(pth).lower() == name.lower():
return os.path.join(root, pth)
else:
for flenam in files:
if case == "y" and flenam == name:
return os.path.join(root, flenam)
elif flenam.lower() == name.lower():
return os.path.join(root, flenam)
def sendMail(server, ex, to, subj, mess="", attach=None, embed=None, check=False, timeout=30, local=None, lnkurl=None, wrkdir="."):
"""
A routine to email a message, embed files and/or attach files.
server = A list of the smtp server details i.e.
[host, port, security, auth, username, password]
ex = The from address.
to = A list of recipients.
subj = The subject.
mess = The Message string or a tuple having (text, html).
attach = A list of attachments.
embed = A list of attachments to embed in the body of the message.
check = Check if the mail server is available.
timeout = The number of seconds before timing out defaulting to 30.
local = The local hostname as fqdn.
lnkurl = An http link to add to the embedded attachments
wrkdir = The work directory, defaults to "."
"""
import mimetypes, os, smtplib
try:
from email import encoders as Encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.utils import COMMASPACE, formatdate
except:
from email import Encoders
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEMultipart import MIMEMultipart
from email.Utils import COMMASPACE, formatdate
def mysubj(subj):
words = subj.split()
subj = ""
for word in words:
if not subj:
subj = word[0].upper() + word[1:].lower()
elif word.startswith("RCI"):
subj = "%s %s" % (subj, word)
else:
subj = "%s %s" % (subj, word[0].upper() + word[1:].lower())
return subj
host, port, secu, auth, unam, upwd = server
try:
if secu and int(secu) == 2:
smtp = smtplib.SMTP_SSL(host, port, local, timeout=timeout)
else:
smtp = smtplib.SMTP(host, port, local, timeout=timeout)
if secu and int(secu) == 1:
smtp.starttls()
if auth:
smtp.login(unam, upwd)
if check:
smtp.quit()
return
except Exception as err:
if not check:
showException(None, wrkdir, "Mail Server (%s %s) "\
"Invalid or Unavailable\n\n%s" % (host, port, err))
return err
if type(to) == str:
to = [to]
if attach is None:
attach = []
elif type(attach) == str:
attach = [attach]
if embed is None:
embed = []
elif type(embed) == str:
embed = [embed]
msgRoot = MIMEMultipart("mixed")
msgRoot["From"] = ex
msgRoot["To"] = COMMASPACE.join(to)
msgRoot["Date"] = formatdate(localtime=True)
try:
int(subj[:3])
subj = subj[4:]
except:
pass
subj = subj.replace("'", "").replace("(", " ").replace(")", " ")
if not mess:
if attach:
mess = "Attached please find:\n\n%s" % subj
else:
mess = subj
msgRoot["Subject"] = mysubj(subj)
msgRelated = MIMEMultipart("related")
msgRoot.attach(msgRelated)
msgAlternative = MIMEMultipart("alternative")
msgRelated.attach(msgAlternative)
if type(mess) in (list, tuple):
msgText = MIMEText(mess[0], "plain", "utf-8")
mess = mess[1]
else:
msgText = MIMEText(mess, "plain", "utf-8")
msgAlternative.attach(msgText)
if lnkurl and lnkurl[0] == "Y":
if not mess:
mess = "<p><a href=\"%s\">Visit %s</a></p>" % (lnkurl[1], lnkurl[1])
else:
mess += "<a href=\"%s\">Visit %s</a></p>" % (lnkurl[1], lnkurl[1])
if embed:
seq = 1
for flenam in embed:
name = os.path.basename(flenam)
ctype, encoding = mimetypes.guess_type(flenam)
maintype, subtype = ctype.split("/", 1)
if maintype == "image":
try:
fp = open(flenam, "rb")
msgImage = MIMEImage(fp.read(), _subtype=subtype, name=name)
fp.close()
msgImage.add_header("Content-ID", "<image%s>" % seq)
msgRelated.attach(msgImage)
if lnkurl and lnkurl[0] == "N":
mess = mess + "<a href=\"%s\">" % lnkurl[1]
mess = mess + "<img src=\"cid:image%s\">" % seq
if lnkurl and lnkurl[0] == "N":
mess = mess + "</a>"
mess = mess + "<br>"
seq += 1
except:
pass
msgText = MIMEText(mess.replace("\n", "<br>"), "html", "utf-8")
msgAlternative.attach(msgText)
if attach:
for flenam in attach:
if os.path.isfile(os.path.normpath(flenam)):
name = os.path.basename(flenam)
ctype, encoding = mimetypes.guess_type(flenam)
if ctype:
maintype, subtype = ctype.split("/", 1)
else:
maintype, subtype = ("application", "octet-stream")
part = MIMEBase(maintype, subtype, name=name)
part.set_payload(open(os.path.normpath(flenam),"rb").read())
Encoders.encode_base64(part)
part.add_header("Content-Disposition",
'attachment; filename="%s"' % os.path.basename(flenam))
msgRoot.attach(part)
try:
smtp.sendmail(ex, to, msgRoot.as_string())
smtp.quit()
return
except Exception as err:
try:
smtp.quit()
except:
pass
return err
def mthendDate(date):
"""
Function to return the month-end date of a date
"""
import calendar
yy = int(date / 10000)
mm = int((date % 10000) / 100)
dy = calendar.monthrange(yy, mm)[1]
return int((yy * 10000) + (mm * 100) + dy)
def projectDate(date, period, typ="days"):
"""
Function to return a date which is the result of a date +- period
typ can be days, months or years
"""
import datetime
yy = int(date / 10000)
mm = int(date / 100) % 100
dd = date % 100
mthend = False
if (typ == "days" and period == 365) or typ in ("months", "years"):