Index: /pykota/trunk/pykota/tool.py
===================================================================
--- /pykota/trunk/pykota/tool.py (revision 1021)
+++ /pykota/trunk/pykota/tool.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.41  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.40  2003/06/10 16:37:54  jalet
 # Deletion of the second user which is not needed anymore.
@@ -305,5 +308,9 @@
             touser = "%s@%s" % (touser, self.smtpserver)
         server = smtplib.SMTP(self.smtpserver)
-        server.sendmail(adminmail, [touser], fullmessage)
+        try :
+            server.sendmail(adminmail, [touser], fullmessage)
+        except smtplib.SMTPRecipientsRefused, answer :    
+            for (k, v) in answer.recipients.items() :
+                self.logger.log_message(_("Impossible to send mail to %s, error %s : %s") % (k, v[0], v[1]), "error")
         server.quit()
         
@@ -317,54 +324,106 @@
         self.sendMessage(adminmail, adminmail, "Subject: %s\n\n%s" % (subject, message))
         
-    def checkGroupPQuota(self, groupname, printername) :    
+    def checkGroupPQuota(self, grouppquota) :    
         """Checks the group quota on a printer and deny or accept the job."""
-        printerid = self.storage.getPrinterId(printername)
-        policy = self.config.getPrinterPolicy(printername)
-        groupid = self.storage.getGroupId(groupname)
-        limitby = self.storage.getGroupLimitBy(groupid)
-        if limitby == "balance" : 
-            balance = self.storage.getGroupBalance(groupid)
-            if balance is None :
+        group = grouppquota.Group
+        printer = grouppquota.Printer
+        if group.LimitBy.lower() == "balance" : 
+            # TODO : there's no warning (no account balance soft limit)
+            if float(group.AccountBalance) <= 0.0 :
+                action = "DENY"
+            else :    
+                action = "ALLOW"
+        else :
+            if grouppquota.SoftLimit is not None :
+                softlimit = int(grouppquota.SoftLimit)
+                if grouppquota.PageCounter < softlimit :
+                    action = "ALLOW"
+                else :    
+                    if grouppquota.HardLimit is None :
+                        # only a soft limit, this is equivalent to having only a hard limit
+                        action = "DENY"
+                    else :    
+                        hardlimit = int(grouppquota.HardLimit)
+                        if softlimit <= grouppquota.PageCounter < hardlimit :    
+                            now = DateTime.now()
+                            if grouppquota.DateLimit is not None :
+                                datelimit = DateTime.ISO.ParseDateTime(grouppquota.DateLimit)
+                            else :
+                                datelimit = now + self.config.getGraceDelay(printer.Name)
+                                grouppquota.setDateLimit(datelimit)
+                            if now < datelimit :
+                                action = "WARN"
+                            else :    
+                                action = "DENY"
+                        else :         
+                            action = "DENY"
+            else :        
+                if grouppquota.HardLimit is not None :
+                    # no soft limit, only a hard one.
+                    hardlimit = int(grouppquota.HardLimit)
+                    if grouppquota.PageCounter < hardlimit :
+                        action = "ALLOW"
+                    else :      
+                        action = "DENY"
+                else :
+                    # Both are unset, no quota, i.e. accounting only
+                    action = "ALLOW"
+        return action
+    
+    def checkUserPQuota(self, userpquota) :
+        """Checks the user quota on a printer and deny or accept the job."""
+        user = userpquota.User
+        printer = userpquota.Printer
+        
+        # first we check any group the user is a member of
+        for group in self.storage.getUserGroups(user) :
+            grouppquota = self.storage.getGroupPQuota(group, printer)
+            if grouppquota.Exists :
+                action = self.checkGroupPQuota(grouppquota)
+                if action == "DENY" :
+                    return action
+                
+        # then we check the user's own quota
+        policy = self.config.getPrinterPolicy(printer.Name)
+        if user.LimitBy.lower() == "balance" : 
+            if user.AccountBalance is None :
                 if policy == "ALLOW" :
                     action = "POLICY_ALLOW"
                 else :    
                     action = "POLICY_DENY"
-                self.logger.log_message(_("Unable to find group %s's account balance, applying default policy (%s) for printer %s") % (groupname, action, printername))
+                self.logger.log_message(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (user.Name, action, printer.Name))
             else :    
                 # TODO : there's no warning (no account balance soft limit)
-                (balance, lifetimepaid) = balance
-                if balance <= 0.0 :
+                if float(user.AccountBalance or 0.0) <= 0.0 :
                     action = "DENY"
                 else :    
                     action = "ALLOW"
         else :
-            quota = self.storage.getGroupPQuota(groupid, printerid)
-            if quota is None :
-                # Unknown group or printer or combination
+            if not userpquota.Exists :
+                # Unknown userquota 
                 if policy == "ALLOW" :
                     action = "POLICY_ALLOW"
                 else :    
                     action = "POLICY_DENY"
-                self.logger.log_message(_("Unable to match group %s on printer %s, applying default policy (%s)") % (groupname, printername, action))
+                self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (user.Name, printer.Name, action))
             else :    
-                pagecounter = quota["pagecounter"]
-                softlimit = quota["softlimit"]
-                hardlimit = quota["hardlimit"]
-                datelimit = quota["datelimit"]
-                if softlimit is not None :
+                pagecounter = int(userpquota.PageCounter or 0)
+                if userpquota.SoftLimit is not None :
+                    softlimit = int(userpquota.SoftLimit)
                     if pagecounter < softlimit :
                         action = "ALLOW"
                     else :    
-                        if hardlimit is None :
+                        if userpquota.HardLimit is None :
                             # only a soft limit, this is equivalent to having only a hard limit
                             action = "DENY"
                         else :    
+                            hardlimit = int(userpquota.HardLimit)
                             if softlimit <= pagecounter < hardlimit :    
                                 now = DateTime.now()
-                                if datelimit is not None :
-                                    datelimit = DateTime.ISO.ParseDateTime(datelimit)
+                                if userpquota.DateLimit is not None :
+                                    datelimit = DateTime.ISO.ParseDateTime(userpquota.DateLimit)
                                 else :
-                                    datelimit = now + self.config.getGraceDelay(printername)
-                                    self.storage.setGroupDateLimit(groupid, printerid, datelimit)
+                                    datelimit = now + self.config.getGraceDelay(printer.Name)
+                                    userpquota.setDateLimit(datelimit)
                                 if now < datelimit :
                                     action = "WARN"
@@ -374,6 +433,7 @@
                                 action = "DENY"
                 else :        
-                    if hardlimit is not None :
+                    if userpquota.HardLimit is not None :
                         # no soft limit, only a hard one.
+                        hardlimit = int(userpquota.HardLimit)
                         if pagecounter < hardlimit :
                             action = "ALLOW"
@@ -385,126 +445,54 @@
         return action
     
-    def checkUserPQuota(self, username, printername) :
-        """Checks the user quota on a printer and deny or accept the job."""
-        # first we check any group the user is a member of
-        userid = self.storage.getUserId(username)
-        for groupname in self.storage.getUserGroupsNames(userid) :
-            action = self.checkGroupPQuota(groupname, printername)
-            if action in ("DENY", "POLICY_DENY") :
-                return action
-                
-        # then we check the user's own quota
-        printerid = self.storage.getPrinterId(printername)
-        policy = self.config.getPrinterPolicy(printername)
-        limitby = self.storage.getUserLimitBy(userid)
-        if limitby == "balance" : 
-            balance = self.storage.getUserBalance(userid)
-            if balance is None :
-                if policy == "ALLOW" :
-                    action = "POLICY_ALLOW"
-                else :    
-                    action = "POLICY_DENY"
-                self.logger.log_message(_("Unable to find user %s's account balance, applying default policy (%s) for printer %s") % (username, action, printername))
-            else :    
-                # TODO : there's no warning (no account balance soft limit)
-                (balance, lifetimepaid) = balance
-                if balance <= 0.0 :
-                    action = "DENY"
-                else :    
-                    action = "ALLOW"
-        else :
-            quota = self.storage.getUserPQuota(userid, printerid)
-            if quota is None :
-                # Unknown user or printer or combination
-                if policy == "ALLOW" :
-                    action = "POLICY_ALLOW"
-                else :    
-                    action = "POLICY_DENY"
-                self.logger.log_message(_("Unable to match user %s on printer %s, applying default policy (%s)") % (username, printername, action))
-            else :    
-                pagecounter = quota["pagecounter"]
-                softlimit = quota["softlimit"]
-                hardlimit = quota["hardlimit"]
-                datelimit = quota["datelimit"]
-                if softlimit is not None :
-                    if pagecounter < softlimit :
-                        action = "ALLOW"
-                    else :    
-                        if hardlimit is None :
-                            # only a soft limit, this is equivalent to having only a hard limit
-                            action = "DENY"
-                        else :    
-                            if softlimit <= pagecounter < hardlimit :    
-                                now = DateTime.now()
-                                if datelimit is not None :
-                                    datelimit = DateTime.ISO.ParseDateTime(datelimit)
-                                else :
-                                    datelimit = now + self.config.getGraceDelay(printername)
-                                    self.storage.setUserDateLimit(userid, printerid, datelimit)
-                                if now < datelimit :
-                                    action = "WARN"
-                                else :    
-                                    action = "DENY"
-                            else :         
-                                action = "DENY"
-                else :        
-                    if hardlimit is not None :
-                        # no soft limit, only a hard one.
-                        if pagecounter < hardlimit :
-                            action = "ALLOW"
-                        else :      
-                            action = "DENY"
-                    else :
-                        # Both are unset, no quota, i.e. accounting only
-                        action = "ALLOW"
-        return action
-    
-    def warnGroupPQuota(self, groupname, printername) :
+    def warnGroupPQuota(self, grouppquota) :
         """Checks a group quota and send messages if quota is exceeded on current printer."""
-        admin = self.config.getAdmin(printername)
-        adminmail = self.config.getAdminMail(printername)
-        mailto = self.config.getMailTo(printername)
-        action = self.checkGroupPQuota(groupname, printername)
-        groupmembers = self.storage.getGroupMembersNames(groupname)
+        group = grouppquota.Group
+        printer = grouppquota.Printer
+        admin = self.config.getAdmin(printer.Name)
+        adminmail = self.config.getAdminMail(printer.Name)
+        mailto = self.config.getMailTo(printer.Name)
+        action = self.checkGroupPQuota(grouppquota, printer)
         if action.startswith("POLICY_") :
             action = action[7:]
         if action == "DENY" :
-            adminmessage = _("Print Quota exceeded for group %s on printer %s") % (groupname, printername)
+            adminmessage = _("Print Quota exceeded for group %s on printer %s") % (group.Name, printer.Name)
             self.logger.log_message(adminmessage)
             if mailto in [ "BOTH", "ADMIN" ] :
                 self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
-            for username in groupmembers :
+            for user in self.storage.getGroupMembers(group) :
                 if mailto in [ "BOTH", "USER" ] :
-                    self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour group Print Quota is exceeded on printer %s.") % printername)
+                    self.sendMessageToUser(admin, adminmail, user.Name, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour group Print Quota is exceeded on printer %s.") % printer.Name)
         elif action == "WARN" :    
-            adminmessage = _("Print Quota soft limit exceeded for group %s on printer %s") % (groupname, printername)
+            adminmessage = _("Print Quota soft limit exceeded for group %s on printer %s") % (group.Name, printer.Name)
             self.logger.log_message(adminmessage)
             if mailto in [ "BOTH", "ADMIN" ] :
                 self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
-            for username in groupmembers :
+            for user in self.storage.getGroupMembers(group) :
                 if mailto in [ "BOTH", "USER" ] :
-                    self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour group Print Quota is almost reached on printer %s.") % printername)
+                    self.sendMessageToUser(admin, adminmail, user.Name, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour group Print Quota is almost reached on printer %s.") % printer.Name)
         return action        
         
-    def warnUserPQuota(self, username, printername) :
+    def warnUserPQuota(self, userpquota) :
         """Checks a user quota and send him a message if quota is exceeded on current printer."""
-        admin = self.config.getAdmin(printername)
-        adminmail = self.config.getAdminMail(printername)
-        mailto = self.config.getMailTo(printername)
-        action = self.checkUserPQuota(username, printername)
+        user = userpquota.User
+        printer = userpquota.Printer
+        admin = self.config.getAdmin(printer.Name)
+        adminmail = self.config.getAdminMail(printer.Name)
+        mailto = self.config.getMailTo(printer.Name)
+        action = self.checkUserPQuota(userpquota)
         if action.startswith("POLICY_") :
             action = action[7:]
         if action == "DENY" :
-            adminmessage = _("Print Quota exceeded for user %s on printer %s") % (username, printername)
+            adminmessage = _("Print Quota exceeded for user %s on printer %s") % (user.Name, printer.Name)
             self.logger.log_message(adminmessage)
             if mailto in [ "BOTH", "USER" ] :
-                self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printername)
+                self.sendMessageToUser(admin, adminmail, user.Name, _("Print Quota Exceeded"), _("You are not allowed to print anymore because\nyour Print Quota is exceeded on printer %s.") % printer.Name)
             if mailto in [ "BOTH", "ADMIN" ] :
                 self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
         elif action == "WARN" :    
-            adminmessage = _("Print Quota soft limit exceeded for user %s on printer %s") % (username, printername)
+            adminmessage = _("Print Quota soft limit exceeded for user %s on printer %s") % (user.Name, printer.Name)
             self.logger.log_message(adminmessage)
             if mailto in [ "BOTH", "USER" ] :
-                self.sendMessageToUser(admin, adminmail, username, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printername)
+                self.sendMessageToUser(admin, adminmail, user.Name, _("Print Quota Exceeded"), _("You will soon be forbidden to print anymore because\nyour Print Quota is almost reached on printer %s.") % printer.Name)
             if mailto in [ "BOTH", "ADMIN" ] :
                 self.sendMessageToAdmin(adminmail, _("Print Quota"), adminmessage)
Index: /pykota/trunk/pykota/accounters/stupid.py
===================================================================
--- /pykota/trunk/pykota/accounters/stupid.py (revision 1000)
+++ /pykota/trunk/pykota/accounters/stupid.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.4  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.3  2003/05/27 23:00:21  jalet
 # Big rewrite of external accounting methods.
@@ -39,5 +42,5 @@
 
 class Accounter(AccounterBase) :
-    def doAccounting(self, printerid, userid) :
+    def doAccounting(self, printer, user) :
         """Does print accounting by stupidly counting the 'showpage' postscript instructions in the document.
         
@@ -51,6 +54,5 @@
             
         # get last job information for this printer
-        pgc = self.filter.storage.getPrinterPageCounter(printerid)    
-        if pgc is None :
+        if not printer.LastJob.Exists :
             # The printer hasn't been used yet, from PyKota's point of view
             counterbeforejob = 0
@@ -59,8 +61,9 @@
             # Last lifetime page counter before actual job is 
             # last page counter + last job size
-            counterbeforejob = (pgc["pagecounter"] or 0) + (pgc["jobsize"] or 0)
+            counterbeforejob = int(printer.LastJob.PrinterPageCounter or 0) + int(printer.LastJob.JobSize or 0)
             
         # Is the current user allowed to print at all ?
-        action = self.filter.warnUserPQuota(self.filter.username, self.filter.printername)
+        userpquota = self.filter.storage.getUserPQuota(user, printer)
+        action = self.filter.warnUserPQuota(userpquota)
         
         # update the quota for the current user on this printer, if allowed to print
@@ -68,8 +71,8 @@
             jobsize = 0
         else :    
-            self.filter.storage.updateUserPQuota(userid, printerid, jobsize)
+            userpquota.increasePagesUsage(jobsize)
         
         # adds the current job to history    
-        self.filter.storage.addJobToHistory(self.filter.jobid, self.filter.storage.getUserId(self.filter.username), printerid, counterbeforejob, action, jobsize)
+        printer.addJobToHistory(self.filter.jobid, user, counterbeforejob, action, jobsize)
             
         return action
Index: /pykota/trunk/pykota/accounters/external.py
===================================================================
--- /pykota/trunk/pykota/accounters/external.py (revision 1000)
+++ /pykota/trunk/pykota/accounters/external.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.4  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.3  2003/05/27 23:00:21  jalet
 # Big rewrite of external accounting methods.
@@ -41,5 +44,5 @@
 
 class Accounter(AccounterBase) :
-    def doAccounting(self, printerid, userid) :
+    def doAccounting(self, printer, user) :
         """Deletgates the computation of the job size to an external command.
         
@@ -50,6 +53,5 @@
             
         # get last job information for this printer
-        pgc = self.filter.storage.getPrinterPageCounter(printerid)    
-        if pgc is None :
+        if not printer.LastJob.Exists :
             # The printer hasn't been used yet, from PyKota's point of view
             counterbeforejob = 0
@@ -58,8 +60,9 @@
             # Last lifetime page counter before actual job is 
             # last page counter + last job size
-            counterbeforejob = (pgc["pagecounter"] or 0) + (pgc["jobsize"] or 0)
+            counterbeforejob = int(printer.LastJob.PrinterPageCounter or 0) + int(printer.LastJob.JobSize or 0)
             
         # Is the current user allowed to print at all ?
-        action = self.filter.warnUserPQuota(self.filter.username, self.filter.printername)
+        userpquota = self.filter.storage.getUserPQuota(user, printer)
+        action = self.filter.warnUserPQuota(userpquota)
         
         # update the quota for the current user on this printer, if allowed to print
@@ -67,8 +70,8 @@
             jobsize = 0
         else :    
-            self.filter.storage.updateUserPQuota(userid, printerid, jobsize)
+            userpquota.increasePagesUsage(jobsize)
         
         # adds the current job to history    
-        self.filter.storage.addJobToHistory(self.filter.jobid, self.filter.storage.getUserId(self.filter.username), printerid, counterbeforejob, action, jobsize)
+        printer.addJobToHistory(self.filter.jobid, user, counterbeforejob, action, jobsize)
             
         return action
@@ -102,7 +105,4 @@
             # launches child process
             command = "%s <%s >%s 2>%s" % (self.arguments, infilename, outfilename, errfilename)
-            o = open("/tmp/comm", "w")
-            o.write("%s\n" % command)
-            o.close()
             retcode = os.system(command)
             
Index: /pykota/trunk/pykota/accounters/querying.py
===================================================================
--- /pykota/trunk/pykota/accounters/querying.py (revision 988)
+++ /pykota/trunk/pykota/accounters/querying.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.4  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.3  2003/05/06 14:55:47  jalet
 # Missing import !
@@ -38,9 +41,9 @@
 from pykota.requester import openRequester, PyKotaRequesterError
 
-MAXTRIES = 6     # maximum number of tries to get the printer's internal page counter
+MAXTRIES = 12    # maximum number of tries to get the printer's internal page counter
 TIMETOSLEEP = 10 # number of seconds to sleep between two tries to get the printer's internal page counter
 
 class Accounter(AccounterBase) :
-    def doAccounting(self, printerid, userid) :
+    def doAccounting(self, printer, user) :
         """Does print accounting and returns if the job status is ALLOW or DENY."""
         # Get the page counter directly from the printer itself
@@ -65,15 +68,14 @@
         
         # get last job information for this printer
-        pgc = self.filter.storage.getPrinterPageCounter(printerid)    
-        if pgc is None :
+        if not printer.LastJob.Exists :
             # The printer hasn't been used yet, from PyKota's point of view
-            lasthistoryid = None
-            lastjobid = self.filter.jobid
-            lastuserid = userid
-            lastusername = self.filter.username
+            lastjob = None
+            lastuser = user
             lastpagecounter = counterbeforejob
         else :    
             # get last values from Quota Storage
-            (lasthistoryid, lastjobid, lastuserid, lastusername, lastpagecounter) = (pgc["id"], pgc["jobid"], pgc["userid"], pgc["username"], pgc["pagecounter"])
+            lastjob = printer.LastJob
+            lastuser = printer.LastJob.User
+            lastpagecounter = printer.LastJob.PrinterPageCounter
             
         # if printer is off then we assume the correct counter value is the last one
@@ -107,21 +109,25 @@
             # For more accurate accounting, don't switch off your HP printers !
             # explanation at : http://web.mit.edu/source/third/lprng/doc/LPRng-HOWTO-15.html
-            self.filter.logger.log_message(_("Error in page count value %i for user %s on printer %s") % (jobsize, lastusername, self.filter.printername), "error")
+            self.filter.logger.log_message(_("Error in page count value %i for user %s on printer %s") % (jobsize, lastuser.Name, self.filter.printername), "error")
             jobsize = abs(int((10 - abs(jobsize)) / 2))     # Workaround for HP printers' feature !
             
         # update the quota for the previous user on this printer 
-        self.filter.storage.updateUserPQuota(lastuserid, printerid, jobsize)
+        lastuserquota = self.filter.storage.getUserPQuota(lastuser, printer)
+        if lastuserquota.Exists :
+            lastuserquota.increasePagesUsage(jobsize)
         
         # update the last job size in the history
-        self.filter.storage.updateJobSizeInHistory(lasthistoryid, jobsize)
+        if printer.LastJob.Exists :
+            printer.LastJob.setSize(jobsize)
         
         # warns the last user if he is over quota
-        self.filter.warnUserPQuota(lastusername, self.filter.printername)
+        if lastuserquota.Exists :
+            self.filter.warnUserPQuota(lastuserquota)
             
         # Is the current user allowed to print at all ?
-        action = self.filter.warnUserPQuota(self.filter.username, self.filter.printername)
+        action = self.filter.warnUserPQuota(self.filter.storage.getUserPQuota(user, printer))
         
         # adds the current job to history    
-        self.filter.storage.addJobToHistory(self.filter.jobid, self.filter.storage.getUserId(self.filter.username), printerid, counterbeforejob, action)
+        printer.addJobToHistory(self.filter.jobid, user, counterbeforejob, action)
             
         return action
Index: /pykota/trunk/pykota/storages/pgstorage.py
===================================================================
--- /pykota/trunk/pykota/storages/pgstorage.py (revision 1024)
+++ /pykota/trunk/pykota/storages/pgstorage.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.3  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.2  2003/06/12 21:09:57  jalet
 # wrongly placed code.
@@ -34,7 +37,6 @@
 #
 
-import fnmatch
-
 from pykota.storage import PyKotaStorageError
+from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
 
 try :
@@ -74,14 +76,27 @@
                 self.tool.logger.log_message("Database closed.", "debug")
         
-    def doQuery(self, query) :
-        """Does a query."""
-        if type(query) in (type([]), type(())) :
-            query = ";".join(query)
+    def beginTransaction(self) :    
+        """Starts a transaction."""
+        self.database.query("BEGIN;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction begins...", "debug")
+        
+    def commitTransaction(self) :    
+        """Commits a transaction."""
+        self.database.query("COMMIT;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction committed.", "debug")
+        
+    def rollbackTransaction(self) :     
+        """Rollbacks a transaction."""
+        self.database.query("ROLLBACK;")
+        if self.debug :
+            self.tool.logger.log_message("Transaction aborted.", "debug")
+        
+    def doSearch(self, query) :
+        """Does a search query."""
         query = query.strip()    
         if not query.endswith(';') :    
             query += ';'
-        self.database.query("BEGIN;")
-        if self.debug :
-            self.tool.logger.log_message("Transaction began.", "debug")
         try :
             if self.debug :
@@ -89,14 +104,21 @@
             result = self.database.query(query)
         except pg.error, msg :    
-            self.database.query("ROLLBACK;")
-            if self.debug :
-                self.tool.logger.log_message("Transaction aborted.", "debug")
             raise PyKotaStorageError, msg
         else :    
-            self.database.query("COMMIT;")
+            if (result is not None) and (result.ntuples() > 0) : 
+                return result.dictresult()
+            
+    def doModify(self, query) :
+        """Does a (possibly multiple) modify query."""
+        query = query.strip()    
+        if not query.endswith(';') :    
+            query += ';'
+        try :
             if self.debug :
-                self.tool.logger.log_message("Transaction committed.", "debug")
-            return result
-        
+                self.tool.logger.log_message("QUERY : %s" % query, "debug")
+            result = self.database.query(query)
+        except pg.error, msg :    
+            raise PyKotaStorageError, msg
+            
     def doQuote(self, field) :
         """Quotes a field for use as a string in SQL queries."""
@@ -109,266 +131,194 @@
         return pg._quote(field, typ)
         
-    def doParseResult(self, result) :
-        """Returns the result as a list of Python mappings."""
-        if (result is not None) and (result.ntuples() > 0) :
-            return result.dictresult()
-            
+    def getUser(self, username) :    
+        """Extracts user information given its name."""
+        user = StorageUser(self, username)
+        result = self.doSearch("SELECT * FROM users WHERE username=%s LIMIT 1" % self.doQuote(username))
+        if result :
+            fields = result[0]
+            user.ident = fields.get("id")
+            user.LimitBy = fields.get("limitby")
+            user.AccountBalance = fields.get("balance")
+            user.LifeTimePaid = fields.get("lifetimepaid")
+            user.Exists = 1
+        return user
+       
+    def getGroup(self, groupname) :    
+        """Extracts group information given its name."""
+        group = StorageGroup(self, groupname)
+        result = self.doSearch("SELECT * FROM groups WHERE groupname=%s LIMIT 1" % self.doQuote(groupname))
+        if result :
+            fields = result[0]
+            group.ident = fields.get("id")
+            group.LimitBy = fields.get("limitby")
+            result = self.doSearch("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(group.ident))
+            if result :
+                fields = result[0]
+                group.AccountBalance = fields.get("balance")
+                group.LifeTimePaid = fields.get("lifetimepaid")
+            group.Exists = 1
+        return group
+       
+    def getPrinter(self, printername) :        
+        """Extracts printer information given its name."""
+        printer = StoragePrinter(self, printername)
+        result = self.doSearch("SELECT * FROM printers WHERE printername=%s LIMIT 1" % self.doQuote(printername))
+        if result :
+            fields = result[0]
+            printer.ident = fields.get("id")
+            printer.PricePerJob = fields.get("priceperjob")
+            printer.PricePerPage = fields.get("priceperpage")
+            printer.LastJob = self.getPrinterLastJob(printer)
+            printer.Exists = 1
+        return printer    
+            
+    def getUserGroups(self, user) :        
+        """Returns the user's groups list."""
+        groups = []
+        result = self.doSearch("SELECT groupname FROM groupsmembers JOIN groups ON groupsmembers.groupid=groups.id WHERE userid=%s" % self.doQuote(user.ident))
+        if result :
+            for record in result :
+                groups.append(self.getGroup(record.get("groupname")))
+        return groups        
+        
+    def getGroupMembers(self, group) :        
+        """Returns the group's members list."""
+        groupmembers = []
+        result = self.doSearch("SELECT * FROM groupsmembers JOIN users ON groupsmembers.userid=users.id WHERE groupid=%s" % self.doQuote(group.ident))
+        if result :
+            for record in result :
+                user = StorageUser(self, record.get("username"))
+                user.ident = record.get("userid")
+                user.LimitBy = record.get("limitby")
+                user.AccountBalance = record.get("balance")
+                user.LifeTimePaid = record.get("lifetimepaid")
+                user.Exists = 1
+                groupmembers.append(user)
+        return groupmembers        
+        
+    def getUserPQuota(self, user, printer) :        
+        """Extracts a user print quota."""
+        userpquota = StorageUserPQuota(self, user, printer)
+        if user.Exists :
+            result = self.doSearch("SELECT id, lifepagecounter, pagecounter, softlimit, hardlimit, datelimit FROM userpquota WHERE userid=%s AND printerid=%s" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
+            if result :
+                fields = result[0]
+                userpquota.ident = fields.get("id")
+                userpquota.PageCounter = fields.get("pagecounter")
+                userpquota.LifePageCounter = fields.get("lifepagecounter")
+                userpquota.SoftLimit = fields.get("softlimit")
+                userpquota.HardLimit = fields.get("hardlimit")
+                userpquota.DateLimit = fields.get("datelimit")
+                userpquota.Exists = 1
+        return userpquota
+        
+    def getGroupPQuota(self, group, printer) :        
+        """Extracts a group print quota."""
+        grouppquota = StorageGroupPQuota(self, group, printer)
+        if group.Exists :
+            result = self.doSearch("SELECT id, softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
+            if result :
+                fields = result[0]
+                grouppquota.ident = fields.get("id")
+                grouppquota.SoftLimit = fields.get("softlimit")
+                grouppquota.HardLimit = fields.get("hardlimit")
+                grouppquota.DateLimit = fields.get("datelimit")
+                result = self.doSearch("SELECT SUM(lifepagecounter) AS lifepagecounter, SUM(pagecounter) AS pagecounter FROM userpquota WHERE printerid=%s AND userid IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % (self.doQuote(printer.ident), self.doQuote(group.ident)))
+                if result :
+                    fields = result[0]
+                    grouppquota.PageCounter = fields.get("pagecounter")
+                    grouppquota.LifePageCounter = fields.get("lifepagecounter")
+                grouppquota.Exists = 1
+        return grouppquota
+        
+    def getPrinterLastJob(self, printer) :        
+        """Extracts a printer's last job information."""
+        lastjob = StorageLastJob(self, printer)
+        result = self.doSearch("SELECT jobhistory.id, jobid, userid, username, pagecounter, jobsize, jobdate FROM jobhistory, users WHERE printerid=%s AND userid=users.id ORDER BY jobdate DESC LIMIT 1" % self.doQuote(printer.ident))
+        if result :
+            fields = result[0]
+            lastjob.ident = fields.get("id")
+            lastjob.JobId = fields.get("jobid")
+            lastjob.User = self.getUser(fields.get("username"))
+            lastjob.PrinterPageCounter = fields.get("pagecounter")
+            lastjob.JobSize = fields.get("jobsize")
+            lastjob.JobAction = fields.get("action")
+            lastjob.JobDate = fields.get("jobdate")
+            lastjob.Exists = 1
+        return lastjob
+        
     def getMatchingPrinters(self, printerpattern) :
-        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
-        printerslist = []
+        """Returns the list of all printers for which name matches a certain pattern."""
+        printers = []
         # We 'could' do a SELECT printername FROM printers WHERE printername LIKE ...
         # 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.doParseResult(result)
-        if result is not None :
-            for printer in result :
-                if fnmatch.fnmatchcase(printer["printername"], printerpattern) :
-                    printerslist.append((printer["id"], printer["printername"]))
-        return printerslist        
-            
-    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
-            
-    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))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found
-            return
-            
-    def getGroupId(self, groupname) :
-        """Returns a groupid given a grupname."""
-        result = self.doQuery("SELECT id FROM groups WHERE groupname=%s" % self.doQuote(groupname))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found
-            return
-            
-    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)))
-        try :
-            return self.doParseResult(result)[0]["id"]
-        except TypeError :      # Not found    
-            return
-            
-    def getPrinterUsers(self, printerid) :        
-        """Returns the list of userids and 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.doParseResult(result)
-        if result is None :
-            return []
-        else :    
-            return [(record["id"], record["username"]) for record in result]
-        
-    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.doParseResult(result)
-        if result is None :
-            return []
-        else :    
-            return [(record["id"], record["groupname"]) for record in result]
-        
-    def getGroupMembersNames(self, groupname) :        
-        """Returns the list of user's names which are member of this group."""
-        groupid = self.getGroupId(groupname)
-        if groupid is None :
-            return []
-        else :
-            result = self.doQuery("SELECT DISTINCT username FROM users WHERE id IN (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
-            return [record["username"] for record in (self.doParseResult(result) or [])]
-        
-    def getUserGroupsNames(self, userid) :        
-        """Returns the list of groups' names the user is a member of."""
-        result = self.doQuery("SELECT DISTINCT groupname FROM groups WHERE id IN (SELECT groupid FROM groupsmembers WHERE userid=%s)" % self.doQuote(userid))
-        return [record["groupname"] for record in (self.doParseResult(result) or [])]
+        result = self.doSearch("SELECT * FROM printers")
+        if result :
+            for record in result :
+                if self.tool.matchString(record["printername"], [ printerpattern ]) :
+                    printer = StoragePrinter(self, record["printername"])
+                    printer.ident = record.get("id")
+                    printer.PricePerJob = record.get("priceperjob")
+                    printer.PricePerPage = record.get("priceperpage")
+                    printer.LastJob = self.getPrinterLastJob(printer)
+                    printer.Exists = 1
+                    printers.append(printer)
+        return printers        
+        
+    def getPrinterUsersAndQuotas(self, printer, names=None) :        
+        """Returns the list of users who uses a given printer, along with their quotas."""
+        usersandquotas = []
+        result = self.doSearch("SELECT users.id as uid,username,balance,lifetimepaid,limitby,userpquota.id,lifepagecounter,pagecounter,softlimit,hardlimit,datelimit FROM users JOIN userpquota ON users.id=userpquota.userid AND printerid=%s" % self.doQuote(printer.ident))
+        if result :
+            for record in result :
+                user = StorageUser(self, record.get("username"))
+                if (names is None) or self.tool.matchString(user.Name, names) :
+                    user.ident = record.get("uid")
+                    user.LimitBy = record.get("limitby")
+                    user.AccountBalance = record.get("balance")
+                    user.LifeTimePaid = record.get("lifetimepaid")
+                    user.Exists = 1
+                    userpquota = StorageUserPQuota(self, user, printer)
+                    userpquota.ident = record.get("id")
+                    userpquota.PageCounter = record.get("pagecounter")
+                    userpquota.LifePageCounter = record.get("lifepagecounter")
+                    userpquota.SoftLimit = record.get("softlimit")
+                    userpquota.HardLimit = record.get("hardlimit")
+                    userpquota.DateLimit = record.get("datelimit")
+                    userpquota.Exists = 1
+                    usersandquotas.append((user, userpquota))
+        return usersandquotas
+                
+    def getPrinterGroupsAndQuotas(self, printer, names=None) :        
+        """Returns the list of groups which uses a given printer, along with their quotas."""
+        groupsandquotas = []
+        result = self.doSearch("SELECT groupname FROM groups JOIN grouppquota ON groups.id=grouppquota.groupid AND printerid=%s" % self.doQuote(printer.ident))
+        if result :
+            for record in result :
+                group = self.getGroup(record.get("groupname"))
+                if (names is None) or self.tool.matchString(group.Name, names) :
+                    grouppquota = self.getGroupPQuota(group, printer)
+                    groupsandquotas.append((group, grouppquota))
+        return groupsandquotas
         
     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))
-        return self.getPrinterId(printername)
-        
-    def addUser(self, username) :        
+        """Adds a printer to the quota storage, returns it."""
+        self.doModify("INSERT INTO printers (printername) VALUES (%s)" % self.doQuote(printername))
+        return self.getPrinter(printername)
+        
+    def addUser(self, user) :        
         """Adds a user to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO users (username) VALUES (%s)" % self.doQuote(username))
-        return self.getUserId(username)
-        
-    def addGroup(self, groupname) :        
+        self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid) VALUES (%s, %s, %s, %s)" % (self.doQuote(user.Name), self.doQuote(user.LimitBy), self.doQuote(user.AccountBalance), self.doQuote(user.LifeTimePaid)))
+        return self.getUser(user.Name)
+        
+    def addGroup(self, group) :        
         """Adds a group to the quota storage, returns its id."""
-        self.doQuery("INSERT INTO groups (groupname) VALUES (%s)" % self.doQuote(groupname))
-        return self.getGroupId(groupname)
-        
-    def addUserPQuota(self, username, printerid) :
-        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
-        userid = self.getUserId(username)     
-        if userid is None :    
-            userid = self.addUser(username)
-        uqexists = (self.getUserPQuota(userid, printerid) is not None)    
-        if not uqexists : 
-            self.doQuery("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(userid), self.doQuote(printerid)))
-        return (userid, printerid)
-        
-    def addGroupPQuota(self, groupname, printerid) :
-        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
-        groupid = self.getGroupId(groupname)     
-        if groupid is None :    
-            groupid = self.addGroup(groupname)
-        gqexists = (self.getGroupPQuota(groupid, printerid) is not None)    
-        if not gqexists : 
-            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, lifetimepaid FROM users WHERE id=%s" % self.doQuote(userid))
-        try :
-            result = self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        else :    
-            return (result["balance"], result["lifetimepaid"])
-        
-    def getGroupBalance(self, groupid) :    
-        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
-        result = self.doQuery("SELECT SUM(balance) AS balance, SUM(lifetimepaid) AS lifetimepaid FROM users WHERE id in (SELECT userid FROM groupsmembers WHERE groupid=%s)" % self.doQuote(groupid))
-        try :
-            result = self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        else :    
-            return (result["balance"], result["lifetimepaid"])
-        
-    def getUserLimitBy(self, userid) :    
-        """Returns the way in which user printing is limited."""
-        result = self.doQuery("SELECT limitby FROM users WHERE id=%s" % self.doQuote(userid))
-        try :
-            return self.doParseResult(result)[0]["limitby"]
-        except TypeError :      # Not found    
-            return
-        
-    def getGroupLimitBy(self, groupid) :    
-        """Returns the way in which group printing is limited."""
-        result = self.doQuery("SELECT limitby FROM groups WHERE id=%s" % self.doQuote(groupid))
-        try :
-            return self.doParseResult(result)[0]["limitby"]
-        except TypeError :      # Not found    
-            return
-        
-    def setUserBalance(self, userid, balance) :    
-        """Sets the account balance for a given user to a fixed value."""
-        (current, lifetimepaid) = self.getUserBalance(userid)
-        difference = balance - current
-        self.increaseUserBalance(userid, difference)
-        
-    def limitUserBy(self, userid, limitby) :    
-        """Limits a given user based either on print quota or on account balance."""
-        self.doQuery("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(userid)))
-        
-    def limitGroupBy(self, groupid, limitby) :    
-        """Limits a given group based either on print quota or on sum of its users' account balances."""
-        self.doQuery("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(groupid)))
-        
-    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)))
-        
-    def setGroupPQuota(self, groupid, printerid, softlimit, hardlimit) :
-        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
-        self.doQuery("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(groupid), 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)))
-        
-    def resetGroupPQuota(self, groupid, printerid) :    
-        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
-        self.doQuery("UPDATE grouppquota SET pagecounter=0, datelimit=NULL WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
-        
-    def updateUserPQuota(self, userid, printerid, pagecount) :
-        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
-        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)))
-        try :
-            return self.doParseResult(result)[0]
-        except TypeError :      # Not found    
-            return
-        
-    def getGroupPQuota(self, groupid, printerid) :
-        """Returns the Print Quota information for a given (groupid, printerid)."""
-        result = self.doQuery("SELECT softlimit, hardlimit, datelimit FROM grouppquota WHERE groupid=%s AND printerid=%s" % (self.doQuote(groupid), self.doQuote(printerid)))
-        try :
-            grouppquota = self.doParseResult(result)[0]
-        except TypeError :    
-            return
-        else :    
-            result = self.doQuery("SELECT SUM(lifepagecounter) as lifepagecounter, SUM(pagecounter) as pagecounter FROM userpquota WHERE printerid=%s AND userid in (SELECT userid FROM groupsmembers WHERE groupid=%s)" % (self.doQuote(printerid), self.doQuote(groupid)))
-            try :
-                result = self.doParseResult(result)[0]
-            except TypeError :      # Not found    
-                return
-            else :    
-                grouppquota.update({"lifepagecounter": result["lifepagecounter"], "pagecounter": result["pagecounter"]})
-                return grouppquota
-        
-    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)))
-        
-    def setGroupDateLimit(self, groupid, printerid, datelimit) :
-        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
-        self.doQuery("UPDATE grouppquota SET datelimit=%s::TIMESTAMP WHERE groupid=%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(groupid), self.doQuote(printerid)))
-        
-    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
-        """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, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(jobid), self.doQuote(userid), self.doQuote(printerid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
-        return self.getJobHistoryId(jobid, userid, printerid) # in case jobid is not sufficient
-    
-    def updateJobSizeInHistory(self, historyid, jobsize) :
-        """Updates a job size in the history given the history line's id."""
-        self.doQuery("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(historyid)))
-    
-    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, jobsize 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]
-        except TypeError :      # Not found
-            return
-        
-    def addUserToGroup(self, userid, groupid) :    
+        self.doModify("INSERT INTO groups (groupname, limitby) VALUES (%s, %s)" % (self.doQuote(group.Name), self.doQuote(group.LimitBy)))
+        return self.getGroup(group.Name)
+
+    def addUserToGroup(self, user, group) :    
         """Adds an user to a group."""
-        result = self.doQuery("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(groupid), self.doQuote(userid)))
+        result = self.doModify("SELECT COUNT(*) AS mexists FROM groupsmembers WHERE groupid=%s AND userid=%s" % (self.doQuote(group.ident), self.doQuote(user.ident)))
         try :
             mexists = self.doParseResult(result)[0]["mexists"]
@@ -376,32 +326,86 @@
             mexists = 0
         if not mexists :    
-            self.doQuery("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(groupid), self.doQuote(userid)))
-        
-    def deleteUser(self, userid) :    
+            self.doModify("INSERT INTO groupsmembers (groupid, userid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(user.ident)))
+            
+    def addUserPQuota(self, user, printer) :
+        """Initializes a user print quota on a printer."""
+        self.doModify("INSERT INTO userpquota (userid, printerid) VALUES (%s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident)))
+        return self.getUserPQuota(user, printer)
+        
+    def addGroupPQuota(self, group, printer) :
+        """Initializes a group print quota on a printer."""
+        self.doModify("INSERT INTO grouppquota (groupid, printerid) VALUES (%s, %s)" % (self.doQuote(group.ident), self.doQuote(printer.ident)))
+        return self.getGroupPQuota(group, printer)
+        
+    def writePrinterPrices(self, printer) :    
+        """Write the printer's prices back into the storage."""
+        self.doModify("UPDATE printers SET priceperpage=%s, priceperjob=%s WHERE printerid=%s" % (self.doQuote(printer.PricePerPage), self.doQuote(printer.PricePerJob), self.doQuote(printer.ident)))
+        
+    def writeUserLimitBy(self, user, limitby) :    
+        """Sets the user's limiting factor."""
+        self.doModify("UPDATE users SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(user.ident)))
+        
+    def writeGroupLimitBy(self, group, limitby) :    
+        """Sets the group's limiting factor."""
+        self.doModify("UPDATE groups SET limitby=%s WHERE id=%s" % (self.doQuote(limitby), self.doQuote(group.ident)))
+        
+    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :    
+        """Sets the date limit permanently for a user print quota."""
+        self.doModify("UPDATE userpquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(userpquota.ident)))
+            
+    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :    
+        """Sets the date limit permanently for a group print quota."""
+        self.doModify("UPDATE grouppquota SET datelimit::TIMESTAMP=%s WHERE id=%s" % (self.doQuote(datelimit), self.doQuote(grouppquota.ident)))
+        
+    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :    
+       """Sets the new page counters permanently for a user print quota."""
+       self.doModify("UPDATE userpquota SET pagecounter=%s,lifepagecounter=%s WHERE id=%s" % (self.doQuote(newpagecounter), self.doQuote(newlifepagecounter), self.doQuote(userpquota.ident)))
+       
+    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :    
+       """Sets the new account balance and eventually new lifetime paid."""
+       if newlifetimepaid is not None :
+           self.doModify("UPDATE users SET balance=%s, lifetimepaid=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(newlifetimepaid), self.doQuote(user.ident)))
+       else :    
+           self.doModify("UPDATE users SET balance=%s WHERE id=%s" % (self.doQuote(newbalance), self.doQuote(user.ident)))
+            
+    def writeLastJobSize(self, lastjob, jobsize) :        
+        """Sets the last job's size permanently."""
+        self.doModify("UPDATE jobhistory SET jobsize=%s WHERE id=%s" % (self.doQuote(jobsize), self.doQuote(lastjob.ident)))
+        
+    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :    
+        """Adds a job in a printer's history."""
+        if jobsize is not None :
+            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action, jobsize) VALUES (%s, %s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action), self.doQuote(jobsize)))
+        else :    
+            self.doModify("INSERT INTO jobhistory (userid, printerid, jobid, pagecounter, action) VALUES (%s, %s, %s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(printer.ident), self.doQuote(jobid), self.doQuote(pagecounter), self.doQuote(action)))
+            
+    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a user quota."""
+        self.doModify("UPDATE userpquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(userpquota.ident)))
+        
+    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
+        self.doModify("UPDATE grouppquota SET softlimit=%s, hardlimit=%s, datelimit=NULL WHERE id=%s" % (self.doQuote(softlimit), self.doQuote(hardlimit), self.doQuote(grouppquota.ident)))
+
+    def deleteUser(self, user) :    
         """Completely deletes an user from the Quota Storage."""
-        queries = []
-        queries.append("DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM userpquota WHERE userid=%s" % self.doQuote(userid))
-        queries.append("DELETE FROM users WHERE id=%s" % self.doQuote(userid))
         # TODO : What should we do if we delete the last person who used a given printer ?
-        self.doQuery(queries)
-        
-    def deleteGroup(self, groupid) :    
-        """Completely deletes an user from the Quota Storage."""
-        queries = []
-        queries.append("DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(groupid))
-        queries.append("DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(groupid))
-        queries.append("DELETE FROM groups WHERE id=%s" % self.doQuote(groupid))
-        self.doQuery(queries)
-        
-    def computePrinterJobPrice(self, printerid, jobsize) :    
-        """Returns the price for a job on a given printer."""
-        # TODO : create a base class with things like this
-        prices = self.getPrinterPrices(printerid)
-        if prices is None :
-            perpage = perjob = 0.0
-        else :    
-            (perpage, perjob) = prices
-        return perjob + (perpage * jobsize)
-        
+        # TODO : we can't reassign the last job to the previous one, because next user would be
+        # TODO : incorrectly charged (overcharged).
+        for q in [ 
+                    "DELETE FROM groupsmembers WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM jobhistory WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM userpquota WHERE userid=%s" % self.doQuote(user.ident),
+                    "DELETE FROM users WHERE id=%s" % self.doQuote(user.ident),
+                  ] :
+            self.doModify(q)
+        
+    def deleteGroup(self, group) :    
+        """Completely deletes a group from the Quota Storage."""
+        for q in [
+                   "DELETE FROM groupsmembers WHERE groupid=%s" % self.doQuote(group.ident),
+                   "DELETE FROM grouppquota WHERE groupid=%s" % self.doQuote(group.ident),
+                   "DELETE FROM groups WHERE id=%s" % self.doQuote(group.ident),
+                 ] :  
+            self.doModify(q)
+        
Index: /pykota/trunk/pykota/storages/ldapstorage.py
===================================================================
--- /pykota/trunk/pykota/storages/ldapstorage.py (revision 1032)
+++ /pykota/trunk/pykota/storages/ldapstorage.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.11  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.10  2003/06/16 21:55:15  jalet
 # More work on LDAP, again. Problem detected.
@@ -66,7 +69,7 @@
 import time
 import md5
-import fnmatch
 
 from pykota.storage import PyKotaStorageError
+from pykota.storage import StorageObject,StorageUser,StorageGroup,StoragePrinter,StorageLastJob,StorageUserPQuota,StorageGroupPQuota
 
 try :
@@ -114,4 +117,19 @@
         return md5.md5("%s" % time.time()).hexdigest()
         
+    def beginTransaction(self) :    
+        """Starts a transaction."""
+        if self.debug :
+            self.tool.logger.log_message("Transaction begins... WARNING : No transactions in LDAP !", "debug")
+        
+    def commitTransaction(self) :    
+        """Commits a transaction."""
+        if self.debug :
+            self.tool.logger.log_message("Transaction committed. WARNING : No transactions in LDAP !", "debug")
+        
+    def rollbackTransaction(self) :     
+        """Rollbacks a transaction."""
+        if self.debug :
+            self.tool.logger.log_message("Transaction aborted. WARNING : No transaction in LDAP !", "debug")
+        
     def doSearch(self, key, fields=None, base="", scope=ldap.SCOPE_SUBTREE) :
         """Does an LDAP search query."""
@@ -119,5 +137,5 @@
             base = base or self.basedn
             if self.debug :
-                self.tool.logger.log_message("QUERY : BaseDN : %s, Scope : %s, Filter : %s, Attributes : %s" % (base, scope, key, fields), "debug")
+                self.tool.logger.log_message("QUERY : Filter : %s, BaseDN : %s, Scope : %s, Attributes : %s" % (key, base, scope, fields), "debug")
             result = self.database.search_s(base or self.basedn, scope, key, fields)
         except ldap.LDAPError :    
@@ -139,5 +157,14 @@
             return dn
             
-    def doModify(self, dn, fields) :
+    def doDelete(self, dn) :
+        """Deletes an entry from the LDAP directory."""
+        try :
+            if self.debug :
+                self.tool.logger.log_message("QUERY : Delete(%s)" % dn, "debug")
+            self.database.delete_s(dn)
+        except ldap.LDAPError :
+            raise PyKotaStorageError, _("Problem deleting LDAP entry (%s)") % dn
+            
+    def doModify(self, dn, fields, ignoreold=1) :
         """Modifies an entry in the LDAP directory."""
         try :
@@ -145,110 +172,253 @@
             if self.debug :
                 self.tool.logger.log_message("QUERY : Modify(%s, %s ==> %s)" % (dn, oldentry[0][1], fields), "debug")
-            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=1))
+            self.database.modify_s(dn, modlist.modifyModlist(oldentry[0][1], fields, ignore_oldexistent=ignoreold))
         except ldap.LDAPError :
             raise PyKotaStorageError, _("Problem modifying LDAP entry (%s, %s)") % (dn, fields)
         else :
             return dn
+            
+    def getUser(self, username) :    
+        """Extracts user information given its name."""
+        user = StorageUser(self, username)
+        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy"], base=self.info["userbase"])
+        if result :
+            fields = result[0][1]
+            user.ident = result[0][0]
+            user.LimitBy = fields.get("pykotaLimitBy")[0]
+            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["balancerdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"], base=self.info["balancebase"])
+            if result :
+                fields = result[0][1]
+                user.idbalance = result[0][0]
+                user.AccountBalance = fields.get("pykotaBalance")
+                if user.AccountBalance is not None :
+                    if user.AccountBalance[0].upper() == "NONE" :
+                        user.AccountBalance = None
+                    else :    
+                        user.AccountBalance = float(user.AccountBalance[0])
+                user.AccountBalance = user.AccountBalance or 0.0        
+                user.LifeTimePaid = fields.get("pykotaLifeTimePaid")
+                if user.LifeTimePaid is not None :
+                    if user.LifeTimePaid[0].upper() == "NONE" :
+                        user.LifeTimePaid = None
+                    else :    
+                        user.LifeTimePaid = float(user.LifeTimePaid[0])
+                user.LifeTimePaid = user.LifeTimePaid or 0.0        
+            user.Exists = 1
+        return user
+       
+    def getGroup(self, groupname) :    
+        """Extracts group information given its name."""
+        group = StorageGroup(self, groupname)
+        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"], base=self.info["groupbase"])
+        if result :
+            fields = result[0][1]
+            group.ident = result[0][0]
+            group.LimitBy = fields.get("pykotaLimitBy")[0]
+            group.AccountBalance = 0.0
+            group.LifeTimePaid = 0.0
+            group.Members = self.getGroupMembers(group)
+            for member in group.Members :
+                group.AccountBalance += member.AccountBalance
+                group.LifeTimePaid += member.LifeTimePaid
+            group.Exists = 1
+        return group
+       
+    def getPrinter(self, printername) :        
+        """Extracts printer information given its name."""
+        printer = StoragePrinter(self, printername)
+        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
+        if result :
+            fields = result[0][1]
+            printer.ident = result[0][0]
+            printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
+            printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
+            printer.LastJob = self.getPrinterLastJob(printer)
+            printer.Exists = 1
+        return printer    
+            
+    def getUserGroups(self, user) :        
+        """Returns the user's groups list."""
+        groups = []
+        result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], user.Name), [self.info["grouprdn"]], base=self.info["groupbase"])
+        if result :
+            for (groupid, fields) in result :
+                groups.append(self.getGroup(fields.get(self.info["grouprdn"])[0]))
+        return groups        
+        
+    def getGroupMembers(self, group) :        
+        """Returns the group's members list."""
+        groupmembers = []
+        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (group.Name, self.info["grouprdn"], group.Name), [self.info["groupmembers"]], base=self.info["groupbase"])
+        if result :
+            for username in result[0][1].get(self.info["groupmembers"], []) :
+                groupmembers.append(self.getUser(username))
+        return groupmembers        
+        
+    def getUserPQuota(self, user, printer) :        
+        """Extracts a user print quota."""
+        userpquota = StorageUserPQuota(self, user, printer)
+        if user.Exists :
+            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s)(pykotaPrinterName=%s))" % (user.Name, printer.Name), ["pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
+            if result :
+                fields = result[0][1]
+                userpquota.ident = result[0][0]
+                userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
+                userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
+                userpquota.SoftLimit = fields.get("pykotaSoftLimit")
+                if userpquota.SoftLimit is not None :
+                    if userpquota.SoftLimit[0].upper() == "NONE" :
+                        userpquota.SoftLimit = None
+                    else :    
+                        userpquota.SoftLimit = int(userpquota.SoftLimit[0])
+                userpquota.HardLimit = fields.get("pykotaHardLimit")
+                if userpquota.HardLimit is not None :
+                    if userpquota.HardLimit[0].upper() == "NONE" :
+                        userpquota.HardLimit = None
+                    elif userpquota.HardLimit is not None :    
+                        userpquota.HardLimit = int(userpquota.HardLimit[0])
+                userpquota.DateLimit = fields.get("pykotaDateLimit")
+                if userpquota.DateLimit is not None :
+                    if userpquota.DateLimit[0].upper() == "NONE" : 
+                        userpquota.DateLimit = None
+                    else :    
+                        userpquota.DateLimit = userpquota.DateLimit[0]
+                userpquota.Exists = 1
+        return userpquota
+        
+    def getGroupPQuota(self, group, printer) :        
+        """Extracts a group print quota."""
+        grouppquota = StorageGroupPQuota(self, group, printer)
+        if group.Exists :
+            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s)(pykotaPrinterName=%s))" % (group.Name, printer.Name), ["pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["groupquotabase"])
+            if result :
+                fields = result[0][1]
+                grouppquota.ident = result[0][0]
+                grouppquota.SoftLimit = fields.get("pykotaSoftLimit")
+                if grouppquota.SoftLimit is not None :
+                    if grouppquota.SoftLimit[0].upper() == "NONE" :
+                        grouppquota.SoftLimit = None
+                    else :    
+                        grouppquota.SoftLimit = int(grouppquota.SoftLimit[0])
+                grouppquota.HardLimit = fields.get("pykotaHardLimit")
+                if grouppquota.HardLimit is not None :
+                    if grouppquota.HardLimit[0].upper() == "NONE" :
+                        grouppquota.HardLimit = None
+                    else :    
+                        grouppquota.HardLimit = int(grouppquota.HardLimit[0])
+                grouppquota.DateLimit = fields.get("pykotaDateLimit")
+                if grouppquota.DateLimit is not None :
+                    if grouppquota.DateLimit[0].upper() == "NONE" : 
+                        grouppquota.DateLimit = None
+                    else :    
+                        grouppquota.DateLimit = grouppquota.DateLimit[0]
+                grouppquota.PageCounter = 0
+                grouppquota.LifePageCounter = 0
+                if (not hasattr(group, "Members")) or (group.Members is None) :
+                    group.Members = self.getGroupMembers(group)
+                usernamesfilter = "".join(["(pykotaUserName=%s)" % member.Name for member in group.Members])
+                result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s)(|%s))" % (printer.Name, usernamesfilter), ["pykotaPageCounter", "pykotaLifePageCounter"], base=self.info["userquotabase"])
+                if result :
+                    for userpquota in result :    
+                        grouppquota.PageCounter += int(userpquota[1].get("pykotaPageCounter")[0] or 0)
+                        grouppquota.LifePageCounter += int(userpquota[1].get("pykotaLifePageCounter")[0] or 0)
+                grouppquota.Exists = 1
+        return grouppquota
+        
+    def getPrinterLastJob(self, printer) :        
+        """Extracts a printer's last job information."""
+        lastjob = StorageLastJob(self, printer)
+        result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printer.Name, self.info["printerrdn"], printer.Name), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
+        if result :
+            lastjob.lastjobident = result[0][0]
+            lastjobident = result[0][1]["pykotaLastJobIdent"][0]
+            result = self.doSearch("objectClass=pykotaJob", ["pykotaUserName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base="cn=%s,%s" % (lastjobident, self.info["jobbase"]), scope=ldap.SCOPE_BASE)
+            if result :
+                fields = result[0][1]
+                lastjob.ident = result[0][0]
+                lastjob.JobId = fields.get("pykotaJobId")[0]
+                lastjob.User = self.getUser(fields.get("pykotaUserName")[0])
+                lastjob.PrinterPageCounter = int(fields.get("pykotaPrinterPageCounter")[0] or 0)
+                lastjob.JobSize = int(fields.get("pykotaJobSize", [0])[0])
+                lastjob.JobAction = fields.get("pykotaAction")[0]
+                date = fields.get("createTimestamp")[0]
+                year = int(date[:4])
+                month = int(date[4:6])
+                day = int(date[6:8])
+                hour = int(date[8:10])
+                minute = int(date[10:12])
+                second = int(date[12:14])
+                lastjob.JobDate = "%04i-%02i-%02i %02i:%02i:%02i" % (year, month, day, hour, minute, second)
+                lastjob.Exists = 1
+        return lastjob
         
     def getMatchingPrinters(self, printerpattern) :
-        """Returns the list of all printers as tuples (id, name) for printer names which match a certain pattern."""
-        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName"], base=self.info["printerbase"])
-        if result :
-            return [(printerid, printer["pykotaPrinterName"][0]) for (printerid, printer) in result if fnmatch.fnmatchcase(printer["pykotaPrinterName"][0], printerpattern)]
-            
-    def getPrinterId(self, printername) :        
-        """Returns a printerid given a printername."""
-        result = self.doSearch("(&(objectClass=pykotaPrinter)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaPrinterName"], base=self.info["printerbase"])
-        if result :
-            return result[0][0]
-            
-    def getPrinterName(self, printerid) :        
-        """Returns a printerid given a printer id."""
-        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName"], base=printerid, scope=ldap.SCOPE_BASE)
-        if result :
-            return result[0][1]["pykotaPrinterName"][0]
-            
-    def getPrinterPrices(self, printerid) :        
-        """Returns a printer prices per page and per job given a printerid."""
-        result = self.doSearch("(|(pykotaPrinterName=*)(%s=*))" % self.info["printerrdn"], ["pykotaPricePerPage", "pykotaPricePerJob"], base=printerid, scope=ldap.SCOPE_BASE)
-        if result :
-            return (float(result[0][1]["pykotaPricePerPage"][0]), float(result[0][1]["pykotaPricePerJob"][0]))
-            
-    def setPrinterPrices(self, printerid, perpage, perjob) :
-        """Sets prices per job and per page for a given printer."""
-        fields = { 
-                   "pykotaPricePerPage" : str(perpage),
-                   "pykotaPricePerJob" : str(perjob),
-                 } 
-        return self.doModify(printerid, fields)
-    
-    def getUserId(self, username) :
-        """Returns a userid given a username."""
-        result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), [self.info["userrdn"]], base=self.info["userbase"])
-        if result :
-            return result[0][0]
-            
-    def getUserName(self, userid) :
-        """Returns a username given a userid."""
-        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName"], base=userid, scope=ldap.SCOPE_BASE)
-        if result :
-            return result[0][1]["pykotaUserName"][0]
-            
-    def getGroupId(self, groupname) :
-        """Returns a groupid given a grupname."""
-        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), [self.info["grouprdn"]], base=self.info["groupbase"])
-        if result is not None :
-            (groupid, dummy) = result[0]
-            return groupid
-            
-    def getJobHistoryId(self, jobid, userid, printerid) :        
-        """Returns the history line's id given a (jobid, userid, printerid).
-        
-           TODO : delete because shouldn't be needed by the LDAP backend
-        """
-        raise PyKotaStorageError, "Not implemented !"
-            
-    def getPrinterUsers(self, printerid) :        
-        """Returns the list of userids and usernames which uses a given printer."""
-        # first get the printer's name from the id
-        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", self.info["printerrdn"]], base=printerid, scope=ldap.SCOPE_BASE)
-        if result :
-            fields = result[0][1]
-            printername = (fields.get("pykotaPrinterName") or fields.get(self.info["printerrdn"]))[0]
-            result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printername, ["pykotaUserName"], base=self.info["userquotabase"]) 
-            if result :
-                return [(pquotauserid, fields["pykotaUserName"][0]) for (pquotauserid, fields) in result]
-        
-    def getPrinterGroups(self, printerid) :        
-        """Returns the list of groups which uses a given printer."""
-        # first get the printer's name from the id
-        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", self.info["printerrdn"]], base=printerid, scope=ldap.SCOPE_BASE)
-        if result :
-            fields = result[0][1]
-            printername = (fields.get("pykotaPrinterName") or fields.get(self.info["printerrdn"]))[0]
-            result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printername, ["pykotaGroupName"], base=self.info["groupquotabase"]) 
-            if result :
-                return [(pquotagroupid, fields["pykotaGroupName"][0]) for (pquotagroupid, fields) in result]
-        
-    def getGroupMembersNames(self, groupname) :        
-        """Returns the list of user's names which are member of this group."""
-        result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), [self.info["groupmembers"]])
-        if result :
-            fields = result[0][1]
-            return fields.get(self.info["groupmembers"])
-        
-    def getUserGroupsNames(self, userid) :        
-        """Returns the list of groups' names the user is a member of."""
-        username = self.getUserName(userid)
-        if username :
-            result = self.doSearch("(&(objectClass=pykotaGroup)(%s=%s))" % (self.info["groupmembers"], username), [self.info["grouprdn"]], base=self.info["groupbase"])
-            if result :
-                return [v[self.info["grouprdn"]][0] for (k, v) in result]
-        return []        
+        """Returns the list of all printers for which name matches a certain pattern."""
+        printers = []
+        # see comment at the same place in pgstorage.py
+        result = self.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", "pykotaPricePerPage", "pykotaPricePerJob"], base=self.info["printerbase"])
+        if result :
+            for (printerid, fields) in result :
+                printername = fields["pykotaPrinterName"][0]
+                if self.tool.matchString(printername, [ printerpattern ]) :
+                    printer = StoragePrinter(self, printername)
+                    printer.ident = printerid
+                    printer.PricePerJob = float(fields.get("pykotaPricePerJob")[0] or 0.0)
+                    printer.PricePerPage = float(fields.get("pykotaPricePerPage")[0] or 0.0)
+                    printer.LastJob = self.getPrinterLastJob(printer)
+                    printer.Exists = 1
+                    printers.append(printer)
+        return printers        
+        
+    def getPrinterUsersAndQuotas(self, printer, names=None) :        
+        """Returns the list of users who uses a given printer, along with their quotas."""
+        usersandquotas = []
+        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=self.info["userquotabase"])
+        if result :
+            for (userquotaid, fields) in result :
+                user = self.getUser(fields["pykotaUserName"][0])
+                if (names is None) or self.tool.matchString(user.Name, names) :
+                    userpquota = StorageUserPQuota(self, user, printer)
+                    userpquota.ident = userquotaid
+                    userpquota.PageCounter = int(fields.get("pykotaPageCounter")[0] or 0)
+                    userpquota.LifePageCounter = int(fields.get("pykotaLifePageCounter")[0] or 0)
+                    userpquota.SoftLimit = fields.get("pykotaSoftLimit")
+                    if userpquota.SoftLimit is not None :
+                        if userpquota.SoftLimit[0].upper() == "NONE" :
+                            userpquota.SoftLimit = None
+                        else :    
+                            userpquota.SoftLimit = int(userpquota.SoftLimit[0])
+                    userpquota.HardLimit = fields.get("pykotaHardLimit")
+                    if userpquota.HardLimit is not None :
+                        if userpquota.HardLimit[0].upper() == "NONE" :
+                            userpquota.HardLimit = None
+                        elif userpquota.HardLimit is not None :    
+                            userpquota.HardLimit = int(userpquota.HardLimit[0])
+                    userpquota.DateLimit = fields.get("pykotaDateLimit")
+                    if userpquota.DateLimit is not None :
+                        if userpquota.DateLimit[0].upper() == "NONE" : 
+                            userpquota.DateLimit = None
+                        else :    
+                            userpquota.DateLimit = userpquota.DateLimit[0]
+                    userpquota.Exists = 1
+                    usersandquotas.append((user, userpquota))
+        return usersandquotas
+                
+    def getPrinterGroupsAndQuotas(self, printer, names=None) :        
+        """Returns the list of groups which uses a given printer, along with their quotas."""
+        groupsandquotas = []
+        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaPrinterName=%s))" % printer.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
+        if result :
+            for (groupquotaid, fields) in result :
+                group = self.getGroup(fields.get("pykotaGroupName")[0])
+                if (names is None) or self.tool.matchString(user.Name, names) :
+                    grouppquota = self.getGroupPQuota(group, printer)
+                    groupsandquotas.append((group, grouppquota))
+        return groupsandquotas
         
     def addPrinter(self, printername) :        
-        """Adds a printer to the quota storage, returns its id."""
+        """Adds a printer to the quota storage, returns it."""
         fields = { self.info["printerrdn"] : printername,
                    "objectClass" : ["pykotaObject", "pykotaPrinter"],
+                   "cn" : printername,
                    "pykotaPrinterName" : printername,
                    "pykotaPricePerPage" : "0.0",
@@ -256,276 +426,146 @@
                  } 
         dn = "%s=%s,%s" % (self.info["printerrdn"], printername, self.info["printerbase"])
-        return self.doAdd(dn, fields)
-        
-    def addUser(self, username) :        
-        """Adds a user to the quota storage, returns its id."""
-        fields = { self.info["userrdn"] : username,
-                   "objectClass" : ["pykotaObject", "pykotaAccount", "pykotaAccountBalance"],
-                   "pykotaUserName" : username,
-                   "pykotaLimitBy" : "quota",
-                   "pykotaBalance" : "0.0",
-                   "pykotaLifeTimePaid" : "0.0",
+        self.doAdd(dn, fields)
+        return self.getPrinter(printername)
+        
+    def addUser(self, user) :        
+        """Adds a user to the quota storage, returns it."""
+        fields = { self.info["userrdn"] : user.Name,
+                   "objectClass" : ["pykotaObject", "pykotaAccount"],
+                   "cn" : user.Name,
+                   "pykotaUserName" : user.Name,
+                   "pykotaLimitBY" : (user.LimitBy or "quota"),
                  } 
-        dn = "%s=%s,%s" % (self.info["userrdn"], username, self.info["userbase"])
-        return self.doAdd(dn, fields)
-        
-    def addGroup(self, groupname) :        
-        """Adds a group to the quota storage, returns its id."""
-        fields = { self.info["grouprdn"] : groupname,
+        dn = "%s=%s,%s" % (self.info["userrdn"], user.Name, self.info["userbase"])
+        self.doAdd(dn, fields)
+        fields = { 
+                   "objectClass" : ["pykotaObject", "pykotaAccountBalance"],
+                   "cn" : user.Name,
+                   "pykotaUserName" : user.Name,
+                   "pykotaBalance" : str(user.AccountBalance or 0.0),
+                   "pykotaLifeTimePaid" : str(user.LifeTimePaid or 0.0),
+                 } 
+        dn = "cn=%s,%s" % (user.Name, self.info["balancebase"])
+        self.doAdd(dn, fields)
+        return self.getUser(user.Name)
+        
+    def addGroup(self, group) :        
+        """Adds a group to the quota storage, returns it."""
+        fields = { self.info["grouprdn"] : group.Name,
                    "objectClass" : ["pykotaObject", "pykotaGroup"],
-                   "pykotaGroupName" : groupname,
-                   "pykotaLimitBy" : "quota",
+                   "cn" : group.Name,
+                   "pykotaGroupName" : group.Name,
+                   "pykotaLimitBY" : (group.LimitBy or "quota"),
                  } 
-        dn = "%s=%s,%s" % (self.info["grouprdn"], groupname, self.info["groupbase"])
-        return self.doAdd(dn, fields)
-        
-    def addUserPQuota(self, username, printerid) :
-        """Initializes a user print quota on a printer, adds the user to the quota storage if needed."""
+        dn = "%s=%s,%s" % (self.info["grouprdn"], group.Name, self.info["groupbase"])
+        self.doAdd(dn, fields)
+        return self.getGroup(group.Name)
+        
+    def addUserToGroup(self, user, group) :    
+        """Adds an user to a group."""
+        if user.Name not in [u.Name for u in group.Members] :
+            result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)    
+            if result :
+                fields = result[0][1]
+                fields[self.info["groupmembers"]].append(user.Name)
+                self.doModify(group.ident, fields)
+                group.Members.append(user)
+                
+    def addUserPQuota(self, user, printer) :
+        """Initializes a user print quota on a printer."""
         uuid = self.genUUID()
-        fields = { "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
-                   "cn" : uuid,
-                   "pykotaUserName" : username,
-                   "pykotaPrinterName" : self.getPrinterName(printerid), 
+        fields = { "cn" : uuid,
+                   "objectClass" : ["pykotaObject", "pykotaUserPQuota"],
+                   "pykotaUserName" : user.Name,
+                   "pykotaPrinterName" : printer.Name,
+                   "pykotaDateLimit" : "None",
                    "pykotaPageCounter" : "0",
                    "pykotaLifePageCounter" : "0",
-                   "pykotaSoftLimit" : "0",
-                   "pykotaHardLimit" : "0",
-                   "pykotaDateLimit" : "None",
                  } 
         dn = "cn=%s,%s" % (uuid, self.info["userquotabase"])
         self.doAdd(dn, fields)
-        return (dn, printerid)
-        
-    def addGroupPQuota(self, groupname, printerid) :
-        """Initializes a group print quota on a printer, adds the group to the quota storage if needed."""
+        return self.getUserPQuota(user, printer)
+        
+    def addGroupPQuota(self, group, printer) :
+        """Initializes a group print quota on a printer."""
         uuid = self.genUUID()
-        fields = { "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
-                   "cn" : uuid,
-                   "pykotaGroupName" : groupname,
-                   "pykotaPrinterName" : self.getPrinterName(printerid), 
-                   "pykotaSoftLimit" : "0",
-                   "pykotaHardLimit" : "0",
+        fields = { "cn" : uuid,
+                   "objectClass" : ["pykotaObject", "pykotaGroupPQuota"],
+                   "pykotaGroupName" : group.Name,
+                   "pykotaPrinterName" : printer.Name,
                    "pykotaDateLimit" : "None",
                  } 
         dn = "cn=%s,%s" % (uuid, self.info["groupquotabase"])
         self.doAdd(dn, fields)
-        return (dn, printerid)
-        
-    def increaseUserBalance(self, userquotaid, amount) :    
-        """Increases (or decreases) an user's account balance by a given amount."""
-        balance = self.getUserBalance(userquotaid)
-        if balance :
-            (newbal, newpaid) = [(float(v) + float(amount)) for v in balance]
-            result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName"], base=userquotaid, scope=ldap.SCOPE_BASE)
-            if result :
-                username = result[0][1]["pykotaUserName"][0]
-                if username :
-                    result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % username , [ "pykotaBalance", "pykotaLifeTimePaid"])
-                    fields = {
-                               "pykotaBalance" : str(newbal),
-                               "pykotaLifeTimePaid" : str(newpaid),
-                             }
-                    return self.doModify(result[0][0], fields)         
-        
-    def getUserBalance(self, userquotaid) :    
-        """Returns the current account balance for a given user quota identifier."""
-        # first get the user's name from the user quota id
-        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName"], base=userquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            username = result[0][1]["pykotaUserName"][0]
-            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"])
-            if result :
-                fields = result[0][1]
-                return (float(fields["pykotaBalance"][0]), float(fields["pykotaLifeTimePaid"][0]))
-        
-    def getUserBalanceFromUserId(self, userid) :    
-        """Returns the current account balance for a given user id."""
-        # first get the user's name from the user id
-        result = self.doSearch("objectClass=pykotaAccount", ["pykotaUserName", self.info["userrdn"]], base=userid, scope=ldap.SCOPE_BASE)
-        if result :
-            fields = result[0][1]
-            username = (fields.get("pykotaUserName") or fields.get(self.info["userrdn"]))[0]
-            result = self.doSearch("(&(objectClass=pykotaAccountBalance)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaBalance", "pykotaLifeTimePaid"])
-            if result :
-                fields = result[0][1]
-                return (float(fields["pykotaBalance"][0]), float(fields["pykotaLifeTimePaid"][0]))
-        
-    def getGroupBalance(self, groupquotaid) :    
-        """Returns the current account balance for a given group, as the sum of each of its users' account balance."""
-        # first get the group's name from the group quota id
-        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName"], base=groupquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            groupname = result[0][1]["pykotaGroupName"][0]
-            members = self.getGroupMembersNames(groupname) or []
-            balance = lifetimepaid = 0.0
-            for member in members :
-                userid = self.getUserId(member)
-                if userid :
-                    userbal = self.getUserBalanceFromUserId(userid)
-                    if userbal :
-                        (bal, paid) = userbal
-                        balance += bal
-                        lifetimepaid += paid
-            return (balance, lifetimepaid)            
-        
-    def getUserLimitBy(self, userquotaid) :    
-        """Returns the way in which user printing is limited."""
-        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName"], base=userquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            username = result[0][1]["pykotaUserName"][0]
-            result = self.doSearch("(&(objectClass=pykotaAccount)(|(pykotaUserName=%s)(%s=%s)))" % (username, self.info["userrdn"], username), ["pykotaLimitBy"])
-            if result :
-                return result[0][1]["pykotaLimitBy"][0]
-        
-    def getGroupLimitBy(self, groupquotaid) :    
-        """Returns the way in which group printing is limited."""
-        # first get the group's name from the group quota id
-        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName"], base=groupquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            groupname = result[0][1]["pykotaGroupName"][0]
-            result = self.doSearch("(&(objectClass=pykotaGroup)(|(pykotaGroupName=%s)(%s=%s)))" % (groupname, self.info["grouprdn"], groupname), ["pykotaLimitBy"])
-            if result :
-                return result[0][1]["pykotaLimitBy"][0]
-        
-    def setUserBalance(self, userquotaid, balance) :    
-        """Sets the account balance for a given user to a fixed value."""
-        oldbalance = self.getUserBalance(userquotaid)
-        if oldbalance :
-            (oldbal, oldpaid) = oldbalance
-            difference = balance - oldbal
-            return self.increaseUserBalance(userquotaid, difference)
-        
-    def limitUserBy(self, userquotaid, limitby) :    
-        """Limits a given user based either on print quota or on account balance."""
-        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName"], base=userquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            username = result[0][1]["pykotaUserName"][0]
-            fields = {
-                       "pykotaLimitBy" : limitby,
-                     }
-            self.doModify(self.getUserId(username), fields)
-        
-    def limitGroupBy(self, groupquotaid, limitby) :    
-        """Limits a given group based either on print quota or on sum of its users' account balances."""
-        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName"], base=groupquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            groupname = result[0][1]["pykotaGroupName"][0]
-            fields = {
-                       "pykotaLimitBy" : limitby,
-                     }
-            self.doModify(self.getGroupId(groupname), fields)
-        
-    def setUserPQuota(self, userquotaid, printerid, softlimit, hardlimit) :
-        """Sets soft and hard limits for a user quota on a specific printer given (userid, printerid)."""
-        fields = { 
-                   "pykotaSoftLimit" : str(softlimit),
-                   "pykotaHardLimit" : str(hardlimit),
-                   "pykotaDateLimit" : "None",
-                 } 
-        return self.doModify(userquotaid, fields)
-        
-    def setGroupPQuota(self, groupquotaid, printerid, softlimit, hardlimit) :
-        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
-        fields = { 
-                   "pykotaSoftLimit" : str(softlimit),
-                   "pykotaHardLimit" : str(hardlimit),
-                   "pykotaDateLimit" : "None",
-                 } 
-        return self.doModify(groupquotaid, fields)
-        
-    def resetUserPQuota(self, userquotaid, printerid) :    
-        """Resets the page counter to zero for a user on a printer. Life time page counter is kept unchanged."""
-        fields = {
-                   "pykotaPageCounter" : "0",
-                   "pykotaDateLimit" : "None",
-                 }
-        return self.doModify(userquotaid, fields)      
-        
-    def resetGroupPQuota(self, groupquotaid, printerid) :    
-        """Resets the page counter to zero for a group on a printer. Life time page counter is kept unchanged."""
-        fields = {
-                   "pykotaPageCounter" : "0",
-                   "pykotaDateLimit" : "None",
-                 }
-        return self.doModify(groupquotaid, fields)      
-        
-    def updateUserPQuota(self, userquotaid, printerid, pagecount) :
-        """Updates the used user Quota information given (userid, printerid) and a job size in pages."""
-        jobprice = self.computePrinterJobPrice(printerid, pagecount)
-        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaPageCounter", "pykotaLifePageCounter"], base=userquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            oldfields = result[0][1]
-            fields = {
-                       "pykotaPageCounter" : str(pagecount + int(oldfields["pykotaPageCounter"][0])),
-                       "pykotaLifePageCounter" : str(pagecount + int(oldfields["pykotaLifePageCounter"][0])),
-                     }  
-            return self.doModify(userquotaid, fields)         
-        
-    def getUserPQuota(self, userquotaid, printerid) :
-        """Returns the Print Quota information for a given (userquotaid, printerid)."""
-        # first get the user's name from the id
-        result = self.doSearch("objectClass=pykotaUserPQuota", ["pykotaUserName", "pykotaPageCounter", "pykotaLifePageCounter", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=userquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            fields = result[0][1]
-            datelimit = fields["pykotaDateLimit"][0].strip()
-            if (not datelimit) or (datelimit.upper() == "NONE") : 
-                datelimit = None
-            return { "lifepagecounter" : int(fields["pykotaLifePageCounter"][0]), 
-                     "pagecounter" : int(fields["pykotaPageCounter"][0]),
-                     "softlimit" : int(fields["pykotaSoftLimit"][0]),
-                     "hardlimit" : int(fields["pykotaHardLimit"][0]),
-                     "datelimit" : datelimit
-                   }
-        
-    def getGroupPQuota(self, grouppquotaid, printerid) :
-        """Returns the Print Quota information for a given (grouppquotaid, printerid)."""
-        result = self.doSearch("objectClass=pykotaGroupPQuota", ["pykotaGroupName", "pykotaSoftLimit", "pykotaHardLimit", "pykotaDateLimit"], base=grouppquotaid, scope=ldap.SCOPE_BASE)
-        if result :
-            fields = result[0][1]
-            groupname = fields["pykotaGroupName"][0]
-            datelimit = fields["pykotaDateLimit"][0].strip()
-            if (not datelimit) or (datelimit.upper() == "NONE") : 
-                datelimit = None
-            quota = {
-                      "softlimit" : int(fields["pykotaSoftLimit"][0]),
-                      "hardlimit" : int(fields["pykotaHardLimit"][0]),
-                      "datelimit" : datelimit
-                    }
-            members = self.getGroupMembersNames(groupname) or []
-            pagecounter = lifepagecounter = 0
-            printerusers = self.getPrinterUsers(printerid)
-            if printerusers :
-                for (userid, username) in printerusers :
-                    if username in members :
-                        userpquota = self.getUserPQuota(userid, printerid)
-                        if userpquota :
-                            pagecounter += userpquota["pagecounter"]
-                            lifepagecounter += userpquota["lifepagecounter"]
-            quota.update({"pagecounter": pagecounter, "lifepagecounter": lifepagecounter})                
-            return quota
-        
-    def setUserDateLimit(self, userquotaid, printerid, datelimit) :
-        """Sets the limit date for a soft limit to become an hard one given (userid, printerid)."""
+        return self.getGroupPQuota(group, printer)
+        
+    def writePrinterPrices(self, printer) :    
+        """Write the printer's prices back into the storage."""
+        fields = {
+                   "pykotaPricePerPage" : str(printer.PricePerPage),
+                   "pykotaPricePerJob" : str(printer.PricePerJob),
+                 }
+        self.doModify(printer.ident, fields)
+        
+    def writeUserLimitBy(self, user, limitby) :    
+        """Sets the user's limiting factor."""
+        fields = {
+                   "pykotaLimitBy" : limitby,
+                 }
+        self.doModify(user.ident, fields)         
+        
+    def writeGroupLimitBy(self, group, limitby) :    
+        """Sets the group's limiting factor."""
+        fields = {
+                   "pykotaLimitBy" : limitby,
+                 }
+        self.doModify(group.ident, fields)         
+        
+    def writeUserPQuotaDateLimit(self, userpquota, datelimit) :    
+        """Sets the date limit permanently for a user print quota."""
         fields = {
                    "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
                  }
-        return self.doModify(userquotaid, fields)
-        
-    def setGroupDateLimit(self, groupquotaid, printerid, datelimit) :
-        """Sets the limit date for a soft limit to become an hard one given (groupid, printerid)."""
+        return self.doModify(userpquota.ident, fields)
+            
+    def writeGroupPQuotaDateLimit(self, grouppquota, datelimit) :    
+        """Sets the date limit permanently for a group print quota."""
         fields = {
                    "pykotaDateLimit" : "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second),
                  }
-        return self.doModify(groupquotaid, fields)
-        
-    def addJobToHistory(self, jobid, userid, printerid, pagecounter, action, jobsize=None) :
-        """Adds a job to the history: (jobid, userid, printerid, last page counter taken from requester)."""
+        return self.doModify(grouppquota.ident, fields)
+        
+    def writeUserPQuotaPagesCounters(self, userpquota, newpagecounter, newlifepagecounter) :    
+        """Sets the new page counters permanently for a user print quota."""
+        fields = {
+                   "pykotaPageCounter" : str(newpagecounter),
+                   "pykotaLifePageCounter" : str(newlifepagecounter),
+                 }  
+        return self.doModify(userpquota.ident, fields)         
+       
+    def writeUserAccountBalance(self, user, newbalance, newlifetimepaid=None) :    
+        """Sets the new account balance and eventually new lifetime paid."""
+        fields = {
+                   "pykotaBalance" : str(newbalance),
+                 }
+        if newlifetimepaid is not None :
+            fields.update({ "pykotaLifeTimePaid" : str(newlifetimepaid) })
+        return self.doModify(user.idbalance, fields)         
+            
+    def writeLastJobSize(self, lastjob, jobsize) :        
+        """Sets the last job's size permanently."""
+        fields = {
+                   "pykotaJobSize" : str(jobsize),
+                 }
+        self.doModify(lastjob.ident, fields)         
+        
+    def writeJobNew(self, printer, user, jobid, pagecounter, action, jobsize=None) :    
+        """Adds a job in a printer's history."""
         uuid = self.genUUID()
-        printername = self.getPrinterName(printerid)
         fields = {
                    "objectClass" : ["pykotaObject", "pykotaJob"],
                    "cn" : uuid,
-                   "pykotaUserName" : self.getUserName(userid),
-                   "pykotaPrinterName" : printername,
+                   "pykotaUserName" : user.Name,
+                   "pykotaPrinterName" : printer.Name,
                    "pykotaJobId" : jobid,
                    "pykotaPrinterPageCounter" : str(pagecounter),
@@ -536,11 +576,9 @@
         dn = "cn=%s,%s" % (uuid, self.info["jobbase"])
         self.doAdd(dn, fields)
-        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaPrinterName=%s))" % printername, None, base=self.info["lastjobbase"])
-        if result :
-            lastjdn = result[0][0] 
+        if printer.LastJob.Exists :
             fields = {
                        "pykotaLastJobIdent" : uuid,
                      }
-            self.doModify(lastjdn, fields)         
+            self.doModify(printer.LastJob.lastjobident, fields)         
         else :    
             lastjuuid = self.genUUID()
@@ -549,57 +587,85 @@
                        "objectClass" : ["pykotaObject", "pykotaLastJob"],
                        "cn" : lastjuuid,
-                       "pykotaPrinterName" : printername,
+                       "pykotaPrinterName" : printer.Name,
                        "pykotaLastJobIdent" : uuid,
                      }  
             self.doAdd(lastjdn, fields)          
-    
-    def updateJobSizeInHistory(self, historyid, jobsize) :
-        """Updates a job size in the history given the history line's id."""
-        result = self.doSearch("(&(objectClass=pykotaJob)(cn=%s))" % historyid, ["cn"], base=self.info["jobbase"])
-        if result :
-            fields = {
-                       "pykotaJobSize" : str(jobsize),
-                     }
-            self.doModify(result[0][0], fields)         
-    
-    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.doSearch("objectClass=pykotaPrinter", ["pykotaPrinterName", self.info["printerrdn"]], base=printerid, scope=ldap.SCOPE_BASE)
+            
+    def writeUserPQuotaLimits(self, userpquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a user quota."""
+        fields = { 
+                   "pykotaSoftLimit" : str(softlimit),
+                   "pykotaHardLimit" : str(hardlimit),
+                 }
+        self.doModify(userpquota.ident, fields)
+        
+    def writeGroupPQuotaLimits(self, grouppquota, softlimit, hardlimit) :
+        """Sets soft and hard limits for a group quota on a specific printer given (groupid, printerid)."""
+        fields = { 
+                   "pykotaSoftLimit" : str(softlimit),
+                   "pykotaHardLimit" : str(hardlimit),
+                 }
+        self.doModify(grouppquota.ident, fields)
+            
+    def deleteUser(self, user) :    
+        """Completely deletes an user from the Quota Storage."""
+        # TODO : What should we do if we delete the last person who used a given printer ?
+        # TODO : we can't reassign the last job to the previous one, because next user would be
+        # TODO : incorrectly charged (overcharged).
+        result = self.doSearch("(&(objectClass=pykotaLastJob)(pykotaUserName=%s))" % user.Name, base=self.info["lastjobbase"])
+        for (ident, fields) in result :
+            self.doDelete(ident)
+        result = self.doSearch("(&(objectClass=pykotaJob)(pykotaUserName=%s))" % user.Name, base=self.info["jobbase"])
+        for (ident, fields) in result :
+            self.doDelete(ident)
+        result = self.doSearch("(&(objectClass=pykotaUserPQuota)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["userquotabase"])
+        for (ident, fields) in result :
+            self.doDelete(ident)
+        result = self.doSearch("objectClass=pykotaAccount", None, base=user.ident, scope=ldap.SCOPE_BASE)    
         if result :
             fields = result[0][1]
-            printername = (fields.get("pykotaPrinterName") or fields.get(self.info["printerrdn"]))[0]
-            result = self.doSearch("(&(objectClass=pykotaLastjob)(|(pykotaPrinterName=%s)(%s=%s)))" % (printername, self.info["printerrdn"], printername), ["pykotaLastJobIdent"], base=self.info["lastjobbase"])
-            if result :
-                lastjobident = result[0][1]["pykotaLastJobIdent"][0]
-                result = self.doSearch("(&(objectClass=pykotaJob)(cn=%s))" % lastjobident, ["pykotaUserName", "pykotaPrinterName", "pykotaJobId", "pykotaPrinterPageCounter", "pykotaJobSize", "pykotaAction", "createTimestamp"], base=self.info["jobbase"])
-                if result :
-                    fields = result[0][1]
-                    return { "id": lastjobident, 
-                             "jobid" : fields.get("pykotaJobId")[0],
-                             "userid" : self.getUserId(fields.get("pykotaUserName")[0]),
-                             "username" : fields.get("pykotaUserName")[0], 
-                             "pagecounter" : int(fields.get("pykotaPrinterPageCounter")[0]),
-                             "jobsize" : int(fields.get("pykotaJobSize")[0]),
-                           }
-        
-    def addUserToGroup(self, userid, groupid) :    
-        """Adds an user to a group."""
-        raise PyKotaStorageError, "Not implemented !"
-        
-    def deleteUser(self, userid) :    
-        """Completely deletes an user from the Quota Storage."""
-        raise PyKotaStorageError, "Not implemented !"
-        
-    def deleteGroup(self, groupid) :    
-        """Completely deletes an user from the Quota Storage."""
-        raise PyKotaStorageError, "Not implemented !"
-        
-    def computePrinterJobPrice(self, printerid, jobsize) :    
-        """Returns the price for a job on a given printer."""
-        # TODO : create a base class with things like this
-        prices = self.getPrinterPrices(printerid)
-        if prices is None :
-            perpage = perjob = 0.0
-        else :    
-            (perpage, perjob) = prices
-        return perjob + (perpage * jobsize)
+            for k in fields.keys() :
+                if k.startswith("pykota") :
+                    del fields[k]
+                elif k.lower() == "objectclass" :    
+                    todelete = []
+                    for i in range(len(fields[k])) :
+                        if fields[k][i].startswith("pykota") : 
+                            todelete.append(i)
+                    todelete.sort()        
+                    todelete.reverse()
+                    for i in todelete :
+                        del fields[k][i]
+            if fields.get("objectclass") :            
+                self.doModify(user.ident, fields, ignoreold=0)        
+            else :    
+                self.doDelete(user.ident)
+        result = self.doSearch("(&(objectClass=pykotaAccountBalance)(pykotaUserName=%s))" % user.Name, ["pykotaUserName"], base=self.info["balancebase"])
+        for (ident, fields) in result :
+            self.doDelete(ident)
+        
+    def deleteGroup(self, group) :    
+        """Completely deletes a group from the Quota Storage."""
+        result = self.doSearch("(&(objectClass=pykotaGroupPQuota)(pykotaGroupName=%s))" % group.Name, ["pykotaGroupName"], base=self.info["groupquotabase"])
+        for (ident, fields) in result :
+            self.doDelete(ident)
+        result = self.doSearch("objectClass=pykotaGroup", None, base=group.ident, scope=ldap.SCOPE_BASE)    
+        if result :
+            fields = result[0][1]
+            for k in fields.keys() :
+                if k.startswith("pykota") :
+                    del fields[k]
+                elif k.lower() == "objectclass" :    
+                    todelete = []
+                    for i in range(len(fields[k])) :
+                        if fields[k][i].startswith("pykota") : 
+                            todelete.append(i)
+                    todelete.sort()        
+                    todelete.reverse()
+                    for i in todelete :
+                        del fields[k][i]
+            if fields.get("objectclass") :            
+                self.doModify(group.ident, fields, ignoreold=0)        
+            else :    
+                self.doDelete(group.ident)
+            
Index: /pykota/trunk/pykota/storage.py
===================================================================
--- /pykota/trunk/pykota/storage.py (revision 1021)
+++ /pykota/trunk/pykota/storage.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.14  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.13  2003/06/10 16:37:54  jalet
 # Deletion of the second user which is not needed anymore.
@@ -84,4 +87,190 @@
     __str__ = __repr__
         
+class StorageObject :
+    """Object present in the Quota Storage."""
+    def __init__(self, parent) :
+        "Initialize minimal data."""
+        self.parent = parent
+        self.ident = None
+        self.Exists = 0
+        
+class StorageUser(StorageObject) :        
+    """User class."""
+    def __init__(self, parent, name) :
+        StorageObject.__init__(self, parent)
+        self.Name = name
+        self.LimitBy = None
+        self.AccountBalance = None
+        self.LifeTimePaid = None
+        
+    def consumeAccountBalance(self, amount) :     
+        """Consumes an amount of money from the user's account balance."""
+        newbalance = float(self.AccountBalance or 0.0) - amount
+        self.parent.writeUserAccountBalance(self, newbalance)
+        self.AccountBalance = newbalance
+        
+    def setAccountBalance(self, balance, lifetimepaid) :    
+        """Sets the user's account balance in case he pays more money."""
+        
+    def setLimitBy(self, limitby) :    
+        """Sets the user's limiting factor."""
+        limitby = limitby.lower()
+        if limitby in ["quota", "balance"] :
+            self.parent.writeUserLimitBy(self, limitby)
+            self.LimitBy = limitby
+        
+    def delete(self) :    
+        """Deletes an user from the Quota Storage."""
+        self.parent.beginTransaction()
+        try :
+            self.parent.deleteUser(self)
+        except PyKotaStorageError, msg :    
+            self.parent.rollbackTransaction()
+            raise PyKotaStorageError, msg
+        else :    
+            self.parent.commitTransaction()
+        
+class StorageGroup(StorageObject) :        
+    """User class."""
+    def __init__(self, parent, name) :
+        StorageObject.__init__(self, parent)
+        self.Name = name
+        self.LimitBy = None
+        self.AccountBalance = None
+        self.LifeTimePaid = None
+        
+    def setLimitBy(self, limitby) :    
+        """Sets the user's limiting factor."""
+        limitby = limitby.lower()
+        if limitby in ["quota", "balance"] :
+            self.parent.writeGroupLimitBy(self, limitby)
+            self.LimitBy = limitby
+        
+    def delete(self) :    
+        """Deletes a group from the Quota Storage."""
+        self.parent.beginTransaction()
+        try :
+            self.parent.deleteGroup(self)
+        except PyKotaStorageError, msg :    
+            self.parent.rollbackTransaction()
+            raise PyKotaStorageError, msg
+        else :    
+            self.parent.commitTransaction()
+        
+class StoragePrinter(StorageObject) :
+    """Printer class."""
+    def __init__(self, parent, name) :
+        StorageObject.__init__(self, parent)
+        self.Name = name
+        self.PricePerPage = None
+        self.PricePerJob = None
+        self.LastJob = None
+        
+    def addJobToHistory(self, jobid, user, pagecounter, action, jobsize=None) :    
+        """Adds a job to the printer's history."""
+        self.parent.writeJobNew(self, user, jobid, pagecounter, action, jobsize)
+        # TODO : update LastJob object ? Probably not needed.
+        
+    def setPrices(self, priceperpage = None, priceperjob = None) :    
+        """Sets the printer's prices."""
+        if priceperpage is None :
+            priceperpage = self.PricePerPage
+        else :    
+            self.PricePerPage = float(priceperpage)
+        if priceperjob is None :    
+            priceperjob = self.PricePerJob
+        else :    
+            self.PricePerJob = float(priceperjob)
+        self.parent.writePrinterPrices(self)
+        
+class StorageUserPQuota(StorageObject) :
+    """User Print Quota class."""
+    def __init__(self, parent, user, printer) :
+        StorageObject.__init__(self, parent)
+        self.User = user
+        self.Printer = printer
+        self.PageCounter = None
+        self.LifePageCounter = None
+        self.SoftLimit = None
+        self.HardLimit = None
+        self.DateLimit = None
+        
+    def setDateLimit(self, datelimit) :    
+        """Sets the date limit for this quota."""
+        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
+        self.parent.writeUserPQuotaDateLimit(self, date)
+        self.DateLimit = date
+        
+    def setLimits(self, softlimit, hardlimit) :    
+        """Sets the soft and hard limit for this quota."""
+        self.parent.writeUserPQuotaLimits(self, softlimit, hardlimit)
+        self.SoftLimit = softlimit
+        self.HardLimit = hardlimit
+        
+    def reset(self) :    
+        """Resets page counter to 0."""
+        self.parent.writeUserPQuotaPagesCounters(self, 0, int(self.LifePageCounter or 0))
+        self.PageCounter = 0
+        
+    def increasePagesUsage(self, nbpages) :
+        """Increase the value of used pages and money."""
+        if nbpages :
+            jobprice = (float(self.Printer.PricePerPage or 0.0) * nbpages) + float(self.Printer.PricePerJob or 0.0)
+            newpagecounter = int(self.PageCounter or 0) + nbpages
+            newlifepagecounter = int(self.LifePageCounter or 0) + nbpages
+            self.parent.beginTransaction()
+            try :
+                if jobprice : # optimization : don't access the database if unneeded.
+                    self.User.consumeAccountBalance(jobprice)
+                self.parent.writeUserPQuotaPagesCounters(self, newpagecounter, newlifepagecounter)
+            except PyKotaStorageError, msg :    
+                self.parent.rollbackTransaction()
+                raise PyKotaStorageError, msg
+            else :    
+                self.parent.commitTransaction()
+                self.PageCounter = newpagecounter
+                self.LifePageCounter = newlifepagecounter
+        
+class StorageGroupPQuota(StorageObject) :
+    """Group Print Quota class."""
+    def __init__(self, parent, group, printer) :
+        StorageObject.__init__(self, parent)
+        self.Group = group
+        self.Printer = printer
+        self.PageCounter = None
+        self.LifePageCounter = None
+        self.SoftLimit = None
+        self.HardLimit = None
+        self.DateLimit = None
+        
+    def setDateLimit(self, datelimit) :    
+        """Sets the date limit for this quota."""
+        date = "%04i-%02i-%02i %02i:%02i:%02i" % (datelimit.year, datelimit.month, datelimit.day, datelimit.hour, datelimit.minute, datelimit.second)
+        self.parent.writeGroupPQuotaDateLimit(self, date)
+        self.DateLimit = date
+        
+    def setLimits(self, softlimit, hardlimit) :    
+        """Sets the soft and hard limit for this quota."""
+        self.parent.writeGroupPQuotaLimits(self, softlimit, hardlimit)
+        self.SoftLimit = softlimit
+        self.HardLimit = hardlimit
+        
+class StorageLastJob(StorageObject) :
+    """Printer's Last Job class."""
+    def __init__(self, parent, printer) :
+        StorageObject.__init__(self, parent)
+        self.Printer = printer
+        self.JobId = None
+        self.User = None
+        self.PrinterPageCounter = None
+        self.JobSize = None
+        self.JobAction = None
+        self.JobDate = None
+        
+    def setSize(self, jobsize) :
+        """Sets the last job's size."""
+        self.parent.writeLastJobSize(self, jobsize)
+        self.JobSize = jobsize
+    
 def openConnection(pykotatool) :
     """Returns a connection handle to the appropriate Quota Storage Database."""
Index: /pykota/trunk/pykota/config.py
===================================================================
--- /pykota/trunk/pykota/config.py (revision 1029)
+++ /pykota/trunk/pykota/config.py (revision 1041)
@@ -21,4 +21,7 @@
 #
 # $Log$
+# Revision 1.30  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.29  2003/06/14 22:44:21  jalet
 # More work on LDAP storage backend.
@@ -201,4 +204,5 @@
         ldapinfo = {}
         for option in [ "userbase", "userrdn", \
+                        "balancebase", "balancerdn", \
                         "groupbase", "grouprdn", "groupmembers", \
                         "printerbase", "printerrdn", \
Index: /pykota/trunk/bin/warnpykota
===================================================================
--- /pykota/trunk/bin/warnpykota (revision 975)
+++ /pykota/trunk/bin/warnpykota (revision 1041)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.20  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.19  2003/04/29 22:03:38  jalet
 # Better error handling.
@@ -84,4 +87,7 @@
 
 import sys
+import os
+import pwd
+import grp
 
 from pykota import version
@@ -96,5 +102,5 @@
 command line usage :
 
-  warnpykota [options] 
+  warnpykota  [options]  [names]
 
 options :
@@ -125,8 +131,13 @@
   any printer.
 
-  $ warnpykota --groups --printer "laserjet*"
-  
-  This will warn all users of groups which have exceeded 
-  their print quota on any printer which name begins with "laserjet"
+  $ warnpykota --groups --printer "laserjet*" "dev*"
+  
+  This will warn all users of groups which names begins with "dev" and
+  who have exceeded their print quota on any printer which name begins 
+  with "laserjet"
+  
+  If launched by a non-root user, additionnal arguments representing
+  users or groups names are ignored, and only the current user/group
+  is warned.
 
 This program is free software; you can redistribute it and/or modify
@@ -148,16 +159,33 @@
 class WarnPyKota(PyKotaTool) :        
     """A class for warnpykota."""
-    def main(self, options) :
+    def main(self, ugnames, options) :
         """Warn users or groups over print quota."""
+        uid = os.geteuid()
+        if not uid :
+            # root user
+            if not ugnames :
+                # no username, means all usernames
+                ugnames = [ "*" ]
+        else :        
+            # not the root user
+            # warns only the current user
+            # the utility of this is discutable, but at least it
+            # protects other users from mail bombing if they are
+            # over quota.
+            if options["groups"] :
+                ugnames = [ grp.getgrgid(pwd.getpwuid(uid)[3])[0] ]
+            else :
+                ugnames = [ pwd.getpwuid(uid)[0] ]
+        
         printers = self.storage.getMatchingPrinters(options["printer"])
         if not printers :
             raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
-        for (printerid, printer) in printers :
+        for printer in printers :
             if options["groups"] :
-                for (ident, name) in self.storage.getPrinterGroups(printerid) :
-                    self.warnGroupPQuota(name, printer)
+                for (group, grouppquota) in self.storage.getPrinterGroupsAndQuotas(printer, ugnames) :
+                    self.warnGroupPQuota(grouppquota)
             else :
-                for (ident, name) in self.storage.getPrinterUsers(printerid) :
-                    self.warnUserPQuota(name, printer)
+                for (user, userpquota) in self.storage.getPrinterUsersAndQuotas(printer, ugnames) :
+                    self.warnUserPQuota(userpquota)
                      
 if __name__ == "__main__" : 
@@ -188,8 +216,6 @@
         elif options["users"] and options["groups"] :    
             raise PyKotaToolError, _("incompatible options, see help.")
-        elif args :    
-            raise PyKotaToolError, _("unused arguments [%s]. Aborting.") % ", ".join(args)
         else :
-            sys.exit(sender.main(options))
+            sys.exit(sender.main(args, options))
     except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :            
         sys.stderr.write("%s\n" % msg)
Index: /pykota/trunk/bin/edpykota
===================================================================
--- /pykota/trunk/bin/edpykota (revision 1031)
+++ /pykota/trunk/bin/edpykota (revision 1041)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.47  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.46  2003/06/16 11:59:09  jalet
 # More work on LDAP
@@ -330,40 +333,24 @@
     def main(self, names, options) :
         """Edit user or group quotas."""
-        printeradded = 0
-        printers = self.storage.getMatchingPrinters(options["printer"])
-        if not printers :
-            pname = options["printer"]
-            if options["add"] and pname :
-                if self.isValidName(pname) :
-                    printerid = self.storage.addPrinter(pname)
-                    printers = [ (printerid, pname) ]
-                    printeradded = 1
-                else :    
-                    raise PyKotaToolError, _("Invalid printer name %s") % pname
-            else :
-                raise PyKotaToolError, _("There's no printer matching %s") % pname
-                
+        
+        suffix = (options["groups"] and "Group") or "User"        
+        
         softlimit = hardlimit = None    
-        if options["softlimit"] :
-            try :
-                softlimit = int(options["softlimit"].strip())
-            except ValueError :    
-                raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
-        if options["hardlimit"] :
-            try :
-                hardlimit = int(options["hardlimit"].strip())
-            except ValueError :    
-                raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
-        if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :        
-            # error, exchange them
-            self.logger.log_message(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
-            (softlimit, hardlimit) = (hardlimit, softlimit)
+        if not options["noquota"] :
+            if options["softlimit"] :
+                try :
+                    softlimit = int(options["softlimit"].strip())
+                except ValueError :    
+                    raise PyKotaToolError, _("Invalid softlimit value %s.") % options["softlimit"]
+            if options["hardlimit"] :
+                try :
+                    hardlimit = int(options["hardlimit"].strip())
+                except ValueError :    
+                    raise PyKotaToolError, _("Invalid hardlimit value %s.") % options["hardlimit"]
+            if (softlimit is not None) and (hardlimit is not None) and (hardlimit < softlimit) :        
+                # error, exchange them
+                self.logger.log_message(_("Hard limit %i is less than soft limit %i, values will be exchanged.") % (hardlimit, softlimit))
+                (softlimit, hardlimit) = (hardlimit, softlimit)
             
-        if not names :    
-            if options["add"] and not printeradded :
-                raise PyKotaToolError, _("You have to pass user or group names on the command line")
-            else :    
-                names = [ "*" ] # all users
-                
         balance = options["balance"]
         if balance :
@@ -394,54 +381,67 @@
             groupnames = []
             
-        uwaschanged = {}         # tracks changed made at the user level
-        gwaschanged = {}         # tracks changed made at the group level
-        for (printerid, printer) in printers :
+        if options["prototype"] :    
+            protoentry = getattr(self.storage, "get%s" % suffix)(options["prototype"])
+            
+        printeradded = 0
+        printers = self.storage.getMatchingPrinters(options["printer"])
+        if not printers :
+            pname = options["printer"]
+            if options["add"] and pname :
+                if self.isValidName(pname) :
+                    printers = [ self.storage.addPrinter(pname) ]
+                    if printers[0].Exists :
+                        printeradded = 1
+                    else :    
+                        raise PyKotaToolError, _("Impossible to add printer %s") % pname
+                else :    
+                    raise PyKotaToolError, _("Invalid printer name %s") % pname
+            else :
+                raise PyKotaToolError, _("There's no printer matching %s") % pname
+        if not names :    
+            if options["add"] and not printeradded :
+                raise PyKotaToolError, _("You have to pass user or group names on the command line")
+            else :    
+                names = [ "*" ] # all users
+                
+        changed = {} # tracks changes made at the user/group level
+        for printer in printers :
             if options["charge"] :
                 (perpage, perjob) = charges
-                if perjob is None :
-                    # we don't want to change this one, get the old value
-                    (dummy, perjob) = self.storage.getPrinterPrices(printerid)
-                self.storage.setPrinterPrices(printerid, perpage, perjob)    
+                printer.setPrices(perpage, perjob)    
+                
             if options["prototype"] :
-                if options["groups"] :
-                    prototype = self.storage.getGroupPQuota(self.storage.getGroupId(options["prototype"]), printerid)
-                else :     
-                    # default is user quota edition
-                    prototype = self.storage.getUserPQuota(self.storage.getUserId(options["prototype"]), printerid)
-                if prototype is None :
-                    self.logger.log_message(_("Prototype %s not found in Quota Storage for printer %s.") % (options["prototype"], printer))
-                    continue    # skip this printer
-                else :    
-                    (softlimit, hardlimit) = (prototype["softlimit"], prototype["hardlimit"])
-            if hardlimit is None :    
-                hardlimit = softlimit
-                if hardlimit is not None :
-                    self.logger.log_message(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer))
-            if softlimit is None :    
-                softlimit = hardlimit
-                if softlimit is not None :
-                    self.logger.log_message(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer))
-            if (not options["ingroups"] and not options["reset"] and not options["noquota"] and not options["prototype"] and not options["limitby"] and not options["balance"] and not options["delete"] and not options["charge"]) and ((hardlimit is None) or (softlimit is None)) :
-                raise PyKotaToolError, _("Both hard and soft limits must be set ! Aborting.")
+                if protoentry.Exists :
+                    protoquota = getattr(self.storage, "get%PQuota" % suffix)(protoentry, printer)
+                    if not protoquota.Exists :
+                        self.logger.log_message(_("Prototype %s not found in Quota Storage for printer %s.") % (protoentry.Name, printer.Name))
+                        continue    # skip this printer
+                    else :    
+                        (softlimit, hardlimit) = (protoquota.SoftLimit, protoquota.HardLimit)
+                else :        
+                    self.logger.log_message(_("Prototype object %s not found in Quota Storage.") % protoentry.Name)
+            if not options["noquota"] :    
+                if hardlimit is None :    
+                    hardlimit = softlimit
+                    if hardlimit is not None :
+                        self.logger.log_message(_("Undefined hard limit set to soft limit (%s) on printer %s.") % (str(hardlimit), printer.Name))
+                if softlimit is None :    
+                    softlimit = hardlimit
+                    if softlimit is not None :
+                        self.logger.log_message(_("Undefined soft limit set to hard limit (%s) on printer %s.") % (str(softlimit), printer.Name))
+                        
             if options["add"] :    
-                if options["groups"] :    
-                    allidnames = [(self.storage.getGroupId(n), n) for n in names]
-                else :
-                    allidnames = [(self.storage.getUserId(n), n) for n in names]
+                allentries = []    
+                for name in names :
+                    entry = getattr(self.storage, "get%s" % suffix)(name)
+                    entrypquota = getattr(self.storage, "get%sPQuota" % suffix)(entry, printer)
+                    allentries.append((entry, entrypquota))
             else :   
-                if options["groups"] :    
-                    allidnames = self.storage.getPrinterGroups(printerid) or []
-                else :    
-                    allidnames = self.storage.getPrinterUsers(printerid) or []
-            for (ident, name) in [(i, n) for (i, n) in allidnames if self.matchString(n, names)]:
-                if options["groups"] :
-                    if not gwaschanged.has_key(name) :
-                        gwaschanged[name] = {}
-                    quota = self.storage.getGroupPQuota(ident, printerid)
-                else :
-                    if not uwaschanged.has_key(name) :
-                        uwaschanged[name] = {"ingroups": []}
-                    quota = self.storage.getUserPQuota(ident, printerid)
-                if quota is None :
+                allentries = getattr(self.storage, "getPrinter%ssAndQuotas" % suffix)(printer)
+                
+            for (entry, entrypquota) in [(e, q) for (e, q) in allentries if self.matchString(e.Name, names)] :
+                if not changed.has_key(entry.Name) :
+                    changed[entry.Name] = {}
+                if not entrypquota.Exists :
                     # not found
                     if options["add"] :
@@ -450,60 +450,47 @@
                         # like /etc/passwd because users may be defined 
                         # only remotely
-                        if options["groups"] :
-                            if self.isValidName(name) :
-                                (ident, printerid) = self.storage.addGroupPQuota(name, printerid)
-                                quota = self.storage.getGroupPQuota(ident, printerid)
+                        if self.isValidName(entry.Name) :
+                            if not entry.Exists :
+                                entry = getattr(self.storage, "add%s" % suffix)(entry)
+                            entrypquota = getattr(self.storage, "add%sPQuota" % suffix)(entry, printer)
+                        else :    
+                            if options["groups"] :
+                                self.logger.log_message(_("Invalid group name %s") % entry.Name)
                             else :    
-                                self.logger.log_message(_("Invalid group name %s") % name)
-                        else :
-                            if self.isValidName(name) :
-                                (ident, printerid) = self.storage.addUserPQuota(name, printerid)
-                                quota = self.storage.getUserPQuota(ident, printerid)
-                            else :    
-                                self.logger.log_message(_("Invalid user name %s") % name)
-                if quota is None :     
-                    self.logger.log_message(_("Quota not found for object %s on printer %s.") % (name, printer))
+                                self.logger.log_message(_("Invalid user name %s") % entry.Name)
+                if not entrypquota.Exists :     
+                    self.logger.log_message(_("Quota not found for object %s on printer %s.") % (entry.Name, printer.Name))
                 else :    
                     if options["delete"] :
-                        if options["groups"] :
-                            self.storage.deleteGroup(ident)
-                        else :
-                            self.storage.deleteUser(ident)
+                        entry.delete()
                     else :
-                        if options["groups"] :
-                            if options["noquota"] or options["prototype"] or ((softlimit is not None) and (hardlimit is not None)) :
-                                self.storage.setGroupPQuota(ident, printerid, softlimit, hardlimit)
+                        if options["noquota"] or options["prototype"] or ((softlimit is not None) and (hardlimit is not None)) :
+                            entrypquota.setLimits(softlimit, hardlimit)
+                        if limitby :
+                            if changed[entry.Name].get("limitby") is None :
+                                entry.setLimitBy(limitby)
+                                changed[entry.Name]["limitby"] = limitby
+                        
+                        if not options["groups"] :
                             if options["reset"] :
-                                self.storage.resetGroupPQuota(ident, printerid)
-                            if limitby :
-                                if gwaschanged[name].get("limitby") is None :
-                                    self.storage.limitGroupBy(ident, limitby)
-                                    gwaschanged[name]["limitby"] = limitby
-                            self.warnGroupPQuota(name, printer)    
-                        else :
-                            if options["noquota"] or options["prototype"] or ((softlimit is not None) and (hardlimit is not None)) :
-                                self.storage.setUserPQuota(ident, printerid, softlimit, hardlimit)
-                            if options["reset"] :
-                                self.storage.resetUserPQuota(ident, printerid)
-                            if limitby :
-                                if uwaschanged[name].get("limitby") is None :
-                                    self.storage.limitUserBy(ident, limitby)
-                                    uwaschanged[name]["limitby"] = limitby
+                                entrypquota.reset()
+                                
                             if balance :
-                                if uwaschanged[name].get("balance") is None :
+                                if changed[entry.Name].get("balance") is None :
                                     if balance.startswith("+") or balance.startswith("-") :
-                                        self.storage.increaseUserBalance(ident, balancevalue)
+                                        entry.consumeAccountBalance(-balancevalue)
                                     else :
-                                        self.storage.setUserBalance(ident, balancevalue)
-                                    uwaschanged[name]["balance"] = balance
+                                        entry.consumeAccountBalance(float(entry.AccountBalance or 0.0) - balancevalue)
+                                    changed[entry.Name]["balance"] = balance
                             for groupname in groupnames :        
-                                if groupname not in uwaschanged[name]["ingroups"] :
-                                    groupid = self.storage.getGroupId(groupname)
-                                    if groupid is not None :
-                                        self.storage.addUserToGroup(ident, groupid)
-                                        uwaschanged[name]["ingroups"].append(groupname)
+                                if groupname not in changed[name]["ingroups"] :
+                                    group = self.storage.getGroup(groupname)
+                                    if group.Exists :
+                                        self.storage.addUserToGroup(entry, group)
+                                        changed[entry.Name]["ingroups"].append(groupname)
                                     else :
                                         self.logger.log_message(_("Group %s not found in the PyKota Storage.") % groupname)
-                            self.warnUserPQuota(name, printer)    
+                                        
+                        getattr(self, "warn%sPQuota" % suffix)(entrypquota)    
                      
 if __name__ == "__main__" : 
Index: /pykota/trunk/bin/pykota
===================================================================
--- /pykota/trunk/bin/pykota (revision 1026)
+++ /pykota/trunk/bin/pykota (revision 1041)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.35  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.34  2003/06/13 18:54:17  jalet
 # Bug with remote jobs and LPRng fixed.
@@ -239,12 +242,12 @@
     
     # Get the last page counter and last username from the Quota Storage backend
-    printerid = kotafilter.storage.getPrinterId(kotafilter.printername)
-    if printerid is None :
+    printer = kotafilter.storage.getPrinter(kotafilter.printername)
+    if not printer.Exists :
         # The printer is unknown from the Quota Storage perspective
         # we let the job pass through, but log a warning message
         kotafilter.logger.log_message(_("Printer %s not registered in the PyKota system") % kotafilter.printername, "warn")
     else :    
-        userid = kotafilter.storage.getUserId(kotafilter.username)
-        if userid is None :
+        user = kotafilter.storage.getUser(kotafilter.username)
+        if not user.Exists :
             # The user is unknown from the Quota Storage perspective
             # Depending on the default policy for this printer, we
@@ -261,5 +264,5 @@
         else :
             # Now does the accounting and act depending on the result
-            action = kotafilter.accounter.doAccounting(printerid, userid)
+            action = kotafilter.accounter.doAccounting(printer, user)
             
             # if not allowed to print then die, else proceed.
Index: /pykota/trunk/bin/repykota
===================================================================
--- /pykota/trunk/bin/repykota (revision 1030)
+++ /pykota/trunk/bin/repykota (revision 1041)
@@ -23,4 +23,7 @@
 #
 # $Log$
+# Revision 1.39  2003/06/25 14:10:01  jalet
+# Hey, it may work (edpykota --reset excepted) !
+#
 # Revision 1.38  2003/06/15 22:26:52  jalet
 # More work on LDAP
@@ -147,4 +150,7 @@
 
 import sys
+import os
+import pwd
+import grp
 
 from mx import DateTime
@@ -187,4 +193,14 @@
   
   This will print the quota status for all users on all printers.
+  
+  $ repykota --printer "laser*" jerome "jo*"
+  
+  This will print the quota status for user jerome and all users
+  whose name begins with "jo" on all printers which name begin
+  with "laser"
+  
+  If launched by a non-root user, additionnal arguments representing
+  users or groups names are ignored, and only the current user/group
+  is reported.
 
 This program is free software; you can redistribute it and/or modify
@@ -206,21 +222,30 @@
 class RePyKota(PyKotaTool) :        
     """A class for repykota."""
-    def main(self, options) :
+    def main(self, ugnames, options) :
         """Print Quota reports generator."""
+        uid = os.geteuid()
+        if not uid :
+            # root user
+            if not ugnames :
+                # no username, means all usernames
+                ugnames = [ "*" ]
+        else :        
+            # not the root user
+            # reports only the current user
+            if options["groups"] :
+                ugnames = [ grp.getgrgid(pwd.getpwuid(uid)[3])[0] ]
+            else :
+                ugnames = [ pwd.getpwuid(uid)[0] ]
+        
         printers = self.storage.getMatchingPrinters(options["printer"])
         if not printers :
             raise PyKotaToolError, _("There's no printer matching %s") % options["printer"]
-        for (printerid, printer) in printers :
-            print _("*** Report for %s quota on printer %s") % ((options["groups"] and "group") or "user", printer)
-            print _("Pages grace time: %i days") % self.config.getGraceDelay(printer)
-            prices = self.storage.getPrinterPrices(printerid)
-            if prices is None :
-                (perpage, perjob) = (None, None)
-            else :    
-                (perpage, perjob) = prices
-            if perjob is not None :
-                print _("Price per job: %.3f") % perjob
-            if perpage is not None :    
-                print _("Price per page: %.3f") % perpage
+        for printer in printers :
+            print _("*** Report for %s quota on printer %s") % ((options["groups"] and "group") or "user", printer.Name)
+            print _("Pages grace time: %i days") % self.config.getGraceDelay(printer.Name)
+            if printer.PricePerJob is not None :
+                print _("Price per job: %.3f") % printer.PricePerJob
+            if printer.PricePerPage is not None :    
+                print _("Price per page: %.3f") % printer.PricePerPage
             total = 0
             totalmoney = 0.0
@@ -228,9 +253,6 @@
                 print _("Group           used    soft    hard    balance grace         total       paid") 
                 print "------------------------------------------------------------------------------"
-                for (ident, name) in (self.storage.getPrinterGroups(printerid) or []) :
-                    quota = self.storage.getGroupPQuota(ident, printerid) 
-                    balance = self.storage.getGroupBalance(ident)
-                    limitby = self.storage.getGroupLimitBy(ident)
-                    (pages, money) = self.printQuota(name, quota, balance, limitby)
+                for (group, grouppquota) in self.storage.getPrinterGroupsAndQuotas(printer, ugnames) :
+                    (pages, money) = self.printQuota(group, grouppquota)
                     total += pages
                     totalmoney += money
@@ -239,16 +261,12 @@
                 print _("User            used    soft    hard    balance grace         total       paid") 
                 print "------------------------------------------------------------------------------"
-                for (ident, name) in (self.storage.getPrinterUsers(printerid) or []) :
-                    quota = self.storage.getUserPQuota(ident, printerid)
-                    balance = self.storage.getUserBalance(ident)
-                    limitby = self.storage.getUserLimitBy(ident)
-                    (pages, money) = self.printQuota(name, quota, balance, limitby)
+                for (user, userpquota) in self.storage.getPrinterUsersAndQuotas(printer, ugnames) :
+                    (pages, money) = self.printQuota(user, userpquota)
                     total += pages
                     totalmoney += money
             if total or totalmoney :        
                 print (" " * 50) + (_("Total : %9i") % total) + ("%11s" % ("%7.2f" % totalmoney)[:11])
-            printerpagecounter = self.storage.getPrinterPageCounter(printerid)
             try :
-                msg = "%9i" % printerpagecounter["pagecounter"]
+                msg = "%9i" % printer.LastJob.PrinterPageCounter
             except TypeError :     
                 msg = _("unknown")
@@ -258,36 +276,32 @@
             print _("Totals may be inaccurate if some users are members of several groups.")
                         
-    def printQuota(self, name, quota, balance, limitby) :
+    def printQuota(self, entry, quota) :
         """Prints the quota information."""
-        if quota is not None :
-            lifepagecounter = quota["lifepagecounter"] or 0
-            pagecounter = quota["pagecounter"] or 0
-            softlimit = quota["softlimit"]
-            hardlimit = quota["hardlimit"]
-            datelimit = quota["datelimit"]
-            if balance is not None :
-                (balance, lifetimepaid) = balance
-            else :    
-                (balance, lifetimepaid) = (0.0, 0.0)
-            if datelimit is not None :
-                now = DateTime.now()
-                datelimit = DateTime.ISO.ParseDateTime(datelimit)
-                if now >= datelimit :
-                    datelimit = "DENY"
-            else :    
-                datelimit = ""
-            if limitby == "balance" :    
-                reached = (((balance <= 0) and "+") or "-") + "B"
-            else :
-                reached = (((softlimit is not None) and (pagecounter >= softlimit) and "+") or "-") + "Q"
-            balance = balance or 0.0    
-            lifetimepaid = lifetimepaid or 0.0
-            strbalance = ("%5.2f" % balance)[:10]
-            strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
-            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)
-            return (lifepagecounter, lifetimepaid)
+        lifepagecounter = int(quota.LifePageCounter or 0)
+        pagecounter = int(quota.PageCounter or 0)
+        balance = float(entry.AccountBalance or 0.0)
+        lifetimepaid = float(entry.LifeTimePaid or 0.0)
+        
+        if quota.DateLimit is not None :
+            now = DateTime.now()
+            datelimit = DateTime.ISO.ParseDateTime(quota.DateLimit)
+            if now >= datelimit :
+                datelimit = "DENY"
+        elif (quota.HardLimit is not None) and (pagecounter >= quota.HardLimit) :    
+            datelimit = "DENY"
+        elif (quota.HardLimit is None) and (quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) :
+            datelimit = "DENY"
         else :    
-            return (0, 0)
-        
+            datelimit = ""
+            
+        if entry.LimitBy.lower() == "balance" :    
+            reached = (((balance <= 0) and "+") or "-") + "B"
+        else :
+            reached = (((quota.SoftLimit is not None) and (pagecounter >= quota.SoftLimit) and "+") or "-") + "Q"
+            
+        strbalance = ("%5.2f" % balance)[:10]
+        strlifetimepaid = ("%6.2f" % lifetimepaid)[:10]
+        print "%-9.9s %s %7i %7s %7s %10s %-10.10s %8i %10s" % (entry.Name, reached, pagecounter, str(quota.SoftLimit), str(quota.HardLimit), strbalance, str(datelimit)[:10], lifepagecounter, strlifetimepaid)
+        return (lifepagecounter, lifetimepaid)
                     
 if __name__ == "__main__" : 
@@ -318,8 +332,6 @@
         elif options["users"] and options["groups"] :    
             raise PyKotaToolError, _("incompatible options, see help.")
-        elif args :    
-            raise PyKotaToolError, _("unused arguments [%s]. Aborting.") % ", ".join(args)
         else :
-            sys.exit(reporter.main(options))
+            sys.exit(reporter.main(args, options))
     except (PyKotaToolError, PyKotaConfigError, PyKotaStorageError), msg :            
         sys.stderr.write("%s\n" % msg)
Index: /pykota/trunk/initscripts/ldap/pykota.schema
===================================================================
--- /pykota/trunk/initscripts/ldap/pykota.schema (revision 1036)
+++ /pykota/trunk/initscripts/ldap/pykota.schema (revision 1041)
@@ -55,12 +55,12 @@
 attributetype ( 1.3.6.1.4.1.16868.1.1.6 NAME 'pykotaSoftLimit'
         DESC 'Soft limit in maximal number of pages'
-        EQUALITY integerMatch
-        SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
+        EQUALITY caseIgnoreIA5Match
+        SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
         
 # pykotaHardLimit        
 attributetype ( 1.3.6.1.4.1.16868.1.1.7 NAME 'pykotaHardLimit'
         DESC 'Hard limit in maximal number of pages'
-        EQUALITY integerMatch
-        SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
+        EQUALITY caseIgnoreIA5Match
+        SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
 
 # pykotaDateLimit
@@ -97,6 +97,6 @@
 attributetype ( 1.3.6.1.4.1.16868.1.1.13 NAME 'pykotaJobSize'
         DESC 'Current job size in number of pages in the history'
-        EQUALITY integerMatch
-        SYNTAX 1.3.6.1.4.1.1466.115.121.1.27 SINGLE-VALUE )
+        EQUALITY caseIgnoreIA5Match
+        SYNTAX 1.3.6.1.4.1.1466.115.121.1.26 SINGLE-VALUE )
 
 # pykotaAction
Index: /pykota/trunk/NEWS
===================================================================
--- /pykota/trunk/NEWS (revision 1029)
+++ /pykota/trunk/NEWS (revision 1041)
@@ -22,4 +22,19 @@
 PyKota NEWS :
 
+    - 1.09alpha2 :
+    
+        - LDAP schema modified a bit. Please upgrade.
+        
+        - LDAP backend works !
+        
+        - repykota and warnpykota allow the root user to pass
+          users or groups names on the command line. Users 
+          and groups names may contain wildcards.
+          
+        - repykota and warnpykota only reports or warns the
+          current user when launched by non-root users.
+          
+        - Minor bug fixes.  
+    
     - 1.09alpha1 :
     
