Changeset 2773

Show
Ignore:
Timestamp:
03/02/06 12:37:52 (18 years ago)
Author:
jerome
Message:

pkusers is now optimized like pkprinters, pkbcodes and edpykota.

Location:
pykota/trunk
Files:
9 modified

Legend:

Unmodified
Added
Removed
  • pykota/trunk/bin/pkusers

    r2765 r2773  
    3131 
    3232from pykota.tool import PyKotaTool, PyKotaToolError, PyKotaCommandLineError, crashed, N_ 
     33from pykota.storage import StorageUser, StorageGroup 
    3334 
    3435__doc__ = N_("""pkusers v%(__version__)s (c) %(__years__)s %(__author__)s 
     
    158159class PKUsers(PyKotaTool) :         
    159160    """A class for a users and users groups manager.""" 
     161    def modifyEntry(self, entry, groups, limitby, description, overcharge=None, balance=None, balancevalue=None, comment=None, email=None) : 
     162        """Modifies an entry.""" 
     163        if description is not None : # NB : "" is allowed ! 
     164            entry.setDescription(description) 
     165        if limitby :     
     166            entry.setLimitBy(limitby) 
     167        if not groups : 
     168            if email : 
     169                entry.Email = email 
     170            if overcharge is not None : # NB : 0 is allowed !      
     171                entry.setOverChargeFactor(overcharge) 
     172            if balance : 
     173                if balance.startswith("+") or balance.startswith("-") : 
     174                    newbalance = float(entry.AccountBalance or 0.0) + balancevalue 
     175                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + balancevalue 
     176                    entry.setAccountBalance(newbalance, newlifetimepaid, comment) 
     177                else : 
     178                    diff = balancevalue - float(entry.AccountBalance or 0.0) 
     179                    newlifetimepaid = float(entry.LifeTimePaid or 0.0) + diff 
     180                    entry.setAccountBalance(balancevalue, newlifetimepaid, comment) 
     181                     
     182    def manageUsersGroups(self, ugroups, user, remove) :         
     183        """Manage user group membership.""" 
     184        for ugroup in ugroups : 
     185            if remove : 
     186                ugroup.delUserFromGroup(user) 
     187            else : 
     188                ugroup.addUserToGroup(user) 
     189                 
    160190    def main(self, names, options) : 
    161191        """Manage users or groups.""" 
     
    163193        suffix = (options["groups"] and "Group") or "User"         
    164194         
    165         if options["delete"] :     
    166             self.display("%s...\n" % _("Deletion")) 
    167             todelete = getattr(self.storage, "getMatching%ss" % suffix)(",".join(names)) 
    168             nbtotal = len(todelete) 
    169             for i in range(nbtotal) : 
    170                 entry = todelete[i] 
    171                 if entry.Exists : 
    172                     entry.delete() 
    173                 percent = 100.0 * float(i) / float(nbtotal) 
    174                 self.display("\r%.02f%%" % percent) 
     195        if not options["add"] : 
     196            if not options["list"] : 
     197                self.display(_("Extracting datas...")) 
     198            if not names :      # NB : can't happen for --delete because it's catched earlier 
     199                names = ["*"] 
     200            entries = getattr(self.storage, "getMatching%ss" % suffix)(",".join(names)) 
     201            if not entries : 
     202                raise PyKotaCommandLineError, _("There's no %s matching %s") % (_(suffix.lower()), " ".join(names)) 
     203                 
     204        if options["list"] : 
     205            if suffix == "User" : 
     206                maildomain = self.config.getMailDomain() 
     207                smtpserver = self.config.getSMTPServer() 
     208                for entry in entries : 
     209                    email = entry.Email 
     210                    if not email : 
     211                        if maildomain :      
     212                            email = "%s@%s" % (entry.Name, maildomain) 
     213                        elif smtpserver :     
     214                            email = "%s@%s" % (entry.Name, smtpserver) 
     215                        else :     
     216                            email = "%s@%s" % (entry.Name, "localhost") 
     217                    msg = "%s - <%s>" % (entry.Name, email) 
     218                    if entry.Description : 
     219                        msg += " - %s" % entry.Description 
     220                    print msg     
     221                    print "    %s" % (_("Limited by : %s") % entry.LimitBy) 
     222                    print "    %s" % (_("Account balance : %.2f") % (entry.AccountBalance or 0.0)) 
     223                    print "    %s" % (_("Total paid so far : %.2f") % (entry.LifeTimePaid or 0.0)) 
     224                    print "    %s" % (_("Overcharging factor : %.2f") % entry.OverCharge) 
     225                    print 
     226            else :     
     227                for entry in entries : 
     228                    msg = "%s" % entry.Name 
     229                    if entry.Description : 
     230                        msg += " - %s" % entry.Description 
     231                    print msg     
     232                    print "    %s" % (_("Limited by : %s") % entry.LimitBy) 
     233                    print "    %s" % (_("Group balance : %.2f") % (entry.AccountBalance or 0.0)) 
     234                    print "    %s" % (_("Total paid so far : %.2f") % (entry.LifeTimePaid or 0.0)) 
     235                    print 
     236        elif options["delete"] :     
     237            self.display("\n%s..." % _("Deletion")) 
     238            getattr(self.storage, "deleteMany%ss" % suffix)(entries) 
     239            self.display("\n") 
    175240        else : 
    176             if options["add"] :     
    177                 self.display("%s...\n" % _("Creation")) 
    178                 rejectunknown = self.config.getRejectUnknown()     
    179                 entries = [] 
    180                 nbtotal = len(names) 
    181                 for i in range(nbtotal) : 
    182                     ename = names[i] 
    183                     email = "" 
    184                     if not options["groups"] : 
    185                         splitname = ename.split('/', 1)     # username/email 
    186                         if len(splitname) == 1 : 
    187                             splitname.append("") 
    188                         (ename, email) = splitname 
    189                         if email and (email.count('@') != 1) : 
    190                             self.printInfo(_("Invalid email address %s") % email) 
    191                             email = "" 
    192                     entry = getattr(self.storage, "get%s" % suffix)(ename) 
    193                     if entry.Exists : 
    194                         if options["skipexisting"] : 
    195                             self.printInfo(_("%s %s already exists, skipping.") % (suffix, entry.Name)) 
    196                         else :     
    197                             self.printInfo(_("%s %s already exists, will be modified.") % (suffix, entry.Name)) 
    198                             entries.append(entry) 
    199                     else : 
    200                         if self.isValidName(entry.Name) : 
     241            limitby = options["limitby"] 
     242            if limitby : 
     243                limitby = limitby.strip().lower() 
     244            if limitby : 
     245                if limitby not in ('quota', 'balance', 'noquota', \ 
     246                                            'noprint', 'nochange') : 
     247                    raise PyKotaCommandLineError, _("Invalid limitby value %s") % options["limitby"] 
     248                if (limitby in ('nochange', 'noprint')) and options["groups"] :     
     249                    raise PyKotaCommandLineError, _("Invalid limitby value %s") % options["limitby"] 
     250                 
     251            overcharge = options["overcharge"] 
     252            if overcharge : 
     253                try : 
     254                    overcharge = float(overcharge.strip()) 
     255                except (ValueError, AttributeError) :     
     256                    raise PyKotaCommandLineError, _("Invalid overcharge value %s") % options["overcharge"] 
     257                     
     258            balance = options["balance"] 
     259            if balance : 
     260                balance = balance.strip() 
     261                try : 
     262                    balancevalue = float(balance) 
     263                except ValueError :     
     264                    raise PyKotaCommandLineError, _("Invalid balance value %s") % options["balance"] 
     265                 
     266            if options["ingroups"] : 
     267                usersgroups = self.storage.getMatchingGroups(options["ingroups"]) 
     268                if not usersgroups : 
     269                    raise PyKotaCommandLineError, _("There's no users group matching %s") % " ".join(options["ingroups"].split(',')) 
     270            else :          
     271                usersgroups = [] 
     272                     
     273            description = options["description"] 
     274            if description : 
     275                description = options["description"].strip() 
     276                 
     277            comment = options["comment"] 
     278            if comment : 
     279                comment = options["comment"].strip() 
     280            skipexisting = options["skipexisting"]     
     281            groups = options["groups"] 
     282            remove = options["remove"] 
     283            self.storage.beginTransaction() 
     284            try :     
     285                if options["add"] :     
     286                    self.display("%s...\n" % _("Creation")) 
     287                    rejectunknown = self.config.getRejectUnknown()     
     288                    nbtotal = len(names) 
     289                    for i in range(nbtotal) : 
     290                        ename = names[i] 
     291                        email = None 
     292                        if not groups : 
     293                            splitname = ename.split('/', 1)     # username/email 
     294                            if len(splitname) == 1 : 
     295                                splitname.append("") 
     296                            (ename, email) = splitname 
     297                            if email and (email.count('@') != 1) : 
     298                                raise PyKotaCommandLineError, _("Invalid email address %s") % email 
     299                        if self.isValidName(ename) : 
    201300                            reject = 0 
    202301                            if rejectunknown : 
    203                                 if options["groups"] : 
     302                                if groups : 
    204303                                    try : 
    205                                         grp.getgrnam(entry.Name) 
     304                                        grp.getgrnam(ename) 
    206305                                    except KeyError :     
    207                                         self.printInfo(_("Unknown group %s") % entry.Name, "error") 
     306                                        self.printInfo(_("Unknown group %s") % ename, "error") 
    208307                                        reject = 1 
    209308                                else :     
    210309                                    try : 
    211                                         pwd.getpwnam(entry.Name) 
     310                                        pwd.getpwnam(ename) 
    212311                                    except KeyError :     
    213                                         self.printInfo(_("Unknown user %s") % entry.Name, "error") 
     312                                        self.printInfo(_("Unknown user %s") % ename, "error") 
    214313                                        reject = 1 
    215314                            if not reject :         
    216                                 if email : 
    217                                     entry.Email = email 
    218                                 entry = getattr(self.storage, "add%s" % suffix)(entry) 
    219                                 entries.append(entry) 
     315                                entry = globals()["Storage%s" % suffix](self.storage, ename) 
     316                                if groups : 
     317                                    self.modifyEntry(entry, groups, limitby, \ 
     318                                                     description) 
     319                                else :     
     320                                    self.modifyEntry(entry, groups, limitby, \ 
     321                                                     description, overcharge,\ 
     322                                                     balance, balancevalue, \ 
     323                                                     comment, email) 
     324                                oldentry = getattr(self.storage, "add%s" % suffix)(entry) 
     325                                if oldentry is not None : 
     326                                    if skipexisting : 
     327                                        self.printInfo(_("%s %s already exists, skipping.") % (_(suffix), ename)) 
     328                                    else :     
     329                                        self.printInfo(_("%s %s already exists, will be modified.") % (_(suffix), ename)) 
     330                                        if groups : 
     331                                            self.modifyEntry(oldentry, groups, \ 
     332                                                     limitby, description) 
     333                                        else : 
     334                                            self.modifyEntry(oldentry, groups, limitby, \ 
     335                                                     description, overcharge,\ 
     336                                                     balance, balancevalue, \ 
     337                                                     comment, email) 
     338                                        oldentry.save() 
     339                                        if not groups : 
     340                                            self.manageUsersGroups(usersgroups, oldentry, remove) 
     341                                elif usersgroups and not groups : 
     342                                    self.manageUsersGroups(usersgroups, \ 
     343                                                           self.storage.getUser(ename), \ 
     344                                                           remove) 
     345                        else : 
     346                            raise PyKotaCommandLineError, _("Invalid name %s") % ename 
     347                        percent = 100.0 * float(i) / float(nbtotal) 
     348                        self.display("\r%.02f%%" % percent) 
     349                else : 
     350                    self.display("\n%s...\n" % _("Modification")) 
     351                    nbtotal = len(entries) 
     352                    for i in range(nbtotal) :         
     353                        entry = entries[i] 
     354                        if groups : 
     355                            self.modifyEntry(entry, groups, limitby, description) 
    220356                        else :     
    221                             if options["groups"] : 
    222                                 self.printInfo(_("Invalid group name %s") % entry.Name) 
    223                             else :     
    224                                 self.printInfo(_("Invalid user name %s") % entry.Name) 
    225                                  
    226                     percent = 100.0 * float(i) / float(nbtotal) 
    227                     self.display("\r%.02f%%" % percent) 
    228                 self.done() 
    229             else :         
    230                 entries = getattr(self.storage, "getMatching%ss" % suffix)(",".join(names)) 
    231                 if not entries : 
    232                     raise PyKotaCommandLineError, _("There's no %s matching %s") % (suffix.lower(), " ".join(names)) 
    233                          
    234             if options["list"] : 
    235                 if suffix == "User" : 
    236                     maildomain = self.config.getMailDomain() 
    237                     smtpserver = self.config.getSMTPServer() 
    238                     for entry in entries : 
    239                         if entry.Exists : 
    240                             email = entry.Email 
    241                             if not email : 
    242                                 if maildomain :      
    243                                     email = "%s@%s" % (entry.Name, maildomain) 
    244                                 elif smtpserver :     
    245                                     email = "%s@%s" % (entry.Name, smtpserver) 
    246                                 else :     
    247                                     email = "%s@%s" % (entry.Name, "localhost") 
    248                             msg = "%s - <%s>" % (entry.Name, email) 
    249                             if entry.Description : 
    250                                 msg += " - %s" % entry.Description 
    251                             print msg     
    252                             print "    %s" % (_("Limited by : %s") % entry.LimitBy) 
    253                             print "    %s" % (_("Account balance : %.2f") % (entry.AccountBalance or 0.0)) 
    254                             print "    %s" % (_("Total paid so far : %.2f") % (entry.LifeTimePaid or 0.0)) 
    255                             print "    %s" % (_("Overcharging factor : %.2f") % entry.OverCharge) 
    256                             print 
    257                 else :     
    258                     for entry in entries : 
    259                         if entry.Exists : 
    260                             msg = "%s" % entry.Name 
    261                             if entry.Description : 
    262                                 msg += " - %s" % entry.Description 
    263                             print msg     
    264                             print "    %s" % (_("Limited by : %s") % entry.LimitBy) 
    265                             print "    %s" % (_("Group balance : %.2f") % (entry.AccountBalance or 0.0)) 
    266                             print "    %s" % (_("Total paid so far : %.2f") % (entry.LifeTimePaid or 0.0)) 
    267                             print 
    268             else : 
    269                 self.display("%s...\n" % _("Modification")) 
    270                  
    271                 limitby = options["limitby"] 
    272                 if limitby : 
    273                     limitby = limitby.strip().lower() 
    274                 if limitby : 
    275                     if limitby not in ('quota', 'balance', 'noquota', \ 
    276                                                 'noprint', 'nochange') : 
    277                         raise PyKotaCommandLineError, _("Invalid limitby value %s") % options["limitby"] 
    278                     if (limitby in ('nochange', 'noprint')) and options["groups"] :     
    279                         raise PyKotaCommandLineError, _("Invalid limitby value %s") % options["limitby"] 
    280                      
    281                 overcharge = options["overcharge"] 
    282                 if overcharge : 
    283                     try : 
    284                         overcharge = float(overcharge.strip()) 
    285                     except (ValueError, AttributeError) :     
    286                         raise PyKotaCommandLineError, _("Invalid overcharge value %s") % options["overcharge"] 
    287                          
    288                 balance = options["balance"] 
    289                 if balance : 
    290                     balance = balance.strip() 
    291                     try : 
    292                         balancevalue = float(balance) 
    293                     except ValueError :     
    294                         raise PyKotaCommandLineError, _("Invalid balance value %s") % options["balance"] 
    295                      
    296                 if options["ingroups"] : 
    297                     usersgroups = self.storage.getMatchingGroups(options["ingroups"]) 
    298                     if not usersgroups : 
    299                         raise PyKotaCommandLineError, _("There's no users group matching %s") % " ".join(options["ingroups"].split(',')) 
    300                 else :          
    301                     usersgroups = [] 
    302                          
    303                 description = options["description"] 
    304                 if description : 
    305                     description = options["description"].strip() 
    306                      
    307                 comment = options["comment"] 
    308                 if comment : 
    309                     comment = options["comment"].strip() 
    310                      
    311                 nbtotal = len(entries) 
    312                 for i in range(nbtotal) :         
    313                     entry = entries[i] 
    314                      
    315                     # We need a transaction because we may have to create a record 
    316                     # in the payments' table at the same time we modify the user's balance. 
    317                     self.storage.beginTransaction() 
    318                     try : 
    319                         if description is not None : # NB : "" is allowed ! 
    320                             entry.setDescription(description) 
    321                         if limitby :     
    322                             entry.setLimitBy(limitby) 
    323                              
    324                         if suffix == "User" :     
    325                             if overcharge is not None : # NB : 0 is allowed !      
    326                                 entry.setOverChargeFactor(overcharge) 
    327                          
    328                         if suffix == "User" : 
    329                             if balance : 
    330                                 if balance.startswith("+") or balance.startswith("-") : 
    331                                     newbalance = float(entry.AccountBalance or 0.0) + balancevalue 
    332                                     newlifetimepaid = float(entry.LifeTimePaid or 0.0) + balancevalue 
    333                                     entry.setAccountBalance(newbalance, newlifetimepaid, comment) 
    334                                 else : 
    335                                     diff = balancevalue - float(entry.AccountBalance or 0.0) 
    336                                     newlifetimepaid = float(entry.LifeTimePaid or 0.0) + diff 
    337                                     entry.setAccountBalance(balancevalue, newlifetimepaid, comment) 
    338                                              
    339                             for ugroup in usersgroups : 
    340                                 if options["remove"] : 
    341                                     ugroup.delUserFromGroup(entry) 
    342                                 else : 
    343                                     ugroup.addUserToGroup(entry) 
     357                            self.modifyEntry(entry, groups, limitby, description, \ 
     358                                             overcharge, balance, balancevalue, \ 
     359                                             comment) 
     360                            self.manageUsersGroups(usersgroups, entry, remove)                 
    344361                        entry.save()     
    345                     except : 
    346                         self.storage.rollbackTransaction() 
    347                         raise 
    348                     else :     
    349                         self.storage.commitTransaction() 
    350  
    351                     percent = 100.0 * float(i) / float(nbtotal) 
    352                     self.display("\r%.02f%%" % percent) 
     362                        percent = 100.0 * float(i) / float(nbtotal) 
     363                        self.display("\r%.02f%%" % percent) 
     364            except :                     
     365                self.storage.rollbackTransaction() 
     366                raise 
     367            else :     
     368                self.storage.commitTransaction() 
    353369                                 
    354370        if not options["list"] :                 
  • pykota/trunk/NEWS

    r2768 r2773  
    2222PyKota NEWS : 
    2323        
    24     - 1.24alpha15 (2006-03-01) : 
    25          
    26         - optimized pkbcodes and pkprinters using edpykota as the model. 
     24    - 1.24alpha15 (2006-03-02) : 
     25         
     26        - optimized pkbcodes, pkprinters and pkusers using edpykota as  
     27          the model. 
    2728         
    2829        - 'edpykota --list' and 'pkusers --list' are now authorized  
  • pykota/trunk/pykota/storage.py

    r2735 r2773  
    6767        self.OverCharge = 1.0 
    6868        self.Payments = [] # TODO : maybe handle this smartly for SQL, for now just don't retrieve them 
     69        self.PaymentsBacklog = [] 
    6970         
    7071    def consumeAccountBalance(self, amount) :      
     
    7879        self.AccountBalance = balance 
    7980        self.LifeTimePaid = lifetimepaid 
    80         self.parent.writeNewPayment(self, diff, comment) 
    81         self.isDirty = True 
     81        if diff : 
     82            self.PaymentsBacklog.append((diff, comment)) 
     83        self.isDirty = True 
     84         
     85    def save(self) :     
     86        """Saves an user and flush its payments backlog.""" 
     87        for (value, comment) in self.PaymentsBacklog : 
     88            self.parent.writeNewPayment(self, value, comment) 
     89        self.PaymentsBacklog = []     
     90        StorageObject.save(self)     
    8291         
    8392    def setLimitBy(self, limitby) :     
  • pykota/trunk/pykota/storages/ldapstorage.py

    r2768 r2773  
    909909         
    910910    def addUser(self, user) :         
    911         """Adds a user to the quota storage, returns it.""" 
     911        """Adds a user to the quota storage, returns the old value if it already exists.""" 
     912        oldentry = self.getUser(user.Name) 
     913        if oldentry.Exists : 
     914            return oldentry # we return the existing entry 
    912915        uname = self.userCharsetToDatabase(user.Name) 
    913916        newfields = { 
     
    971974                dn = "%s=%s,%s" % (self.info["balancerdn"], uname, self.info["balancebase"]) 
    972975                self.doAdd(dn, fields) 
    973              
    974         return self.getUser(user.Name) 
     976        user.idbalance = dn 
     977        if user.PaymentsBacklog : 
     978            for (value, comment) in user.PaymentsBacklog : 
     979                self.writeNewPayment(user, value, comment) 
     980            user.PaymentsBacklog = [] 
     981        user.isDirty = False 
     982        return None # the entry created doesn't need further modification 
    975983         
    976984    def addGroup(self, group) :         
    977         """Adds a group to the quota storage, returns it.""" 
     985        """Adds a group to the quota storage, returns the old value if it already exists.""" 
     986        oldentry = self.getGroup(group.Name) 
     987        if oldentry.Exists : 
     988            return oldentry # we return the existing entry 
    978989        gname = self.userCharsetToDatabase(group.Name) 
    979990        newfields = {  
     
    10141025            dn = "%s=%s,%s" % (self.info["grouprdn"], gname, self.info["groupbase"]) 
    10151026            self.doAdd(dn, fields) 
    1016         return self.getGroup(group.Name) 
     1027        group.isDirty = False 
     1028        return None # the entry created doesn't need further modification 
    10171029         
    10181030    def addUserToGroup(self, user, group) :     
  • pykota/trunk/pykota/storages/mysqlstorage.py

    r2741 r2773  
    130130            self.cursor.execute(query) 
    131131        except self.database.Error, msg :     
     132            self.tool.logdebug("Query failed : %s" % repr(msg)) 
    132133            raise PyKotaStorageError, str(msg) 
    133134        else :     
  • pykota/trunk/pykota/storages/pgstorage.py

    r2741 r2773  
    115115            result = self.database.query(query) 
    116116        except PGError, msg :     
     117            self.tool.logdebug("Query failed : %s" % repr(msg)) 
    117118            raise PyKotaStorageError, str(msg) 
    118119        else :     
  • pykota/trunk/pykota/storages/sqlitestorage.py

    r2741 r2773  
    121121            self.cursor.execute(query) 
    122122        except self.database.Error, msg :     
     123            self.tool.logdebug("Query failed : %s" % repr(msg)) 
    123124            raise PyKotaStorageError, str(msg) 
    124125        else :     
  • pykota/trunk/pykota/storages/sql.py

    r2771 r2773  
    562562         
    563563    def addUser(self, user) :         
    564         """Adds a user to the quota storage, returns it.""" 
    565         self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email, overcharge, description) VALUES (%s, %s, %s, %s, %s, %s, %s)" % \ 
     564        """Adds a user to the quota storage, returns the old value if it already exists.""" 
     565        try : 
     566            self.doModify("INSERT INTO users (username, limitby, balance, lifetimepaid, email, overcharge, description) VALUES (%s, %s, %s, %s, %s, %s, %s)" % \ 
    566567                                         (self.doQuote(self.userCharsetToDatabase(user.Name)), \ 
    567568                                          self.doQuote(user.LimitBy or 'quota'), \ 
     
    571572                                          self.doQuote(user.OverCharge), \ 
    572573                                          self.doQuote(self.userCharsetToDatabase(user.Description)))) 
    573         return self.getUser(user.Name) 
     574        except PyKotaStorageError :     
     575            # TODO : check if this is an error different from a duplicate insert 
     576            # return the existing entry which has to be modified 
     577            return self.getUser(user.Name) 
     578        else :     
     579            if user.PaymentsBacklog : 
     580                for (value, comment) in user.PaymentsBacklog : 
     581                    self.writeNewPayment(user, value, comment) 
     582                user.PaymentsBacklog = [] 
     583            user.isDirty = False 
     584            return None # the entry created doesn't need further modification 
    574585         
    575586    def addGroup(self, group) :         
    576         """Adds a group to the quota storage, returns it.""" 
    577         self.doModify("INSERT INTO groups (groupname, limitby, description) VALUES (%s, %s, %s)" % \ 
    578                                           (self.doQuote(self.userCharsetToDatabase(group.Name)), \ 
    579                                            self.doQuote(group.LimitBy or "quota"), \ 
    580                                            self.doQuote(self.userCharsetToDatabase(group.Description)))) 
    581         return self.getGroup(group.Name) 
     587        """Adds a group to the quota storage, returns the old value if it already exists.""" 
     588        try : 
     589            self.doModify("INSERT INTO groups (groupname, limitby, description) VALUES (%s, %s, %s)" % \ 
     590                                  (self.doQuote(self.userCharsetToDatabase(group.Name)), \ 
     591                                   self.doQuote(group.LimitBy or "quota"), \ 
     592                                   self.doQuote(self.userCharsetToDatabase(group.Description)))) 
     593        except PyKotaStorageError :     
     594            # TODO : check if this is an error different from a duplicate insert 
     595            # return the existing entry which has to be modified 
     596            return self.getGroup(group.Name) 
     597        else :     
     598            group.isDirty = False 
     599            return None # the entry created doesn't need further modification 
    582600 
    583601    def addUserToGroup(self, user, group) :     
     
    693711    def writeNewPayment(self, user, amount, comment="") : 
    694712        """Adds a new payment to the payments history.""" 
    695         self.doModify("INSERT INTO payments (userid, amount, description) VALUES (%s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment)))) 
     713        if user.ident is not None : 
     714            self.doModify("INSERT INTO payments (userid, amount, description) VALUES (%s, %s, %s)" % (self.doQuote(user.ident), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment)))) 
     715        else :     
     716            self.doModify("INSERT INTO payments (userid, amount, description) VALUES ((SELECT id FROM users WHERE username=%s), %s, %s)" % (self.doQuote(self.userCharsetToDatabase(user.Name)), self.doQuote(amount), self.doQuote(self.userCharsetToDatabase(comment)))) 
    696717         
    697718    def writeLastJobSize(self, lastjob, jobsize, jobprice) :         
  • pykota/trunk/tests/filldb.py

    r2748 r2773  
    7272    usernames = [ "test-user-%05i" % i for i in range(number) ] 
    7373    argsfile = open("arguments.list", "w") 
    74     argsfile.write('--add\n--limitby\nbalance\n--balance\n50.0\n--description\n"an user"\n') 
     74    argsfile.write('--add\n--limitby\nbalance\n--balance\n50.0\n--description\n"an user"\n--comment\n"fake payment"\n') 
    7575    for uname in usernames : 
    7676        argsfile.write("%s\n" % uname)