Esempio 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
Esempio n. 2
0
    def test_request(self):
        """
        python -m unittest tests.models.heure.TestHeure.test_request

        """
        l_heure = Heure.get_heure(path=self.path)
        self.assertEqual(len(l_heure), 1)
        self.assertEqual(l_heure[0], self.heure_id)

        # Test from index instance method
        test_heure = Heure.from_index_({'heure_id': self.heure_id},
                                       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_heure.__getattribute__(k), v)
Esempio n. 3
0
    def control_process(data):

        data['success'] = True
        if data['af1'] == '-' or data['af2'] == '-':
            return 'alert("Veuillez selectionner des affaires");'

        # Get affaire
        lmdb = lambda x: {
            'affaire_num': x.split('/')[0],
            'affaire_ind': x.split('/')[1]
        }
        l_af = [
            Affaire.from_index_(lmdb(data['af1'])),
            Affaire.from_index_(lmdb(data['af2']))
        ]
        l_dv = [
            Devis.from_index_({'devis_id': l_af[0].devis_id}),
            Devis.from_index_({'devis_id': l_af[1].devis_id})
        ]

        # Merge and Update devis
        try:
            dv_merged = Devis.merge(l_dv[0], l_dv[1])

        except AssertionError:
            data['success'] = False
            err_msg = 'Problem with price of resulting devis'
            return 'alert("{} Voir avec DSI");'.format(err_msg)

        # delete ref of sub affaire in commande, facture, heure tables
        try:
            Commande.merge_affaire(l_af), Facture.merge_affaire(
                l_af), Heure.merge_affaire(l_af)
            dv_merged.alter(), l_dv[1].delete(), l_af[-1].delete()
        except IndexError:
            err_msg = 'Critical problem with data integrity during merge of {af1} and {af2}'.format(
                af1='/'.join([l_af[0].affaire_num, l_af[0].affaire_ind]),
                af2='/'.join([l_af[1].affaire_num, l_af[1].affaire_ind]))
            return 'alert("{}. Voir avec DSI de toute urgence");'.format(
                err_msg)

        # Get script
        success_msg = \
            'alert("les affaires {af1} et {af2} ainsi que les devis {dv1} et {dv2} ont bien ete fusionner, ' \
            'respectivement sous les indices {af1} et {dv1}");'.format(
                af1='/'.join([l_af[0].affaire_num, l_af[0].affaire_ind]),
                af2='/'.join([l_af[1].affaire_num, l_af[1].affaire_ind]),
                dv1=l_af[0].devis_id, dv2=l_af[1].devis_id,
            )
        script = '$.ajax({method: "POST", url: "/url_success_form", data: {"table_key": "affaire", "index": "%s"}})' \
                 '.done(function (response, status, request) { %s ' \
                 'var url = response["url"].concat(response["data"]);' \
                 'window.location = url});'

        return script % ('/'.join([l_af[0].affaire_num, l_af[0].affaire_ind
                                   ]), success_msg)
Esempio n. 4
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
Esempio n. 5
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
Esempio n. 6
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
Esempio n. 7
0
    def load_view(return_cols=True):

        # Load affaire db
        df = Affaire.load_db()
        l_models_cols = []

        # Join devis information
        df_devis = Devis.load_db()
        df_devis = df_devis[[
            c for c in df_devis.columns
            if c not in ['creation_date', 'maj_date']
        ]]
        df_devis = df_devis.rename(columns={
            c: '{}_devis'.format(c)
            for c in df_devis.columns if c != 'devis_id'
        })
        df = df.merge(df_devis, on='devis_id', how='left')

        l_models_cols += [c for c in df_devis.columns if c != 'devis_id']

        # Load billing and Build affaire index
        df_facture = Facture.load_db()
        df_facture = FeuilleTravaux.split_main_indices(df_facture)

        # For each situation join amount factured
        for i in range(1, 13):
            df_facture_ = df_facture.loc[df_facture['situation'] == i]\
                .rename(columns={'montant_ht': 'montant_situation_{}'.format(i)})
            df = FeuilleTravaux.merge_to_main(
                df, df_facture_, ['montant_situation_{}'.format(i)])
            l_models_cols += ['montant_situation_{}'.format(i)]

        # Join command information
        df_commande = Commande.load_db()
        df_commande = FeuilleTravaux.split_main_indices(df_commande)

        df = FeuilleTravaux\
            .merge_to_main(
                df, df_commande.rename(columns={'montant_ht': 'montant_total_commande'}), ['montant_total_commande']
            )

        l_models_cols += ['montant_total_commande']

        # Load hours information
        df_heure = Heure.load_db()
        df_heure = FeuilleTravaux.split_main_indices(df_heure)

        # Heures non interimaires
        df_heure_ = df_heure.loc[df_heure['name'] != 'interim']\
            .rename(columns={'heure_prod': 'heure_prod_saisie', 'heure_autre': 'heure_autre_saisie'})
        df = FeuilleTravaux.merge_to_main(
            df, df_heure_, ['heure_prod_saisie', 'heure_autre_saisie'])

        # Heures interimaires
        df_heure_ = df_heure.loc[df_heure['name'] == 'interim']\
            .rename(columns={'heure_prod': 'heure_prod_saisie_interim', 'heure_autre': 'heure_autre_saisie_interim'})
        df = FeuilleTravaux.merge_to_main(
            df, df_heure_,
            ['heure_prod_saisie_interim', 'heure_autre_saisie_interim'])

        l_models_cols += [
            'heure_prod_saisie', 'heure_autre_saisie',
            'heure_prod_saisie_interim', 'heure_autre_saisie_interim'
        ]

        if return_cols:
            return df, l_models_cols

        return df
Esempio n. 8
0
    def test_basic(self):
        """
        python -m unittest tests.models.heure.TestHeure.test_basic

        """
        # Add Fournisseur
        test_heure = Heure(self.d_index, self.d_data, path=self.path)
        test_heure.add()

        # Assert new Fournisseur is in the database
        df = test_heure.load_db(test_heure.path)

        for k, v in {'heure_id': self.heure_id + 1}.items():
            df = df.loc[df[k] == v]
        self.assertTrue(not df.empty)

        # Make sure same Fournisseur can't added twice
        try:
            test_heure = Heure({'heure_id': self.heure_id + 1},
                               self.d_data,
                               path=self.path)
            test_heure.add()
            self.assertTrue(False)
        except ValueError:
            self.assertTrue(True)

        # test alter Fournisseur
        test_heure.nb_heure_ch = 30
        test_heure.alter()

        # Assert record has bee changed in the database
        df = test_heure.load_db(test_heure.path)

        for k, v in {'heure_id': self.heure_id + 1}.items():
            df = df.loc[df[k] == v]
        self.assertEqual(df.iloc[0]['nb_heure_ch'], 30)

        # Assert deletion works
        test_heure.delete()
        df = test_heure.load_db(test_heure.path)
        for k, v in {'heure_id': self.heure_id + 1}.items():
            df = df.loc[df[k] == v]

        self.assertTrue(df.empty)