root / pykota / trunk / bin / pkbcodes @ 2723

Revision 2723, 8.8 kB (checked in by jerome, 18 years ago)

Doesn't delete anymore entries which don't exist.

  • 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_
32
33__doc__ = N_("""pkbcodes v%(__version__)s (c) %(__years__)s %(__author__)s
34
35A billing codes Manager for PyKota.
36
37command line usage :
38
39  pkbcodes [options] code1 code2 code3 ... codeN
40
41options :
42
43  -v | --version       Prints pkbcodes version number then exits.
44  -h | --help          Prints this message then exits.
45 
46  -a | --add           Adds billing codes if they don't exist in PyKota's
47                       database. If they exist, they are modified
48                       unless -s|--skipexisting is also used.
49
50  -d | --delete        Deletes billing codes from PyKota's database.
51                       NB : the history entries with this billing code
52                       are not deleted, voluntarily.
53
54  -D | --description d Adds a textual description to billing codes.
55
56  -l | --list          List informations about the billing codes.
57
58  -r | --reset         Resets the billing codes' balance and page counters
59                       to 0.
60
61  -s | --skipexisting  In combination with the --add option above, tells
62                       pkbcodes to not modify existing billing codes.
63
64  code1 through codeN can contain wildcards if the --add option
65  is not set.
66
67examples :                             
68
69  $ pkbcodes --add -D "My project" myproj
70
71  Will create the myproj billing code with "My project"
72  as the description.
73
74  $ pkbcodes --delete "*"
75
76  This will completely delete all the billing codes, but without
77  removing any matching job from the history. USE WITH CARE ANYWAY !
78 
79  $ pkbcodes --list "my*"
80 
81  This will list all billing codes which name begins with 'my'.
82""")
83       
84class PKBcodes(PyKotaTool) :       
85    """A class for a billing codes manager."""
86    def main(self, names, options) :
87        """Manage billing codes."""
88        if (not self.config.isAdmin) and (not options["list"]) :
89            raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command."))
90           
91        if options["delete"] :   
92            self.display("%s...\n" % _("Deletion"))
93            todelete = self.storage.getMatchingBillingCodes(",".join(names))
94            nbtotal = len(todelete)
95            for i in range(nbtotal) :
96                entry = todelete[i]
97                if entry.Exists :
98                    entry.delete()
99                percent = 100.0 * float(i) / float(nbtotal)
100                self.display("\r%.02f%%" % percent)
101        else :
102            if options["add"] :   
103                self.display("%s...\n" % _("Creation"))
104                billingcodes = []
105                nbtotal = len(names)
106                for i in range(nbtotal) :
107                    bname = names[i]
108                    billingcode = self.storage.getBillingCode(bname)
109                    if billingcode.Exists :
110                        if options["skipexisting"] :
111                            self.printInfo(_("Billing code [%s] already exists, skipping.") % billingcode.BillingCode)
112                        else :   
113                            self.printInfo(_("Billing code [%s] already exists, will be modified.") % billingcode.BillingCode)
114                            billingcodes.append(billingcode)
115                    else :
116                        billingcode = self.storage.addBillingCode(bname)
117                        if not billingcode.Exists :
118                            raise PyKotaToolError, _("Impossible to add billingcode %s") % bname
119                        else :     
120                            billingcodes.append(billingcode)
121                    percent = 100.0 * float(i) / float(nbtotal)
122                    self.display("\r%.02f%%" % percent)
123                self.display("\r100.00%%\r        \r%s\n" % _("Done."))
124            else :       
125                if not names :
126                    names = ["*"]
127                billingcodes = self.storage.getMatchingBillingCodes(",".join(names))
128                if not billingcodes :
129                    raise PyKotaCommandLineError, _("There's no billingcode matching %s") % " ".join(names)
130                       
131            if options["list"] :
132                for billingcode in billingcodes :
133                    print "%s [%s] %s %s %s %.2f %s" % \
134                          (billingcode.BillingCode, billingcode.Description, \
135                           billingcode.PageCounter, \
136                           _("pages"), \
137                           _("and"), \
138                           billingcode.Balance, \
139                           _("credits"))
140            else :               
141                self.display("%s...\n" % _("Modification"))
142                reset = options["reset"]
143                if reset or options["description"] : # optimize when nothing to do
144                    if options["description"] :
145                        description = options["description"].strip()
146                    nbtotal = len(billingcodes)           
147                    for i in range(nbtotal) :       
148                        billingcode = billingcodes[i]
149                        if reset :
150                            billingcode.reset()   
151                        if description is not None : # NB : "" is allowed !
152                            billingcode.setDescription(description)
153                        billingcode.save()   
154                        percent = 100.0 * float(i) / float(nbtotal)
155                        self.display("\r%.02f%%" % percent)
156                       
157        if not options["list"] :               
158            self.display("\r100.00%%\r        \r%s\n" % _("Done."))
159                     
160if __name__ == "__main__" : 
161    retcode = 0
162    try :
163        short_options = "hvaD:dlrs"
164        long_options = ["help", "version", "add", "description=", "delete", "list", "reset", "skipexisting"]
165       
166        # Initializes the command line tool
167        manager = PKBcodes(doc=__doc__)
168        manager.deferredInit()
169       
170        # parse and checks the command line
171        (options, args) = manager.parseCommandline(sys.argv[1:], short_options, long_options)
172       
173        # sets long options
174        options["help"] = options["h"] or options["help"]
175        options["version"] = options["v"] or options["version"]
176        options["add"] = options["a"] or options["add"]
177        options["description"] = options["D"] or options["description"]
178        options["delete"] = options["d"] or options["delete"] 
179        options["list"] = options["l"] or options["list"]
180        options["reset"] = options["r"] or options["reset"]
181        options["skipexisting"] = options["s"] or options["skipexisting"]
182       
183        if options["help"] :
184            manager.display_usage_and_quit()
185        elif options["version"] :
186            manager.display_version_and_quit()
187        elif (options["delete"] and (options["add"] or options["reset"] or options["description"])) \
188           or (options["skipexisting"] and not options["add"]) \
189           or (options["list"] and (options["add"] or options["delete"] or options["reset"] or options["description"])) :
190            raise PyKotaCommandLineError, _("incompatible options, see help.")
191        elif (not args) and (options["add"] or options["delete"]) :   
192            raise PyKotaCommandLineError, _("You have to pass billing codes on the command line")
193        else :
194            retcode = manager.main(args, options)
195    except KeyboardInterrupt :       
196        sys.stderr.write("\nInterrupted with Ctrl+C !\n")
197        retcode = -3
198    except PyKotaCommandLineError, msg :   
199        sys.stderr.write("%s : %s\n" % (sys.argv[0], msg))
200        retcode = -2
201    except SystemExit :       
202        pass
203    except :
204        try :
205            manager.crashed("pkbcodes failed")
206        except :   
207            crashed("pkbcodes failed")
208        retcode = -1
209
210    try :
211        manager.storage.close()
212    except (TypeError, NameError, AttributeError) :   
213        pass
214       
215    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.