root / pykota / trunk / bin / pkbcodes @ 2765

Revision 2765, 8.5 kB (checked in by jerome, 18 years ago)

Optimized pkbcodes like edpykota.

  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKota Billing Codes manager
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22#
23# $Id$
24#
25#
26
27import os
28import sys
29import pwd
30
31from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, crashed, N_
32from pykota.storage import StorageBillingCode
33
34__doc__ = N_("""pkbcodes v%(__version__)s (c) %(__years__)s %(__author__)s
35
36A billing codes Manager for PyKota.
37
38command line usage :
39
40  pkbcodes [options] code1 code2 code3 ... codeN
41
42options :
43
44  -v | --version       Prints pkbcodes version number then exits.
45  -h | --help          Prints this message then exits.
46 
47  -a | --add           Adds billing codes if they don't exist in PyKota's
48                       database. If they exist, they are modified
49                       unless -s|--skipexisting is also used.
50
51  -d | --delete        Deletes billing codes from PyKota's database.
52                       NB : the history entries with this billing code
53                       are not deleted, voluntarily.
54
55  -D | --description d Adds a textual description to billing codes.
56
57  -l | --list          List informations about the billing codes.
58
59  -r | --reset         Resets the billing codes' balance and page counters
60                       to 0.
61
62  -s | --skipexisting  In combination with the --add option above, tells
63                       pkbcodes to not modify existing billing codes.
64
65  code1 through codeN can contain wildcards if the --add option
66  is not set.
67
68examples :                             
69
70  $ pkbcodes --add -D "My project" myproj
71
72  Will create the myproj billing code with "My project"
73  as the description.
74
75  $ pkbcodes --delete "*"
76
77  This will completely delete all the billing codes, but without
78  removing any matching job from the history. USE WITH CARE ANYWAY !
79 
80  $ pkbcodes --list "my*"
81 
82  This will list all billing codes which name begins with 'my'.
83""")
84       
85class PKBcodes(PyKotaTool) :       
86    """A class for a billing codes manager."""
87    def modifyBillingCode(self, billingcode, reset, description) :
88        """Modifies a billing code."""
89        if reset :
90            billingcode.reset()   
91        if description is not None : # NB : "" is allowed !
92            billingcode.setDescription(description)
93       
94    def main(self, names, options) :
95        """Manage billing codes."""
96        if (not self.config.isAdmin) and (not options["list"]) :
97            raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
98           
99        if not options["add"] :
100            if not options["list"] :
101                self.display(_("Extracting datas..."))
102            if not names :      # NB : can't happen for --delete because it's catched earlier
103                names = ["*"]
104            billingcodes = self.storage.getMatchingBillingCodes(",".join(names))
105            if not billingcodes :
106                raise PyKotaCommandLineError, _("There's no billingcode matching %s") % " ".join(names)
107                       
108        reset = options["reset"]
109        description = options["description"]
110        if description :
111            description = options["description"].strip()
112               
113        if options["delete"] :   
114            self.display("\n%s..." % _("Deletion"))
115            self.storage.deleteManyBillingCodes(billingcodes)
116            self.display("\n")
117        elif options["add"] :   
118            self.display("%s...\n" % _("Creation"))
119            nbtotal = len(names)
120            for i in range(nbtotal) :
121                bname = names[i]
122                billingcode = StorageBillingCode(self.storage, bname)
123                self.modifyBillingCode(billingcode, reset, description)
124                oldbillingcode = self.storage.addBillingCode(billingcode)
125                if oldbillingcode is not None :
126                    if options["skipexisting"] :
127                        self.printInfo(_("Billing code [%s] already exists, skipping.") % bname)
128                    else :   
129                        self.printInfo(_("Billing code [%s] already exists, will be modified.") % bname)
130                        self.modifyBillingCode(oldbillingcode, reset, description)
131                        oldbillingcode.save()
132                percent = 100.0 * float(i) / float(nbtotal)
133                self.display("\r%.02f%%" % percent)
134        else :       
135            if options["list"] :
136                for billingcode in billingcodes :
137                    if billingcode.Exists :
138                        print "%s [%s] %s %s %s %.2f %s" % \
139                          (billingcode.BillingCode, billingcode.Description, \
140                           billingcode.PageCounter, \
141                           _("pages"), \
142                           _("and"), \
143                           billingcode.Balance, \
144                           _("credits"))
145            else :               
146                self.display("\n%s...\n" % _("Modification"))
147                nbtotal = len(billingcodes)           
148                for i in range(nbtotal) :       
149                    billingcode = billingcodes[i]
150                    self.modifyBillingCode(billingcode, reset, description)
151                    billingcode.save()   
152                    percent = 100.0 * float(i) / float(nbtotal)
153                    self.display("\r%.02f%%" % percent)
154                   
155        if not options["list"] :               
156            self.done()
157                     
158if __name__ == "__main__" : 
159    retcode = 0
160    try :
161        short_options = "hvaD:dlrs"
162        long_options = ["help", "version", "add", "description=", "delete", "list", "reset", "skipexisting"]
163       
164        # Initializes the command line tool
165        manager = PKBcodes(doc=__doc__)
166        manager.deferredInit()
167       
168        # parse and checks the command line
169        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
170       
171        # sets long options
172        options["help"] = options["h"] or options["help"]
173        options["version"] = options["v"] or options["version"]
174        options["add"] = options["a"] or options["add"]
175        options["description"] = options["D"] or options["description"]
176        options["delete"] = options["d"] or options["delete"] 
177        options["list"] = options["l"] or options["list"]
178        options["reset"] = options["r"] or options["reset"]
179        options["skipexisting"] = options["s"] or options["skipexisting"]
180       
181        if options["help"] :
182            manager.display_usage_and_quit()
183        elif options["version"] :
184            manager.display_version_and_quit()
185        elif (options["delete"] and (options["add"] or options["reset"] or options["description"])) \
186           or (options["skipexisting"] and not options["add"]) \
187           or (options["list"] and (options["add"] or options["delete"] or options["reset"] or options["description"])) :
188            raise PyKotaCommandLineError, _("incompatible options, see help.")
189        elif (not args) and (options["add"] or options["delete"]) :   
190            raise PyKotaCommandLineError, _("You have to pass billing codes on the command line")
191        else :
192            retcode = manager.main(args, options)
193    except KeyboardInterrupt :       
194        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
195        retcode = -3
196    except PyKotaCommandLineError, msg :   
197        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
198        retcode = -2
199    except SystemExit :       
200        pass
201    except :
202        try :
203            manager.crashed("pkbcodes failed")
204        except :   
205            crashed("pkbcodes failed")
206        retcode = -1
207
208    try :
209        manager.storage.close()
210    except (TypeError, NameError, AttributeError) :   
211        pass
212       
213    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.