Exemple #1
0
    def split_ecriture(self):
        """ Update an ecriture"""

        data = {}
        data['compte_id'] = self.options.compte
        data['id'] = self.options.id
        if not self.options.ec:
            response = RequestServer.get_method("ecriture",
                                                ecriture=data['id'],
                                                compte=data['compte_id'],
                                                filter={"sort": "ecriture_categorie",}
                                               )
            if response.status_code == 404:
                raise Exception("Impossible de trouver ecriture categorie")
            tmp_response = response.json()
            data['ecriture_categorie_id'] = tmp_response[0]["ecriture_categorie_id"]
        else:    
            data['ecriture_categorie_id'] = self.options.ec
        if not self.options.montant:
            raise Exception("Montant obligatoire")
        if not re.match(r"^\d+([\.,]\d{1,2})?$", self.options.montant):
            raise Exception("Erreur dans le montant")
        data['montant'] = self.options.montant
        if not self.options.categorie:
            raise Exception("Categorie obligatoire")
        if not re.match(r"^\d{1,2}$",self.options.categorie):
            raise Exception("Erreur de categorie")
        data['categorie'] = self.options.categorie

        print data
        response = RequestServer.put_method("split", dumps(data))
        print response
Exemple #2
0
    def update_ecriture(self):
        """ Update an ecriture"""

        data = {}
        data['compte_id'] = self.options.compte
        data['id'] = self.options.id
        if self.options.montant:
            data['montant'] = self.options.montant
        if self.options.type:
            data['type'] = self.options.type
        if self.options.dc and self.options.dc == "d":
            data['dc'] = -1
        elif self.options.dc and  self.options.dc == "c":
            data['dc'] = 1
        if self.options.nom:
            data['nom'] = self.options.nom
        if self.options.description:
            data['description'] = self.options.description
        if self.options.date:
            if not re.match(r"^201[0-9]\/\d{1,2}\/\d{1,2}$", self.options.date):
                raise Exception("format non valide de date")
            data['date'] = self.options.date
        if self.options.categorie:
            data['categorie'] = self.options.categorie

        print data
        response = RequestServer.put_method("ecriture", dumps(data))
        print response
Exemple #3
0
 def get(self):
     """ get data by rest method and print it"""
     self.rqst = RequestServer.get_method(self.rest_method,
                                          self.filter,
                                          self.sort,
                                          self.attribut
                                         )
Exemple #4
0
 def create(self):
     """ create data by rest method """
     if self.options is None:
         pass
     elif self.check_args(self.options.prompt):
         pass
     else:
         print "Erreur de saisie pour l'ajout"
         sys.exit(1)
     self.rqst = RequestServer.post_method(self.rest_method,
                                           self.attribut,
                                          )
Exemple #5
0
    def list_ecriture(self):
        """ List ecriture """

        id = None
        compte = None
        filter = {}
        if self.options.id:
            id = self.options.id
        if self.options.compte:
            compte = self.options.compte
        if self.options.filter:
            filter["filter"] = self.options.filter
        if self.options.valid:
            filter["valide"] = "yes"
        if self.options.unvalid:
            filter["valide"] = "no"
        if self.options.sort:
            filter["sort"] = self.options.sort
        #rqst = RequestServer('localhost', '8080')
        #print rqst.get('ecriture')
        if not filter:
            filter = None
        response = RequestServer.get_method("ecriture",
                                            ecriture=id,
                                            compte=compte,
                                            filter=filter,
                                           )
        if response.status_code == 404:
            return 1
        tmp_response = response.json()
        if isinstance(tmp_response, list):
            for response in tmp_response:
                print "%s - %40s | %8s | %2s | %15s / (%s/%s)" % (response["date"],
                                                   response["nom"],
                                                   response["montant"],
                                                   response["type"],
                                                   response["categorie"],
                                                   response["id"],
                                                   response["ecriture_categorie_id"],
                                                  )
        elif isinstance(tmp_response, dict):
            for k, v in tmp_response.iteritems():
                print "%s -> %s" % (k, v)
        else:
            print tmp_response
Exemple #6
0
    def prompt_categorie(self):
        """ print prompt to choose your categorie """
        if self.cache_categorie is None:
            self.cache_categorie = RequestServer.get_method("categorie",
                                                            {'odata': 'count lt 20'},
                                                            ['nom',],
                                                            []
                                                           )

        for i in range(1, 10):
            tmp_str = ""
            for categorie in self.cache_categorie[(i-1)*5:i*5]:
                tmp_str += "%2d - %10s | " % (categorie['id'], categorie['nom'].strip()[0:10])
            print tmp_str[:-3]
        while True:
            data = unicode(raw_input("categorie (defaut: 5): "))
            if data == "":
                self.attribut['categorie_id'] = 5
                break
            if re.match(r"^\d{1,2}$", data):
                self.attribut['categorie_id'] = data
                break
Exemple #7
0
    def create(self):
        """ Redefine create to add an ecriture """

        if not self.check_args(self.options.prompt):
            print "Erreur de saisie pour l'ajout, champ manquant ou utiliser prompt option"
            sys.exit(1)

        #Add information for table montant
        if self.options.prompt:
            self.prompt_categorie()
            while True:
                data = unicode(raw_input("Montant : "))
                if re.match(r"^[-+]?\d+[,\.]?\d*$", data):
                    self.attribut['montant'] = data
                    break
            self.rqst = RequestServer.post_method('ecriture',
                                                  self.attribut,
                                                 )
            ecriture_id = re.match(r"^\/ecriture\/(?P<ecriture_id>.*)\/$",
                                   self.rqst.headers['Location']
                                  ).group('ecriture_id')
            self.set_tag(ecriture_id, False)
Exemple #8
0
 def set_tag(self, ecriture_id, create=False):
     """ Insert a tag if attribute exist and tag name exists """
     if self.tag:
         if not self.tag_id:
             tags = Tag()
             tags.attribut = {}
             tags.filter = {'nom': self.tag}
             tags.get()
             if tags.rqst != False:
                 self.tag_id = tags.rqst[0]['id']
             elif create:
                 tags.attribut['nom'] = self.tag
                 tags.attribut['valeur'] = ""
                 tags.create()
                 self.tag_id = re.match(r"^\/tag\/(?P<tag_id>.*)\/$",
                                        tags.rqst.headers['Location']
                                       ).group('tag_id')
         self.rqst = RequestServer.post_method("tag_ecriture",
                                               {'ecriture_id': ecriture_id,
                                                'tag_id': self.tag_id
                                               },
                                              )
Exemple #9
0
 def import_data(self, extension='csv'):
     """Import ofx file to database, by account
        Import data from a file
        For csv file, there must hae a header like it :
        date;nom;montant
        In attribute, we muste define these parameter :
        compte_id
        By default, all import has default categorie (5)
        A Tag is created with default date for the import
     """
     if not self.options.importfile:
         sys.exit(1)
     if extension == 'ofx':
         ofx_file = open(self.options.importfile)
         ofx_buf = ofx_file.read()
         parser = LinkParser()
         parser.feed(ofx_buf)
         parser.close()
         ofx_file.close()
     elif extension == 'csv':
         with open(self.options.importfile, 'rb') as csvfile:
             csvreader = csv.DictReader(csvfile, delimiter=';', quoting=csv.QUOTE_NONE)
             for row in csvreader:
                 print "import %s - %s - %s" % (row['date'], row['montant'], row['nom'])
                 self.attribut['date'] = datetime.strptime(row['date'],
                                                           "%d/%m/%y").strftime("%Y/%m/%d")
                 self.attribut['nom'] = row['nom']
                 self.attribut['montant'] = str(row['montant'])
                 if self.options.prompt:
                     self.prompt_categorie()
                 else:
                     self.attribut['categorie_id'] = '5'
                 self.rqst = RequestServer.post_method(self.rest_method,
                                                       self.attribut,
                                                      )
                 ecriture_id = re.match(r"^\/ecriture\/(?P<ecriture_id>.*)\/$",
                                        self.rqst.headers['Location']
                                       ).group('ecriture_id')
                 self.set_tag(ecriture_id, True)
Exemple #10
0
    def insert_ecriture(self):
        """ Insert an ecriture """

        data = {}
        data['compte_id'] = self.options.compte
        if not self.options.type in ["Pr", "Vr", "Prs"]:
            data['nom'] = raw_input("nom :")

        data['montant'] = unicode(raw_input("montant :"))
        if not re.match(r"^\d+([\.,]\d{1,2})?$", data['montant']):
            raise Exception("Erreur dans le montant")

        if not self.options.dc:
            data['dc'] = unicode(raw_input("Débit d / Crédit c : "))
            if data['dc'] == "d":
                data['dc'] = -1
            elif data['dc'] == "c":
                data['dc'] = 1
            else:
                raise Exception("Erreur dans Débit/Crédit")
        else:
            if self.options.dc == "d":
                data['dc'] = -1
            elif self.options.dc == "c":
                data['dc'] = 1

        if not self.options.type:
            data['type'] = unicode(raw_input("Typr [Pr, Vr, Cb, Re, Ch, Li]: "))
            if not re.match(r"^(Pr|Vr|Cb|Re|Ch|Li)$", data['type']):
                raise Exception("Erreur dans le type")
        elif self.options.type in ["Pr", "Vr", "Prs"]:
            if self.options.type == 'Pr':
                data['type'] = 'Pr'
                return_compte = RequestServer.get_method("compte",
                                                         filter="prv"
                                                        )
            elif self.options.type == 'Vr':
                data['type'] = 'Vr'
                return_compte = RequestServer.get_method("compte",
                                                         filter="vir"
                                                        )
            elif self.options.type == 'Prs':
                return_compte = RequestServer.get_method("compte",
                                                         filter="prs"
                                                        )
                data['type'] = 'Vr'
            i = 1
            list_compte = []
            for prs in return_compte.json():
                print "%d - %s" % (i, prs['nom'])
                list_compte.append((prs['nom'], prs['id']))
                i += 1
            input_type = raw_input("Virement :")
            data['nom'] = list_compte[int(input_type)-1][0]
            data['nom_id'] = list_compte[int(input_type)-1][1]
        else:
            data['type'] = self.options.type
        if self.options.description:
            data['description'] = self.options.description
        data['date'] = unicode(raw_input("date [YYYY/]DD/MM] :"))
        if not re.match(r"^(201[0-9]\/)?\d{1,2}\/\d{1,2}$", data['date']):
            raise Exception("Erreur dans la date")
        if re.match(r"^\d{2}\/\d{2}$", data['date']):
            data['date'] = str(date.today().year) + "/" + data['date']
        date_now = datetime.now()
        if date_now < datetime.strptime(data["date"], "%Y/%m/%d"):
            raise Exception("La date ne doit pas être dans le future")
        response = RequestServer.get_method("categorie", filter={"sort": "count"})
        list_categorie = response.json()
        for i in range(1, 5):
            tmp_str = ""
            for categorie in list_categorie[(i-1)*5:i*5]:
                tmp_str += "%2d - %16s | " % (categorie['id'], categorie['nom'].strip())
            print tmp_str[:-3]

        data['categorie'] = unicode(raw_input("categorie [consommation : 5] :"))
        if not data['categorie'].isnumeric():
            raise Exception("Erreur de categorie")

        print data
        response = RequestServer.post_method("ecriture", dumps(data))
        print response
Exemple #11
0
 def delete(self):
     """ delete data by rest method """
     self.rqst = RequestServer.delete_method(self.rest_method,
                                             self.filter,
                                            )
Exemple #12
0
 def update(self):
     """ update data by rest method """
     self.rqst = RequestServer.put_method(self.rest_method,
                                          self.filter,
                                          self.attribut
                                         )
Exemple #13
0
    def check_args(self, prompt=False):
        """ Method to check wich argument is mandatory

            Do an introspection in database
            Check for witch argument give by parse_arg if arugment is missing

            If prompt is True, display en prompt to give argument, test it and save it
            return True if OK
            else False
        """
        #attrs = dict((key,value) for key,value in self.attribut.items())
        attrs = copy.deepcopy(self.attribut)
        for database in self.database:
            mapper = inspect(database)
            for column in mapper.attrs:
                if isinstance(column, ColumnProperty) and \
                   not column.columns[0].primary_key:
                    if not attrs.has_key(column.key) and \
                       not column.columns[0].foreign_keys and \
                       not column.columns[0].nullable:
                        if prompt:
                            # Particularity of type (Pr,Vr) and Name : must return compte_id
                            if mapper.tables[0].name == 'ecriture' and \
                               self.attribut.has_key('type') and \
                               self.attribut['type'] in ('Pr', 'Vr') and \
                               column.key == 'nom':
                                if self.attribut['type'] == 'Pr':
                                    compte_type = {'type': 'prv',
                                                   'archive': 'false'
                                                  }
                                else:
                                    compte_type = {'type': 'prs/vir',
                                                   'archive': 'false'
                                                  }
                                list_compte = RequestServer.get_method("compte",
                                                                       compte_type,
                                                                       ['nom',],
                                                                       []
                                                                      )
                                dict_compte = {}
                                for compte in list_compte:
                                    print "%d - %s" % (compte['id'], compte['nom'])
                                    dict_compte[compte['id']] = compte['nom']
                                while True:
                                    data = unicode(raw_input("compte : "))
                                    if re.match(r"^\d{1,2}$", data):
                                        self.attribut['nom_id'] = data
                                        self.attribut['nom'] = dict_compte[int(data)]
                                        break
                            else:
                                while True:
                                    data = unicode(raw_input("%s [%s]: " % (column.key,
                                                                            column.columns[0].key
                                                                           )
                                                            )
                                                  )
                                    data = self.check_type_data(column.columns[0], data)
                                    if data is None:
                                        print "Type non reconnue pour %s (%s)" % (column.key, column.columns[0].type)
                                    else:
                                        self.attribut[column.key] = data
                                        break
                        else:
                            return False
                    elif attrs.has_key(column.key):
                        del(attrs[column.key])
        if attrs:
            print "champs non reconnu %s" % attrs
            return False
        return True