root / pykota / trunk / bin / repykota @ 975

Revision 975, 11.8 kB (checked in by jalet, 21 years ago)

Better error handling.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2
3# PyKota Print Quota Reports generator
4#
5# PyKota - Print Quotas for CUPS and LPRng
6#
7# (c) 2003 Jerome Alet <alet@librelogiciel.com>
8# This program is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This program is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this program; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
21#
22# $Id$
23#
24# $Log$
25# Revision 1.34  2003/04/29 22:03:38  jalet
26# Better error handling.
27#
28# Revision 1.33  2003/04/28 08:25:48  jalet
29# Small display bug in repykota was fixed.
30#
31# Revision 1.32  2003/04/23 22:13:56  jalet
32# Preliminary support for LPRng added BUT STILL UNTESTED.
33#
34# Revision 1.31  2003/04/23 09:58:17  jalet
35# Prices per page/job are now displayed
36#
37# Revision 1.30  2003/04/18 08:34:51  jalet
38# Minor fix.
39#
40# Revision 1.29  2003/04/18 08:29:30  jalet
41# Minor bug fix
42#
43# Revision 1.28  2003/04/17 09:36:30  jalet
44# Bad alignment in output
45#
46# Revision 1.27  2003/04/17 09:26:21  jalet
47# repykota now reports account balances too.
48#
49# Revision 1.26  2003/04/16 12:35:49  jalet
50# Groups quota work now !
51#
52# Revision 1.25  2003/04/15 11:30:57  jalet
53# More work done on money print charging.
54# Minor bugs corrected.
55# All tools now access to the storage as priviledged users, repykota excepted.
56#
57# Revision 1.24  2003/04/14 20:05:20  jalet
58# Reversed test.
59#
60# Revision 1.23  2003/04/11 14:42:54  jalet
61# Translations
62#
63# Revision 1.21  2003/04/10 21:47:20  jalet
64# Job history added. Upgrade script neutralized for now !
65#
66# Revision 1.20  2003/04/08 21:31:39  jalet
67# (anything or 0) = anything !!! Go back to school Jerome !
68#
69# Revision 1.19  2003/04/08 21:13:44  jalet
70# Prepare --groups option to work.
71#
72# Revision 1.18  2003/04/08 21:10:18  jalet
73# Checks --groups option presence instead of --users because --users is the default.
74#
75# Revision 1.17  2003/03/29 13:45:27  jalet
76# GPL paragraphs were incorrectly (from memory) copied into the sources.
77# Two README files were added.
78# Upgrade script for PostgreSQL pre 1.01 schema was added.
79#
80# Revision 1.16  2003/03/09 23:56:21  jalet
81# Option noquota added to do accounting only.
82#
83# Revision 1.15  2003/03/09 23:39:14  jalet
84# Simplified translations.
85#
86# Revision 1.14  2003/02/27 09:04:02  jalet
87# Missing translation
88#
89# Revision 1.13  2003/02/27 08:44:01  jalet
90# Check to see if the printer was ever used at all, and displays "unknown"
91# as the pagecounter value in this casCheck to see if the printer was ever used at all, and displays "unknown"
92# as the pagecounter value in this case.
93#
94# Revision 1.12  2003/02/17 23:02:23  jalet
95# getGraceDelay for printer
96#
97# Revision 1.11  2003/02/10 12:12:34  jalet
98# Translations.
99#
100# Revision 1.10  2003/02/10 12:07:30  jalet
101# Now repykota should output the recorded total page number for each printer too.
102#
103# Revision 1.9  2003/02/09 13:40:29  jalet
104# typo
105#
106# Revision 1.8  2003/02/09 12:56:53  jalet
107# Internationalization begins...
108#
109# Revision 1.7  2003/02/08 23:17:20  jalet
110# repykota now outputs life time page counters and the total pages printed by
111# all users/groups on each printer.
112#
113# Revision 1.6  2003/02/07 23:39:16  jalet
114# Typos
115#
116# Revision 1.5  2003/02/07 08:38:36  jalet
117# Missing conversion.
118# empty line between two printers
119#
120# Revision 1.4  2003/02/07 08:34:15  jalet
121# Test wrt date limit was wrong
122#
123# Revision 1.3  2003/02/07 00:08:52  jalet
124# Typos
125#
126# Revision 1.2  2003/02/06 23:58:05  jalet
127# repykota should be ok
128#
129#
130#
131
132import sys
133
134from mx import DateTime
135
136from pykota import version
137from pykota.tool import PyKotaTool, PyKotaToolError
138from pykota.config import PyKotaConfigError
139from pykota.storage import PyKotaStorageError
140
141__doc__ = """repykota v%s (C) 2003 C@LL - Conseil Internet & Logiciels Libres
142
143Generates print quota reports.
144
145command line usage :
146
147  repykota [options]
148
149options :
150
151  -v | --version       Prints repykota's version number then exits.
152  -h | --help          Prints this message then exits.
153 
154  -u | --users         Generates a report on users quota, this is
155                       the default.
156 
157  -g | --groups        Generates a report on group quota instead of users.
158 
159  -P | --printer p     Report quotas on this printer only. Actually p can
160                       use wildcards characters to select only
161                       some printers. The default value is *, meaning
162                       all printers.
163 
164examples :                             
165
166  $ repykota --printer lp
167 
168  This will print the quota status for all users who use the lp printer.
169
170  $ repykota
171 
172  This will print the quota status for all users on all printers.
173
174This program is free software; you can redistribute it and/or modify
175it under the terms of the GNU General Public License as published by
176the Free Software Foundation; either version 2 of the License, or
177(at your option) any later version.
178
179This program is distributed in the hope that it will be useful,
180but WITHOUT ANY WARRANTY; without even the implied warranty of
181MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
182GNU General Public License for more details.
183
184You should have received a copy of the GNU General Public License
185along with this program; if not, write to the Free Software
186Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
187
188Please e-mail bugs to: %s""" % (version.__version__, version.__author__)
189       
190class RePyKota(PyKotaTool) :       
191    """A class for repykota."""
192    def __init__(self, doc) :
193        """Initializes the tool as a non-priviledged storage user."""
194        PyKotaTool.__init__(self, asadmin=0, doc=doc)
195       
196    def main(self, options) :
197        """Print Quota reports generator."""
198        printers = self.storage.getMatchingPrinters(options["printer"])
199        if not printers :
200            raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
201        for (printerid, printer) in printers :
202            print _("*** Report for %s quota on printer %s") % ((options["groups"] and "group") or "user", printer)
203            print _("Pages grace time: %i days") % self.config.getGraceDelay(printer)
204            prices = self.storage.getPrinterPrices(printerid)
205            if prices is None :
206                (perpage, perjob) = (None, None)
207            else :   
208                (perpage, perjob) = prices
209            if perjob is not None :
210                print _("Price per job: %.3f") % perjob
211            if perpage is not None :   
212                print _("Price per page: %.3f") % perpage
213            total = 0
214            totalmoney = 0.0
215            if options["groups"] :
216                print _("Group           used    soft    hard    balance grace         total       paid") 
217                print "------------------------------------------------------------------------------"
218                for (ident, name) in self.storage.getPrinterGroups(printerid) :
219                    quota = self.storage.getGroupPQuota(ident, printerid) 
220                    balance = self.storage.getGroupBalance(ident)
221                    limitby = self.storage.getGroupLimitBy(ident)
222                    (pages, money) = self.printQuota(name, quota, balance, limitby)
223                    total += pages
224                    totalmoney += money
225            else :
226                # default is user quota report
227                print _("User            used    soft    hard    balance grace         total       paid") 
228                print "------------------------------------------------------------------------------"
229                for (ident, name) in self.storage.getPrinterUsers(printerid) :
230                    quota = self.storage.getUserPQuota(ident, printerid)
231                    balance = self.storage.getUserBalance(ident)
232                    limitby = self.storage.getUserLimitBy(ident)
233                    (pages, money) = self.printQuota(name, quota, balance, limitby)
234                    total += pages
235                    totalmoney += money
236            if total or totalmoney :       
237                print (" " * 50) + (_("Total : %9i") % total) + ("%11s" % ("%7.2f" % totalmoney)[:11])
238            printerpagecounter = self.storage.getPrinterPageCounter(printerid)
239            try :
240                msg = "%9i" % printerpagecounter["pagecounter"]
241            except TypeError :     
242                msg = _("unknown")
243            print (" " * 51) + (_("Real : %s") % msg)
244            print       
245        if options["groups"] :   
246            print _("Totals may be inaccurate if some users are members of several groups.")
247                       
248    def printQuota(self, name, quota, balance, limitby) :
249        """Prints the quota information."""
250        if quota is not None :
251            lifepagecounter = quota["lifepagecounter"] or 0
252            pagecounter = quota["pagecounter"] or 0
253            softlimit = quota["softlimit"]
254            hardlimit = quota["hardlimit"]
255            datelimit = quota["datelimit"]
256            if balance is not None :
257                (balance, lifetimepaid) = balance
258            else :   
259                (balance, lifetimepaid) = 0.0
260            if datelimit is not None :
261                now = DateTime.now()
262                datelimit = DateTime.ISO.ParseDateTime(datelimit)
263                if now >= datelimit :
264                    datelimit = "DENY"
265            else :   
266                datelimit = ""
267            if limitby == "balance" :   
268                reached = (((balance <= 0) and "+") or "-") + "B"
269            else :
270                reached = (((softlimit is not None) and (pagecounter >= softlimit) and "+") or "-") + "Q"
271            balance = balance or 0.0   
272            lifetimepaid = lifetimepaid or 0.0
273            strbalance = ("%5.2f" % balance)[:10]
274            strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
275            print "%-9.9s %s %7i %7s %7s %10s %-10.10s %8i %10s" % (name, reached, pagecounter, str(softlimit), str(hardlimit), strbalance, str(datelimit)[:10], lifepagecounter, strlifetimepaid)
276            return (lifepagecounter, lifetimepaid)
277       
278                   
279if __name__ == "__main__" : 
280    try :
281        defaults = { \
282                     "printer" : "*", \
283                   }
284        short_options = "vhugP:"
285        long_options = ["help", "version", "users", "groups", "printer="]
286       
287        # Initializes the command line tool
288        reporter = RePyKota(doc=__doc__)
289       
290        # parse and checks the command line
291        (options, args) = reporter.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
292       
293        # sets long options
294        options["help"] = options["h"] or options["help"]
295        options["version"] = options["v"] or options["version"]
296        options["users"] = options["u"] or options["users"]
297        options["groups"] = options["g"] or options["groups"]
298        options["printer"] = options["P"] or options["printer"] or defaults["printer"]
299       
300        if options["help"] :
301            reporter.display_usage_and_quit()
302        elif options["version"] :
303            reporter.display_version_and_quit()
304        elif options["users"] and options["groups"] :   
305            raise PyKotaToolError, _("incompatible options, see help.")
306        elif args :   
307            raise PyKotaToolError, _("unused arguments [%s]. Aborting.") % ", ".join(args)
308        else :
309            sys.exit(reporter.main(options))
310    except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :           
311        sys.stderr.write("%s\n" % msg)
312        sys.stderr.flush()
313        sys.exit(-1)
Note: See TracBrowser for help on using the browser.