Index: /pykota/trunk/setup.py
===================================================================
--- /pykota/trunk/setup.py (revision 1018)
+++ /pykota/trunk/setup.py (revision 1048)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.17  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
 # Revision 1.16  2003/06/06 20:49:15  jalet
 # Very latest schema. UNTESTED.
@@ -228,5 +231,5 @@
       author_email = "alet@librelogiciel.com",
       url = "http://www.librelogiciel.com/software/",
-      packages = [ "pykota", "pykota.storages", "pykota.requesters", "pykota.loggers", "pykota.accounters" ],
+      packages = [ "pykota", "pykota.storages", "pykota.requesters", "pykota.loggers", "pykota.accounters", "pykota.reporters" ],
       scripts = [ "bin/pykota", "bin/edpykota", "bin/repykota", "bin/warnpykota" ],
       data_files = data_files)
Index: /pykota/trunk/pykota/tool.py
===================================================================
--- /pykota/trunk/pykota/tool.py (revision 1041)
+++ /pykota/trunk/pykota/tool.py (revision 1048)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.42  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
 # Revision 1.41  2003/06/25 14:10:01  jalet
 # Hey, it may work (edpykota --reset excepted) !
@@ -498,3 +501,2 @@
                 self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
         return action        
-    
Index: /pykota/trunk/pykota/reporters/__init__.py
===================================================================
--- /pykota/trunk/pykota/reporters/__init__.py (revision 1048)
+++ /pykota/trunk/pykota/reporters/__init__.py (revision 1048)
@@ -0,0 +1,21 @@
+# PyKota
+#
+# PyKota : Print Quotas for CUPS and LPRng
+#
+# (c) 2003 Jerome Alet <alet@librelogiciel.com>
+# 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 2 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
Index: /pykota/trunk/pykota/reporters/text.py
===================================================================
--- /pykota/trunk/pykota/reporters/text.py (revision 1048)
+++ /pykota/trunk/pykota/reporters/text.py (revision 1048)
@@ -0,0 +1,104 @@
+#! /usr/bin/env python
+
+# PyKota - Print Quotas for CUPS and LPRng
+#
+# (c) 2003 Jerome Alet <alet@librelogiciel.com>
+# 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 2 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
+# $Log$
+# Revision 1.1  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
+#
+#
+
+import sys
+
+from mx import DateTime
+
+from pykota.reporter import BaseReporter, PyKotaReporterError
+    
+class Reporter(BaseReporter) :    
+    """Base class for all PyKota command line tools."""
+    def generateReport(self) :
+        """Produces a simple text report."""
+        self.report = []
+        for printer in self.printers :
+            self.report.append(_("*** Report for %s quota on printer %s") % ((self.isgroup and "group") or "user", printer.Name))
+            self.report.append(_("Pages grace time: %i days") % self.tool.config.getGraceDelay(printer.Name))
+            if printer.PricePerJob is not None :
+                self.report.append(_("Price per job: %.3f") % printer.PricePerJob)
+            if printer.PricePerPage is not None :    
+                self.report.append(_("Price per page: %.3f") % printer.PricePerPage)
+            total = 0
+            totalmoney = 0.0
+            if self.isgroup :
+                self.report.append(_("Group           used    soft    hard    balance grace         total       paid"))
+                self.report.append("------------------------------------------------------------------------------")
+                for (group, grouppquota) in self.tool.storage.getPrinterGroupsAndQuotas(printer, self.ugnames) :
+                    (pages, money) = self.printQuota(group, grouppquota)
+                    total += pages
+                    totalmoney += money
+            else :
+                # default is user quota report
+                self.report.append(_("User            used    soft    hard    balance grace         total       paid"))
+                self.report.append("------------------------------------------------------------------------------")
+                for (user, userpquota) in self.tool.storage.getPrinterUsersAndQuotas(printer, self.ugnames) :
+                    (pages, money) = self.printQuota(user, userpquota)
+                    total += pages
+                    totalmoney += money
+            if total or totalmoney :        
+                self.report.append((" " * 50) + (_("Total : %9i") % total) + ("%11s" % ("%7.2f" % totalmoney)[:11]))
+            try :
+                msg = "%9i" % printer.LastJob.PrinterPageCounter
+            except TypeError :     
+                msg = _("unknown")
+            self.report.append((" " * 51) + (_("Real : %s") % msg))
+            self.report.append("")        
+        if self.isgroup :    
+            self.report.append(_("Totals may be inaccurate if some users are members of several groups."))
+        return "\n".join(self.report)    
+                        
+    def printQuota(self, entry, quota) :
+        """Prints the quota information."""
+        lifepagecounter = int(quota.LifePageCounter or 0)
+        pagecounter = int(quota.PageCounter or 0)
+        balance = float(entry.AccountBalance or 0.0)
+        lifetimepaid = float(entry.LifeTimePaid or 0.0)
+        
+        if quota.DateLimit is not None :
+            now = DateTime.now()
+            datelimit = DateTime.ISO.ParseDateTime(quota.DateLimit)
+            if now >= datelimit :
+                datelimit = "DENY"
+        elif (quota.HardLimit is not None) and (pagecounter >= quota.HardLimit) :    
+            datelimit = "DENY"
+        elif (quota.HardLimit is None) and (quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) :
+            datelimit = "DENY"
+        else :    
+            datelimit = ""
+            
+        if entry.LimitBy.lower() == "balance" :    
+            reached = (((balance <= 0) and "+") or "-") + "B"
+        else :
+            reached = (((quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) and "+") or "-") + "Q"
+            
+        strbalance = ("%5.2f" % balance)[:10]
+        strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
+        self.report.append("%-9.9s %s %7i %7s %7s %10s %-10.10s %8i %10s" % (entry.Name, reached, pagecounter, str(quota.SoftLimit), str(quota.HardLimit), strbalance, str(datelimit)[:10], lifepagecounter, strlifetimepaid))
+        return (lifepagecounter, lifetimepaid)
+    
Index: /pykota/trunk/pykota/reporter.py
===================================================================
--- /pykota/trunk/pykota/reporter.py (revision 1048)
+++ /pykota/trunk/pykota/reporter.py (revision 1048)
@@ -0,0 +1,54 @@
+# PyKota
+#
+# PyKota : Print Quotas for CUPS and LPRng
+#
+# (c) 2003 Jerome Alet <alet@librelogiciel.com>
+# 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 2 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, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
+#
+# $Id$
+#
+# $Log$
+# Revision 1.1  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
+#
+#
+
+class PyKotaReporterError(Exception):
+    """An exception for Reporter related stuff."""
+    def __init__(self, message = ""):
+        self.message = message
+        Exception.__init__(self, message)
+    def __repr__(self):
+        return self.message
+    __str__ = __repr__
+    
+class BaseReporter :    
+    """Base class for all reports."""
+    def __init__(self, tool, printers, ugnames, isgroup) :
+        """Initialize local datas."""
+        self.tool = tool
+        self.printers = printers
+        self.ugnames = ugnames
+        self.isgroup = isgroup
+        
+def openReporter(tool, reporttype, printers, ugnames, isgroup) :
+    """Returns a reporter instance of the proper reporter."""
+    try :
+        exec "from pykota.reporters import %s as reporterbackend" % reporttype.lower()    
+    except ImportError :
+        raise PyKotaReporterError, _("Unsupported reporter backend %s") % reporttype
+    else :    
+        return getattr(reporterbackend, "Reporter")(tool, printers, ugnames, isgroup)
Index: /pykota/trunk/cgi-bin/printquota.cgi
===================================================================
--- /pykota/trunk/cgi-bin/printquota.cgi (revision 952)
+++ /pykota/trunk/cgi-bin/printquota.cgi (revision 1048)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.7  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
 # Revision 1.6  2003/04/23 22:13:56  jalet
 # Preliminary support for LPRng added BUT STILL UNTESTED.
@@ -48,4 +51,9 @@
 import os
 import cgi
+
+from pykota import version
+from pykota.tool import PyKotaTool, PyKotaToolError
+from pykota.config import PyKotaConfigError
+from pykota.storage import PyKotaStorageError
 
 header = """Content-type: text/html
Index: /pykota/trunk/bin/repykota
===================================================================
--- /pykota/trunk/bin/repykota (revision 1041)
+++ /pykota/trunk/bin/repykota (revision 1048)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.40  2003/06/30 12:46:15  jalet
+# Extracted reporting code.
+#
 # Revision 1.39  2003/06/25 14:10:01  jalet
 # Hey, it may work (edpykota --reset excepted) !
@@ -160,4 +163,6 @@
 from pykota.config import PyKotaConfigError
 from pykota.storage import PyKotaStorageError
+from pykota.reporter import PyKotaReporterError
+from pykota import reporter
 
 __doc__ = """repykota v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
@@ -241,67 +246,7 @@
         if not printers :
             raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
-        for printer in printers :
-            print _("*** Report for %s quota on printer %s") % ((options["groups"] and "group") or "user", printer.Name)
-            print _("Pages grace time: %i days") % self.config.getGraceDelay(printer.Name)
-            if printer.PricePerJob is not None :
-                print _("Price per job: %.3f") % printer.PricePerJob
-            if printer.PricePerPage is not None :    
-                print _("Price per page: %.3f") % printer.PricePerPage
-            total = 0
-            totalmoney = 0.0
-            if options["groups"] :
-                print _("Group           used    soft    hard    balance grace         total       paid") 
-                print "------------------------------------------------------------------------------"
-                for (group, grouppquota) in self.storage.getPrinterGroupsAndQuotas(printer, ugnames) :
-                    (pages, money) = self.printQuota(group, grouppquota)
-                    total += pages
-                    totalmoney += money
-            else :
-                # default is user quota report
-                print _("User            used    soft    hard    balance grace         total       paid") 
-                print "------------------------------------------------------------------------------"
-                for (user, userpquota) in self.storage.getPrinterUsersAndQuotas(printer, ugnames) :
-                    (pages, money) = self.printQuota(user, userpquota)
-                    total += pages
-                    totalmoney += money
-            if total or totalmoney :        
-                print (" " * 50) + (_("Total : %9i") % total) + ("%11s" % ("%7.2f" % totalmoney)[:11])
-            try :
-                msg = "%9i" % printer.LastJob.PrinterPageCounter
-            except TypeError :     
-                msg = _("unknown")
-            print (" " * 51) + (_("Real : %s") % msg)
-            print        
-        if options["groups"] :    
-            print _("Totals may be inaccurate if some users are members of several groups.")
-                        
-    def printQuota(self, entry, quota) :
-        """Prints the quota information."""
-        lifepagecounter = int(quota.LifePageCounter or 0)
-        pagecounter = int(quota.PageCounter or 0)
-        balance = float(entry.AccountBalance or 0.0)
-        lifetimepaid = float(entry.LifeTimePaid or 0.0)
-        
-        if quota.DateLimit is not None :
-            now = DateTime.now()
-            datelimit = DateTime.ISO.ParseDateTime(quota.DateLimit)
-            if now >= datelimit :
-                datelimit = "DENY"
-        elif (quota.HardLimit is not None) and (pagecounter >= quota.HardLimit) :    
-            datelimit = "DENY"
-        elif (quota.HardLimit is None) and (quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) :
-            datelimit = "DENY"
-        else :    
-            datelimit = ""
             
-        if entry.LimitBy.lower() == "balance" :    
-            reached = (((balance <= 0) and "+") or "-") + "B"
-        else :
-            reached = (((quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) and "+") or "-") + "Q"
-            
-        strbalance = ("%5.2f" % balance)[:10]
-        strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
-        print "%-9.9s %s %7i %7s %7s %10s %-10.10s %8i %10s" % (entry.Name, reached, pagecounter, str(quota.SoftLimit), str(quota.HardLimit), strbalance, str(datelimit)[:10], lifepagecounter, strlifetimepaid)
-        return (lifepagecounter, lifetimepaid)
+        self.reportingtool = reporter.openReporter(self, "text", printers, ugnames, (options["groups"] and 1) or 0)    
+        print self.reportingtool.generateReport()
                     
 if __name__ == "__main__" : 
@@ -314,8 +259,8 @@
         
         # Initializes the command line tool
-        reporter = RePyKota(doc=__doc__)
+        reportTool = RePyKota(doc=__doc__)
         
         # parse and checks the command line
-        (options, args) = reporter.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
+        (options, args) = reportTool.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
         
         # sets long options
@@ -327,12 +272,12 @@
         
         if options["help"] :
-            reporter.display_usage_and_quit()
+            reportTool.display_usage_and_quit()
         elif options["version"] :
-            reporter.display_version_and_quit()
+            reportTool.display_version_and_quit()
         elif options["users"] and options["groups"] :    
             raise PyKotaToolError, _("incompatible options, see help.")
         else :
-            sys.exit(reporter.main(args, options))
-    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :            
+            sys.exit(reportTool.main(args, options))
+    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError, PyKotaReporterError), msg :            
         sys.stderr.write("%s\n" % msg)
         sys.stderr.flush()
