root / pykota / trunk / pykota / reporter.py @ 2945

Revision 2945, 6.6 kB (checked in by jerome, 18 years ago)

Replaced the 'exec' statements with the use of the standard 'imp' module.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
Line 
1# PyKota
2# -*- coding: ISO-8859-15 -*-
3#
4# PyKota : Print Quotas for CUPS and LPRng
5#
6# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20#
21# $Id$
22#
23#
24
25import os
26import imp
27from mx import DateTime
28
29class PyKotaReporterError(Exception):
30    """An exception for Reporter related stuff."""
31    def __init__(self, message = ""):
32        self.message = message
33        Exception.__init__(self, message)
34    def __repr__(self):
35        return self.message
36    __str__ = __repr__
37   
38class BaseReporter :   
39    """Base class for all reports."""
40    def __init__(self, tool, printers, ugnames, isgroup) :
41        """Initialize local datas."""
42        self.tool = tool
43        self.printers = printers
44        self.ugnames = ugnames
45        self.isgroup = isgroup
46       
47    def getPrinterTitle(self, printer) :     
48        return (_("Report for %s quota on printer %s") % ((self.isgroup and "group") or "user", printer.Name)) + (" (%s)" % printer.Description)
49       
50    def getPrinterGraceDelay(self, printer) :   
51        return _("Pages grace time: %i days") % self.tool.config.getGraceDelay(printer.Name)
52       
53    def getPrinterPrices(self, printer) :   
54        return (_("Price per job: %.3f") % (printer.PricePerJob or 0.0), _("Price per page: %.3f") % (printer.PricePerPage or 0.0))
55           
56    def getReportHeader(self) :       
57        if self.isgroup :
58            return _("Group          overcharge   used    soft    hard    balance grace         total       paid warn")
59        else :   
60            return _("User           overcharge   used    soft    hard    balance grace         total       paid warn")
61           
62    def getPrinterRealPageCounter(self, printer) :       
63        msg = _("unknown")
64        if printer.LastJob.Exists :
65            try :
66                msg = "%9i" % printer.LastJob.PrinterPageCounter
67            except TypeError :     
68                pass
69        return _("Real : %s") % msg
70               
71    def getTotals(self, total, totalmoney) :           
72        return (_("Total : %9i") % (total or 0.0), ("%11s" % ("%7.2f" % (totalmoney or 0.0))[:11]))
73           
74    def getQuota(self, entry, quota) :
75        """Prints the quota information."""
76        lifepagecounter = int(quota.LifePageCounter or 0)
77        pagecounter = int(quota.PageCounter or 0)
78        balance = float(entry.AccountBalance or 0.0)
79        lifetimepaid = float(entry.LifeTimePaid or 0.0)
80        if not hasattr(entry, "OverCharge") :
81            overcharge = _("N/A")       # Not available for groups
82        else :   
83            overcharge = float(entry.OverCharge or 0.0)
84        if not hasattr(quota, "WarnCount") :   
85            warncount = _("N/A")        # Not available for groups
86        else :   
87            warncount = int(quota.WarnCount or 0)
88       
89        if (not entry.LimitBy) or (entry.LimitBy.lower() == "quota") :
90            if (quota.HardLimit is not None) and (pagecounter >= quota.HardLimit) :   
91                datelimit = "DENY"
92            elif (quota.HardLimit is None) and (quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) :
93                datelimit = "DENY"
94            elif quota.DateLimit is not None :
95                now = DateTime.now()
96                datelimit = DateTime.ISO.ParseDateTime(str(quota.DateLimit))
97                if now >= datelimit :
98                    datelimit = "DENY"
99            else :   
100                datelimit = ""
101            reached = (((quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) and "+") or "-") + "Q"
102        else :
103            if entry.LimitBy.lower() == "balance" :
104                balancezero = self.tool.config.getBalanceZero()
105                if balance == balancezero :
106                    if entry.OverCharge > 0 :
107                        datelimit = "DENY"
108                        reached = "+B"
109                    else :   
110                        # overcharging by a negative or nul factor means user is always allowed to print
111                        # TODO : do something when printer prices are negative as well !
112                        datelimit = ""
113                        reached = "-B"
114                elif balance < balancezero :
115                    datelimit = "DENY"
116                    reached = "+B"
117                elif balance <= self.tool.config.getPoorMan() :
118                    datelimit = "WARNING"
119                    reached = "?B"
120                else :   
121                    datelimit = ""
122                    reached = "-B"
123            elif entry.LimitBy.lower() == "noquota" :
124                reached = "NQ"
125                datelimit = ""
126            elif entry.LimitBy.lower() == "nochange" :
127                reached = "NC"
128                datelimit = ""
129            else :
130                # noprint
131                reached = "NP"
132                datelimit = "DENY"
133           
134        strbalance = ("%5.2f" % balance)[:10]
135        strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
136        strovercharge = ("%5s" % overcharge)[:5]
137        strwarncount = ("%4s" % warncount)[:4]
138        return (lifepagecounter, lifetimepaid, entry.Name, reached, \
139                pagecounter, str(quota.SoftLimit), str(quota.HardLimit), \
140                strbalance, str(datelimit)[:10], lifepagecounter, \
141                strlifetimepaid, strovercharge, strwarncount)
142       
143def openReporter(tool, reporttype, printers, ugnames, isgroup) :
144    """Returns a reporter instance of the proper reporter."""
145    try :
146        reporterbackend = imp.load_source("reporterbackend", 
147                                           os.path.join(os.path.dirname(__file__),
148                                                        "reporters",
149                                                        "%s.py" % reporttype.lower()))
150    except ImportError :
151        raise PyKotaReporterError, _("Unsupported reporter backend %s") % reporttype
152    else :   
153        return reporterbackend.Reporter(tool, printers, ugnames, isgroup)
Note: See TracBrowser for help on using the browser.