[2660] | 1 | #! /usr/bin/env python |
---|
| 2 | # -*- coding: ISO-8859-15 -*- |
---|
| 3 | |
---|
| 4 | # PyKota Invoice generator |
---|
| 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 | |
---|
| 27 | import sys |
---|
| 28 | import os |
---|
| 29 | import pwd |
---|
[2663] | 30 | import cStringIO |
---|
| 31 | |
---|
| 32 | try : |
---|
| 33 | from reportlab.pdfgen import canvas |
---|
| 34 | from reportlab.lib import pagesizes |
---|
| 35 | from reportlab.lib.units import cm |
---|
| 36 | except ImportError : |
---|
| 37 | hasRL = 0 |
---|
| 38 | else : |
---|
| 39 | hasRL = 1 |
---|
| 40 | |
---|
| 41 | try : |
---|
| 42 | import PIL.Image |
---|
| 43 | except ImportError : |
---|
| 44 | hasPIL = 0 |
---|
| 45 | else : |
---|
| 46 | hasPIL = 1 |
---|
| 47 | |
---|
[2666] | 48 | from pykota.tool import PyKotaToolError, PyKotaCommandLineError, crashed, N_ |
---|
| 49 | from pykota.dumper import DumPyKota |
---|
[2660] | 50 | from pykota.config import PyKotaConfigError |
---|
| 51 | from pykota.storage import PyKotaStorageError |
---|
| 52 | |
---|
| 53 | __doc__ = N_("""pkinvoice v%(__version__)s (c) %(__years__)s %(__author__)s |
---|
| 54 | |
---|
| 55 | An invoice generator for PyKota. |
---|
| 56 | |
---|
| 57 | command line usage : |
---|
| 58 | |
---|
| 59 | pkinvoice [options] user1 user2 ... userN |
---|
| 60 | |
---|
| 61 | options : |
---|
| 62 | |
---|
| 63 | -v | --version Prints edpykota's version number then exits. |
---|
| 64 | -h | --help Prints this message then exits. |
---|
| 65 | |
---|
[2661] | 66 | -l | --logo img Use the image as the banner's logo. The logo will |
---|
| 67 | be drawn at the center top of the page. The default |
---|
| 68 | logo is /usr/share/pykota/logos/pykota.jpeg |
---|
| 69 | |
---|
| 70 | -p | --pagesize sz Sets sz as the page size. Most well known |
---|
| 71 | page sizes are recognized, like 'A4' or 'Letter' |
---|
| 72 | to name a few. The default size is A4. |
---|
| 73 | |
---|
| 74 | -n | --number N Sets the number of the first invoice. This number |
---|
| 75 | will automatically be incremented for each invoice. |
---|
| 76 | |
---|
[2660] | 77 | -o | --output f.pdf Defines the name of the invoice file which will |
---|
| 78 | be generated as a PDF document. If not set or |
---|
| 79 | set to '-', the PDF document is sent to standard |
---|
| 80 | output. |
---|
| 81 | |
---|
| 82 | -u | --unit u Defines the name of the unit to use on the invoice. |
---|
| 83 | The default unit is 'Credits', optionally translated |
---|
| 84 | to your native language if it is supported by PyKota. |
---|
| 85 | |
---|
[2662] | 86 | -V | --vat p Sets the percent value of the applicable VAT to be |
---|
| 87 | exposed. The default is 0.0, meaning no VAT |
---|
| 88 | information will be included. |
---|
[2660] | 89 | |
---|
[2666] | 90 | -s | --start date Sets the starting date for the print jobs invoiced. |
---|
[2660] | 91 | |
---|
[2666] | 92 | -e | --end date Sets the ending date for the print jobs invoiced. |
---|
| 93 | |
---|
| 94 | user1 through userN can use wildcards if needed. If no user argument is |
---|
| 95 | used, a wildcard of '*' is assumed, meaning include all users. |
---|
| 96 | |
---|
| 97 | Dates formating with --start and --end : |
---|
| 98 | |
---|
| 99 | YYYY : year boundaries |
---|
| 100 | YYYYMM : month boundaries |
---|
| 101 | YYYYMMDD : day boundaries |
---|
| 102 | YYYYMMDDhh : hour boundaries |
---|
| 103 | YYYYMMDDhhmm : minute boundaries |
---|
| 104 | YYYYMMDDhhmmss : second boundaries |
---|
| 105 | yesterday[+-NbDays] : yesterday more or less N days (e.g. : yesterday-15) |
---|
| 106 | today[+-NbDays] : today more or less N days (e.g. : today-15) |
---|
| 107 | tomorrow[+-NbDays] : tomorrow more or less N days (e.g. : tomorrow-15) |
---|
| 108 | now[+-NbDays] : now more or less N days (e.g. now-15) |
---|
| 109 | |
---|
| 110 | 'now' and 'today' are not exactly the same since today represents the first |
---|
| 111 | or last second of the day depending on if it's used in a start= or end= |
---|
| 112 | date expression. The utility to be able to specify dates in the future is |
---|
| 113 | a question which remains to be answered :-) |
---|
| 114 | |
---|
[2660] | 115 | examples : |
---|
| 116 | |
---|
[2666] | 117 | $ pkinvoice --unit EURO --output invoices.pdf --start=now-30 |
---|
[2660] | 118 | |
---|
[2666] | 119 | Will generate a PDF document containing invoices for all users |
---|
| 120 | who have spent some credits last month. Invoices will be done in |
---|
| 121 | EURO. No VAT information will be included. |
---|
[2660] | 122 | """) |
---|
| 123 | |
---|
[2666] | 124 | class PKInvoice(DumPyKota) : |
---|
[2660] | 125 | """A class for pkinvoice.""" |
---|
[2663] | 126 | def getPageSize(self, pgsize) : |
---|
| 127 | """Returns the correct page size or None if not found.""" |
---|
| 128 | try : |
---|
| 129 | return getattr(pagesizes, pgsize.upper()) |
---|
| 130 | except AttributeError : |
---|
| 131 | try : |
---|
| 132 | return getattr(pagesizes, pgsize.lower()) |
---|
| 133 | except AttributeError : |
---|
| 134 | pass |
---|
| 135 | |
---|
[2666] | 136 | def pagePDF(self, invoicenumber, entry, vat, start, end) : |
---|
[2663] | 137 | """Generates a new page in the PDF document.""" |
---|
| 138 | self.canvas.doForm("background") |
---|
[2666] | 139 | |
---|
| 140 | extractonly = { "username" : entry.Name } |
---|
| 141 | if start : |
---|
| 142 | extractonly["start"] = start |
---|
| 143 | if end : |
---|
| 144 | extractonly["end"] = end |
---|
| 145 | records = self.storage.extractHistory(extractonly) |
---|
| 146 | amount = vatamount = 0.0 |
---|
| 147 | vatamount = 0.0 |
---|
| 148 | if records : |
---|
| 149 | records = self.summarizeDatas(records, "history", extractonly, True) |
---|
| 150 | fieldnames = records[0] |
---|
| 151 | fields = {} |
---|
| 152 | for i in range(len(fieldnames)) : |
---|
| 153 | fields[fieldnames[i]] = i |
---|
| 154 | numberofbytes = records[1][fields["jobsizebytes"]] |
---|
| 155 | numberofpages = records[1][fields["jobsize"]] |
---|
| 156 | amount = records[1][fields["jobprice"]] |
---|
| 157 | if amount > 0.0 : |
---|
| 158 | # There's something due ! |
---|
| 159 | ht = ((amount * 10000.0) / (100.0 + vat)) / 100.0 |
---|
| 160 | vatamount = amount - ht |
---|
| 161 | sys.stderr.write("#%06i %s %s %s %.2f %.2f\n" % (invoicenumber, entry.Name, numberofpages, numberofbytes, amount, vatamount)) |
---|
| 162 | |
---|
[2663] | 163 | self.canvas.showPage() |
---|
| 164 | |
---|
[2666] | 165 | def initPDF(self, logo) : |
---|
[2663] | 166 | """Initializes the PDF document.""" |
---|
| 167 | self.pdfDocument = cStringIO.StringIO() |
---|
[2666] | 168 | self.canvas = c = canvas.Canvas(self.pdfDocument, \ |
---|
| 169 | pagesize=self.pagesize, \ |
---|
| 170 | pageCompression=1) |
---|
[2663] | 171 | |
---|
| 172 | c.setAuthor(pwd.getpwuid(os.geteuid())[0]) |
---|
| 173 | c.setTitle("PyKota invoices") |
---|
| 174 | c.setSubject("This is an invoice generated with PyKota") |
---|
| 175 | |
---|
[2666] | 176 | xcenter = self.pagesize[0] / 2.0 |
---|
| 177 | ycenter = self.pagesize[1] / 2.0 |
---|
[2663] | 178 | |
---|
[2666] | 179 | ypos = self.pagesize[1] - (2 * cm) |
---|
[2663] | 180 | |
---|
| 181 | self.canvas.beginForm("background") |
---|
| 182 | self.canvas.saveState() |
---|
| 183 | |
---|
| 184 | if logo : |
---|
| 185 | try : |
---|
| 186 | imglogo = PIL.Image.open(logo) |
---|
| 187 | except : |
---|
| 188 | self.printInfo("Unable to open image %s" % logo, "warn") |
---|
| 189 | else : |
---|
| 190 | (width, height) = imglogo.size |
---|
| 191 | multi = float(width) / (8 * cm) |
---|
| 192 | width = float(width) / multi |
---|
| 193 | height = float(height) / multi |
---|
| 194 | xpos = xcenter - (width / 2.0) |
---|
| 195 | ypos -= height |
---|
| 196 | c.drawImage(logo, xpos, ypos, width, height) |
---|
| 197 | |
---|
| 198 | # New top |
---|
[2666] | 199 | xpos = self.pagesize[0] / 5.0 |
---|
[2663] | 200 | ypos -= (1 * cm) + 20 |
---|
| 201 | |
---|
| 202 | self.canvas.restoreState() |
---|
| 203 | self.canvas.endForm() |
---|
| 204 | |
---|
| 205 | def endPDF(self, fname) : |
---|
| 206 | """Flushes the PDF generator.""" |
---|
| 207 | self.canvas.save() |
---|
| 208 | if fname != "-" : |
---|
| 209 | outfile = open(fname, "w") |
---|
| 210 | outfile.write(self.pdfDocument.getvalue()) |
---|
| 211 | outfile.close() |
---|
| 212 | else : |
---|
| 213 | sys.stdout.write(self.pdfDocument.getvalue()) |
---|
| 214 | sys.stdout.flush() |
---|
| 215 | |
---|
[2660] | 216 | def main(self, names, options) : |
---|
| 217 | """Generate invoices.""" |
---|
[2663] | 218 | if not hasRL : |
---|
| 219 | raise PyKotaToolError, "The ReportLab module is missing. Download it from http://www.reportlab.org" |
---|
| 220 | if not hasPIL : |
---|
| 221 | raise PyKotaToolError, "The Python Imaging Library is missing. Download it from http://www.pythonware.com/downloads" |
---|
| 222 | |
---|
[2660] | 223 | if not self.config.isAdmin : |
---|
| 224 | raise PyKotaCommandLineError, "%s : %s" % (pwd.getpwuid(os.geteuid())[0], _("You're not allowed to use this command.")) |
---|
| 225 | |
---|
[2661] | 226 | try : |
---|
| 227 | vat = float(options["vat"]) |
---|
| 228 | if not (0.0 <= vat < 100.0) : |
---|
| 229 | raise ValueError |
---|
| 230 | except : |
---|
| 231 | raise PyKotaCommandLineError, _("Incorrect value '%s' for the --vat command line option") % options["vat"] |
---|
| 232 | |
---|
| 233 | try : |
---|
| 234 | number = float(options["number"]) |
---|
| 235 | if number <= 0 : |
---|
| 236 | raise ValueError |
---|
| 237 | except : |
---|
| 238 | raise PyKotaCommandLineError, _("Incorrect value '%s' for the --number command line option") % options["number"] |
---|
| 239 | |
---|
[2666] | 240 | self.pagesize = self.getPageSize(options["pagesize"]) |
---|
| 241 | if self.pagesize is None : |
---|
| 242 | self.pagesize = self.getPageSize("a4") |
---|
[2663] | 243 | self.printInfo(_("Invalid 'pagesize' option %s, defaulting to A4.") % options["pagesize"], "warn") |
---|
| 244 | |
---|
[2660] | 245 | if not names : |
---|
| 246 | names = [ "*" ] |
---|
| 247 | |
---|
[2661] | 248 | outfname = options["output"] |
---|
| 249 | if outfname != "-" : |
---|
| 250 | self.display("%s...\n" % _("Processing")) |
---|
| 251 | |
---|
[2666] | 252 | entries = self.storage.getMatchingUsers(",".join(names)) |
---|
[2663] | 253 | if entries : |
---|
[2666] | 254 | self.initPDF(options["logo"].strip()) |
---|
[2663] | 255 | nbtotal = len(entries) |
---|
| 256 | for i in range(nbtotal) : |
---|
| 257 | entry = entries[i] |
---|
[2666] | 258 | self.pagePDF(number, entry, vat, options["start"], options["end"]) |
---|
| 259 | number += 1 |
---|
[2663] | 260 | if outfname != "-" : |
---|
| 261 | percent = 100.0 * float(i) / float(nbtotal) |
---|
| 262 | self.display("\r%.02f%%" % percent) |
---|
| 263 | |
---|
| 264 | self.endPDF(outfname) |
---|
| 265 | |
---|
| 266 | if outfname != "-" : |
---|
[2661] | 267 | self.display("\r100.00%%\r ") |
---|
| 268 | self.display("\r%s\n" % _("Done.")) |
---|
[2660] | 269 | |
---|
| 270 | if __name__ == "__main__" : |
---|
| 271 | retcode = 0 |
---|
| 272 | try : |
---|
[2666] | 273 | defaults = { "vat" : "0.0", |
---|
[2662] | 274 | "unit" : N_("Credits"), |
---|
[2660] | 275 | "output" : "-", |
---|
[2661] | 276 | "pagesize" : "a4", \ |
---|
| 277 | "logo" : "/usr/share/pykota/logos/pykota.jpeg", |
---|
| 278 | "number" : "1", |
---|
[2660] | 279 | } |
---|
[2666] | 280 | short_options = "vho:r:u:V:p:l:n:s:e:" |
---|
| 281 | long_options = ["help", "version", "start=", "end=", \ |
---|
| 282 | "reference=", "unit=", "output=", \ |
---|
[2661] | 283 | "pagesize=", "logo=", "vat=", "number="] |
---|
[2660] | 284 | |
---|
| 285 | # Initializes the command line tool |
---|
| 286 | invoiceGenerator = PKInvoice(doc=__doc__) |
---|
| 287 | invoiceGenerator.deferredInit() |
---|
| 288 | |
---|
| 289 | # parse and checks the command line |
---|
[2662] | 290 | (options, args) = invoiceGenerator.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=True) |
---|
[2660] | 291 | |
---|
| 292 | # sets long options |
---|
| 293 | options["help"] = options["h"] or options["help"] |
---|
| 294 | options["version"] = options["v"] or options["version"] |
---|
| 295 | |
---|
[2666] | 296 | options["start"] = options["s"] or options["start"] |
---|
| 297 | options["end"] = options["e"] or options["end"] |
---|
[2660] | 298 | options["vat"] = options["V"] or options["vat"] or defaults["vat"] |
---|
| 299 | options["unit"] = options["u"] or options["unit"] or defaults["unit"] |
---|
| 300 | options["output"] = options["o"] or options["output"] or defaults["output"] |
---|
[2661] | 301 | options["pagesize"] = options["p"] or options["pagesize"] or defaults["pagesize"] |
---|
| 302 | options["number"] = options["n"] or options["number"] or defaults["number"] |
---|
| 303 | options["logo"] = options["l"] or options["logo"] |
---|
| 304 | if options["logo"] is None : # Allows --logo="" to disable the logo entirely |
---|
| 305 | options["logo"] = defaults["logo"] |
---|
[2660] | 306 | |
---|
| 307 | if options["help"] : |
---|
| 308 | invoiceGenerator.display_usage_and_quit() |
---|
| 309 | elif options["version"] : |
---|
| 310 | invoiceGenerator.display_version_and_quit() |
---|
| 311 | else : |
---|
| 312 | retcode = invoiceGenerator.main(args, options) |
---|
| 313 | except KeyboardInterrupt : |
---|
| 314 | sys.stderr.write("\nInterrupted with Ctrl+C !\n") |
---|
| 315 | retcode = -3 |
---|
| 316 | except PyKotaCommandLineError, msg : |
---|
| 317 | sys.stderr.write("%s : %s\n" % (sys.argv[0], msg)) |
---|
| 318 | retcode = -2 |
---|
| 319 | except SystemExit : |
---|
| 320 | pass |
---|
| 321 | except : |
---|
| 322 | try : |
---|
| 323 | invoiceGenerator.crashed("pkinvoice failed") |
---|
| 324 | except : |
---|
| 325 | crashed("pkinvoice failed") |
---|
| 326 | retcode = -1 |
---|
| 327 | |
---|
| 328 | try : |
---|
| 329 | invoiceGenerator.storage.close() |
---|
| 330 | except (TypeError, NameError, AttributeError) : |
---|
| 331 | pass |
---|
| 332 | |
---|
| 333 | sys.exit(retcode) |
---|