Exemple #1
0
    def list(kw):

        if kw == 'fournisseur':
            return zip(Fournisseur.get_fournisseurs(),
                       Fournisseur.get_fournisseurs())
        elif kw == 'affaire':
            return zip(Affaire.get_affaire(), map(str, Affaire.get_affaire()))
        else:
            return []
    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)
    def form_document_loading():

        index_node = StringFields(title=u"Numéro d'affaire",
                                  name='index',
                                  l_choices=zip(Affaire.get_affaire(),
                                                Affaire.get_affaire()))
        document_node = StringFields(title=u'Nom document',
                                     name='document',
                                     l_choices=FeuilleTravaux.l_documents)

        return {'nodes': [document_node.sn, index_node.sn]}
Exemple #4
0
 def list(kw):
     if kw == 'affaire':
         return zip(Affaire.get_affaire(), map(str, Affaire.get_affaire()))
     elif kw == 'situation':
         return [(i, u'Situation numero {}'.format(i))
                 for i in range(1, 13)]
     elif kw == 'type':
         return [(u'facture', u'Facture'), (u'avoir', u'Avoir')]
     elif kw == 'tva':
         return [(0.2, u'20%'), (0.1, u'10%'), (0.055, u'5,5%'),
                 (0.021, u'2,1%')]
     else:
         return []
Exemple #5
0
    def test_request(self):
        """
        python -m unittest tests.models.affaire.TestAffaire.test_request

        """
        l_affaire = Affaire.get_affaire(path=self.path)

        self.assertEqual(len(l_affaire), 1)
        self.assertEqual(l_affaire[0], self.affaire_id)

        # Test from index instance method
        test_affaire = Affaire.from_index_({'affaire_id': self.affaire_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_affaire.__getattribute__(k), v)
Exemple #6
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 []
Exemple #7
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
Exemple #8
0
    def load_view():
        # Load affaire db
        df = Facture.load_db()
        df['affaire_num'] = df.affaire_id.apply(lambda x: x.split('/')[0])
        df['affaire_ind'] = df.affaire_id.apply(lambda x: x.split('/')[1])

        # Join devis information
        df_devis = Devis.load_db()
        df_devis = df_devis[[
            'devis_id', 'designation_client', 'object', 'price', 'date_start',
            'date_end', 'base_prix'
        ]]

        df_info = Affaire.load_db()
        df_info = df_info[['affaire_num', 'affaire_ind', 'devis_id', 'contact_facturation_client', 'responsable', 'fae']]\
            .merge(df_devis, on='devis_id', how='left')

        # Join info to billing table
        df = df.merge(df_info, on=['affaire_num', 'affaire_ind'], how='left')

        return df
Exemple #9
0
    def load_view():
        # Load affaire db
        df = Commande.load_db()
        df['affaire_num'] = df.affaire_id.apply(lambda x: x.split('/')[0])
        df['affaire_ind'] = df.affaire_id.apply(lambda x: x.split('/')[1])

        # Join devis information
        df_devis = Devis.load_db()
        df_devis = df_devis[[
            'devis_id', 'designation_client', 'object', 'date_start',
            'date_end', 'base_prix', 'montant_achat', 'coef_achat'
        ]]

        df_info = Affaire.load_db()
        df_info = df_info[[
            'affaire_num', 'affaire_ind', 'devis_id', 'responsable',
            'contact_chantier_interne', 'contact_chantier_client',
            'chantier_id'
        ]].merge(df_devis, on='devis_id', how='left')

        # Join info to command table
        df = df.merge(df_info, on=['affaire_num', 'affaire_ind'], how='left')

        return df
Exemple #10
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
Exemple #11
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
    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
    def control_loading():
        # May be have a view of case sold out, case running
        d_control_data = {}
        df, _ = FeuilleTravaux.load_view()

        # App 1 repartition categorie among employes
        df['montant_facture'] = df[[
            c for c in df.columns if 'montant_situation_' in c
        ]].sum(axis=1)
        df['state'] = df[['price_devis', 'montant_facture']]\
            .apply(
            lambda row: u'Cloturé' if abs(row['price_devis'] - row['montant_facture']) < max(5, 0.001 * row['price_devis'])
            else u'En cours', axis=1
        )

        df_ca = df[['price_devis', 'state']].groupby('state')\
            .sum()\
            .reset_index()\
            .rename(columns={'state': 'name', 'price_devis': 'value'})

        df_ca['hover'] = df['price_devis'].apply(
            lambda x: '{:,.2f} Euros'.format(float(int(x * 100) / 100)))

        d_control_data['repca'] = {
            'plot': {
                'k': 'pie',
                'd': df_ca,
                'o': {
                    'hover': True
                }
            },
            'rows': [('title', [{
                'content': 'title',
                'value': u"Chiffre d'affaire cloturé et en cours",
                'cls': 'text-center'
            }]), ('figure', [{
                'content': 'plot'
            }])],
            'rank':
            0
        }

        # App 2: form of merge of affaire
        l_affaires = [('-', '-')] + zip(Affaire.get_affaire(),
                                        Affaire.get_affaire())
        l_nodes = [
            StringFields(title="Affaire principal",
                         name='af1',
                         l_choices=l_affaires),
            StringFields(title="Affaire a fusionner",
                         name='af2',
                         l_choices=l_affaires)
        ]

        d_control_data['mergeca'] = {
            'form': {
                'nodes': [f.sn for f in l_nodes],
                'mapping': {
                    'af1': None,
                    'af2': None
                }
            },
            'rows': [('title', [{
                'content': 'title',
                'value': "Fusion des affaires",
                'cls': 'text-center'
            }]), ('form', [{
                'content': 'form'
            }])],
            'rank':
            1
        }

        return d_control_data
Exemple #14
0
    def test_basic(self):
        """
        python -m unittest tests.models.affaire.TestAffaire.test_basic

        """
        # Add Affaire
        test_affaire = Affaire(self.d_index, self.d_data, path=self.path)
        test_affaire.add()

        # Assert new Fournisseur is in the database
        df = test_affaire.load_db(test_affaire.path)
        for k, v in {'affaire_id': self.affaire_id + 1}.items():
            df = df.loc[df[k] == v]

        self.assertTrue(not df.empty)

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

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