Ejemplo n.º 1
0
def process_table(table_key):

    # Clean facile doc tmpdir
    clean_tmp_dir()

    # Create tmp dir
    driver = FileDriver('tmp_doc', '')
    tmpdir = driver.TempDir(create=True, prefix='tmp_doc_')

    if table_key == 'employe':
        full_path = driver.join(tmpdir.path, 'table_employe.xlsx')
        Employe.table_loading(full_path=full_path, type='excel')

    elif table_key == 'fournisseur':
        full_path = driver.join(tmpdir.path, 'table_fournisseur.xlsx')
        Fournisseur.table_loading(full_path=full_path, type='excel')

    elif table_key == 'client':
        full_path = driver.join(tmpdir.path, 'table_client.xlsx')
        Client.table_loading(full_path=full_path, type='excel')

    elif table_key == 'contact':
        full_path = driver.join(tmpdir.path, 'table_contact.xlsx')
        Contact.table_loading(full_path=full_path, type='excel')

    elif table_key == 'chantier':
        full_path = driver.join(tmpdir.path, 'table_chantier.xlsx')
        Chantier.table_loading(full_path=full_path, type='excel')

    elif table_key == 'affaire':
        full_path = driver.join(tmpdir.path, 'table_affaire.xlsx')
        FeuilleTravaux.table_loading(full_path=full_path, type='excel')

    elif table_key == 'devis':
        full_path = driver.join(tmpdir.path, 'table_devis.xlsx')
        Devis.table_loading(full_path=full_path, type='excel')

    elif table_key == 'facture':
        full_path = driver.join(tmpdir.path, 'table_facture.xlsx')
        Facture.table_loading(full_path=full_path, type='excel')

    elif table_key == 'commande':
        full_path = driver.join(tmpdir.path, 'table_commande.xlsx')
        Commande.table_loading(full_path=full_path, type='excel')

    elif table_key == 'heure':
        full_path = driver.join(tmpdir.path, 'table_heure.xlsx')
        Heure.table_loading(full_path=full_path, type='excel')

    else:
        raise ValueError('key not understood {}'.format(table_key))
    import time
    time.sleep(1)
    return full_path, tmpdir
Ejemplo n.º 2
0
    def test_request(self):
        """
        python -m unittest tests.models.employe.TestEmploye.test_request

        """
        l_client = Employe.get_employes(path=self.path)
        self.assertEqual(len(l_client), 1)
        self.assertEqual(l_client[0], "Jean Dujardin")

        # Test from index instance method
        test_employe = Employe.from_index_({'nom': 'Dujardin', 'prenom': 'Jean'}, path=self.path)

        for k, v in self.d_init[0].items():
            if k not in [sch.name for sch in BaseModel.l_hfields]:
                self.assertEqual(test_employe.__getattribute__(k), v)
Ejemplo n.º 3
0
 def list(kw):
     if kw == 'employe':
         return zip(Employe.get_employes(), Employe.get_employes()) + [
             (u'interim', u'Intérimaires')
         ]
     elif kw == 'affaire':
         return zip(Affaire.get_affaire(), map(str, Affaire.get_affaire()))
     elif kw == 'week':
         current_monday = dates.get_current_start_date()
         l_dates = pd.DatetimeIndex(
             start=current_monday - pd.Timedelta(days=30),
             end=current_monday + pd.Timedelta(days=6),
             freq='w')
         return [str((t + pd.Timedelta(days=1)).date()) for t in l_dates]
     elif kw == 'heures':
         return zip(range(1000), range(1000))
     else:
         return []
Ejemplo n.º 4
0
    def list(kw):

        d_month = {
            1: 'Janvier {}', 2: 'Fevrier {}', 3: 'Mars {}', 4: 'Avril {}', 5: 'Mai {}', 6: 'Juin {}', 7: 'Juillet {}',
            8: 'Aout {}', 9: 'Septembre {}', 10: 'Octobre {}', 11: 'Novembre {}', 12: 'Decembre {}'
        }

        if kw == 'client':
            return zip(Client.get_clients(), Client.get_clients())
        elif kw == 'contact':
            return Contact.get_contact('client_commande', return_id=True)
        elif kw == 'responsable':
            return zip(Employe.get_employes(**{'categorie': 'charge affaire'}),
                       Employe.get_employes(**{'categorie': 'charge affaire'}))
        elif kw == 'base_prix':
            d = pd.Timestamp.now().date()
            l_dates = pd.DatetimeIndex(start=d - pd.Timedelta(days=95), end=d + pd.Timedelta(days=95), freq='M')
            return [(d_month[t.month].format(t.year), d_month[t.month].format(t.year)) for t in l_dates]
        else:
            return []
Ejemplo n.º 5
0
 def list(id_, **kwlist):
     if id_ == 'responsable':
         return zip(Employe.get_employes(**{'categorie': 'charge affaire'}),
                    Employe.get_employes(**{'categorie': 'charge affaire'}))
     elif id_ == 'devis':
         return zip(Devis.get_devis(), Devis.get_devis())
     elif id_ == 'chantier':
         kwargs = kwlist.get('chantier', {})
         return Chantier.get_chantier(return_id=True, **kwargs)
     elif id_ == 'contact_chantier_client':
         return Contact.get_contact('client_chantier',
                                    return_id=True,
                                    **kwlist.get('contact', {}))
     elif id_ == 'contact_facturation_client':
         return Contact.get_contact('client_administration',
                                    return_id=True,
                                    **kwlist.get('contact', {}))
     elif id_ == 'contact_chantier_interne':
         return zip(Employe.get_employes(**{'categorie': 'chantier'}),
                    Employe.get_employes(**{'categorie': 'chantier'}))
     else:
         return []
Ejemplo n.º 6
0
def build_table(table_key, reduced=True, load_jQuery=False, head_class="table-active"):

    if table_key == 'employe':
        df_table, d_footer, kwargs = Employe.table_loading(reduced=reduced)

    elif table_key == 'fournisseur':
        df_table, d_footer, kwargs = Fournisseur.table_loading(reduced=reduced)

    elif table_key == 'client':
        df_table, d_footer, kwargs = Client.table_loading(reduced=reduced)

    elif table_key == 'contact':
        df_table, d_footer, kwargs = Contact.table_loading(reduced=reduced)

    elif table_key == 'chantier':
        df_table, d_footer, kwargs = Chantier.table_loading(reduced=reduced)

    elif table_key == 'affaire':
        if reduced:
            df_table, d_footer, kwargs = Affaire.table_loading()
        else:
            df_table, d_footer, kwargs = FeuilleTravaux.table_loading()

    elif table_key == 'devis':
        df_table, d_footer, kwargs = Devis.table_loading(reduced=reduced)

    elif table_key == 'facture':
        df_table, d_footer, kwargs = Facture.table_loading(reduced=reduced)

    elif table_key == 'commande':
        df_table, d_footer, kwargs = Commande.table_loading(reduced=reduced)

    elif table_key == 'heure':
        df_table, d_footer, kwargs = Heure.table_loading(reduced=reduced)

    else:
        raise ValueError('key not understood {}'.format(table_key))

    table = html_table.Table(df_table.columns, 'overview-{}'.format(table_key), head_class=head_class,
                             load_jQuery=load_jQuery, **kwargs)

    html = table.render_table_from_pandas(df_table, d_footer=d_footer)

    return html
Ejemplo n.º 7
0
def build_form(table_key,
               request,
               deform_template_path,
               step=0,
               force_get=True,
               data={},
               validate=True,
               script=None,
               session=None):

    if 'index' in request.form.keys() and 'Ajouter' not in data.get(
            'action', ''):
        index = request.form['index']
    else:
        index = None

    if table_key == 'employe':
        d_form_data = Employe.form_loading(step, index, data)
        nb_step_form = Employe.nb_step_form

    elif table_key == 'fournisseur':
        d_form_data = Fournisseur.form_loading(step, index, data)
        nb_step_form = Fournisseur.nb_step_form

    elif table_key == 'client':
        d_form_data = Client.form_loading(step, index, data)
        nb_step_form = Client.nb_step_form

    elif table_key == 'contact':
        d_form_data = Contact.form_loading(step, index, data)
        nb_step_form = Contact.nb_step_form

    elif table_key == 'chantier':
        d_form_data = Chantier.form_loading(step, index, data)
        nb_step_form = Chantier.nb_step_form

    elif table_key == 'affaire':
        if index is None and 'secondaire' in data.get('action', ''):
            index = request.form['index']

        d_form_data = Affaire.form_loading(step, index, data)
        nb_step_form = Affaire.nb_step_form

    elif table_key == 'devis':
        d_form_data = Devis.form_loading(step, index, data)
        nb_step_form = Devis.nb_step_form

    elif table_key == 'facture':
        # Accountant Admin restriction on this form
        restricted = True
        if session is not None:
            if 'CADMIN' in session['rights'] or 'SADMIN' in session['rights']:
                restricted = False

        d_form_data = Facture.form_loading(step,
                                           index,
                                           data,
                                           restricted=restricted)
        nb_step_form = Facture.nb_step_form

    elif table_key == 'commande':
        d_form_data = Commande.form_loading(step, index, data)
        nb_step_form = Commande.nb_step_form

    elif table_key == 'heure':
        d_form_data = Heure.form_loading(step, index, data)
        nb_step_form = Heure.nb_step_form

    else:
        raise ValueError('key not understood {}'.format(table_key))

    web, data = mutlistep.MultipleStepForm(request, deform_template_path, step, nb_step_form, **d_form_data)\
        .process_form(force_get=force_get, validate=validate, d_format=d_form_data['formatting'], script=script)

    return web, data
Ejemplo n.º 8
0
def process_form(table_key, d_data, action):

    # Code to download document at the completion of some form (Devis, Affaire, ...)
    script = u'$.ajax({method: "POST", url: "/url_success_form", data: {"table_key": %s, "index": %s}})' \
             u'.done(function (response, status, request) {alert(%s %s);});'

    if table_key in ['affaire', 'devis', 'facture', 'commande'
                     ] and 'Suprimer' not in action:
        script = u'$.ajax({method: "POST", url: "/url_success_form", data: {"table_key": %s, "index": %s}})' \
                 u'.done(function (response, status, request) { alert(%s %s);' \
                 u'var url = response["url"].concat(response["data"]);' \
                 u'window.location = url});'

    if table_key == 'employe':
        l_index, l_fields = Employe.l_index, Employe.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Employe,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'fournisseur':
        l_index, l_fields = Fournisseur.l_index, Fournisseur.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Fournisseur,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'client':
        l_index, l_fields = Client.l_index, Client.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Client,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'contact':
        l_index, l_fields = Contact.l_index, Contact.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Contact,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'chantier':
        l_index, l_fields = Chantier.l_index, Chantier.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Chantier,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'affaire':
        l_index, l_fields = Affaire.l_index, Affaire.l_fields()
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Affaire,
                                      action,
                                      d_data=d_data,
                                      table_key=table_key)

    elif table_key == 'devis':
        l_index, l_fields = Devis.l_index, [f for f in Devis.l_fields()]
        d_data['price'] = 0
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Devis,
                                      action,
                                      d_data,
                                      table_key=table_key)

    elif table_key == 'commande':

        # Create tmp dir
        driver = FileDriver('tmp_upload', '')
        tmpdir = driver.TempDir(create=True, prefix='tmp_upload_')

        # Create s3 ressources
        ressource = boto3.resource(
            's3',
            aws_access_key_id=d_sconfig['aws_access_key_id'],
            aws_secret_access_key=d_sconfig['aws_secret_access_key'])

        filename = ''.join(
            ['{}',
             mimetypes.guess_extension(d_data['details']['mimetype'])])
        d_files = {
            filename: {
                'f': d_data['details']['fp'],
                'bucket':
                ressource.Bucket(d_sconfig.get('bucket_name', 'lstcmd')),
                'tmpfile': FileDriver('', '').join(tmpdir.path, filename)
            }
        }

        l_index, l_fields = Commande.l_index, [f for f in Commande.l_fields()]
        d_data['montant_ttc'], d_data['montant_tva'] = 0, 0
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Commande,
                                      action,
                                      d_data,
                                      table_key=table_key,
                                      d_files=d_files)

    elif table_key == 'facture':
        l_index, l_fields = Facture.l_index, [f for f in Facture.l_fields()]
        d_data['montant_ttc'], d_data['montant_tva'] = 0, 0
        statue = generic_process_form(l_index,
                                      l_fields,
                                      Facture,
                                      action,
                                      d_data,
                                      table_key=table_key)

    elif table_key == 'heure':
        l_index, l_fields, statue = Heure.l_index, Heure.l_fields(), {
            'success': True
        }

        # Load current database of hours
        df, l_hid = Heure.load_db(), []
        df = df.loc[df['semaine'] == d_data['index']]

        # Alter or add hours that have been sent
        for d_heure in d_data['heure']:
            d_data_ = {
                k: v
                for k, v in d_heure.items() +
                [('semaine', d_data['index']), ('index', d_data['index'])]
            }

            if d_heure['heure_id'] == l_index[0].sn.missing:
                statue = generic_process_form(l_index,
                                              l_fields,
                                              Heure,
                                              'Ajouter',
                                              d_data_,
                                              table_key=table_key)
            else:
                l_hid += [d_data_[l_index[0].name]]
                statue = generic_process_form(l_index,
                                              l_fields,
                                              Heure,
                                              'Modifier',
                                              d_data_,
                                              table_key=table_key)

        # Remove hours that have been deleted if any
        for hid in set(df.heure_id.values).difference(l_hid):
            d_data_ = {'index': d_data['index'], l_index[0].name: hid}
            statue = generic_process_form(l_index,
                                          l_fields,
                                          Heure,
                                          'Suprimer',
                                          d_data_,
                                          table_key=table_key)

        if 'success' in statue:
            statue.update({
                'data':
                (u'"{}"'.format(table_key), u'"{}"'.format(d_data['index']),
                 u'"{}: {}'.format(table_key, d_data['index']),
                 u' {} avec succes"'.format("edite"))
            })
    else:
        statue = {'error': u'Unknown table'}

    if 'success' not in statue:
        if statue['error'] == 'index':
            script = \
                u'alert("Erreur: l\'element {} existe dans la base. Modifier l\'element existant ou changer la valeur' \
                u' du champ {}");'.format(statue['index'], statue['index_name'])

        else:
            raise ValueError('{}'.format(statue))

    else:
        script = script % statue['data']
    return script
Ejemplo n.º 9
0
    def test_basic(self):
        """
        python -m unittest tests.models.employe.TestEmploye.test_basic

        """

        # Add employe
        test_employe = Employe(self.d_index, self.d_data, path=self.path)
        test_employe.add()

        # Assert new employe is in the database
        df = test_employe.load_db(test_employe.path)
        for k, v in self.d_index.items():
            df = df.loc[df[k] == v]
        self.assertTrue(not df.empty)

        # Make sure same employe can't added twice
        try:
            test_employe = Employe(self.d_index, self.d_data, path=self.path)
            test_employe.add()
            self.assertTrue(False)
        except ValueError:
            self.assertTrue(True)

        # test alter employe
        test_employe.num_tel = '0607070707'
        test_employe.alter()

        # Assert record has bee changed in the database
        df = test_employe.load_db(test_employe.path)
        for k, v in self.d_index.items():
            df = df.loc[df[k] == v]
        self.assertEqual(df.iloc[0]['num_tel'], '0607070707')

        # Assert deletion works
        test_employe.delete()
        df = test_employe.load_db(test_employe.path)
        for k, v in self.d_index.items():
            df = df.loc[df[k] == v]
        self.assertTrue(df.empty)