Index: controlies/trunk/applications/controlies/models/menu.py
===================================================================
--- controlies/trunk/applications/controlies/models/menu.py	(revision 346)
+++ controlies/trunk/applications/controlies/models/menu.py	(revision 347)
@@ -47,7 +47,7 @@
    )]
 
 response.menu+=[('Base Datos', False, None,[            
-            ('Portátiles', False,URL( 'database', 'laptops')),   
+            ('Portátiles', False,URL( 'laptops', 'index')),   
             ]
    )]
 
Index: controlies/trunk/applications/controlies/views/database/laptops.html
===================================================================
--- controlies/trunk/applications/controlies/views/database/laptops.html	(revision 346)
+++ controlies/trunk/applications/controlies/views/database/laptops.html	(nonexistent)
@@ -1,237 +0,0 @@
-<!-- Libreria Multiselect -->
-{{response.files.append(URL('static','js/multiselect/jquery.multiselect.css'))}}
-{{response.files.append(URL('static','js/multiselect/jquery.multiselect.min.js'))}}
-{{response.files.append(URL('static','js/multiselect/jquery.multiselect.es.js'))}}
-{{#response.files.append(URL('static','css/helper.css'))}}
-{{#response.files.append(URL('static','css/dropdown.css'))}}
-{{#response.files.append(URL('static','css/default.advanced.css'))}}
- 
-{{extend 'layout.html'}}
-
-        <div id="tabla_clientes" class="centerGrid">
-            <table width="100%" align="center">
-            <tr>
-                <td style="width:2%"></td>
-                <td style="text-align:center;"><table id="list" width="100%"></table></td>
-                <td style="width:2%"></td>
-            </tr>
-            </table>
-            <div id="pager" style=""></div> 
-            <div id="filter" style="margin-left:30%;display:none">Buscar nada</div>
-        </div>
-
-        <div id="dialog-form"></div>
-        <div id="dialog-form2"></div>        
-
-        <div id="dialog-confirm" title="¿Borrar el registro seleccionado?" style="display:none;">
-            <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Este elemento quedará permanentemente eliminado. ¿Está seguro?</p>
-        </div>
-
-        <div id="dialog-alert" title="Atención" style="display:none;">
-            <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Para operar sobre un registro debe seleccionarlo previamente.</p>
-        </div>
-
-
-<script type="text/javascript">  
-    
-    jQuery(function() {
-        jQuery("#dialog-confirm").dialog({ autoOpen: false });
-        jQuery("#dialog-alert").dialog({ autoOpen: false });
-    });
-    
-                
-    function print_grid(){  
-          jQuery("#list").jqGrid({
-                url:"{{=URL(c='laptops',f='call',args=['json','list'])}}",
-                data: "{}",
-                datatype: 'json',
-                mtype: 'GET',
-                contentType: "application/json; charset=utf-8",
-                complete: function(jsondata, stat) {
-                    if (stat == "success") {
-                        var thegrid = jQuery("#list")[0];
-                        thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
-                    }
-                },
-                
-                colNames:['Marca','Modelo','Número Serie'],
-                colModel:[ 
-                    {name:'marca',index:'marca', width:60, align:"center"},
-                    {name:'modelo',index:'modelo', width:115, align:"center"},
-                    {name:'numero_serie',index:'numero_serie', width:115, align:"center"}
-                ], 
-                rowNum:25,
-                height:335,
-                width: 900,
-                rowList:[25,50,75],  
-                pager: '#pager', 
-                sortname: 'marca', 
-                autowidth: false,
-                viewrecords: true, 
-                sortorder: "desc", 
-                caption:"Portátiles"    
-        
-          }); 
-          jQuery("#list").jqGrid('navGrid','#pager',{add:false,edit:false,del:false,search:false,refresh:false});
-        
-            jQuery("#list").jqGrid('navButtonAdd','#pager',{
-                    caption: "Insertar",
-                    buttonicon :'ui-icon-plus',
-                    onClickButton : function (){ 
-                        addRecord();
-                    } 
-            }); 
-            jQuery("#list").jqGrid('navButtonAdd','#pager',{
-                    caption: "Modificar", 
-                    buttonicon :'ui-icon-pencil',
-                    onClickButton : function (){ 
-                        modifyRecord();
-                } 
-            }); 
-            jQuery("#list").jqGrid('navButtonAdd','#pager',{
-                    caption: "Borrar", 
-                    buttonicon :'ui-icon-trash',
-                    onClickButton : function (){ 
-                        deleteRecord();
-                } 
-            }); 
-        
-          
-          jQuery("#list").jqGrid('filterToolbar'); 
-       
-    }
-    
-    
-    function rowSelected(){
-            var uid = jQuery("#list").jqGrid('getGridParam','selrow'); 
-        
-            if( uid == null ){
-                jQuery( "#dialog-alert" ).dialog({
-                    resizable: false,
-                    height:150,
-                    width:290,
-                    modal: true,
-                    buttons: { "Aceptar": function() { $( this ).dialog( "close" ); }}
-                }).dialog('open');
-                return false;
-            }
-            return uid;
-    }           
-    
-    function addRecord(){
-    
-            jQuery("#messageLoading").show();
-        
-            jQuery("#dialog-form").html("").css("display","none");
-            jQuery("#dialog-form").load("form.html", function() {
-                getAllGroups();
-                jQuery("#form_data #action").val("add");
-                jQuery("#form_data #homeDirectoryP").css("display","block");
-                
-                jQuery("#form_data #messageForm").html("Todos los campos son obligatorios");                                     
-        
-                x = (jQuery(window).width()-350)/2;
-                y = (jQuery(window).height()-500)/2;
-        
-                jQuery("#messageLoading").hide();
-        
-                jQuery("#dialog-form").dialog({
-                    resizable: false,
-                    position: top,
-                    modal: true,
-                    width: 350,
-                    title: "Añadir Portátil"
-                }).dialog('option', 'position', [x, y]);
-            });
-    }
-    
-    function modifyRecord(){
-                    var uid;
-    
-                    jQuery("#messageLoading").show();
-                    
-                    var uid = rowSelected();
-                    if(uid==false)
-                        return false;
-    
-                    jQuery("#dialog-form").html("").css("display","none");
-                    jQuery("#dialog-form").load("form.html", function() {
-                        
-                        getAllGroups();
-                        
-                        jQuery("#form_data #action").val("modify");
-                        jQuery("#form_data #user").attr("readonly","true");
-                        jQuery("#form_data #user").css("background-color","#DDD");
-                        jQuery("#form_data #messageForm").html("Si deja la contraseña en blanco no se modificará<br>El resto de campos son obligatorios");
-                        
-                        jQuery.post('call/json/getUserData',{ username: uid }, function(result) {
-                            //var result = jQuery.parseJSON(data);
-    
-                            if(result.response['type']=="teacher")
-                                var textType = "Profesor";
-                            else
-                                var textType = "Alumno";
-                                
-                            var dep = Array(result.response['groups']['departments']);
-    
-                            jQuery("#form_data #type").replaceWith(textType+"<input type='hidden' id='type' name='type' value='"+result.response['type']+"'/>");
-                            jQuery("#form_data #name").val(result.response['name']);
-                            jQuery("#form_data #nif").val(result.response['nif']);       
-                            jQuery("#form_data #user").val(result.response['user']);
-                            jQuery("#form_data #surname").val(result.response['surname']);
-                            if (result.response['photo']!='')
-                                jQuery("#form_data #photo").attr("src","data:image/png;base64,"+result.response['photo']);                       
-    
-                            $.each(result.response['groups']['departments'], function(i, l){
-                                jQuery('#form_data input:checkbox[value='+l+']').attr('checked', true);                          
-                            });
-    
-                            $.each(result.response['groups']['classrooms'], function(i, l){
-                                jQuery('#form_data input:checkbox[value='+l+']').attr('checked', true);                          
-                            });                     
-    
-                            x = (jQuery(window).width()-350)/2;
-                            y = (jQuery(window).height()-500)/2;
-                            
-                            jQuery("#messageLoading").hide();
-                            
-                            jQuery("#dialog-form").dialog({
-                                resizable: false,
-                                modal: true,
-                                width: 350,
-                                title: "Modificar Usuario"
-                            }).dialog('option', 'position', [x, y]);                        
-                        });               
-                    });
-    }
-    
-    function deleteRecord(){
-        
-            var uid = rowSelected();
-            if(uid==false)
-                return false;
-        
-            jQuery( "#dialog-confirm" ).dialog({
-                resizable: false,
-                height:160,
-                width:350,
-                modal: true,
-                buttons: {
-                    "Borrar": function() {
-                        jQuery.post("call/json/delete","user="+uid, function(data){
-                            jQuery("#dialog-confirm").dialog( "close" );
-                            jQuery("#list").trigger("reloadGrid");
-                        });
-                    },
-                    "Cancelar": function() {
-                        $(this).dialog( "close" );
-                    }
-                }
-            }).dialog('open');
-    }
-    
-</script>
-
-<script type="text/javascript">
-  jQuery(document).ready(function(){  print_grid();}); 
-</script>

Property changes on: controlies/trunk/applications/controlies/views/database/laptops.html
___________________________________________________________________
Deleted: svn:executable
## -1 +0,0 ##
-*
\ No newline at end of property
Index: controlies/trunk/applications/controlies/controllers/laptops.py
===================================================================
--- controlies/trunk/applications/controlies/controllers/laptops.py	(revision 346)
+++ controlies/trunk/applications/controlies/controllers/laptops.py	(revision 347)
@@ -8,132 +8,48 @@
 
 @service.json
 @auth.requires_login()
-def list():
+def list():    
     my = MySQLConnection()
-    l = Laptops(my,"","")
+    l = Laptops(my,"","","")
     response = l.list(request.vars)
-    #my.close()
     return response
 
 @service.json
-@auth.requires_login()    
-def searchUsername():
-    l=conecta()
-    u = Users(l,"",request.vars['name'],request.vars['name'],"","","","","","")
-    response = u.searchNewUsername() 
-    l.close()                
+def getLaptopData():
+    my = MySQLConnection()
+    l = Laptops(my,request.vars['id_portatil'],"","")
+    response = l.getLaptopData()
     return dict(response=response)
-    
+
 @service.json
-def getUserData():
-    l=conecta()
-    u = Users(l,"","","","",request.vars['username'],"","","","")
-    response = u.getUserData()
-    l.close()
+def getAllLaptopTypes():
+    my = MySQLConnection()
+    l = Laptops(my,"","","")
+    response = l.getAllLaptopTypes()
     return dict(response=response)
 
-
-@service.json      
-def getAllUsers():
-    import applications.controlies.modules.Utils.LdapUtils as LdapUtils
-    l=conecta()
-    response = LdapUtils.getAllUsers(l)
-    l.close()
-    return response
-
 @service.json
 @auth.requires_login()       
 def delete():
-    l=conecta()
-    u = Users(l,"","","","",request.vars['user'],"","","","")
-    response = u.delete()  
-    l.close()                          
+    my = MySQLConnection()
+    l = Laptops(my,request.vars["id_portatil"],"","")
+    response = l.delete()                         
     return dict(response=response)
 
 @service.json
 @auth.requires_login()    
-def modify_user():
+def modify():
+    my = MySQLConnection()
+    l = Laptops(my,request.vars["id_portatil"],request.vars["numero_serie"],request.vars["marca_modelo"])
+    response = l.process(request.vars["action"])
+    return dict(response = response)            
 
-    l=conecta() 
-    departments=[]
-    classrooms=[]                
-    if 'multiselect_departments' in request.vars: departments = request.vars['multiselect_departments']
-    if 'multiselect_classrooms' in request.vars:classrooms = request.vars['multiselect_classrooms']
+def laptops():
+    return dict()
 
-    u = Users(l,request.vars['type'],request.vars['name'],request.vars['name'],request.vars['nif'],request.vars['user'],request.vars['password'],request.vars['password2'],departments,classrooms)
-    response = u.process(request.vars['action'])
-    l.close()
-    return dict(response = response)    
-    #return dict(response = "OK")        
-
-@service.json
-@auth.requires_login()   
-def create_home_directory_withoutpass():
-    from applications.controlies.modules.SSHConnection import SSHConnection
-
-    c = SSHConnection("servidor","root","")
-    response = c.connectWithoutPass("/var/web2py/applications/controlies/.ssh/id_rsa")
-
-    if response != True:
-		return dict(response = response)
-		
-    l=conecta()
-    u = Users(l,"","","","",request.vars['username'],"","","","")
-    responseUser = u.getUserData()
-    l.close()
-
-    homeDirectory = Utils.homeDirectory(request.vars['type'])+responseUser["user"]
-			
-    c.exec_command("cp -r /etc/skel "+homeDirectory)
-    c.exec_command("chown -R "+responseUser["uidnumber"]+":"+responseUser["gidnumber"]+" "+homeDirectory)
-    c.close()
-
-    return dict(response = "OK")
-
-
-@service.json
-@auth.requires_login()   
-def create_home_directory():
-    from applications.controlies.modules.SSHConnection import SSHConnection
-
-    #c = SSHConnection(request.vars['host'],request.vars['user'],request.vars['password'])
-    c = SSHConnection("servidor","root",request.vars['password'])
-    response = c.process()
-    print request.vars
-    if response != True:
-		return dict(response = response)
-
-    l=conecta()
-    u = Users(l,"","","","",request.vars['username'],"","","","")
-    responseUser = u.getUserData()
-    l.close()
-
-    homeDirectory = Utils.homeDirectory(request.vars['type'])+responseUser["user"]
-			
-    c.exec_command("cp -r /etc/skel "+homeDirectory)
-    c.exec_command("chown -R "+responseUser["uidnumber"]+":"+responseUser["gidnumber"]+" "+homeDirectory)
-
-    try:
-		if request.vars["trustRelationship"] == "on":
-			dir_ssh = "/var/web2py/applications/controlies"
-			Utils.generateRSAkeys(dir_ssh)
-			c.open_ftp()
-			c.removeFile("/tmp/controlIES_rsa.pub")
-			c.putFile(dir_ssh+"/.ssh/id_rsa.pub","/tmp/controlIES_rsa.pub")
-			c.exec_command('cat /tmp/controlIES_rsa.pub >> /root/.ssh/authorized_keys')
-			c.close_ftp()
-    except:
-		pass
-
-    c.close()    
-    return dict(response = "OK")       
-    
 def form():
     return dict()
 
-def form_home_directory():
-    return dict()
-
 def call():
     """
     exposes services. for example:
Index: controlies/trunk/applications/controlies/modules/MySQLConnection.py
===================================================================
--- controlies/trunk/applications/controlies/modules/MySQLConnection.py	(revision 346)
+++ controlies/trunk/applications/controlies/modules/MySQLConnection.py	(revision 347)
@@ -34,22 +34,11 @@
         self.passwd = "controlies"
         self.database = "controlies"
 
-    def process(self,sql):
-        self.connect()
-        result = self.execute(sql)
-        return result
-
-    def connect(self):
-        self.db = MySQLdb.connect(host=self.host,user=self.user, passwd=self.passwd,db=self.database)      
-
-        return True
-
     def execute(self,sql):
-        self.cursor=self.db.cursor()
-        self.cursor.execute(sql)
-        result = self.cursor.fetchall()
-        self.cursor.close()        
-        return result
-
-    def close(self):
-        self.db.close()
+        db = MySQLdb.connect(host=self.host,user=self.user, passwd=self.passwd,db=self.database)
+        cursor=db.cursor()
+        cursor.execute(sql)
+        result = cursor.fetchall()
+        cursor.close()
+        db.close()
+        return result
\ No newline at end of file
Index: controlies/trunk/applications/controlies/modules/Laptops.py
===================================================================
--- controlies/trunk/applications/controlies/modules/Laptops.py	(revision 346)
+++ controlies/trunk/applications/controlies/modules/Laptops.py	(revision 347)
@@ -1,13 +1,13 @@
 ##############################################################################
 # -*- coding: utf-8 -*-
 # Project:      ControlIES
-# Module:       Users.py
-# Purpose:      Users class
+# Module:       Laptops.py
+# Purpose:      Laptops class
 # Language:     Python 2.5
-# Date:         7-Feb-2011.
-# Ver:          7-Feb-2011.
+# Date:         31-May-2012.
+# Ver:          31-May-2012.
 # Author:       Manuel Mora Gordillo
-# Copyright:    2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
+# Copyright:    2012 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
 #
 # ControlIES is free software: you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -29,18 +29,28 @@
     def __init__(self):
         pass
     
-    def __init__(self,MySQL,numero_serie,marca_modelo):
+    def __init__(self,MySQL,id_portatil,numero_serie,id_marca_modelo):
         self.MySQL = MySQL
+        self.id_portatil = id_portatil        
         self.numero_serie = numero_serie
-        self.marca_modelo = marca_modelo        
+        self.id_marca_modelo = id_marca_modelo        
         
     def validation(self,action):
-        
+
+        if self.id_marca_modelo == "none":
+            return "marca_modelo"
+
         if self.numero_serie == "":
             return "numero_serie"
+        
+        exists = self.existsSerialNumber(self.numero_serie)
+        
+        if action=="add" and exists!=False:
+            return "existe_numero_serie"
 
-        if self.marca_modelo == "":
-            return "marca_modelo"
+        if action=="modify" and exists!=False:
+            if exists!=self.id_portatil:
+                return "existe_numero_serie"
                 
         return "OK"
 
@@ -66,30 +76,32 @@
             
     def list(self,args):
 
-        sql="SELECT p.id_portatil, pmm.marca, pmm.modelo, p.numero_serie FROM portatiles p, portatiles_marca_modelo pmm "
-        sql=sql+"WHERE p.id_marca_modelo=pmm.id_marca_modelo"
-
+        sql = "SELECT p.id_portatil, pmm.marca, pmm.modelo, p.numero_serie FROM portatiles p, portatiles_marca_modelo pmm "
+        sql = sql+"WHERE p.id_marca_modelo=pmm.id_marca_modelo"
+        
         try:
-            sql = sql+" AND p.numero_serie LIKE '%"+args['numero_serie']+"%'"
+            if str(args['numero_serie']) != "None":
+                sql = sql+" AND p.numero_serie LIKE '%"+str(args['numero_serie'])+"%'"
         except LookupError:
             pass
 
         try:
-            sql = sql+" AND pmm.marca LIKE '%"+args['marca']+"%'"
+            if str(args['marca']) != "None":
+                sql = sql+" AND pmm.marca LIKE '%"+str(args['marca'])+"%'"
         except LookupError:
             pass
 
         try:
-            sql = sql+" AND pmm.modelo LIKE '%"+args['modelo']+"%'"
+            if str(args['modelo']) != "None":
+                sql = sql+" AND pmm.modelo LIKE '%"+str(args['modelo'])+"%'"
         except LookupError:
-            pass        
+            pass
 
-        sql = sql +" ORDER BY "+args['sidx']+" "+args['sord']
-        result = self.MySQL.process(sql)
+        sql = sql + " ORDER BY "+args['sidx']+" "+args['sord']
+        result = self.MySQL.execute(sql)
 
         rows = []
         for reg in result:
-
             row = {
 				"id":reg[0],
 				"cell":[reg[1],reg[2],reg[3]],
@@ -121,224 +133,57 @@
         return { "page":page, "total":totalPages, "records":len(rows), "rows":rows[start:finish] }
 
 
-    """def add(self):        
-
-        
-        attr = [
-        ('objectclass', ['top','posixAccount','shadowAccount','person','inetOrgPerson']),
-        ('uid', [self.user]),
-        ('cn', [self.name] ),
-        ('employeenumber', [self.nif] ),        
-        ('sn', [self.name] ),
-        ('uidnumber', [maxID] ),
-        ('gidnumber', [maxID] ),    
-        ('loginshell', ['/bin/bash'] ),
-        ('homeDirectory', [LdapUtils.whatHome(self.type) + self.user] ),
-        #('jpegPhoto', ['jpegPhoto'] ),     
-        ('userpassword', [passwd])
-        ]
-        if self.foto is not None:
-            attr.append(('jpegPhoto',[self.foto]))
-
-        self.ldap.add("uid="+self.user+",ou=People", attr)
-
-        # Add private group
-        attr = [
-        ('objectclass', ['top','posixGroup','lisGroup']),
-        ('grouptype', ['private']), 
-        ('gidnumber', [maxID] ),    
-        ('cn', [self.user] ),
-        ('description', [self.name+' personal group'] )
-        ]
-
-        self.ldap.add("cn="+self.user+",ou=Group", attr)
-        
-        
-        # Add selected groups   
-        attr = [
-        (ldap.MOD_ADD, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
-        (ldap.MOD_ADD, 'memberUid', [self.user] )
-        ]
-
-        if self.departments != ['']:                   
-            for n in self.departments:
-                self.ldap.modify('cn='+ n +',ou=Group', attr)
-    
-        if self.classrooms != ['']:  
-            for n in self.classrooms:
-                self.ldap.modify('cn='+ n +',ou=Group', attr)
-            
-        if self.type=='teacher':
-            self.ldap.modify('cn=teachers,ou=Group', attr)
-        elif self.type=='student':
-            self.ldap.modify('cn=students,ou=Group', attr)
+    def add(self):        
+        sql = "INSERT INTO portatiles (id_portatil, numero_serie, id_marca_modelo) "
+        sql = sql + "VALUES(null,'"+self.numero_serie+"','"+self.id_marca_modelo+"')"
+        result = self.MySQL.execute(sql)
                         
         return "OK"
             
             
     def modify(self):
-        attr = [
-        (ldap.MOD_REPLACE, 'cn', [self.name] ),
-        (ldap.MOD_REPLACE, 'employeenumber', [self.nif] ),      
-        (ldap.MOD_REPLACE, 'sn', [self.surname] )       
-        ]
-
-        if self.password!="":
-            passwd = '{SSHA}' + Utils.encrypt(self.password)
-            attr.append((ldap.MOD_REPLACE, 'userpassword', [passwd]))
-        
-        self.ldap.modify("uid="+self.user+",ou=People", attr)
-
-        # Get current groups
-        currentGroups = self.getUserGroups()
-        
-        groupsDepartments = Utils.cmpLists(currentGroups["departments"], self.departments)
-        groupsClassrooms = Utils.cmpLists(currentGroups["classrooms"], self.classrooms)     
-        
-        # Delete unselected groups      
-        deleteDepartments = groupsDepartments["onlyInList1"]
-        deleteClassrooms = groupsClassrooms["onlyInList1"]
-        
-        attr = [
-        (ldap.MOD_DELETE, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
-        (ldap.MOD_DELETE, 'memberUid', [self.user] )
-        ]
-
-        for d in deleteDepartments:
-            self.ldap.modify('cn='+ d +',ou=Group', attr)
-
-        for d in deleteClassrooms:
-            self.ldap.modify('cn='+ d +',ou=Group', attr)
+        sql = "UPDATE portatiles SET numero_serie='"+self.numero_serie+"', id_marca_modelo='"+self.id_marca_modelo+"' "
+        sql = sql + "WHERE id_portatil='"+str(self.id_portatil)+"'"
+        result = self.MySQL.execute(sql)
                     
-        # Add selected groups   
-        newDepartments = groupsDepartments["onlyInList2"]
-        newClassrooms = groupsClassrooms["onlyInList2"]
-        
-        attr = [
-        (ldap.MOD_ADD, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
-        (ldap.MOD_ADD, 'memberUid', [self.user] )
-        ]
-
-        for n in newDepartments:
-            self.ldap.modify('cn='+ n +',ou=Group', attr)
-
-        for n in newClassrooms:
-            self.ldap.modify('cn='+ n +',ou=Group', attr)
-                    
         return "OK"
 
 
     def delete(self):
-        
-        self.ldap.delete('uid='+ self.user +',ou=People')
-        self.ldap.delete("cn="+self.user+",ou=Group")
-        
-        # Delete unselected groups      
-        currentGroups = self.getUserGroups()
-
-        attr = [
-        (ldap.MOD_DELETE, 'member', ['uid='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es'] ),
-        (ldap.MOD_DELETE, 'memberUid', [self.user] )
-        ]
-
-        for d in currentGroups["departments"]:
-            self.ldap.modify('cn='+ d +',ou=Group', attr)
-
-        for d in currentGroups["classrooms"]:
-            self.ldap.modify('cn='+ d +',ou=Group', attr)
+        sql = "DELETE FROM portatiles WHERE id_portatil='"+str(self.id_portatil)+"'"
+        result = self.MySQL.execute(sql)
             
         return "OK"
 
 
-    def existsUsername(self):
+    def existsSerialNumber(self,serial):
         
-        result = self.ldap.search("ou=People","uid="+self.user,["uid"])
-
+        sql = "SELECT p.id_portatil FROM portatiles p WHERE p.numero_serie='"+serial+"'"
+        result = self.MySQL.execute(sql)
         if len(result) > 0:
-            return True
+            return str(result[0][0])
         
         return False
-
-
-    def searchNewUsername(self):
-
-        result = self.ldap.search("ou=People","uid=*",["uid"])
-        users = []
-        for i in result:
-            users.append(i[0][1]['uid'][0])
-
-        n = self.name.lower().split(" ")
         
-        username = ""
-        if len(n) > 0:
-            username = n[0][0:1]
+    def getLaptopData(self):
+		
+        sql="SELECT * FROM portatiles p WHERE id_portatil='"+self.id_portatil+"'"
+        result = self.MySQL.execute(sql)
+        dataLaptop = {
+            "id_portatil":str(result[0][1]),
+            "numero_serie":result[0][0],
+            "id_marca_modelo":str(result[0][2])
+        }
+        return dataLaptop
 
-        if len(n) > 1:
-             username = username + n[1]
-             
-        if len(n) > 2:
-            username = username + n[2][0:1]
-
-        num = 1
-        searching = username + "0" + str(num)
-
-        found = True
-        while found:
-            try:
-                users.index(searching)
-                num = num + 1
-                
-                if len(str(num)) == 1:
-                    searching = username + "0" + str(num)
-                else:
-                    searching = username + str(num)
-            except:
-                found = False
-                
-        return searching
-
-    def getUserGroups(self):
-        result = self.ldap.search("ou=Group","(&(memberUid="+self.user+")(|(groupType=school_department)(groupType=school_class)))",["cn","groupType"])
-
-        departments = []
-        classrooms = []     
-        for g in result:
-            if g[0][1]["groupType"][0] == "school_department":
-                departments.append(g[0][1]["cn"][0])
-            elif g[0][1]["groupType"][0] == "school_class":
-                classrooms.append(g[0][1]["cn"][0])
-        
-        departments.sort()
-        classrooms.sort()
-        return { "departments":departments, "classrooms":classrooms }
-        
-    def getUserData(self):
-        self.getUserGroups()
-        result = self.ldap.search("ou=People","uid="+self.user,["uid","cn","sn","employeenumber","homedirectory","uidnumber","gidnumber","jpegPhoto"])
-        
-        if len(result) == 0:
-            return { "user":"", "name":"", "surname":"", "nif":"", "photo":"", "type":"","uidnumber":"","gidnumber":"", "groups":[] }
-        
-        type = "student"
-        if result[0][0][1]["homeDirectory"][0][0:14]=="/home/profesor":
-            type = "teacher"
-        
-        try:
-            photo = base64.b64encode(result[0][0][1]["jpegPhoto"][0])
-        except:
-            photo = ""
-        userdata=result[0][0][1]  
-        if "employeeNumber" not in userdata: userdata["employeeNumber"]=["0"]
-        dataUser = {
-            "user":userdata["uid"][0],
-            "name":userdata["cn"][0],
-            "surname":userdata["sn"][0],
-            "nif":userdata["employeeNumber"][0],
-            "uidnumber":userdata["uidNumber"][0],
-            "gidnumber":userdata["gidNumber"][0],
-            "photo":photo,
-            "type":type,
-            "groups":self.getUserGroups()
-         }
-         
-        return dataUser"""
+    def getAllLaptopTypes(self):
+        sql="SELECT id_marca_modelo, marca, modelo FROM portatiles_marca_modelo ORDER BY marca"
+        result = self.MySQL.execute(sql)
+        data=[]
+        for r in result:
+            dataType = {
+                "id_marca_modelo":str(r[0]),
+                "marca_modelo":r[1]+" / "+r[2]
+            }
+            data.append(dataType)
+        return data
\ No newline at end of file
