Index: /pykota/trunk/pykota/tool.py
===================================================================
--- /pykota/trunk/pykota/tool.py (revision 900)
+++ /pykota/trunk/pykota/tool.py (revision 915)
@@ -21,4 +21,9 @@
 #
 # $Log$
+# Revision 1.31  2003/04/15 11:30:57  jalet
+# More work done on money print charging.
+# Minor bugs corrected.
+# All tools now access to the storage as priviledged users, repykota excepted.
+#
 # Revision 1.30  2003/04/10 21:47:20  jalet
 # Job history added. Upgrade script neutralized for now !
@@ -153,5 +158,5 @@
 class PyKotaTool :    
     """Base class for all PyKota command line tools."""
-    def __init__(self, isfilter=0, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
+    def __init__(self, asadmin=1, doc="PyKota %s (c) 2003 %s" % (version.__version__, version.__author__)) :
         """Initializes the command line tool."""
         # locale stuff
@@ -166,5 +171,5 @@
         self.config = config.PyKotaConfig("/etc")
         self.logger = logger.openLogger(self.config)
-        self.storage = storage.openConnection(self.config, asadmin=(not isfilter))
+        self.storage = storage.openConnection(self.config, asadmin=asadmin)
         self.printername = os.environ.get("PRINTER", None)
         self.smtpserver = self.config.getSMTPServer()
Index: /pykota/trunk/pykota/storages/sql.py
===================================================================
--- /pykota/trunk/pykota/storages/sql.py (revision 900)
+++ /pykota/trunk/pykota/storages/sql.py (revision 915)
@@ -21,4 +21,9 @@
 #
 # $Log$
+# Revision 1.23  2003/04/15 11:30:57  jalet
+# More work done on money print charging.
+# Minor bugs corrected.
+# All tools now access to the storage as priviledged users, repykota excepted.
+#
 # Revision 1.22  2003/04/10 21:47:20  jalet
 # Job history added. Upgrade script neutralized for now !
@@ -107,5 +112,5 @@
         # but we don't because other storages semantics may be different, so every
         # storage should use fnmatch to match patterns and be storage agnostic
-        result = self.doQuery("SELECT id, printername FROM printers;")
+        result = self.doQuery("SELECT id, printername FROM printers")
         result = self.doParseResult(result)
         if result is not None :
@@ -117,13 +122,26 @@
     def getPrinterId(self, printername) :        
         """Returns a printerid given a printername."""
-        result = self.doQuery("SELECT id FROM printers WHERE printername=%s;" % self.doQuote(printername))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found    
-            return
-            
+        result = self.doQuery("SELECT id FROM printers WHERE printername=%s" % self.doQuote(printername))
+        try :
+            return self.doParseResult(result)[0]["id"]
+        except TypeError :      # Not found    
+            return
+            
+    def getPrinterPrices(self, printerid) :        
+        """Returns a printer prices per page and per job given a printerid."""
+        result = self.doQuery("SELECT priceperpage, priceperjob FROM printers WHERE id=%s" % self.doQuote(printerid))
+        try :
+            printerprices = self.doParseResult(result)[0]
+            return (printerprices["priceperpage"], printerprices["priceperjob"])
+        except TypeError :      # Not found    
+            return
+            
+    def setPrinterPrices(self, printerid, perpage, perjob) :
+        """Sets prices per job and per page for a given printer."""
+        self.doQuery("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE id=%s" % (self.doQuote(perpage), self.doQuote(perjob), self.doQuote(printerid)))
+    
     def getUserId(self, username) :
         """Returns a userid given a username."""
-        result = self.doQuery("SELECT id FROM users WHERE username=%s;" % self.doQuote(username))
+        result = self.doQuery("SELECT id FROM users WHERE username=%s" % self.doQuote(username))
         try :
             return self.doParseResult(result)[0]["id"]
@@ -133,5 +151,5 @@
     def getGroupId(self, groupname) :
         """Returns a groupid given a grupname."""
-        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s;" % self.doQuote(groupname))
+        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
         try :
             return self.doParseResult(result)[0]["id"]
@@ -141,5 +159,5 @@
     def getJobHistoryId(self, jobid, userid, printerid) :        
         """Returns the history line's id given a (jobid, userid, printerid)."""
-        result = self.doQuery("SELECT id FROM jobhistory WHERE jobid=%s AND userid=%s AND printerid=%s;" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid)))
+        result = self.doQuery("SELECT id FROM jobhistory WHERE jobid=%s AND userid=%s AND printerid=%s" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid)))
         try :
             return self.doParseResult(result)[0]["id"]
@@ -149,5 +167,5 @@
     def getPrinterUsers(self, printerid) :        
         """Returns the list of usernames which uses a given printer."""
-        result = self.doQuery("SELECT DISTINCT id, username FROM users WHERE id IN (SELECT userid FROM userpquota WHERE printerid=%s) ORDER BY username;" % self.doQuote(printerid))
+        result = self.doQuery("SELECT DISTINCT id, username FROM users WHERE id IN (SELECT userid FROM userpquota WHERE printerid=%s) ORDER BY username" % self.doQuote(printerid))
         result = self.doParseResult(result)
         if result is None :
@@ -158,5 +176,5 @@
     def getPrinterGroups(self, printerid) :        
         """Returns the list of groups which uses a given printer."""
-        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s);" % self.doQuote(printerid))
+        result = self.doQuery("SELECT DISTINCT id, groupname FROM groups WHERE id IN (SELECT groupid FROM grouppquota WHERE printerid=%s)" % self.doQuote(printerid))
         result = self.doParseResult(result)
         if result is None :
@@ -167,15 +185,15 @@
     def addPrinter(self, printername) :        
         """Adds a printer to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO printers (printername) VALUES (%s);" % self.doQuote(printername))
+        self.doQuery("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
         return self.getPrinterId(printername)
         
     def addUser(self, username) :        
         """Adds a user to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO users (username) VALUES (%s);" % self.doQuote(username))
+        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
         return self.getUserId(username)
         
     def addGroup(self, groupname) :        
         """Adds a group to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO groups (groupname) VALUES (%s);" % self.doQuote(groupname))
+        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
         return self.getGroupId(groupname)
         
@@ -185,5 +203,5 @@
         if userid is None :    
             userid = self.addUser(username)
-        self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s);" % (self.doQuote(userid), self.doQuote(printerid)))
+        self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
         return (userid, printerid)
         
@@ -193,22 +211,52 @@
         if groupid is None :    
             groupid = self.addUser(groupname)
-        self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s);" % (self.doQuote(groupid), self.doQuote(printerid)))
+        self.doQuery("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(printerid)))
         return (groupid, printerid)
+        
+    def increaseUserBalance(self, userid, amount) :    
+        """Increases (or decreases) an user's account balance by a given amount."""
+        self.doQuery("UPDATE users SET balance=balance+(%s), lifetimepaid=lifetimepaid+(%s) WHERE id=%s" % (self.doQuote(amount), self.doQuote(amount), self.doQuote(userid)))
+        
+    def getUserBalance(self, userid) :    
+        """Returns the current account balance for a given user."""
+        result = self.doQuery("SELECT balance FROM users WHERE id=%s" % self.doQuote(userid))
+        try :
+            return self.doParseResult(result)[0]["balance"]
+        except TypeError :      # Not found    
+            return
+        
+    def setUserBalance(self, userid, balance) :    
+        """Sets the account balance for a given user to a fixed value."""
+        current = self.getUserBalance(userid)
+        difference = balance - current
+        self.increaseUserBalance(userid, difference)
+        
+    def limitUserByQuota(self, userid) :    
+        """Limits a given user based on print quota."""
+        self.doQuery("UPDATE users SET limitby='quota' WHERE id=%s" % self.doQuote(userid))
+        
+    def limitUserByBalance(self, userid) :    
+        """Limits a given user based on account balance."""
+        self.doQuery("UPDATE users SET limitby='balance' WHERE id=%s" % self.doQuote(userid))
         
     def setUserPQuota(self, userid, printerid, softlimit, hardlimit) :
         """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
-        self.doQuery("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE userid=%s AND printerid=%s;" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userid), self.doQuote(printerid)))
+        self.doQuery("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userid), self.doQuote(printerid)))
         
     def resetUserPQuota(self, userid, printerid) :    
         """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
-        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s;" % (self.doQuote(userid), self.doQuote(printerid)))
+        self.doQuery("UPDATE userpquota SET pagecounter=0, datelimit=NULL WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
         
     def updateUserPQuota(self, userid, printerid, pagecount) :
         """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
-        self.doQuery("UPDATE userpquota SET lifepagecounter=lifepagecounter+(%s), pagecounter=pagecounter+(%s) WHERE userid=%s AND printerid=%s;" % (self.doQuote(pagecount), self.doQuote(pagecount), self.doQuote(userid), self.doQuote(printerid)))
+        jobprice = self.computePrinterJobPrice(printerid, pagecount)
+        queries = []    
+        queries.append("UPDATE userpquota SET lifepagecounter=lifepagecounter+(%s), pagecounter=pagecounter+(%s) WHERE userid=%s AND printerid=%s" % (self.doQuote(pagecount), self.doQuote(pagecount), self.doQuote(userid), self.doQuote(printerid)))
+        queries.append("UPDATE users SET balance=balance-(%s) WHERE id=%s" % (self.doQuote(jobprice), self.doQuote(userid)))
+        self.doQuery(queries)
         
     def getUserPQuota(self, userid, printerid) :
         """Returns the Print Quota information for a given (userid, printerid)."""
-        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s;" % (self.doQuote(userid), self.doQuote(printerid)))
+        result = self.doQuery("SELECT lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(userid), self.doQuote(printerid)))
         try :
             return self.doParseResult(result)[0]
@@ -218,9 +266,9 @@
     def setUserDateLimit(self, userid, printerid, datelimit) :
         """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
-        self.doQuery("UPDATE userpquota SET datelimit=%s::TIMESTAMP WHERE userid=%s AND printerid=%s;" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(userid), self.doQuote(printerid)))
+        self.doQuery("UPDATE userpquota SET datelimit=%s::TIMESTAMP WHERE userid=%s AND printerid=%s" % (self.doQuote("%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)), self.doQuote(userid), self.doQuote(printerid)))
         
     def addJobToHistory(self, jobid, userid, printerid, pagecounter, action) :
         """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
-        self.doQuery("INSERT INTO jobhistory (jobid, userid, printerid, pagecounter, action) VALUES (%s, %s, %s, %s, %s);" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid), self.doQuote(pagecounter), self.doQuote(action)))
+        self.doQuery("INSERT INTO jobhistory (jobid, userid, printerid, pagecounter, action) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid), self.doQuote(pagecounter), self.doQuote(action)))
         return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
     
@@ -231,5 +279,5 @@
     def getPrinterPageCounter(self, printerid) :
         """Returns the last page counter value for a printer given its id, also returns last username, last jobid and history line id."""
-        result = self.doQuery("SELECT jobhistory.id, jobid, userid, username, pagecounter FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1;" % self.doQuote(printerid))
+        result = self.doQuery("SELECT jobhistory.id, jobid, userid, username, pagecounter FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printerid))
         try :
             return self.doParseResult(result)[0]
@@ -237,2 +285,10 @@
             return
         
+    def computePrinterJobPrice(self, printerid, jobsize) :    
+        """Returns the price for a job on a given printer."""
+        prices = self.getPrinterPrices(printerid)
+        if prices is None :
+            perpage = perjob = 0.0
+        else :    
+            (perpage, perjob) = prices
+        return perjob + (perpage * jobsize)
Index: /pykota/trunk/pykota/storages/postgresql.py
===================================================================
--- /pykota/trunk/pykota/storages/postgresql.py (revision 873)
+++ /pykota/trunk/pykota/storages/postgresql.py (revision 915)
@@ -21,4 +21,9 @@
 #
 # $Log$
+# Revision 1.7  2003/04/15 11:30:57  jalet
+# More work done on money print charging.
+# Minor bugs corrected.
+# All tools now access to the storage as priviledged users, repykota excepted.
+#
 # Revision 1.6  2003/03/29 13:45:27  jalet
 # GPL paragraphs were incorrectly (from memory) copied into the sources.
@@ -82,8 +87,18 @@
     def doQuery(self, query) :
         """Does a query."""
+        if type(query) in (type([]), type(())) :
+            query = ";".join(query)
+        query = query.strip()    
+        if not query.endswith(';') :    
+            query += ';'
+        self.database.query("BEGIN;")
         try :
-            return self.database.query(query)
+            result = self.database.query(query)
         except pg.error, msg :    
+            self.database.query("ROLLBACK;")
             raise PyKotaStorageError, msg
+        else :    
+            self.database.query("COMMIT;")
+            return result
         
     def doQuote(self, field) :
Index: /pykota/trunk/bin/pykota
===================================================================
--- /pykota/trunk/bin/pykota (revision 914)
+++ /pykota/trunk/bin/pykota (revision 915)
@@ -23,4 +23,9 @@
 #
 # $Log$
+# Revision 1.23  2003/04/15 11:30:57  jalet
+# More work done on money print charging.
+# Minor bugs corrected.
+# All tools now access to the storage as priviledged users, repykota excepted.
+#
 # Revision 1.22  2003/04/15 11:09:04  jalet
 # Small bug was fixed when a printer was never used and its internal
@@ -111,5 +116,5 @@
     """Class for the PyKota filter."""
     def __init__(self, username) :
-        PyKotaTool.__init__(self, isfilter=1)
+        PyKotaTool.__init__(self)
         self.username = username
         self.requester = openRequester(self.config, self.printername)
Index: /pykota/trunk/bin/repykota
===================================================================
--- /pykota/trunk/bin/repykota (revision 912)
+++ /pykota/trunk/bin/repykota (revision 915)
@@ -23,4 +23,9 @@
 #
 # $Log$
+# Revision 1.25  2003/04/15 11:30:57  jalet
+# More work done on money print charging.
+# Minor bugs corrected.
+# All tools now access to the storage as priviledged users, repykota excepted.
+#
 # Revision 1.24  2003/04/14 20:05:20  jalet
 # Reversed test.
@@ -156,4 +161,8 @@
 class RePyKota(PyKotaTool) :        
     """A class for repykota."""
+    def __init__(self, doc) :
+        """Initializes the tool as a non-priviledged storage user."""
+        PyKotaTool.__init__(self, asadmin=0, doc=doc)
+        
     def main(self, options) :
         """Print Quota reports generator."""
@@ -181,8 +190,8 @@
                 print (" " * 43) + (_("Total : %9i") % total)
             printerpagecounter = self.storage.getPrinterPageCounter(printerid)
-            if printerpagecounter is None :    
+            try :
+                msg = "%9i" % printerpagecounter["pagecounter"]
+            except TypeError :     
                 msg = _("unknown")
-            else :
-                msg = "%9i" % printerpagecounter["pagecounter"]
             print (" " * 44) + (_("Real : %s") % msg)
             print        
Index: /pykota/trunk/initscripts/pykota-postgresql.sql
===================================================================
--- /pykota/trunk/initscripts/pykota-postgresql.sql (revision 911)
+++ /pykota/trunk/initscripts/pykota-postgresql.sql (revision 915)
@@ -20,4 +20,9 @@
 --
 -- $Log$
+-- Revision 1.13  2003/04/15 11:30:57  jalet
+-- More work done on money print charging.
+-- Minor bugs corrected.
+-- All tools now access to the storage as priviledged users, repykota excepted.
+--
 -- Revision 1.12  2003/04/14 20:01:02  jalet
 -- Typo
@@ -99,5 +104,6 @@
 --
 CREATE TABLE groups(id SERIAL PRIMARY KEY NOT NULL,
-                    groupname TEXT UNIQUE NOT NULL);
+                    groupname TEXT UNIQUE NOT NULL,
+                    limitby TEXT DEFAULT 'quota');
                     
 --
Index: /pykota/trunk/NEWS
===================================================================
--- /pykota/trunk/NEWS (revision 913)
+++ /pykota/trunk/NEWS (revision 915)
@@ -71,4 +71,6 @@
         - A small display bug in repykota was introduced in preliminary 
           1.03 versions, and fixed later on.
+          
+        - Some minor bugs which happened in rare situations were fixed.
         
     - 1.02 :
