Example #1
0
class bk3030(object):
    def __init__(self, **opts):
        self.opts = opts
        if self.setVariables():
            self.mainProcess()
            if "wait" in self.opts:
                self.df.mstFrame.wait_window()
            else:
                self.opts["mf"].startLoop()

    def setVariables(self):
        self.sql = Sql(self.opts["mf"].dbm, tables=["bkmmst", "bkmcon",
            "bkmrtt", "bkmtrn", "bkmunm", "ctlmst", "ctlvtf", "gentrn",
            "tplmst"], prog=self.__class__.__name__)
        if self.sql.error:
            return
        gc = GetCtl(self.opts["mf"])
        ctl = gc.getCtl("ctlmst", self.opts["conum"])
        if not ctl:
            return
        for col in (
                "ctm_name", "ctm_add1", "ctm_add2", "ctm_add3", "ctm_pcode",
                "ctm_regno", "ctm_taxno", "ctm_taxdf", "ctm_tel", "ctm_fax",
                "ctm_b_name", "ctm_b_ibt", "ctm_b_acno", "ctm_logo"):
            setattr(self, col, ctl[col])
        if self.ctm_logo and "LETTERHEAD" in os.environ:
            self.ctm_logo = os.environ["LETTERHEAD"]
        if not self.ctm_logo or not os.path.exists(self.ctm_logo):
            self.ctm_logo = None
        bkmctl = gc.getCtl("bkmctl", self.opts["conum"])
        if not bkmctl:
            return
        self.glint = bkmctl["cbk_glint"]
        self.tplnam = bkmctl["cbk_invtpl"]
        self.fromad = bkmctl["cbk_emadd"]
        if self.glint == "Y":
            ctlctl = gc.getCtl("ctlctl", self.opts["conum"])
            if not ctlctl:
                return
            ctls = ["vat_ctl", "bkm_ctl"]
            if gc.chkRec(self.opts["conum"], ctlctl, ctls):
                return
            self.vatctl = ctlctl["vat_ctl"]
            self.bkmctl = ctlctl["bkm_ctl"]
        t = time.localtime()
        self.sysdtw = ((t[0] * 10000) + (t[1] * 100) + t[2])
        return True

    def mainProcess(self):
        self.tit = ("%03i %s" % (self.opts["conum"], self.opts["conam"]),
            "Booking Arrivals Listing (%s)" % self.__class__.__name__)
        tpm = {
            "stype": "R",
            "tables": ("tplmst",),
            "cols": (
                ("tpm_tname", "", 0, "Template"),
                ("tpm_title", "", 0, "Title", "Y")),
            "where": [
                ("tpm_type", "=", "I"),
                ("tpm_system", "=", "BKM")],
            "order": "tpm_tname"}
        r1s = (("Weekdays","D"), ("Weekend","E"), ("Range", "R"))
        r2s = (("Yes","Y"), ("No","N"))
        fld = (
            (("T",0,0,0),("IRB",r1s),0,"Period","",
                "D","Y",self.doPeriod,None,None,None),
            (("T",0,1,0),"ID1",10,"Starting Date","",
                0,"N",self.doStartDate,None,None,("efld",)),
            (("T",0,2,0),"ID1",10,"Ending Date","",
                0,"N",self.doEndDate,None,None,("efld",)),
            (("T",0,3,0),("IRB",r2s),0,"Include Queries","",
                "N","Y",self.doQuery,None,None,None),
            (("T",0,4,0),("IRB",r2s),0,"Housekeeping Report","",
                "Y","Y",self.doHkRpt,None,None,None),
            (("T",0,5,0),("IRB",r2s),0,"Generate Invoices","",
                "Y","Y",self.doGenInv,None,None,None),
            (("T",0,6,0),("IRB",r2s),0,"Print Invoices","",
                "Y","Y",self.doPrtInv,None,None,None),
            (("T",0,7,0),"INA",20,"Template Name","",
                self.tplnam,"N",self.doTplNam,tpm,None,None))
        tnd = ((self.doEnd,"y"), )
        txt = (self.doExit, )
        if "args" in self.opts:
            tops = self.opts["args"]
        else:
            tops = False
        self.df = TartanDialog(self.opts["mf"], tops=tops, title=self.tit,
            eflds=fld, tend=tnd, txit=txt, view=("N","P"), mail=("Y","N"))

    def doPeriod(self, frt, pag, r, c, p, i, w):
        self.period = w
        if self.period in ("D", "E"):
            self.start = self.getStart()
            self.df.loadEntry(frt, pag, p+1, data=self.start)

    def doStartDate(self, frt, pag, r, c, p, i, w):
        self.start = w
        if self.period in ("D", "E"):
            if self.getStart(self.start):
                return "Invalid Start Date"
            if self.period == "D":
                self.end = projectDate(self.start, 3)
            else:
                self.end = projectDate(self.start, 2)
            self.df.loadEntry(frt, pag, p+1, data=self.end)
            return "sk1"

    def getStart(self, date=None):
        if self.period == "D":
            chk = 0
        else:
            chk = 4
        if date:
            year = int(date / 10000)
            month = int(date / 100) % 100
            day = date % 100
            if datetime.date(year, month, day).weekday() != chk:
                return True
        else:
            date = projectDate(self.sysdtw, -1)
            dte = 99
            while dte != chk:
                date = projectDate(date, 1)
                year = int(date / 10000)
                month = int(date / 100) % 100
                day = date % 100
                dte = datetime.date(year, month, day).weekday()
            return date

    def doEndDate(self, frt, pag, r, c, p, i, w):
        if w < self.start:
            return "Invalid End Date, Before Start Date"
        days = dateDiff(self.start, w, ptype="days")
        if days > 7:
            return "Range More Than 7 Days"
        self.end = w

    def doQuery(self, frt, pag, r, c, p, i, w):
        self.query = w

    def doHkRpt(self, frt, pag, r, c, p, i, w):
        self.house = w

    def doGenInv(self, frt, pag, r, c, p, i, w):
        self.geninv = w
        if self.geninv == "N":
            self.prtinv = "N"
            self.df.loadEntry(frt, pag, p+1, data=self.prtinv)
            return "sk2"

    def doPrtInv(self, frt, pag, r, c, p, i, w):
        self.prtinv = w
        if self.prtinv == "N":
            return "sk1"

    def doTplNam(self, frt, pag, r, c, p, i, w):
        acc = self.sql.getRec("tplmst", where=[("tpm_tname", "=", w),
            ("tpm_type", "=", "I"), ("tpm_system", "=", "BKM")], limit=1)
        if not acc:
            return "Invalid Template Name"
        self.tname = w

    def doEnd(self):
        self.df.closeProcess()
        # Headings and Mail subject
        self.cdes = "%-30s" % self.opts["conam"]
        start = self.getDate(self.start)
        end = self.getDate(projectDate(self.end, 1))
        if self.period == "D":
            self.hdes = "Arrivals for Weekdays %s to %s" % (start, end)
        elif self.period == "E":
            self.hdes = "Arrivals for Weekend %s to %s" % (start, end)
        else:
            self.hdes = "Arrivals for Period %s to %s" % (start, end)
        self.fpdf = MyFpdf(name=self.__class__.__name__, head=80, auto=True)
        self.fpdf.header = self.pageHeading
        self.rtyp = "A"
        self.doArrival()
        if self.house == "Y":
            self.rtyp = "H"
            self.hdes = self.hdes.replace("Arrivals", "Units")
            if self.fpdf.page:
                self.fpdf.add_page()
            self.doHKeeping()
        if self.fpdf.page:
            pdfnam = getModName(self.opts["mf"].rcdic["wrkdir"],
                self.__class__.__name__, self.opts["conum"], ext="pdf")
            self.fpdf.output(pdfnam, "F")
            subj = "%s - %s" % (self.cdes, self.hdes)
            doPrinter(mf=self.opts["mf"], conum=self.opts["conum"],
                pdfnam=pdfnam, header=subj, repprt=self.df.repprt,
                fromad=self.fromad, repeml=self.df.repeml)
        if self.prtinv == "Y" and self.docs:
            # Print Invoice
            self.docs.sort()
            PrintBookingInvoice(self.opts["mf"], self.opts["conum"],
                self.opts["conam"], "I", self.docs, tname=self.tname,
                repprt=self.df.repprt, repeml=self.df.repeml)
            # Print Statement
            self.book.sort()
            callModule(self.opts["mf"], None, "bk3070",
                coy=(self.opts["conum"], self.opts["conam"]),
                args=[self.book, self.df.repprt, self.df.repeml])
        if "wait" not in self.opts:
            self.opts["mf"].closeLoop()

    def doArrival(self):
        state = ["C", "S"]
        if self.query == "Y":
            state.append("Q")
        recs = self.sql.getRec("bkmmst", where=[("bkm_cono", "=",
            self.opts["conum"]), ("bkm_state", "in", tuple(state))],
            order="bkm_ccode")
        self.book = []
        self.docs = []
        last = 0
        for rec in recs:
            number = rec[self.sql.bkmmst_col.index("bkm_number")]
            ccode = rec[self.sql.bkmmst_col.index("bkm_ccode")]
            btype = rec[self.sql.bkmmst_col.index("bkm_btype")]
            arrive = rec[self.sql.bkmmst_col.index("bkm_arrive")]
            depart = rec[self.sql.bkmmst_col.index("bkm_depart")]
            if btype == "A":
                if depart <= self.start or arrive > self.end:
                    continue
            elif depart < self.start or arrive > self.end:
                continue
            if self.geninv == "Y":
                self.doRaiseInvoice(number, arrive)
            con = self.sql.getRec("bkmcon", where=[("bkc_cono", "=",
                self.opts["conum"]), ("bkc_ccode", "=", ccode)], limit=1)
            sname = con[self.sql.bkmcon_col.index("bkc_sname")].strip()
            names = con[self.sql.bkmcon_col.index("bkc_names")].strip()
            if names:
                name = "%s %s (%s)" % (names.split()[0], sname, number)
            else:
                name = "%s (%s)" % (sname, number)
            bal = self.sql.getRec("bkmtrn", cols=["sum(bkt_tramt)"],
                where=[("bkt_cono", "=", self.opts["conum"]), ("bkt_number",
                "=", number)], limit=1)
            rtts = self.sql.getRec("bkmrtt", cols=["brt_udesc",
                "brt_uroom", "sum(brt_quant)"], where=[("brt_cono", "=",
                self.opts["conum"]), ("brt_number", "=", number)],
                group="brt_utype, brt_ucode, brt_udesc, brt_uroom",
                order="brt_utype, brt_ucode, brt_uroom")
            if not rtts:
                continue
            units = []
            unt = None
            for rtt in rtts:
                if rtt[1]:
                    if not unt:
                        unt = ["%s - R%s" % (rtt[0], rtt[1]), rtt[2]]
                    else:
                        unt = ["%s & R%s" % (unt[0], rtt[1]), rtt[2]]
                else:
                    unt = (rtt[0], rtt[2])
                units.append(unt)
            namq = len(wrap(name, break_long_words=False, width=25))
            untq = 0
            for unit in units:
                untq += len(wrap(unit[0], break_long_words=False, width=25))
            if namq and untq > namq:
                hh = [(untq * 8.0) / namq, 8, untq * 8]
            elif untq and namq > untq:
                hh = [8, (namq * 8.0) / untq, namq * 8]
            elif namq:
                hh = [8, 8, namq * 8]
            else:
                hh = [8, 8, untq * 8]
            if not self.fpdf.page or self.fpdf.get_y() + hh[0] > 280:
                self.fpdf.add_page()
            oldnm = None
            for unit in units:
                if name == oldnm:
                    name = ""
                else:
                    oldnm = name
                if arrive >= self.start:
                    yr = int(arrive / 10000)
                    mt = int(arrive / 100) % 100
                    dy = arrive % 100
                    d = datetime.date(yr, mt, dy)
                    arr = d.strftime("%a")
                else:
                    arr = "<--"
                if btype == "A":
                    td = projectDate(depart, -1)
                else:
                    td = depart
                if td <= self.end:
                    yr = int(depart / 10000)
                    mt = int(depart / 100) % 100
                    dy = depart % 100
                    e = datetime.date(yr, mt, dy)
                    dep = e.strftime("%a")
                else:
                    dep = "-->"
                if last != number and bal[0]:
                    amt = CCD(bal[0], "SD", 13.2).disp
                else:
                    amt = CCD(0, "SD", 13.2).disp
                self.printLine(name, unit[0], unit[1], arr, dep, amt, hh)
                last = number
        self.opts["mf"].dbm.commitDbase()

    def doHKeeping(self):
        recs = self.sql.getRec("bkmunm", cols=["bum_btyp", "bum_code",
            "bum_desc"], where=[("bum_cono", "=", self.opts["conum"]),
            ("bum_room", "<>", 999)], order="bum_btyp, bum_code")
        for rec in recs:
            col = ["bkm_number", "bkm_btype", "bkm_group", "bkc_sname",
                "bkc_names", "bkm_arrive", "bkm_depart", "sum(brt_quant)"]
            state = ["C", "S"]
            if self.query == "Y":
                state.append("Q")
            bks = self.sql.getRec(tables=["bkmmst", "bkmrtt", "bkmcon"],
                cols=col, where=[("bkm_cono", "=", self.opts["conum"]),
                ("bkm_state", "in", tuple(state)), ("brt_cono=bkm_cono",),
                ("brt_number=bkm_number",), ("brt_utype", "=", rec[0]),
                ("brt_ucode", "=", rec[1]), ("bkc_cono=bkm_cono",),
                ("bkc_ccode=bkm_ccode",)], order="bkm_arrive, bkc_sname")
            qty = ""
            arr = ""
            dep = ""
            amt = ""
            totq = 0
            lines = []
            hh = [8, 8, 8]
            for bk in bks:
                number = bk[0]
                btype = bk[1]
                if bk[2]:
                    name = bk[2]
                elif bk[4]:
                    name = "%s %s" % (bk[4].split()[0], bk[3])
                else:
                    name = bk[3]
                name = "%s\n(%s)" % (name.strip(), number)
                arrive = bk[5]
                depart = bk[6]
                if btype == "A":
                    if depart <= self.start or arrive > self.end:
                        continue
                elif depart < self.start or arrive > self.end:
                    continue
                if arrive >= self.start:
                    yr = int(arrive / 10000)
                    mt = int(arrive / 100) % 100
                    dy = arrive % 100
                    dt = datetime.date(yr, mt, dy)
                    arrive = dt.strftime("%a")
                else:
                    arrive = "<--"
                if btype == "A":
                    td = projectDate(depart, -1)
                else:
                    td = depart
                if td <= self.end:
                    yr = int(depart / 10000)
                    mt = int(depart / 100) % 100
                    dy = depart % 100
                    dt = datetime.date(yr, mt, dy)
                    depart = dt.strftime("%a")
                else:
                    depart = "-->"
                rms = self.sql.getRec("bkmrtt",
                    cols=["brt_uroom"],
                    where=[
                        ("brt_cono", "=", self.opts["conum"]),
                        ("brt_number", "=", number),
                        ("brt_utype", "=", rec[0]),
                        ("brt_ucode", "=", rec[1])],
                    order="brt_uroom")
                rm = False
                for r in rms:
                    if not r[0]:
                        continue
                    if not rm:
                        name = "%s - R%s" % (name, r[0])
                        rm = True
                    else:
                        name = "%s & R%s" % (name, r[0])
                quant = bk[7]
                bal = self.sql.getRec("bkmtrn", cols=["sum(bkt_tramt)"],
                    where=[("bkt_cono", "=", self.opts["conum"]), ("bkt_number",
                    "=", number)], limit=1)
                namq = len(wrap(name, break_long_words=False, width=25))
                totq += namq
                hh[2] = namq * 8
                qty = CCD(quant, "UI", 3).disp
                arr = CCD(arrive, "NA", 3).disp
                dep = CCD(depart, "NA", 3).disp
                amt = CCD(bal[0], "SD", 13.2).disp
                lines.append([name, qty, arr, dep, amt, copyList(hh)])
            if not self.fpdf.page or self.fpdf.get_y() + (totq * 8) > 280:
                self.fpdf.add_page()
            untq = len(wrap(rec[2], break_long_words=False, width=25))
            if not lines:
                hh[1] = hh[2] = 8.0 * untq
                self.y = self.fpdf.get_y()
                self.printLine(rec[2], "", "", "", "", "", hh)
                self.fpdf.set_y(self.y)
                self.printLine(None, "", "", "", "", "", hh)
            else:
                if untq > totq:
                    hh[1] = hh[2] = (untq * 8.0) / totq
                elif totq > untq:
                    hh[0] = (totq * 8.0) / untq
                else:
                    hh[2] = totq * 8
                self.y = self.fpdf.get_y()
                self.printLine(rec[2], "", "", "", "", "", hh)
                self.fpdf.set_y(self.y)
                for l in lines:
                    self.printLine(None, l[0], l[1], l[2], l[3], l[4], l[5])

    def doRaiseInvoice(self, number, trdt):
        # Raise the Invoice
        incamt = 0
        vatamt = 0
        curdt = int(trdt / 100)
        batno = "B%s" % curdt
        gls = {}
        recs = self.sql.getRec("bkmrtt", where=[("brt_cono",
            "=", self.opts["conum"]), ("brt_number", "=", number),
            ("brt_invno", "=", 0)])
        if not recs:
            return
        invno = self.getRef(number)
        self.docs.append(invno)
        if number not in self.book:
            self.book.append(number)
        for rec in recs:
            utyp = rec[self.sql.bkmrtt_col.index("brt_utype")]
            ucod = rec[self.sql.bkmrtt_col.index("brt_ucode")]
            rcod = rec[self.sql.bkmrtt_col.index("brt_rcode")]
            rbas = rec[self.sql.bkmrtt_col.index("brt_rbase")]
            quan = rec[self.sql.bkmrtt_col.index("brt_quant")]
            rate = rec[self.sql.bkmrtt_col.index("brt_arate")]
            days = rec[self.sql.bkmrtt_col.index("brt_bdays")]
            umst = self.sql.getRec("bkmunm", where=[("bum_cono",
                "=", self.opts["conum"]), ("bum_btyp", "=", utyp),
                ("bum_code", "=", ucod)], limit=1)
            vatc = umst[self.sql.bkmunm_col.index("bum_vatc")]
            if not vatc:
                vatc = self.ctm_taxdf
            vrte = getVatRate(self.sql, self.opts["conum"], vatc, trdt)
            if vrte is None:
                vrte = 0.0
            if rbas == "A":
                inca = quan * days * rate
            elif rbas == "B":
                inca = quan * rate
            elif rbas == "C":
                inca = days * rate
            else:
                inca = rate
            vata = round(inca * vrte / (100 + vrte), 2)
            exca = float(ASD(inca) - ASD(vata))
            incamt = float(ASD(incamt) + ASD(inca))
            vatamt = float(ASD(vatamt) - ASD(vata))
            if self.glint == "Y":
                slsa = umst[self.sql.bkmunm_col.index("bum_slsa")]
                if slsa not in gls:
                    gls[slsa] = [0, 0, vatc]
                gls[slsa][0] = float(ASD(gls[slsa][0]) - ASD(exca))
                gls[slsa][1] = float(ASD(gls[slsa][1]) - ASD(vata))
            data = [self.opts["conum"], number, 2, invno, batno, trdt, inca,
                vata, curdt, "Booking %s-%s Raised" % (utyp, ucod), vatc, "",
                self.opts["capnm"], self.sysdtw, 0]
            self.sql.insRec("bkmtrn", data=data)
            self.sql.updRec("bkmrtt", cols=["brt_invno", "brt_invdt",
                "brt_vrate"], data=[invno, trdt, vrte],
                where=[("brt_cono", "=", self.opts["conum"]),
                ("brt_number", "=", number), ("brt_utype", "=", utyp),
                ("brt_ucode", "=", ucod), ("brt_rcode", "=", rcod)])
            if vata:
                exc = float(ASD(0) - ASD(exca))
                vat = float(ASD(0) - ASD(vata))
                data = [self.opts["conum"], vatc, "O", curdt, "B", 1, batno,
                    invno, trdt, number, "Booking %s" % number, exc, vat, 0,
                    self.opts["capnm"], self.sysdtw, 0]
                self.sql.insRec("ctlvtf", data=data)
        if self.glint == "Y":
            data = [self.opts["conum"], self.bkmctl, curdt, trdt, 1, invno,
                batno, incamt, 0, "Booking %s" % number, "", "", 0,
                self.opts["capnm"], self.sysdtw, 0]
            self.sql.insRec("gentrn", data=data)
            for acc in gls:
                data = [self.opts["conum"], acc, curdt, trdt, 1, invno,
                    batno, gls[acc][0], gls[acc][1], "Booking %s" % number,
                    gls[acc][2], "", 0, self.opts["capnm"], self.sysdtw, 0]
                self.sql.insRec("gentrn", data=data)
                if gls[acc][1]:
                    data = [self.opts["conum"], self.vatctl, curdt, trdt, 1,
                        invno, batno, gls[acc][1], 0, "Booking %s" % number,
                        "", "", 0, self.opts["capnm"], self.sysdtw, 0]
                    self.sql.insRec("gentrn", data=data)
        return True

    def getRef(self, number):
        rec = self.sql.getRec("bkmtrn", cols=["max(bkt_refno)"],
            where=[("bkt_cono", "=", self.opts["conum"]), ("bkt_number",
            "=", number), ("bkt_refno", "like", "%7s%s" % (number, "%"))],
            limit=1)
        if not rec or not rec[0]:
            num = 1
        else:
            num = int(rec[0][-2:]) + 1
        return "%7s%02i" % (number, num)

    def pageHeading(self):
        self.fpdf.drawText(self.cdes, x=7, font=["courier", "B", 24])
        self.fpdf.drawText(font=["courier", "B", 14])
        self.fpdf.drawText(self.hdes, x=7, font=["courier", "B", 16])
        if self.query == "Y":
            ides = "Queries Included"
        else:
            ides = "Queries Not Included"
        if self.rtyp == "A":
            if self.geninv == "Y":
                ides = "%s, Invoices Generated" % ides
            else:
                ides = "%s, Invoices Not Generated" % ides
        self.fpdf.drawText()
        self.fpdf.drawText(ides, x=7, font=["courier", "B", 16])
        if self.rtyp == "A":
            self.fpdf.drawText(font=["courier", "B", 12])
            self.printLine("%-25s" % "Name or Group",
                "%-25s" % "Unit Description", "Qty", "Arr",
                "Dep", "     Balance ", (8, 8, 8), fill=1)
        else:
            self.fpdf.drawText(font=["courier", "B", 12])
            self.printLine("%-25s" % "Unit Description",
                "%-25s" % "Name or Group", "Qty", "Arr",
                "Dep", "     Balance ", (8, 8, 8), fill=1)

    def getDate(self, date):
        if type(date) == str:
            date = int(date.replace("-", ""))
        yy = int(date / 10000)
        mm = int(date / 100) % 100
        dd = date % 100
        return "%s %s %s" % (dd, mthnam[mm][1], yy)

    def printLine(self, a, b, c, d, e, f, hh, bdr="TLB", fill=0):
        if self.rtyp == "H" and a is None:
            if hh[2] > 8:
                ctyp = "M"
            else:
                ctyp = "S"
        elif hh[0] > 8 or hh[1] > 8 or hh[2] > 8:
            ctyp = "M"
        else:
            ctyp = "S"
        ft = ["courier", "B", 12]
        self.fpdf.set_font(ft[0], ft[1], ft[2])
        w = self.fpdf.get_string_width("X" * 26)
        x = 7
        y = self.fpdf.get_y()
        if a:
            self.fpdf.drawText(a, x=x, y=y, w=w, h=hh[0], border=bdr,
                fill=fill, ctyp=ctyp, font=ft)
            if self.rtyp == "H" and not fill:
                return
        x += w
        w = self.fpdf.get_string_width("X" * 26)
        self.fpdf.drawText(b, x=x, y=y, w=w, h=hh[1], border=bdr,
            fill=fill, ctyp=ctyp, font=ft)
        x += w
        w = self.fpdf.get_string_width("X" * 4) + 1
        h = self.fpdf.get_y() - y
        if self.rtyp == "A":
            self.fpdf.drawText(c, x=x, y=y, w=w, h=h, border=bdr,
                align="R", fill=fill, font=ft)
        else:
            self.fpdf.drawText(c, x=x, y=y, w=w, h=hh[2], border=bdr,
                align="R", fill=fill, ctyp=ctyp, font=ft)
        ly = self.fpdf.get_y()
        if a or self.rtyp == "H":
            x += w
            w = self.fpdf.get_string_width("X" * 4)
            if self.rtyp == "A":
                self.fpdf.drawText(d, x=x, y=y, w=w, h=hh[2], border=bdr,
                    fill=fill, font=ft)
            else:
                self.fpdf.drawText(d, x=x, y=y, w=w, h=hh[2], border=bdr,
                    fill=fill, ctyp=ctyp, font=ft)
            x += w
            w = self.fpdf.get_string_width("X" * 4)
            if self.rtyp == "A":
                self.fpdf.drawText(e, x=x, y=y, w=w, h=hh[2], border=bdr,
                    fill=fill, font=ft)
            else:
                self.fpdf.drawText(e, x=x, y=y, w=w, h=hh[2], border=bdr,
                    fill=fill, ctyp=ctyp, font=ft)
            x += w
            w = self.fpdf.get_string_width("X" * 14)
            if self.rtyp == "A":
                self.fpdf.drawText(f, x=x, y=y, w=w, h=hh[2], border="TLRB",
                    fill=fill, font=ft)
            else:
                self.fpdf.drawText(f, x=x, y=y, w=w, h=hh[2], border="TLRB",
                    fill=fill, ctyp=ctyp, font=ft)
        self.fpdf.set_y(ly)

    def doExit(self):
        self.df.closeProcess()
        if "wait" not in self.opts:
            self.opts["mf"].closeLoop()
Example #2
0
class bs3010(object):
    def __init__(self, **opts):
        self.opts = opts
        if self.setVariables():
            self.mainProcess()
            self.opts["mf"].startLoop()

    def setVariables(self):
        self.sql = Sql(self.opts["mf"].dbm, ["bksmst", "bksaut", "bksown"],
                       prog=self.__class__.__name__)
        if self.sql.error:
            return
        t = time.localtime()
        self.curdt = time.strftime("%Y-%m", t)
        self.image = os.path.join(self.opts["mf"].rcdic["wrkdir"], "books.png")
        if not os.path.exists(self.image):
            getImage("books", fle=self.image)
        if not os.path.exists(self.image):
            self.image = None
        return True

    def mainProcess(self):
        lst = {
            "stype": "R",
            "tables": ("bksmst", ),
            "cols": (("bmf_mnth", "", 0, "Month"), ),
            "where": [("bmf_cono", "=", self.opts["conum"])],
            "group": "bmf_mnth",
            "order": "bmf_mnth"
        }
        r1s = (("All", "A"), ("Current", "C"), ("Removed", "R"))
        r2s = (("Title", "T"), ("Date", "D"), ("Author", "A"), ("Owner", "O"))
        fld = ((("T", 0, 0, 0), "ID2", 7, "Last Meeting", "", "", "N",
                self.doLast, lst, None, ("efld", )),
               (("T", 0, 1, 0), ("IRB", r1s), 0, "Status", "", "A", "N",
                self.doStatus, None, None, None),
               (("T", 0, 2, 0), ("IRB", r2s), 0, "Order", "", "T", "N",
                self.doOrder, None, None, None))
        tnd = ((self.doEnd, "y"), )
        txt = (self.doExit, )
        self.df = TartanDialog(self.opts["mf"],
                               tops=False,
                               eflds=fld,
                               tend=tnd,
                               txit=txt,
                               view=("N", "V"),
                               mail=("B", "Y"))

    def doLast(self, frt, pag, r, c, p, i, w):
        self.last = w
        self.new = False

    def doStatus(self, frt, pag, r, c, p, i, w):
        self.status = w

    def doOrder(self, frt, pag, r, c, p, i, w):
        self.order = w

    def doEnd(self):
        self.df.closeProcess()
        if self.df.repeml[1] == "Y":
            if not self.df.repeml[2]:
                owns = self.sql.getRec("bksown",
                                       cols=["bof_mail"],
                                       where=[("bof_mail", "<>", ""),
                                              ("bof_stat", "=", "C")])
                adds = None
                for own in owns:
                    if not adds:
                        adds = own[0]
                    else:
                        adds = "%s,%s" % (adds, own[0])
                self.df.repeml[2] = adds
            if not self.df.repeml[3]:
                self.df.repeml[3] = """Dear Member

Attached please find the latest list of books.

All books which came onto the list at the last meeting are highlighted and, if available, a precis will be printed at the end.

Thanks and Regards.
"""
        tab = ["bksmst", "bksaut", "bksown"]
        col = [
            "bmf_stat", "bmf_titl", "bmf_code", "baf_snam", "baf_fnam",
            "bmf_mnth", "bof_fnam", "bof_snam"
        ]
        odr = ""
        if self.status == "C":
            whr = [("bmf_stat", "=", "C")]
        elif self.status == "R":
            whr = [("bmf_stat", "=", "X")]
        else:
            whr = []
            odr = "bmf_stat"
        whr.extend([("baf_code=bmf_auth", ), ("bof_code=bmf_ownr", )])
        if self.order == "T":
            if odr:
                odr = "%s, bmf_titl" % odr
            else:
                odr = "bmf_titl"
        elif self.order == "D":
            if odr:
                odr = "%s, bmf_mnth, bmf_titl" % odr
            else:
                odr = "bmf_mnth, bmf_titl"
        elif self.order == "A":
            if odr:
                odr = "%s, baf_snam, baf_fnam, bmf_titl" % odr
            else:
                odr = "baf_snam, baf_fnam, bmf_titl"
        elif self.order == "O":
            if odr:
                odr = "%s, bmf_ownr, bmf_titl" % odr
            else:
                odr = "bmf_ownr, bmf_titl"
        recs = self.sql.getRec(tables=tab, cols=col, where=whr, order=odr)
        if not recs:
            showError(self.opts["mf"].body, "Selection Error",
                      "No Records Selected")
            self.opts["mf"].closeLoop()
            return
        self.fpdf = MyFpdf(name="bs3010", head=90, auto=True)
        self.fpdf.header = self.pageHeading
        self.stat = recs[0][0]
        self.fpdf.add_page()
        new = []
        for rec in recs:
            stat = CCD(rec[0], "UA", 1).disp
            if stat != self.stat:
                self.stat = stat
                self.fpdf.add_page()
            titl = CCD(rec[1], "NA", 30).disp
            code = CCD(rec[2], "UI", 4).disp
            auth = CCD("%s, %s" % (rec[3], rec[4]), "NA", 30).disp
            mnth = CCD(rec[5], "D2", 7).disp
            ownr = CCD("%s %s" % (rec[6], rec[7][0]), "NA", 12).disp
            if rec[5] < self.last:
                fill = 0
            else:
                new.append([auth, titl])
                fill = 1
            self.fpdf.drawText("%1s %30s %4s %30s %7s %10s" %
                               (stat, titl, code, auth, mnth, ownr),
                               h=5,
                               fill=fill)
        if new:
            sp = SplashScreen(
                self.opts["mf"].body,
                "Preparing Summary of New Books ... Please Wait")
            self.new = True
            self.fpdf.add_page()
            for book in new:
                try:
                    if self.fpdf.get_y() > 260:
                        self.fpdf.add_page()
                    desc = self.getDesc(book)
                    if desc:
                        w = self.fpdf.cwth * 9
                        desc = desc.rstrip().encode("latin-1",
                                                    "ignore").decode(
                                                        "latin-1", "ignore")
                        self.fpdf.drawText(w=w, txt="Title: ", font="B", ln=0)
                        self.fpdf.drawText(txt=book[1].rstrip(), font="I")
                        self.fpdf.drawText(w=w, txt="Author: ", font="B", ln=0)
                        self.fpdf.drawText(txt=book[0].rstrip(), font="I")
                        self.fpdf.drawText(w=w,
                                           txt="Details: ",
                                           font="B",
                                           ln=0)
                        self.fpdf.drawText(txt=desc, font="I", ctyp="M")
                        if book != new[-1]:
                            self.fpdf.drawText()
                except:
                    pass
            sp.closeSplash()
        pdfnam = getModName(self.opts["mf"].rcdic["wrkdir"],
                            self.__class__.__name__,
                            self.opts["conum"],
                            ext="pdf")
        self.fpdf.output(pdfnam, "F")
        head = "Book List as at %s" % (self.curdt)
        doPrinter(mf=self.opts["mf"],
                  conum=self.opts["conum"],
                  pdfnam=pdfnam,
                  header=head,
                  repprt=self.df.repprt,
                  repeml=self.df.repeml)
        self.opts["mf"].closeLoop()

    def pageHeading(self, new=False):
        self.fpdf.setFont("Arial", "B", 15)
        x = self.fpdf.get_x()
        if self.image:
            self.fpdf.image(self.image, 11, 10, 15, 20)
            self.fpdf.image(self.image, 185, 10, 15, 20)
            self.fpdf.cell(20)
        self.fpdf.set_x(x)
        self.fpdf.cell(0, 10, self.opts["conam"], "TLR", 1, "C")
        if self.new:
            txt = "Summary of New Books"
        elif self.stat == "C":
            txt = "Current Books as at %s" % self.curdt
        else:
            txt = "Removed Books as at %s" % self.curdt
        self.fpdf.cell(0, 10, txt, "LRB", 1, "C")
        self.fpdf.ln(8)
        self.fpdf.setFont(style="B")
        if not self.new:
            self.fpdf.cell(
                0, 5, "%-1s %-30s %-4s %-30s %-7s %-12s" %
                ("S", "Title", "Code", "Author", "Mth-Rec", "Owner"), "B")
        self.fpdf.ln(5)

    def getDesc(self, book):
        auth = book[0].strip().lower()
        titl = book[1].strip().lower().replace(",", "")
        if titl[:4] == "the ":
            titl = titl[4:]
        elif titl[-4:] == " the":
            titl = titl[:-4]
        get = requests.get("https://www.googleapis.com/books/v1/volumes?q="\
            "{intitle:'%s'+inauthor:'%s'" % (titl, auth), timeout=5)
        if get.status_code == 200 and get.json()["totalItems"]:
            ok = False
            for item in get.json()["items"]:
                tita = titl.lower().\
                    replace("the ","").replace(", the", "")
                titb = item["volumeInfo"]["title"].lower().\
                    replace("the ","").replace(", the", "")
                if titb.count(tita):
                    if "description" in item["volumeInfo"]:
                        ok = True
                        break
            if ok:
                return item["volumeInfo"]["description"]

    def doExit(self):
        self.df.closeProcess()
        self.opts["mf"].closeLoop()
Example #3
0
class bc3100(object):
    def __init__(self, **opts):
        self.opts = opts
        if self.setVariables():
            self.mainProcess()
            self.opts["mf"].startLoop()

    def setVariables(self):
        self.sql = Sql(self.opts["mf"].dbm, ["bwlcmp", "bwlgme", "bwltab",
            "bwltyp", "bwlpts", "bwlent"], prog=self.__class__.__name__)
        if self.sql.error:
            return
        gc = GetCtl(self.opts["mf"])
        bwlctl = gc.getCtl("bwlctl", self.opts["conum"])
        if not bwlctl:
            return
        self.fromad = bwlctl["ctb_emadd"]
        return True

    def mainProcess(self):
        com = {
            "stype": "R",
            "tables": ("bwlcmp",),
            "cols": (
                ("bcm_code", "", 0, "Cod"),
                ("bcm_name", "", 0, "Name", "Y")),
            "where": [("bcm_cono", "=", self.opts["conum"])]}
        gme = {
            "stype": "R",
            "tables": ("bwlgme",),
            "cols": (("bcg_game", "", 0, "GC"),),
            "where": [("bcg_cono", "=", self.opts["conum"])],
            "whera": [("T", "bcg_ccod", 0, 0)],
            "group": "bcg_game"}
        r1s = (("Yes", "Y"), ("No", "N"))
        fld = (
            (("T",0,0,0),"I@bcm_code",0,"","",
                0,"N",self.doCmpCod,com,None,None),
            (("T",0,0,0),"ONA",30,""),
            (("T",0,1,0),"IUI",2,"Last Game","",
                0,"N",self.doLstGam,gme,None,("efld",)),
            (("T",0,2,0),("IRB",r1s),0,"Game Report","",
                "N","N",self.doGamRep,None,None,None),
            (("T",0,3,0),("IRB",r1s),0,"Session Prizes","",
                "N","N",self.doSesPrz,None,None,None),
            (("T",0,4,0),("IRB",r1s),0,"Session Prizes by Group","",
                "N","N",self.doSesGrp,None,None,None))
        tnd = ((self.doEnd,"y"),)
        txt = (self.doExit,)
        self.df = TartanDialog(self.opts["mf"], tops=False,
            eflds=fld, tend=tnd, txit=txt, view=("N","V"), mail=("B","N"))

    def doCmpCod(self, frt, pag, r, c, p, i, w):
        chk = self.sql.getRec("bwlcmp", where=[("bcm_cono", "=",
            self.opts["conum"]), ("bcm_code", "=", w)], limit=1)
        if not chk:
            return "Invalid Competition Code"
        self.ccod = w
        self.cdes = chk[self.sql.bwlcmp_col.index("bcm_name")]
        self.ctyp = chk[self.sql.bwlcmp_col.index("bcm_type")]
        self.poff = chk[self.sql.bwlcmp_col.index("bcm_poff")]
        chk = self.sql.getRec("bwltyp", where=[("bct_cono", "=",
            self.opts["conum"]), ("bct_code", "=", self.ctyp)], limit=1)
        self.cfmat = chk[self.sql.bwltyp_col.index("bct_cfmat")]
        self.tsize = chk[self.sql.bwltyp_col.index("bct_tsize")]
        if self.cfmat == "R":
            games = self.sql.getRec("bwlgme", cols=["count(*)"],
                where=[("bcg_cono", "=", self.opts["conum"]),
                ("bcg_ccod", "=", self.ccod), ("bcg_game", "=", 1)],
                group="bcg_group")
            self.games = 0
            for gme in games:
                if gme[0] > self.games:
                    self.games = gme[0]
            self.games -= 1
        elif self.cfmat in ("D", "K"):
            self.games = self.sql.getRec("bwlgme", cols=["count(*)"],
                where=[("bcg_cono", "=", self.opts["conum"]),
                ("bcg_ccod", "=", self.ccod), ("bcg_game", "=", 1)],
                limit=1)[0] - 1
        else:
            self.games = chk[self.sql.bwltyp_col.index("bct_games")]
        self.groups = chk[self.sql.bwltyp_col.index("bct_groups")]
        self.grgame = chk[self.sql.bwltyp_col.index("bct_grgame")]
        col = ["bcg_game", "bcg_aflag", "sum(bcg_sfor)",
            "sum(bcg_sagt)", "sum(bcg_points)"]
        game = self.sql.getRec("bwlgme", cols=col, where=[("bcg_cono",
            "=", self.opts["conum"]), ("bcg_ccod", "=", self.ccod)],
            group="bcg_game, bcg_aflag", order="bcg_game")
        self.lgame = 0
        for g in game:
            if not g[1] and not g[2] and not g[3] and not g[4]:
                break
            self.lgame = g[0]
        if not self.lgame:
            return "Knockout or No Completed Games"
        self.df.loadEntry(frt, pag, p+1, data=self.cdes)
        self.df.loadEntry(frt, pag, p+2, data=self.lgame)

    def doLstGam(self, frt, pag, r, c, p, i, w):
        if not w:
            chk = self.sql.getRec("bwlgme", cols=["bcg_game",
                "sum(bcg_points)"], where=[("bcg_cono", "=",
                self.opts["conum"]), ("bcg_ccod", "=", self.ccod)],
                group="bcg_game", order="bcg_game")
            game = 0
            for g in chk:
                if g[1]:
                    game = g[0]
                else:
                    break
            if not game:
                return "No Completed Games"
            self.df.loadEntry(frt, pag, p, data=game)
        else:
            game = w
        chk = self.sql.getRec("bwlgme", cols=["count(*)"],
            where=[("bcg_cono", "=", self.opts["conum"]), ("bcg_ccod",
            "=", self.ccod), ("bcg_game", "=", game), ("bcg_aflag",
            "=", "A")], group="bcg_aflag", limit=1)
        if chk and chk[0]:
            return "Game Abandoned"
        chk = self.sql.getRec("bwlgme", where=[("bcg_cono", "=",
            self.opts["conum"]), ("bcg_ccod", "=", self.ccod), ("bcg_game",
            "=", game), ("bcg_aflag", "in", ("", "D"))])
        if not chk:
            return "Invalid Game Number"
        ptyp = chk[0][self.sql.bwlgme_col.index("bcg_type")]
        pts = self.sql.getRec("bwlpts", where=[("bcp_cono",
            "=", self.opts["conum"]), ("bcp_code", "=", self.ctyp),
            ("bcp_ptyp", "=", ptyp)], limit=1)
        self.ponly = pts[self.sql.bwlpts_col.index("bcp_p_only")]
        non = []
        for ck in chk:
            scod = ck[self.sql.bwlgme_col.index("bcg_scod")]
            ocod = ck[self.sql.bwlgme_col.index("bcg_ocod")]
            if scod > 900000 or ocod > 900000:
                continue
            if self.ponly == "Y":
                fors = ck[self.sql.bwlgme_col.index("bcg_points")]
                agts = self.sql.getRec("bwlgme",
                    cols=["bcg_points"], where=[("bcg_cono", "=",
                    self.opts["conum"]), ("bcg_ccod", "=", self.ccod),
                    ("bcg_game", "=", game), ("bcg_scod", "=", ocod)],
                    limit=1)[0]
            else:
                fors = ck[self.sql.bwlgme_col.index("bcg_sfor")]
                agts = ck[self.sql.bwlgme_col.index("bcg_sagt")]
            if not fors and not agts:
                if scod not in non:
                    non.append(scod)
        if non:
            return "%s Result(s) Not Yet Entered" % int(len(non) / 2)
        self.pgame = w
        if self.pgame == 1:
            self.gamrep = "N"
            self.df.loadEntry(frt, pag, p+1, data=self.gamrep)
            if self.pgame < self.games:
                self.sesp = "N"
                self.sesg = "N"
                self.df.loadEntry(frt, pag, p+1, data=self.sesp)
                self.df.loadEntry(frt, pag, p+2, data=self.sesg)
                return "sk3"
            return "sk1"
        if self.cfmat in ("D", "K", "R") or self.pgame < self.lgame:
            self.df.topf[0][3][5] = "N"
        else:
            self.df.topf[0][3][5] = "Y"

    def doGamRep(self, frt, pag, r, c, p, i, w):
        self.gamrep = w
        if self.cfmat in ("D", "K", "R") or self.pgame < self.lgame:
            self.sesp = "N"
            self.sesg = "N"
            self.df.loadEntry(frt, pag, p+1, data=self.sesp)
            self.df.loadEntry(frt, pag, p+2, data=self.sesg)
            return "sk2"

    def doSesPrz(self, frt, pag, r, c, p, i, w):
        self.sesp = w
        if self.sesp == "N" or self.groups == "N":
            self.sesg = "N"
            self.df.loadEntry(frt, pag, p+1, data=self.sesg)
            return "sk1"

    def doSesGrp(self, frt, pag, r, c, p, i, w):
        self.sesg = w

    def doEnd(self):
        self.df.closeProcess()
        chk = self.sql.getRec("bwlgme", cols=["bcg_group", "bcg_scod"],
            where=[("bcg_cono", "=", self.opts["conum"]), ("bcg_ccod", "=",
            self.ccod), ("bcg_game", "=", self.pgame)], order="bcg_group")
        if chk[0][0] and self.cfmat == "R":
            groups = "Y"
        else:
            groups = self.groups
        self.grps = {}
        for rec in chk:
            if rec[0] not in self.grps:
                self.grps[rec[0]] = [[rec[1]], [], []]
            else:
                self.grps[rec[0]][0].append(rec[1])
        self.keys = list(self.grps.keys())
        self.keys.sort()
        self.fpdf = MyFpdf(name=self.__class__.__name__, head=65)
        self.lastg = None
        for g in self.keys:
            self.pageHeading()
            if self.gamrep == "Y":
                self.doReport("G", g)
                if g == 0 and len(chk) > 20:
                    self.pageHeading()
            self.doReport("M", g)
        if self.pgame == self.games:
            # Enter Prizes
            for key in self.keys:
                if self.cfmat == "R" and groups == "Y":
                    self.grps[key][1] = 0
                else:
                    self.doPrizes(key)
            # Match Winners & Summary
            self.gqty = len(self.keys)
            self.wins = {}
            self.allp = []
            self.swin = []
            self.where = [
                ("bcg_cono", "=", self.opts["conum"]),
                ("bcg_ccod", "=", self.ccod),
                ("bcg_game", "<=", self.pgame),
                ("btb_cono=bcg_cono",),
                ("btb_tab=bcg_scod",)]
            for grp in range(self.gqty):
                if groups == "Y":
                    gcod = grp + 1
                else:
                    gcod = grp
                whr = copyList(self.where)
                whr.append(("bcg_group", "=", gcod))
                col = [
                    "bcg_scod", "btb_surname", "btb_names",
                    "sum(bcg_a_sfor) as sfor",
                    "sum(bcg_a_sagt) as sagt",
                    "sum(bcg_a_sfor - bcg_a_sagt) as agg",
                    "sum(bcg_a_points) as pts"]
                recs = self.sql.getRec(tables=["bwlgme", "bwltab"], cols=col,
                    where=whr, group="bcg_scod, btb_surname, btb_names",
                    order="pts desc, agg desc, sagt asc")
                if not recs:
                    continue
                self.wins[gcod] = []
                for x in range(self.grps[gcod][1]):
                    self.allp.append(recs[x][0])
                    if recs[x][2]:
                        nam = "%s, %s" % (recs[x][1], recs[x][2].split()[0])
                    else:
                        nam = recs[x][1]
                    self.wins[gcod].append(nam)
                if self.cfmat == "R" and groups == "Y":
                    self.swin.append(self.grps[gcod][0][0])
            if self.sesp == "Y":
                self.pageHeading("S")
                self.doSesWin()
            else:
                for grp in self.wins:
                    if self.wins[grp]:
                        self.pageHeading("S")
                        break
            self.doMatchWin()
        pdfnam = getModName(self.opts["mf"].rcdic["wrkdir"],
            self.__class__.__name__, "report", ext="pdf")
        self.fpdf.output(pdfnam, "F")
        if self.df.repeml[1] == "Y":
            if not self.df.repeml[2]:
                col = ["btb_mail"]
                whr = [
                    ("bce_cono", "=", self.opts["conum"]),
                    ("bce_ccod", "=", self.ccod),
                    ("btb_cono=bce_cono",),
                    ("btb_tab=bce_scod",),
                    ("btb_mail", "<>", "")]
                recs = self.sql.getRec(tables=["bwlent", "bwltab"], cols=col,
                    where=whr)
                self.df.repeml[2] = []
                for rec in recs:
                    self.df.repeml[2].append(rec[0])
        head = "%s - Results after game %s" % (self.cdes, self.pgame)
        doPrinter(mf=self.opts["mf"], conum=self.opts["conum"], pdfnam=pdfnam,
            header=head, repprt=self.df.repprt, fromad=self.fromad,
            repeml=self.df.repeml)
        if self.pgame == self.lgame and self.cfmat == "R" and \
                groups == "Y" and not self.poff:
            ok = askQuestion(self.opts["mf"].body, "Play-Offs",
                "Must a Play-Off Draw be Created and/or Printed?",
                default="yes")
            if ok == "yes":
                self.doSecEnd()
        self.opts["mf"].closeLoop()

    def doReport(self, rtyp, grp):
        whr = [
            ("bcg_cono", "=", self.opts["conum"]),
            ("bcg_ccod", "=", self.ccod),
            ("btb_tab=bcg_scod",)]
        col = ["bcg_scod", "btb_surname", "btb_names"]
        if rtyp == "G":
            whr.extend([
                ("bcg_scod", "in", self.grps[grp][0]),
                ("bcg_game", "=", self.pgame)])
            col.extend([
                "sum(bcg_sfor) as sfor",
                "sum(bcg_sagt) as sagt",
                "sum(bcg_sfor - bcg_sagt) as agg",
                "sum(bcg_points) as pts"])
        else:
            whr.extend([
                ("bcg_scod", "in", self.grps[grp][0]),
                ("bcg_game", "<=", self.pgame)])
            if self.pgame <= self.grgame:
                col.extend([
                    "sum(bcg_sfor) as sfor",
                    "sum(bcg_sagt) as sagt",
                    "sum(bcg_sfor - bcg_sagt) as agg",
                    "sum(bcg_points) as pts"])
            else:
                col.extend([
                    "sum(bcg_a_sfor) as sfor",
                    "sum(bcg_a_sagt) as sagt",
                    "sum(bcg_a_sfor - bcg_a_sagt) as agg",
                    "sum(bcg_a_points) as pts"])
        recs = self.sql.getRec(tables=["bwlgme", "bwltab"], cols=col,
            where=whr, group="btb_tab, btb_surname, btb_names",
            order="pts desc, agg desc, sagt asc")
        if not recs:
            return
        self.groupHeading(rtyp, grp)
        if self.cfmat == "X":
            tms = {"H": [0, 0, 0, 0], "V": [0, 0, 0, 0]}
        for num, (scod,snam,fnam,sfor,sagt,agg,pts) in enumerate(recs):
            if fnam:
                nam = "%s, %s" % (snam.upper(), fnam.split()[0].upper())
            else:
                nam = snam.upper()
            a = CCD(num+1, "UI", 3)
            b = CCD(nam, "NA", 30)
            c = CCD(sfor, "SD", 7.1)
            d = CCD(sagt, "SD", 7.1)
            e = CCD(agg, "SD", 7.1)
            f = CCD(pts, "SD", 7.1)
            self.printLine(a.disp, b.disp, c.disp, d.disp, e.disp, f.disp)
            if self.cfmat == "X":
                tm = self.sql.getRec("bwlent", cols=["bce_tcod"],
                    where=[("bce_cono", "=", self.opts["conum"]),
                    ("bce_ccod", "=", self.ccod), ("bce_scod", "=", scod)],
                    limit=1)
                tms[tm[0]][0] = float(ASD(tms[tm[0]][0]) + ASD(c.work))
                tms[tm[0]][1] = float(ASD(tms[tm[0]][1]) + ASD(d.work))
                tms[tm[0]][2] = float(ASD(tms[tm[0]][2]) + ASD(e.work))
                tms[tm[0]][3] = float(ASD(tms[tm[0]][3]) + ASD(f.work))
            self.pglin += 1
        if self.cfmat == "X":
            cwth = self.fpdf.cwth
            self.fpdf.drawText()
            self.fpdf.drawText("Match Summary", font=["courier", "B", 18])
            self.fpdf.setFont(style="B")
            self.fpdf.drawText()
            self.fpdf.drawText("Home", w=cwth * 32, border="TLRB",
                align="C", fill=1, ln=0)
            self.fpdf.drawText("Visitors", w=cwth * 32, border="TLRB",
                align="C", fill=1, ln=1)
            x = self.fpdf.get_x()
            y = self.fpdf.get_y()
            for tm in ("H", "V"):
                self.fpdf.drawText("+For", x=x, y=y, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=1)
                val = CCD(tms[tm][0], "SD", 7.1)
                self.fpdf.drawText(val.disp, x=x, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=0)
                x += (cwth * 8)
                self.fpdf.drawText("-Agt", x=x, y=y, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=1)
                val = CCD(tms[tm][1], "SD", 7.1)
                self.fpdf.drawText(val.disp, x=x, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=0)
                x += (cwth * 8)
                self.fpdf.drawText("=Dif", x=x, y=y, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=1)
                val = CCD(tms[tm][2], "SD", 7.1)
                self.fpdf.drawText(val.disp, x=x, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=0)
                x += (cwth * 8)
                self.fpdf.drawText("Pts", x=x, y=y, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=1)
                val = CCD(tms[tm][3], "SD", 7.1)
                self.fpdf.drawText(val.disp, x=x, w=cwth * 8, h=8,
                    border="TLRB", align="C", fill=0)
                x += (cwth * 8)

    def doSesWin(self):
        # Session Winners
        sess = {}
        for gme in range(1, self.games + 1):
            col = [
                "bcg_scod", "btb_surname", "btb_names",
                "sum(bcg_sfor) as sfor",
                "sum(bcg_sagt) as sagt",
                "sum(bcg_sfor - bcg_sagt) as agg",
                "sum(bcg_points) as pts"]
            whr = copyList(self.where)
            whr.append(("bcg_game", "=", gme))
            grp = "bcg_scod, btb_surname, btb_names"
            odr = "pts desc, agg desc, sagt asc"
            if self.sesg == "Y" and gme > self.grgame:
                col.append("bcg_group")
                grp = "bcg_group, %s" % grp
                odr = "bcg_group, %s" % odr
            recs = self.sql.getRec(tables=["bwlgme", "bwltab"],
                cols=col, where=whr, group=grp, order=odr)
            done = None
            for rec in recs:
                if len(rec) == 7:
                    gpc = 0
                else:
                    gpc = rec[7]
                if gpc == done:
                    continue
                ign = False
                if self.ponly == "Y" and not rec[6]:
                    break
                if self.ponly == "N" and (not rec[3] and not rec[4]):
                    break
                for grp in range(self.gqty):
                    if rec[0] in self.allp:
                        ign = True
                        break
                if not ign:
                    self.allp.append(rec[0])
                    if gme not in sess:
                        sess[gme] = {}
                    if rec[2]:
                        nam = "%s, %s" % (rec[1], rec[2].split()[0])
                    else:
                        nam = rec[1]
                    sess[gme][gpc] = nam
                    done = gpc
        mess = "Session Winners"
        self.fpdf.setFont(style="B", size=14)
        self.fpdf.drawText(mess, align="C", border="TLRB", fill=1)
        self.fpdf.drawText("Ses", w=12, border="TLRB", fill=1, ln=0)
        if self.sesg == "Y":
            self.fpdf.drawText("Grp", w=12, border="TLRB", fill=1, ln=0)
        self.fpdf.drawText("Name", border="TLRB", fill=1)
        self.fpdf.setFont()
        for gme in range(1, self.games + 1):
            stxt = str("%3s" % gme)
            if gme not in sess:
                self.fpdf.drawText(stxt, w=12, border="TLRB", ln=0)
                if self.sesg == "Y":
                    self.fpdf.drawText("", w=12, border="TLRB", ln=0)
                self.fpdf.drawText("* No Valid Winner or Abandoned *",
                    border="TLRB")
                continue
            grps = list(sess[gme].keys())
            grps.sort()
            for grp in grps:
                gtxt = "%3s" % chr(64 + grp)
                self.fpdf.drawText(stxt, w=12, border="TLRB", ln=0)
                if self.sesg == "Y":
                    self.fpdf.drawText(gtxt, w=12, border="TLRB", ln=0)
                self.fpdf.drawText(sess[gme][grp], border="TLRB")
        self.fpdf.drawText()

    def doMatchWin(self):
        for num, gcod in enumerate(self.keys):
            if self.wins[gcod]:
                if gcod:
                    if self.cfmat == "R":
                        mess = "Match Winners - Section %s" % chr(64 + gcod)
                    else:
                        mess = "Match Winners - Group %s" % chr(64 + gcod)
                else:
                    mess = "Match Winners"
                self.fpdf.setFont(style="B", size=14)
                self.fpdf.drawText(mess, align="C", border="TLRB", fill=1)
                self.fpdf.drawText("Pos", w=12, border="TLRB", fill=1,
                    ln=0)
                self.fpdf.drawText("Name", border="TLRB", fill=1)
                self.fpdf.setFont()
                for n, s in enumerate(self.wins[gcod]):
                    ptxt = "%3s" % (n + 1)
                    self.fpdf.drawText(ptxt, w=12, border="TLRB", ln=0)
                    self.fpdf.drawText(s, border="TLRB")
            if not num % 2:
                ly = self.fpdf.get_y()
            if num % 2 and self.fpdf.get_y() > ly:
                ly = self.fpdf.get_y()
            self.fpdf.drawText()
        place = ["1st", "2nd", "3rd"]
        for x in range(4, 21):
            place.append("%sth" % x)
        if self.tsize == 2:
            ppos = ("Skip", "Lead")
        elif self.tsize == 3:
            ppos = ("Skip", "Second", "Lead")
        elif self.tsize == 4:
            ppos = ("Skip", "Third", "Second", "Lead")
        for gcod in self.keys:
            if not self.grps[gcod][2]:
                continue
            for num, skp in enumerate(self.wins[gcod]):
                self.fpdf.add_page()
                self.fpdf.setFont(style="B", size=24)
                self.fpdf.drawText(self.cdes, h=10, align="C")
                self.fpdf.drawText()
                self.fpdf.setFont(style="B", size=18)
                if gcod:
                    self.fpdf.drawText("GROUP %s" % chr(64 + gcod),
                        h=10, align="C")
                    self.fpdf.drawText()
                self.fpdf.drawText("%s Prize R%s - %s" % (place[num],
                    self.grps[gcod][2][num], skp), h=10, align="C")
                self.fpdf.setFont(style="B", size=16)
                for pos in ppos:
                    self.fpdf.drawText()
                    self.fpdf.drawText()
                    self.fpdf.drawText("%s's Name" % pos, w=50, h=8,
                        border="TLRB", ln=0, fill=1)
                    self.fpdf.drawText("", h=8, border="TLRB")
                    self.fpdf.drawText("Bank Name", w=50, h=8,
                        border="TLRB", ln=0, fill=1)
                    self.fpdf.drawText("", h=8, border="TLRB")
                    self.fpdf.drawText("Branch Name", w=50, h=8,
                        border="TLRB", ln=0, fill=1)
                    self.fpdf.drawText("", h=8, border="TLRB")
                    self.fpdf.drawText("Branch Code", w=50, h=8,
                        border="TLRB", ln=0, fill=1)
                    self.fpdf.drawText("", h=8, border="TLRB")
                    self.fpdf.drawText("Account Number", w=50, h=8,
                        border="TLRB", ln=0, fill=1)
                    self.fpdf.drawText("", h=8, border="TLRB")
                self.fpdf.drawText()
                self.fpdf.setFont(style="B", size=18)
                self.fpdf.drawText("Congratulations and Well Done!", h=10,
                    align="C")

    def pageHeading(self, htyp=None):
        self.fpdf.add_page()
        head = "%s - %s" % (self.opts["conam"], self.cdes)
        self.fpdf.drawText(head, font=["courier", "B", 18], align="C")
        if htyp == "S":
            self.fpdf.drawText()
            self.fpdf.drawText("Match Summary", font=["courier", "B", 16],
                align="C")
            self.fpdf.drawText()
            self.pglin = 4
        else:
            self.pglin = 1

    def groupHeading(self, rtyp, group):
        self.fpdf.drawText(font=["courier", "B", 18], align="C")
        if rtyp == "G":
            head = "Results for Game Number: %s" % self.pgame
        else:
            head = "Match Standings After Game Number: %s" % self.pgame
        if group:
            if self.cfmat == "R":
                head += "  for Section: %s" % chr(64 + group)
            else:
                head += "  for Group: %s" % chr(64 + group)
        self.fpdf.drawText(head, font=["courier", "B", 16], align="C")
        self.fpdf.drawText()
        self.fpdf.setFont(style="B")
        self.printLine("Pos", "%-30s" % "Name", "  +For ", "  -Agt ",
            "  =Dif ", "   Pts ", fill=1)
        self.fpdf.setFont()
        self.pglin += 4

    def printLine(self, a, b, c, d, e, f, fill=0):
        x = 10
        w = self.fpdf.get_string_width("X"*len(a)) + 1
        self.fpdf.drawText(a, x=x, w=w, border="TLB", fill=fill, ln=0)
        x += w
        w = self.fpdf.get_string_width("X"*len(b)) + 1
        self.fpdf.drawText(b, x=x, w=w, border="TLB", fill=fill, ln=0)
        x += w
        w = self.fpdf.get_string_width("X"*len(c)) + 1
        self.fpdf.drawText(c, x=x, w=w, border="TLB", fill=fill, ln=0)
        x += w
        w = self.fpdf.get_string_width("X"*len(d)) + 1
        self.fpdf.drawText(d, x=x, w=w, border="TLB", fill=fill, ln=0)
        x += w
        w = self.fpdf.get_string_width("X"*len(e)) + 1
        self.fpdf.drawText(e, x=x, w=w, border="TLB", fill=fill, ln=0)
        x += w
        w = self.fpdf.get_string_width("X"*len(f)) + 1
        self.fpdf.drawText(f, x=x, w=w, border="TLRB", fill=fill)

    def doPrizes(self, grp):
        self.przgrp = grp
        if grp:
            if self.cfmat == "R":
                tit = "Prizes for Section %s" % chr(64 + grp)
            else:
                tit = "Prizes for Group %s" % chr(64 + grp)
        else:
            tit = "Prizes for Match"
        r1s = (("Yes", "Y"), ("No", "N"))
        fld = (
            (("T",0,0,0),"IUI",2,"Number of Prizes","",
                3,"N",self.doPrzNum,None,None,("efld",)),
            (("T",0,1,0),("IRB",r1s),0,"EFT Forms","",
                "N","N",self.doPrzEft,None,None,None),
            (("T",0,2,0),"IUI",5,"1st Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,3,0),"IUI",5,"2nd Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,4,0),"IUI",5,"3rd Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,5,0),"IUI",5,"4th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,6,0),"IUI",5,"5th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,7,0),"IUI",5,"6th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,8,0),"IUI",5,"7th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,9,0),"IUI",5,"8th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,10,0),"IUI",5,"9th Prize","",
                0,"N",self.doPrzAmt,None,None,None),
            (("T",0,11,0),"IUI",5,"10th Prize","",
                0,"N",self.doPrzAmt,None,None,None))
        tnd = ((self.doPrzEnd,"n"),)
        self.pz = TartanDialog(self.opts["mf"], tops=True, title=tit,
            eflds=fld, tend=tnd, txit=None)
        for x in range(10):
            self.pz.setWidget(self.pz.topLabel[0][2+x], state="hide")
            self.pz.setWidget(self.pz.topEntry[0][2+x], state="hide")
        self.pz.mstFrame.wait_window()

    def doPrzNum(self, frt, pag, r, c, p, i, w):
        if not w and self.cfmat != "R":
            ok = askQuestion(self.opts["mf"].body, "Prizes",
                "Are You Sure that there are No Prizes?", default="no")
            if ok == "no":
                return "Invalid Number od Prizes"
        self.prznum = w
        if not self.prznum:
            self.przeft = []
            self.pz.loadEntry(frt, pag, p+1, data="N")
            return "nd"

    def doPrzEft(self, frt, pag, r, c, p, i, w):
        if w == "N":
            self.przeft = []
            return "nd"
        self.przeft = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        for x in range(self.prznum):
            self.pz.setWidget(self.pz.topLabel[0][2+x], state="show")
            self.pz.setWidget(self.pz.topEntry[0][2+x], state="show")
        for x in range(self.prznum, 10):
            self.pz.setWidget(self.pz.topLabel[0][2+x], state="hide")
            self.pz.setWidget(self.pz.topEntry[0][2+x], state="hide")

    def doPrzAmt(self, frt, pag, r, c, p, i, w):
        self.przeft[p-2] = w
        if p == self.prznum + 1:
            return "nd"

    def doPrzEnd(self):
        self.grps[self.przgrp][1] = self.prznum
        self.grps[self.przgrp][2] = self.przeft
        self.pz.closeProcess()

    def doSecEnd(self):
        ccod = getNextCode(self.sql, "bwlcmp", "bcm_code",
            where=[("bcm_cono", "=", self.opts["conum"])], last=999)
        self.sql.updRec("bwlcmp", cols=["bcm_poff"], data=[ccod],
            where=[("bcm_cono", "=", self.opts["conum"]),
            ("bcm_code", "=", self.ccod)])
        cdes = self.cdes + " Play-Off"
        t = time.localtime()
        cdte = ((t[0] * 10000) + (t[1] * 100) + t[2])
        self.sql.insRec("bwlcmp", data=[self.opts["conum"],
            ccod, cdes, cdte, 0, ""])
        for skp in self.swin:
            self.sql.insRec("bwlent", data=[self.opts["conum"],
                ccod, skp, 0, "Y", ""])
        callModule(self.opts["mf"], self.df, "bc2050", coy=[self.opts["conum"],
            self.opts["conam"]], args=ccod)

    def doExit(self):
        self.df.closeProcess()
        self.opts["mf"].closeLoop()
Example #4
0
class bk3010(object):
    def __init__(self, **opts):
        self.opts = opts
        if self.setVariables():
            self.mainProcess()
            if "wait" in self.opts:
                self.df.mstFrame.wait_window()
            else:
                self.opts["mf"].startLoop()

    def setVariables(self):
        self.sql = Sql(self.opts["mf"].dbm, ["bkmmst", "bkmcon", "bkmtrn"],
            prog=self.__class__.__name__)
        if self.sql.error:
            return
        mc = GetCtl(self.opts["mf"])
        bkmctl = mc.getCtl("bkmctl", self.opts["conum"])
        if not bkmctl:
            return
        self.fromad = bkmctl["cbk_emadd"]
        t = time.localtime()
        self.sysdtw = ((t[0] * 10000) + (t[1] * 100) + t[2])
        return True

    def mainProcess(self):
        tit = ("%03i %s" % (self.opts["conum"], self.opts["conam"]),
            "Deposits Due")
        r1s = (("No","N"), ("Yes","Y"))
        r2s = (("Arrival","A"), ("Due","D"))
        fld = (
            (("T",0,0,0),("IRB",r1s),0,"Expired Only","",
                "N","Y",self.doExpired,None,None,None),
            (("T",0,1,0),("IRB",r2s),0,"Order","",
                "A","Y",self.doOrder,None,None,None))
        tnd = ((self.doEnd,"y"),)
        txt = (self.doExit,)
        if "args" in self.opts:
            tops = self.opts["args"]
        else:
            tops = False
        self.df = TartanDialog(self.opts["mf"], tops=tops, title=tit,
            eflds=fld, tend=tnd, txit=txt, view=("Y","V"), mail=("Y","N"))

    def doExpired(self, frt, pag, r, c, p, i, w):
        self.expired = w

    def doOrder(self, frt, pag, r, c, p, i, w):
        self.order = w

    def doEnd(self):
        self.df.closeProcess()
        tab = ["bkmmst"]
        col = [
            "bkm_number",
            "bkm_group",
            "bkm_ccode",
            "bkm_arrive",
            "bkm_depart",
            "bkm_stddep",
            "bkm_stddte",
            "bkm_grpdep",
            "bkm_grpdte",
            "bkm_state"]
        whr = [
            ("bkm_cono", "=", self.opts["conum"]),
            ("bkm_state", "in", ("C", "Q"))]
        if self.order == "A":
            odr = "bkm_arrive, bkm_ccode"
        else:
            odr = "bkm_stddte, bkm_grpdte, bkm_ccode"
        recs = self.sql.getRec(tables=tab, cols=col, where=whr, order=odr)
        self.fpdf = MyFpdf(name=self.__class__.__name__, head=80, auto=True)
        self.fpdf.header = self.pageHeading
        self.fpdf.add_page()
        newrec = []
        for rec in recs:
            if not rec[5] and not rec[7]:
                continue
            num = CCD(rec[0], "UI", 6)
            trn = self.sql.getRec("bkmtrn", where=[("bkt_cono", "=",
                self.opts["conum"]), ("bkt_number", "=", num.work)])
            inv = False
            bal = 0.0
            for tr in trn:
                typ = tr[self.sql.bkmtrn_col.index("bkt_type")]
                amt = tr[self.sql.bkmtrn_col.index("bkt_tramt")]
                bal = float(ASD(bal) + ASD(amt))
                if typ == 2:
                    inv = True
            if inv:
                continue
            dp1 = float(ASD(rec[5]) + ASD(bal))
            dt1 = rec[6]
            if dp1 > 0:
                dp2 = rec[7]
                dt2 = rec[8]
            elif rec[7]:
                dp2 = float(ASD(rec[7]) + ASD(dp1))
                dt2 = rec[8]
                dp1 = 0
            else:
                dp1 = 0
                dp2 = 0
                dt2 = 0
            if self.expired == "Y":
                if dp1 and dt1 > self.sysdtw:
                    continue
                if not dp1 and dp2 and dt2 > self.sysdtw:
                    continue
            elif dp1 <= 0 and dp2 <= 0:
                continue
            if dp1 and dp1 > 0:
                b = CCD(dt1, "D1", 10).disp
                if dp2:
                    b = "%s\n%s" % (b, CCD(dt2, "D1", 10).disp)
            elif dp2 and dp2 > 0:
                b = CCD(dt2, "D1", 10).disp
            else:
                continue
            con = self.sql.getRec("bkmcon", where=[("bkc_cono", "=",
                self.opts["conum"]), ("bkc_ccode", "=", rec[2])], limit=1)
            snam = con[self.sql.bkmcon_col.index("bkc_sname")]
            fnam = con[self.sql.bkmcon_col.index("bkc_names")]
            if fnam:
                c = "%s %s" % (fnam.split()[0], snam)
            else:
                c = snam
            l = 8
            if rec[1]:
                c = "%s\n%s" % (c, rec[1])
                l = 16
            d = CCD(rec[3], "D1", 10).disp
            e = CCD(rec[4], "D1", 10).disp
            if dp1:
                f = CCD(dp1, "UD", 10.2).disp
                if dp2:
                    f = "%s\n%s" % (f, CCD(dp2, "UD", 10.2).disp)
                    l = 16
            else:
                f = CCD(dp2, "UD", 10.2).disp
            newrec.append([num.disp, b, c, d, e, f])
        if newrec:
            if self.order == "D":
                newrec = sorted(newrec, key=itemgetter(1))
            for rec in newrec:
                if self.fpdf.get_y() + l > 260:
                    self.fpdf.add_page()
                self.printLine(rec[0], rec[1], rec[2], rec[3], rec[4], rec[5])
        if self.fpdf.page:
            pdfnam = getModName(self.opts["mf"].rcdic["wrkdir"],
                self.__class__.__name__, self.opts["conum"], ext="pdf")
            self.fpdf.output(pdfnam, "F")
            doPrinter(mf=self.opts["mf"], conum=self.opts["conum"],
                header=self.head, pdfnam=pdfnam, repprt=self.df.repprt,
                fromad=self.fromad, repeml=self.df.repeml)
        if "wait" not in self.opts:
            self.opts["mf"].closeLoop()

    def pageHeading(self):
        cd1 = "%-30s" % self.opts["conam"]
        self.fpdf.drawText(cd1, x=7, font=["courier", "B", 24])
        self.fpdf.drawText(font=["courier", "B", 14])
        if self.expired == "N":
            cd2 = "Deposits Due Report"
        else:
            cd2 = "Deposits Expired Report"
        self.head = "%s - %s" % (cd1, cd2)
        self.fpdf.drawText(cd2, x=7, font=["courier", "B", 16])
        self.fpdf.drawText(font=["courier", "B", 14])
        self.printLine("Number", " Due-Date ", "%-20s" % "Name & Group",
            "  Arrive  ", "  Depart  ", "    Amount", fill=1)

    def printLine(self, a, b, c, d, e, f, fill=0):
        ft = ["courier", "B", 13]
        self.fpdf.set_font(ft[0], ft[1], ft[2])
        c, cq = self.getLines(c, self.fpdf.get_string_width("X"*21))
        f, fq = self.getLines(f, self.fpdf.get_string_width("X"*11))
        if cq > fq:
            ch = 8
            h = cq * 8
            fh = int(h / fq)
        elif fq > cq:
            fh = 8
            h = fq * 8
            ch = int(h / cq)
        else:
            h = cq * 8
            ch = fh = 8
        if cq > 1 or fq > 1:
            ctyp = "M"
        else:
            ctyp = "S"
        # Booking number
        x = 7
        y = self.fpdf.get_y()
        w = self.fpdf.get_string_width("X"*7)
        self.fpdf.drawText(a, x=x, y=y, w=w, h=h, border="TLB",
            fill=fill, ctyp=ctyp, font=ft)
        # Name and group
        x += w
        w = self.fpdf.get_string_width("X"*21)
        self.fpdf.drawText(c, x=x, y=y, w=w, h=ch, border="TLB",
            fill=fill, ctyp=ctyp, font=ft)
        # Arrival date
        x += w
        w = self.fpdf.get_string_width("X"*11)
        self.fpdf.drawText(d, x=x, y=y, w=w, h=h, border="TLB",
            fill=fill, ctyp=ctyp, font=ft)
        # Departure date
        x += w
        w = self.fpdf.get_string_width("X"*11)
        self.fpdf.drawText(e, x=x, y=y, w=w, h=h, border="TLB",
            fill=fill, ctyp=ctyp, font=ft)
        # Deposit due date
        x += w
        w = self.fpdf.get_string_width("X"*11)
        self.fpdf.drawText(b, x=x, y=y, w=0, h=fh, border="TLB",
            fill=fill, ctyp=ctyp, font=ft)
        # Deposit amount
        x += w
        w = self.fpdf.get_string_width("X"*11)
        self.fpdf.drawText(f, x=x, y=y, w=w, h=fh, border="TLRB",
            fill=fill, ctyp=ctyp, font=ft)

    def getLines(self, t, w):
        tmp = t.split("\n")
        nam = self.fpdf.multi_cell(w, 8, tmp[0], split_only=True)
        t = nam[0]
        q = 1
        for n in nam[1:]:
            t = "%s\n%s" % (t, n)
            q += 1
        if len(tmp) > 1:
            nam = self.fpdf.multi_cell(w, 8, tmp[1], split_only=True)
            for n in nam:
                t = "%s\n%s" % (t, n)
                q += 1
        return t, q

    def doExit(self):
        self.df.closeProcess()
        if "wait" not in self.opts:
            self.opts["mf"].closeLoop()
Example #5
0
 def doEnd(self):
     self.df.closeProcess()
     # Get data
     cards = []
     whr = [
         ("bft_cono", "=", self.opts["conum"]),
         ("bft_fmat", "=", self.fmat),
         ("bft_type", "=", self.ftyp),
         ("bft_date", "=", self.date)]
     if self.forms == 4:
         maxf = 8
     else:
         maxf = 3
         whr.append(("bft_position", "=", 1))
     col = ["bft_team", "bft_skip", "bft_player"]
     whr.extend([
         ("bfs_cono=bft_cono",),
         ("bfs_fmat=bft_fmat",),
         ("bfs_code=bft_team",),
         ("bfs_league", "=", "M")])
     recs = self.sql.getRec(tables=["bwlflt", "bwlfls"], cols=col,
         where=whr, order="bft_team, bft_skip, bft_position asc")
     for rec in recs:
         match = self.sql.getRec("bwlflm", cols=["bfm_opps",
             "bfm_venue"], where=[("bfm_cono", "=", self.opts["conum"]),
             ("bfm_fmat", "=", self.fmat), ("bfm_type", "=", self.ftyp),
             ("bfm_date", "=", self.date), ("bfm_team", "=", rec[0])],
             limit=1)
         team = self.sql.getRec("bwlfls", cols=["bfs_desc"],
             where=[("bfs_cono", "=", self.opts["conum"]), ("bfs_fmat", "=",
             self.fmat), ("bfs_code", "=", rec[0])], limit=1)
         opp = self.sql.getRec(tables=["bwlflo", "bwlclb"],
             cols=["bfo_desc", "bcc_name"], where=[("bfo_cono", "=",
             self.opts["conum"]), ("bfo_fmat", "=", self.fmat), ("bfo_code",
             "=", match[0]), ("bcc_code=bfo_club",)], limit=1)
         skp = self.sql.getRec("bwltab", cols=["btb_surname",
             "btb_names"], where=[("btb_cono", "=", self.opts["conum"]),
             ("btb_tab", "=", rec[1])], limit=1)
         if self.forms == 4:
             plr = self.sql.getRec(tables=["bwltab", "bwlflt"],
                 cols=["btb_surname", "btb_names", "bft_position"],
                 where=[("bft_cono", "=", self.opts["conum"]), ("bft_fmat",
                 "=", self.fmat), ("bft_date", "=", self.date),
                 ("bft_skip", "=", rec[1]), ("bft_player", "=", rec[2]),
                 ("btb_cono=bft_cono",), ("btb_tab=bft_player",)], limit=1)
         else:
             plr = self.sql.getRec(tables=["bwltab", "bwlflt"],
                 cols=["btb_surname", "btb_names"], where=[("bft_cono",
                 "=", self.opts["conum"]), ("bft_fmat", "=", self.fmat),
                 ("bft_date", "=", self.date), ("bft_skip", "=", rec[1]),
                 ("btb_cono=bft_cono",), ("btb_tab=bft_player",)],
                 order="bft_position")
         if match[1] == "H":
             ven = self.opts["conam"]
         else:
             ven = "%s" % opp[1]
         if self.forms == 4:
             cards.append([team[0], opp[0], ven, self.getName(skp[0],
                 skp[1]), self.getName(plr[0], plr[1]), plr[2]])
         else:
             card = [team[0], opp[0], ven, "%s, %s" % (skp[0], skp[1])]
             for p in plr:
                 card.append(self.getName(p[0], p[1]))
             cards.append(card)
     while len(cards) % maxf:
         if self.forms == 4:
             cards.append(["", "", "", "", "", 0])
         else:
             cards.append(["", "", "", "", "", "", "", ""])
     # Print
     pdfnam = getModName(self.opts["mf"].rcdic["wrkdir"],
         self.__class__.__name__, "assess_%s" % self.date, ext="pdf")
     fpdf = MyFpdf(name=self.__class__.__name__, head=90)
     cw = fpdf.get_string_width("X")
     ld = 4.5
     if self.forms == 4:
         rr = {
             "margins": ((2.5, 47.5), (1.5, 15.5)),
             "repeat": (2, 4),
             "rows": (
                 (2.5, 1.5, 47.5, 14.5),
                 (2.5, 8.5, (
                     (8, 1.5, .8, "Title", True),
                     (12, 1.5, .8, "Out of %s" % self.rate, True),
                     (27.5, 1.5, .8, "Remarks", True))),
                 (2.5, 10, (
                     (8, 1.5, .9, ("Skip", "Third", "Second", "Lead")),
                     (12, 1.5)), 4))}
     else:
         rr = {
             "margins": ((2.5, 47.5), (1.5, 20.5)),
             "repeat": (1, 3),
             "rows": (
                 (2.5, 1.5, 95.1, 19.5),
                 (2.5, 11, (
                     (10, 2, .8, "Position"),
                     (20, 2, .8, "Name"),
                     (12, 2, .8, "Rating 1-%s" % self.rate),
                     (7, 2, .8, "Initial"),
                     (46.1, 2, .8, "Remarks"))),
                 (2.5, 13, (
                     (10, 2, .9, ("Skip", "Third", "Second", "Lead")),
                     (20, 2), (12, 2), (7, 2)), 4))}
     if self.forms == 4:
         ppad = 1
         h1 = "Assessment Form"
         yy = [2, 18, 34, 50]
     else:
         ppad = 1.5
         h1 = "Assessment Form for %s" % self.disp
         yy = [2.5, 23.5, 44.5]
     for x in range(0, len(cards), maxf):
         fpdf.add_page()
         last, table = doDrawTable(fpdf, rr, ppad, spad=2, cw=cw, ld=ld)
         for y in range(maxf):
             card = cards[x + y]
             if self.forms == 4:
                 if y % 2:
                     xx = 53 * cw
                 else:
                     xx = 5 * cw
                 sx = xx
                 fpdf.setFont("helvetica", "B", 12)
                 fpdf.set_y((yy[int(y / 2)]) * ld)
                 fpdf.drawText(x=xx, w=45 * cw, align="C", txt=h1)
                 fpdf.setFont("helvetica", "B", 8)
                 h2 = "%s vs %s at %s on %s" % (card[0], card[1], card[2],
                     self.disp)
                 fpdf.drawText(x=xx, w=45 * cw, align="C", txt=h2)
                 fpdf.setFont("helvetica", "B", 10)
                 h3 = "Skip: %s    Player: %s" % (card[3], card[4])
                 fpdf.drawText(x=xx, w=45 * cw, align="C", txt=h3)
                 fpdf.drawText(h=2)
                 fpdf.setFont("helvetica", "B", 10)
             else:
                 xx = 3 * cw
                 sx = 25 * cw
                 fpdf.setFont("helvetica", "B", 18)
                 fpdf.set_y((yy[y]) * ld)
                 fpdf.drawText(x=xx, w=90 * cw, h=10, align="C", txt=h1)
                 fpdf.setFont("helvetica", "B", 16)
                 h2 = "%s vs %s at %s on %s" % (card[0], card[1], card[2],
                     self.disp)
                 fpdf.drawText(x=xx, w=90 * cw, h=8, align="C", txt=h2)
                 fpdf.drawText()
                 fpdf.setFont("helvetica", "B", 12)
             w1 = fpdf.get_string_width("XXXXXXXXX")
             w2 = fpdf.get_string_width("XXXXX")
             fpdf.drawText(x=sx + (7 * cw), w=w1, txt="Shots-For", border=1,
                 fill=1, ln=0)
             fpdf.drawText(w=w1, txt="Shots-Agt", border=1, fill=1, ln=0)
             fpdf.drawText(w=w1, txt="   Points", border=1, fill=1, ln=0)
             fpdf.drawText(w=w2, txt="Total", border=1, fill=1)
             if self.sets == "Y":
                 for s in range(1, 3):
                     fpdf.drawText(x=sx, h=5, txt="Set %s" % s, ln=0)
                     fpdf.drawText(x=sx + (7 * cw), w=w1, h=5, txt="",
                         border=1, ln=0)
                     fpdf.drawText(w=w1, h=5, txt="", border=1, ln=0)
                     fpdf.drawText(w=w1, h=5, txt="", border=1, ln=0)
                     if s == 1:
                         fpdf.drawText(w=w2, h=5, txt="", border="LR")
                     else:
                         fpdf.drawText(w=w2, h=5, txt="", border="LRB")
             else:
                 fpdf.drawText(x=sx + (7 * cw), w=w1, h=5, txt="",
                     border=1, ln=0)
                 fpdf.drawText(w=w1, h=5, txt="", border=1, ln=0)
                 fpdf.drawText(w=w1, h=5, txt="", border=1, ln=0)
                 fpdf.drawText(w=w2, h=5, txt="", border=1)
             if self.forms == 1:
                 fpdf.setFont("helvetica", "", 12)
                 r = (y * 21) + 4.5
                 for z in range(4):
                     fpdf.set_xy(13.5 * cw, (9 + (z * 2) + r) * ld)
                     fpdf.drawText(txt=card[4 + z])
             elif self.self == "N" and card[5] in (1,2,3,4):
                 if y % 2:
                     posx = 127
                 else:
                     posx = 25
                 if card[5] == 1:
                     posy = fpdf.get_y() + 10
                 elif card[5] == 2:
                     posy = fpdf.get_y() + 16.75
                 elif card[5] == 3:
                     posy = fpdf.get_y() + 23.5
                 else:
                     posy = fpdf.get_y() + 30.25
                 fpdf.drawText(x=posx, y=posy, txt="XXXXXXX")
     fpdf.output(pdfnam, "F")
     head = "Match Assessment Forms for %s" % self.disp
     doPrinter(mf=self.opts["mf"], header=head, pdfnam=pdfnam,
         repprt=self.df.repprt, fromad=self.fromad, repeml=self.df.repeml)
     self.opts["mf"].closeLoop()