Exemple #1
0
    def form_document_loading():

        index_node = StringFields(
            title=u'Numéro de devis', name='index', l_choices=zip(Devis.get_devis(), Devis.get_devis())
        )
        document_node = StringFields(
            title=u'Nom document', name='document', l_choices=Devis.l_documents
        )

        return {'nodes': [document_node.sn, index_node.sn]}
Exemple #2
0
    def form_document_loading():

        index_node = StringFields(title=u'Numéro de facture',
                                  name='index',
                                  l_choices=zip(Facture.get_facture(),
                                                Facture.get_facture()))
        document_node = StringFields(title=u'Nom document',
                                     name='document',
                                     l_choices=Facturation.l_documents)

        return {'nodes': [document_node.sn, index_node.sn]}
Exemple #3
0
    def form_document_loading():

        index_node = StringFields(title=u'Numero de facture',
                                  name='index',
                                  l_choices=zip(Commande.get_commande(),
                                                Commande.get_commande()))
        document_node = StringFields(title=u'Nom document',
                                     name='document',
                                     l_choices=Achat.l_documents)

        return {'nodes': [document_node.sn, index_node.sn]}
    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 #5
0
    def form_loading(step, index=None, data=None):

        if index is not None:
            d_index = {Client.l_index[0].name: index}
        else:
            d_index = None

        form_man = FormLoader(Client.l_index, Client.l_fields(widget=True))
        if step % Client.nb_step_form == 0:
            index_node = StringFields(
                title=u'Designation',
                name='index',
                missing=u'',
                l_choices=zip(Client.get_clients(), Client.get_clients()) +
                [(u'new', u'Nouveau')],
                desc=
                u"En cas de modification ou supression, choisir la raison sociale du client"
            )
            form_man.load_init_form(Client.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Client.from_index_(d_index).__dict__

            form_man.load(step % Client.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data
Exemple #6
0
    def form_loading(step, index=None, data=None, restricted=True):

        if index is not None:
            d_index = {
                Facture.l_index[0].name:
                Facture.l_index[0].processing_db['upload'](index)
            }
        else:
            d_index = None

        form_man = FormLoader(
            Facture.l_index,
            Facture.l_fields(widget=True, restricted=restricted))

        if step % Facture.nb_step_form == 0:
            index_node = StringFields(
                title=u'Numero de facture',
                name='index',
                missing=-1,
                l_choices=zip(Facture.get_facture(), Facture.get_facture()) +
                [(u'new', u'Nouveau')],
                desc=u"En cas de modification choisir un numero de facture")
            form_man.load_init_form(Facture.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Facture.from_index_(d_index).__dict__

            form_man.load(step % Facture.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data
Exemple #7
0
    def form_loading(step, index=None, data=None):

        if index is not None:
            d_index = {Fournisseur.l_index[0].name: index}
        else:
            d_index = None

        form_man = FormLoader(Fournisseur.l_index,
                              Fournisseur.l_fields(widget=True))

        if step % Fournisseur.nb_step_form == 0:
            index_node = StringFields(
                title=u'Raison sociale',
                name='index',
                missing=unicode(''),
                l_choices=zip(Fournisseur.get_fournisseurs(),
                              Fournisseur.get_fournisseurs()) +
                [(u'new', u'Nouveau')],
                desc=u"En cas de modification choisir un fournisseur")
            form_man.load_init_form(Fournisseur.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Fournisseur.from_index_(d_index).__dict__

            form_man.load(step % Fournisseur.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data
Exemple #8
0
    def form_loading(step, index=None, data=None):

        if index is not None:
            l_subindex = [
                Contact.l_fields()[i].name for i in Contact.l_subindex
            ]
            d_index = {k: v for k, v in zip(l_subindex, index.split(' / '))}
        else:
            d_index = None

        form_man = FormLoader(Contact.l_index,
                              Contact.l_fields(widget=True),
                              l_subindex=Contact.l_subindex,
                              use_subindex=True)

        if step % Contact.nb_step_form == 0:
            index_node = StringFields(
                title=u'Nom du contact',
                name='index',
                missing=unicode(''),
                l_choices=zip(Contact.get_contact(), Contact.get_contact()) +
                [('new', 'Nouveau')],
                desc=u"En cas de modification choisir un contact")
            form_man.load_init_form(Contact.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Contact.from_subindex_(d_index).__dict__
            form_man.load(step % Contact.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data
Exemple #9
0
    def form_loading(step, index=None, data=None):

        if index is not None:
            d_index = {Devis.l_index[0].name: Devis.l_index[0].processing_db['upload'](index)}
        else:
            d_index = None

        if step % Devis.nb_step_form == 2:
            # Compute price
            price = Devis.compute_price(
                {'hp': int(data.get('heure_prod', 0)), 'ha': int(data.get('heure_autre', 0)),
                 'php': float(data.get('prix_heure_prod', 0)), 'pha': float(data.get('prix_heure_autre', 0))},
                {'ca': float(data.get('coef_achat', 1)), 'ma': float(data.get('montant_achat', 0))}
            )
            data.update({'price': price})

        form_man = FormLoader(Devis.l_index, Devis.l_fields(widget=True))

        if step % Devis.nb_step_form == 0:
            index_node = StringFields(
                title=u'Numéro de devis', name='index', missing=-1,
                l_choices=zip(Devis.get_devis(), Devis.get_devis()) + [(u'new', u'Nouveau')],
                desc=u"En cas de modification choisir un numéro de devis"
            )
            form_man.load_init_form(Devis.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Devis.from_index_(d_index).__dict__

            form_man.load(step % Devis.nb_step_form, data_db=data_db, data_form=data)

        return form_man.d_form_data
Exemple #10
0
    def form_loading(step, index=None, data=None):

        d_index = {
            Heure.l_fields()[Heure.l_groupindex[0]].name:
            Heure.l_fields()[Heure.l_groupindex[0]].processing_db['upload'](
                index)
        }

        form_man = FormLoader([], [Heure.sequence_field()],
                              use_groupindex=True)

        if step % Heure.nb_step_form == 0:
            index_node = StringFields(title='Semaine',
                                      name='index',
                                      missing=-1,
                                      l_choices=zip(Heure.list('week'),
                                                    Heure.list('week')))
            form_man.load_init_form(Heure.action_field, index_node)

        else:
            l_names = [f.name for f in Heure.l_fields() + Heure.l_index]
            data_db = {
                Heure.sequence_field().name:
                [{k: v
                  for k, v in h.__dict__.items() if k in l_names}
                 for h in Heure.from_groupindex_(d_index)]
            }
            mapping_fields = ['heure']

            form_man.load(step % Heure.nb_step_form,
                          data_db=data_db,
                          data_form=data,
                          sequence_mapping_fields=mapping_fields)

        return form_man.d_form_data
Exemple #11
0
    def form_loading(step, index=None, data=None):

        if index is not None:
            l_index = [sch.name for sch in Employe.l_index]
            d_index = {k: v for k, v in zip(l_index, index.split('-'))}
        else:
            d_index = None

        form_man = FormLoader(Employe.l_index, Employe.l_fields(widget=True))

        if step % Employe.nb_step_form == 0:
            index_node = StringFields(
                title=u'Nom complet', name='index', missing=u'',
                l_choices=zip(Employe.get_employes(sep='-'), Employe.get_employes()) + [(u'new', u'Nouveau')],
                desc=u"En cas de modification choisir un employé"
            )
            form_man.load_init_form(Employe.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Employe.from_index_(d_index).__dict__
            form_man.load(step % Employe.nb_step_form, data_db=data_db, data_form=data)

        return form_man.d_form_data
Exemple #12
0
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', l_choices=Commande.list('affaire'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Fournisseur', name='raison_social', l_choices=Commande.list('fournisseur'),
                              table_reduce=True, rank=2, required=True),
                 MoneyFields(title=u'Montant Commande HT', name='montant_ht', required=True),
                 FileFields(title=u"Détails commande", name='details', required=True)]
        else:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Fournisseur', name='raison_social', table_reduce=True, rank=2, required=True),
                 MoneyFields(title=u'Montant Commande HT', name='montant_ht', required=True),
                 FileFields(title=u"Détails commande", name='details', required=True)]

        return l_fields
Exemple #13
0
    def l_fields(widget=False):
        l_fields = \
            [StringFields(title=u'Raison sociale', name='raison_social', table_reduce=True, rank=1, required=True),
             StringFields(title=u'Division', name='division', table_reduce=True, rank=2),
             StringFields(title=u'Adresse', name='adresse', rank=3, required=True),
             StringFields(title=u'CS/BP', name='cs_bp'),
             StringFields(title=u'Ville', name='ville', rank=4, required=True),
             StringFields(title=u'Code postal', name='code_postal', required=True),
             StringFields(title=u'tel', name='num_tel', table_reduce=True),
             StringFields(title=u'E-mail', name='mail', table_reduce=True)]

        return l_fields
Exemple #14
0
    def form_loading(step, index=None, data=None):
        if index is not None:
            l_index = [sch.name for sch in Affaire.l_index]
            d_index = {k: v for k, v in zip(l_index, index.split('/'))}
        else:
            d_index = None

        # Set filters for list choice
        filters = {}
        if step % Affaire.nb_step_form == 2:
            if data is not None and 'devis_id' in data.keys():
                rs = Devis.from_index_({
                    'devis_id': data['devis_id']
                }).__getattribute__('designation_client')
                filters.update({
                    'contact': {
                        'designation': rs
                    },
                    'chantier': {
                        'designation_client': rs
                    }
                })

        form_man = FormLoader(Affaire.l_index,
                              Affaire.l_fields(widget=True, **filters))

        if step % Affaire.nb_step_form == 0:
            index_node = StringFields(
                title=u"Numéro d'affaire",
                name='index',
                missing=-1,
                l_choices=zip(Affaire.get_affaire(sep='/'),
                              Affaire.get_affaire(sep='/')) +
                [('new', 'Nouveau')],
                desc=
                u"En cas de modification: choisir un numéro d'affaire et un numéro d'indice.\n"
                u"En cas d'affaire secondaire: choisir le numéro d'affaire (peu import l'indice)"
            )

            form_man.load_init_form(Affaire.action_field, index_node)

        else:
            if u'Ajouter une affaire secondaire' == data[
                    'action'] and 'affaire_num' not in data:
                data['affaire_num'] = d_index['affaire_num']

            data_db = None
            if d_index is not None:
                data_db = Affaire.from_index_(d_index).__dict__

            form_man.load(step % Affaire.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data
Exemple #15
0
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u'Désignation du client', name='designation_client', l_choices=Chantier.list('client'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Désignation du chantier', name='nom', table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Adresse', name='adresse', required=True),
                 StringFields(title=u'Ville', name='ville', required=True),
                 StringFields(title=u'Code postal', name='code_postal', required=True),
                 ]
        else:
            l_fields = \
                [StringFields(title=u'Désignation du client', name='designation_client', table_reduce=True, rank=1,
                              required=True),
                 StringFields(title=u'Désignation du chantier', name='nom', table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Adresse', name='adresse', required=True),
                 StringFields(title=u'Ville', name='ville', required=True),
                 StringFields(title=u'Code postal', name='code_postal', required=True),
                 ]

        return l_fields
Exemple #16
0
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u'Désignation client', name='designation_client', l_choices=Devis.list('client'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Contact client', name='contact_id', l_choices=Devis.list('contact'), required=True),
                 StringFields(title=u'Responsable devis', name='responsable', l_choices=Devis.list('responsable'),
                              table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Désignation devis', name='object', required=True),
                 IntegerFields(title=u"Heure autre", name='heure_autre', l_choices=zip(range(9000), range(9000))),
                 IntegerFields(title=u"Heure Production", name='heure_prod', l_choices=zip(range(1000), range(1000))),
                 MoneyFields(title=u"Prix heure autre", name='prix_heure_autre', required=True),
                 MoneyFields(title=u"Prix heure Production", name='prix_heure_prod', required=True),
                 MoneyFields(title=u'Montant achat', name='montant_achat', required=True),
                 FloatFields(title=u'Coefficient achat', name='coef_achat', required=True),
                 StringFields(title=u'Base de prix', name='base_prix', l_choices=Devis.list('base_prix'), required=True),
                 DateFields(title=u'Date de début', name='date_start', required=True),
                 DateFields(title=u'Date de fin', name='date_end', required=True),
                 MoneyFields(title=u'Prix', name='price', round=2, table_reduce=True, rank=3)]
        else:
            l_fields = \
                [StringFields(title=u'Désignation client', name='designation_client', table_reduce=True, rank=1),
                 StringFields(title=u'Contact client', name='contact_id'),
                 StringFields(title=u'Responsable devis', name='responsable', table_reduce=True, rank=2),
                 StringFields(title=u'Désignation devis', name='object'),
                 IntegerFields(title=u"Heure autre", name='heure_autre'),
                 IntegerFields(title=u"Heure Production", name='heure_prod'),
                 MoneyFields(title=u"Prix heure autre", name='prix_heure_autre'),
                 MoneyFields(title=u"Prix heure Production", name='prix_heure_prod'),
                 MoneyFields(title=u'Montant achat', name='montant_achat'),
                 FloatFields(title=u'Coefficient achat', name='coef_achat'),
                 StringFields(title=u'Base de prix', name='base_prix'),
                 DateFields(title=u'Date de début', name='date_start'),
                 DateFields(title=u'Date de fin', name='date_end'),
                 MoneyFields(title=u'Prix', name='price', round=2, table_reduce=True, rank=3)]

        return l_fields
Exemple #17
0
    def l_fields(widget=False):
        l_fields = \
            [StringFields(title=u'Adresse', name='adresse', required=True),
             StringFields(title=u'CS/BP', name='cs_bp'),
             StringFields(title=u'Ville', name='ville', ),
             StringFields(title=u'Code postal', name='code_postal'),
             StringFields(title=u'tel', name='num_tel', table_reduce=True, rank=2),
             StringFields(title=u'E-mail', name='mail', table_reduce=True, rank=3)]

        return l_fields
Exemple #18
0
    def l_fields(widget=False, restricted=True):
        if widget:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', l_choices=Facture.list('affaire'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Type', name='type', l_choices=Facture.list('type'), table_reduce=True,
                              required=True),
                 StringFields(title=u'Objet', name='objet'),
                 MoneyFields(title=u'Montant facture HT', name='montant_ht', required=True),
                 FloatFields(title=u'Taux TVA', name='taux_tva', l_choices=Facture.list('tva'), required=True),
                 MoneyFields(title=u'Montant TVA', name='montant_tva', widget=HiddenWidget()),
                 MoneyFields(title=u'Montant TTC', name='montant_ttc', widget=HiddenWidget(), table_reduce=True, rank=3),
                 IntegerFields(title=u'Numéro de situation', name='situation', l_choices=Facture.list('situation'),
                               required=True),
                 DateFields(title=u'Visa', name='date_visa', missing='1970-01-01'),
                 DateFields(title=u'Encaissement', name='date_payed', missing='1970-01-01')
                 ]

            if restricted:
                l_fields[-2] = DateFields(
                    title=u'Visa',
                    name='date_visa',
                    missing='1970-01-01',
                    widget=HiddenWidget(),
                    processing_form=lambda x: pd.Timestamp(x))
                l_fields[-1] = DateFields(
                    title=u'Encaissement',
                    name='date_payed',
                    missing='1970-01-01',
                    widget=HiddenWidget(),
                    processing_form=lambda x: pd.Timestamp(x))
        else:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Type', name='type', table_reduce=True, required=True),
                 StringFields(title=u'Objet', name='objet', required=True),
                 MoneyFields(title=u'Montant facture HT', name='montant_ht', required=True),
                 FloatFields(title=u'Taux TVA', name='taux_tva', required=True),
                 MoneyFields(title=u'Montant TVA', name='montant_tva'),
                 MoneyFields(title=u'Montant TTC', name='montant_ttc', table_reduce=True, rank=3),
                 IntegerFields(title=u'Numero de situation', name='situation', required=True),
                 DateFields(title=u'Visa', name='date_visa', required=True),
                 DateFields(title=u'Encaissement', name='date_payed', required=True)]

        return l_fields
Exemple #19
0
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u"Semaine", name='semaine', widget=HiddenWidget(), table_reduce=True,
                              rank=1),
                 StringFields(title=u"Numéro d'affaire", name='affaire_id', l_choices=Heure.list('affaire'),
                              table_reduce=True,  rank=2, required=True),
                 StringFields(title=u"Désignation", name='name', l_choices=Heure.list('employe'), table_reduce=True,
                              rank=3, desc=u"Choisir 'Intérimaires' pour ajouter le cumul des heures des intérimaires",
                              required=True),
                 IntegerFields(title=u"Cumul heure prod", name='heure_prod', l_choices=Heure.list('heures'),
                               missing=0, table_reduce=True, rank=4, required=True),
                 IntegerFields(title=u"Cumul heure autre", name='heure_autre', l_choices=Heure.list('heures'),
                               missing=0, table_reduce=True, rank=5, required=True)]
        else:
            l_fields = \
                [StringFields(title=u"Semaine", name='semaine', table_reduce=True, rank=1),
                 StringFields(title=u"Numéro d'affaire", name='affaire_id', table_reduce=True,  rank=2),
                 StringFields(title=u"Désignation", name='name', table_reduce=True, rank=3),
                 IntegerFields(title=u"Cumul heure prod", name='heure_prod', missing=0, table_reduce=True, rank=4),
                 IntegerFields(title=u"Cumul heure autre", name='heure_autre', missing=0, table_reduce=True, rank=5)]

        return l_fields
Exemple #20
0
class Affaire(BaseModel):

    table_name = 'affaire'
    l_index = [
        StringFields(title=u"Numero d'affaire",
                     name='affaire_num',
                     widget=HiddenWidget(),
                     table_reduce=True,
                     rank=0,
                     primary_key=True),
        StringFields(title=u"Indice de l'affaire",
                     name='affaire_ind',
                     widget=HiddenWidget(),
                     table_reduce=True,
                     rank=1,
                     primary_key=True)
    ]
    l_documents = [(u'ftravaux', u'Feuille de travaux')]
    l_actions = map(lambda x: (x.format(u'une affaire'), x.format(u'une affaire')), BaseModel.l_actions) + \
        [(u'Ajouter une affaire secondaire', u'Ajouter une affaire secondaire')]

    action_field = StringFields(title='Action',
                                name='action',
                                l_choices=l_actions,
                                round=0)
    nb_step_form = 3

    @staticmethod
    def l_fields(widget=False, **kwlist):
        if widget:
            l_fields = \
                [StringFields(title=u"Numéro de devis", name='devis_id', l_choices=Affaire.list('devis'),
                              table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Responsable affaire', name='responsable', l_choices=Affaire.list('responsable'),
                              table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Chantier', name='chantier_id', l_choices=Affaire.list('chantier', **kwlist),
                              round=2, required=True),
                 StringFields(title=u'Contact client - chantier', name='contact_chantier_client',
                              l_choices=Affaire.list('contact_chantier_client', **kwlist), round=2, required=True),
                 StringFields(title=u'Contact client - facturation', name='contact_facturation_client',
                              l_choices=Affaire.list('contact_facturation_client', **kwlist), round=2, required=True),
                 StringFields(title=u'Contact interne - chantier', name='contact_chantier_interne',
                              l_choices=Affaire.list('contact_chantier_interne', **kwlist), round=2, required=True),
                 MoneyFields(title=u'FAE', name='fae', missing=0.0, widget=HiddenWidget())]

        else:
            l_fields = \
                [StringFields(title=u"Numéro de devis", name='devis_id', table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Responsable Affaire', name='responsable', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Chantier', name='chantier_id', round=2, required=True),
                 StringFields(title=u'Contact client - chantier', name='contact_chantier_client', round=2, required=True),
                 StringFields(title=u'Contact client - facturation', name='contact_facturation_client', round=2,
                              required=True),
                 StringFields(title=u'Contact interne - chantier', name='contact_chantier_interne', round=2,
                              required=True),
                 MoneyFields(title=u'FAE', name='fae', missing=0.0, widget=HiddenWidget())]

        return l_fields

    @staticmethod
    def declarative_base():
        return BaseModel.declarative_base(
            clsname='Affaire',
            name=Affaire.table_name,
            dbcols=[f.dbcol() for f in Affaire.l_index + Affaire.l_fields()])

    @staticmethod
    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 []

    @staticmethod
    def from_index_(d_index):
        # Series
        s = BaseModel.from_index(Affaire.table_name, d_index)

        return Affaire(d_index,
                       s.loc[[f.name for f in Affaire.l_fields()]].to_dict())

    @staticmethod
    def load_db(**kwargs):

        # Get fields
        l_fields = Affaire.l_index + Affaire.l_fields() + Affaire.l_hfields

        # Load table
        df = BaseModel.load_db(table_name='affaire',
                               l_fields=l_fields,
                               columns=kwargs.get('columns', None))

        return df

    @staticmethod
    def get_affaire(sep='/'):

        # Get affaires
        df = Affaire.driver.select(Affaire.table_name,
                                   columns=['affaire_num', 'affaire_ind'])

        if df.empty:
            return []

        return df.apply(lambda r: '{}'.format(sep).join(
            [r['affaire_num'], r['affaire_ind']]),
                        axis=1).unique()

    def add(self):
        # Get list of affaire
        l_affaires = map(lambda x: x.split('/'), Affaire.get_affaire())

        # Save current contact id
        affaire_num_, affaire_ind_, code_year = self.affaire_num, self.affaire_ind, str(
            pd.Timestamp.now().year)[-2:]

        if self.affaire_num == u'' or self.affaire_num is None:
            if 'AF{}0000'.format(code_year) in [t[0] for t in l_affaires]:
                self.affaire_num = 'AF{}'.format(code_year) + '{0:0=4d}'.format(
                    max(
                        map(
                            lambda t: int(t[0].replace(
                                'AF{}'.format(code_year), '')), l_affaires)) +
                    1)

            else:
                self.affaire_num = 'AF{}0000'.format(code_year)

        if self.affaire_ind == '' or self.affaire_ind is None:
            l_affaires_sub = [
                t for t in l_affaires if t[0] == self.affaire_num
            ]
            if len(l_affaires_sub) > 0:
                self.affaire_ind = '{0:0=3d}'.format(
                    max([int(t[1]) for t in l_affaires_sub]) + 1)
            else:
                self.affaire_ind = '{0:0=3d}'.format(1)

        # Try to add and reset contact id if failed
        try:
            super(Affaire, self).add()

        except ValueError, e:
            self.affaire_num, self.affaire_ind = affaire_num_, affaire_ind_
            raise ValueError(e.message)

        return self
Exemple #21
0
class Contact(BaseModel):

    table_name = 'contact'
    l_index = [
        StringFields(title=u'ID',
                     name='contact_id',
                     widget=HiddenWidget(),
                     missing=-1,
                     table_reduce=True,
                     rank=0,
                     primary_key=True)
    ]
    l_subindex = [1, 2]
    l_actions = map(lambda x: (x.format('un contact'), x.format('un contact')),
                    BaseModel.l_actions)
    action_field = StringFields(title='Action',
                                name='action',
                                l_choices=l_actions,
                                round=0)
    nb_step_form = 2

    @staticmethod
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u'Type de contact', name='type', l_choices=Contact.list('type'), table_reduce=True,
                              rank=1, multiple=True, required=True),
                 StringFields(title=u'Désignation client / fournisseur', name='designation',
                              l_choices=Contact.list('client') + Contact.list('fournisseur'), table_reduce=True, rank=2,
                              required=True),
                 StringFields(title=u'Désignation du contact', name='contact', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Description du contact', name='desc', table_reduce=True, rank=4),
                 StringFields(title=u'Adresse', name='adresse'),
                 StringFields(title=u'CS/BP', name='cs_bp'),
                 StringFields(title=u'Ville', name='ville'),
                 StringFields(title=u'Code postal', name='code_postal'),
                 StringFields(title=u'tel', name='num_tel'),
                 StringFields(title=u'E-mail', name='mail')]
        else:
            l_fields = \
                [StringFields(title=u'Type de contact', name='type', table_reduce=True, rank=1, multiple=True,
                              required=True),
                 StringFields(title=u'Désignation client / fournisseur', name='designation', table_reduce=True, rank=2,
                              required=True),
                 StringFields(title=u'Désignation du contact', name='contact', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Description du contact', name='desc', table_reduce=True, rank=4),
                 StringFields(title=u'Adresse', name='adresse'),
                 StringFields(title=u'CS/BP', name='cs_bp'),
                 StringFields(title=u'Ville', name='ville'),
                 StringFields(title=u'Code postal', name='code_postal'),
                 StringFields(title=u'tel', name='num_tel'),
                 StringFields(title=u'E-mail', name='mail')]

        return l_fields

    @staticmethod
    def declarative_base():
        return BaseModel.declarative_base(
            clsname='Contact',
            name=Contact.table_name,
            dbcols=[f.dbcol() for f in Contact.l_index + Contact.l_fields()])

    @staticmethod
    def list(kw):
        if kw == 'client':
            return zip(Client.load_db()['designation'].unique(),
                       Client.load_db()['designation'].unique())

        elif kw == 'fournisseur':
            return zip(Fournisseur.get_fournisseurs(),
                       Fournisseur.get_fournisseurs())

        elif kw == 'type':
            return [(u'client_chantier', u'Contact chantier client'),
                    (u'client_administration',
                     u'Contact administratif client'),
                    (u'client_commande', u'Contact commande client'),
                    (u'fournisseur', u'fournisseur')]

        else:
            return []

    @staticmethod
    def from_index_(d_index):
        # Series
        s = BaseModel.from_index('contact', d_index)
        return Contact(d_index,
                       s.loc[[f.name for f in Contact.l_fields()]].to_dict())

    @staticmethod
    def from_subindex_(d_subindex):
        d_index = BaseModel.from_subindex('contact', d_subindex,
                                          [f.name for f in Contact.l_index])
        return Contact.from_index_(d_index)

    @staticmethod
    def load_db(**kwargs):

        l_fields = Contact.l_index + Contact.l_fields() + Contact.l_hfields

        # Load table
        df = BaseModel.load_db(table_name='contact',
                               l_fields=l_fields,
                               columns=kwargs.get('columns', None))

        return df

    @staticmethod
    def get_contact(type_='all', return_id=False, **kwargs):

        # Get contact of interest
        df = Contact.driver.select(Contact.table_name, **kwargs)

        if df.empty:
            return []

        if type_ != 'all':
            df = df.loc[df.type.apply(lambda x: type_ in x)]

        if df.empty:
            return []

        d_contacts = df.set_index('contact_id', drop=True)\
            .loc[:, ['designation', 'contact']]\
            .apply(lambda r: u'{} / {}'.format(*[r[c] for c in ['designation', 'contact']]), axis=1)\
            .to_dict()

        if return_id:
            l_contacts = d_contacts.items()
        else:
            l_contacts = d_contacts.values()

        return l_contacts

    def add(self):
        l_contacts = Contact.get_contact(return_id=True)

        # Save current contact id
        contact_id_ = self.contact_id

        if self.contact_id == '' or self.contact_id is None:
            self.contact_id = 'CT{0:0=4d}'.format(
                max(map(lambda t: int(t[0].replace('CT', '')), l_contacts)) +
                1)

        # Try to add and reset contact id if failed
        try:
            super(Contact, self).add()

        except ValueError, e:
            self.contact_id = contact_id_
            raise ValueError(e.message)

        return self
Exemple #22
0
class Devis(BaseModel):

    table_name = 'devis'

    l_index = [StringFields(title=u'Numéro de devis', name='devis_id', widget=HiddenWidget(), table_reduce=True,
                            rank=0, primary_key=True)]
    l_documents = [('devis', 'Devis')]
    l_actions = map(lambda x: (x.format(u'un devis'), x.format(u'un devis')), BaseModel.l_actions)
    action_field = StringFields(title=u'Action', name='action', l_choices=l_actions, round=0)
    nb_step_form = 3

    @staticmethod
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u'Désignation client', name='designation_client', l_choices=Devis.list('client'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Contact client', name='contact_id', l_choices=Devis.list('contact'), required=True),
                 StringFields(title=u'Responsable devis', name='responsable', l_choices=Devis.list('responsable'),
                              table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Désignation devis', name='object', required=True),
                 IntegerFields(title=u"Heure autre", name='heure_autre', l_choices=zip(range(9000), range(9000))),
                 IntegerFields(title=u"Heure Production", name='heure_prod', l_choices=zip(range(1000), range(1000))),
                 MoneyFields(title=u"Prix heure autre", name='prix_heure_autre', required=True),
                 MoneyFields(title=u"Prix heure Production", name='prix_heure_prod', required=True),
                 MoneyFields(title=u'Montant achat', name='montant_achat', required=True),
                 FloatFields(title=u'Coefficient achat', name='coef_achat', required=True),
                 StringFields(title=u'Base de prix', name='base_prix', l_choices=Devis.list('base_prix'), required=True),
                 DateFields(title=u'Date de début', name='date_start', required=True),
                 DateFields(title=u'Date de fin', name='date_end', required=True),
                 MoneyFields(title=u'Prix', name='price', round=2, table_reduce=True, rank=3)]
        else:
            l_fields = \
                [StringFields(title=u'Désignation client', name='designation_client', table_reduce=True, rank=1),
                 StringFields(title=u'Contact client', name='contact_id'),
                 StringFields(title=u'Responsable devis', name='responsable', table_reduce=True, rank=2),
                 StringFields(title=u'Désignation devis', name='object'),
                 IntegerFields(title=u"Heure autre", name='heure_autre'),
                 IntegerFields(title=u"Heure Production", name='heure_prod'),
                 MoneyFields(title=u"Prix heure autre", name='prix_heure_autre'),
                 MoneyFields(title=u"Prix heure Production", name='prix_heure_prod'),
                 MoneyFields(title=u'Montant achat', name='montant_achat'),
                 FloatFields(title=u'Coefficient achat', name='coef_achat'),
                 StringFields(title=u'Base de prix', name='base_prix'),
                 DateFields(title=u'Date de début', name='date_start'),
                 DateFields(title=u'Date de fin', name='date_end'),
                 MoneyFields(title=u'Prix', name='price', round=2, table_reduce=True, rank=3)]

        return l_fields

    @staticmethod
    def declarative_base():
        return BaseModel.declarative_base(
            clsname='Devis', name=Devis.table_name, dbcols=[f.dbcol() for f in Devis.l_index + Devis.l_fields()]
        )

    @staticmethod
    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 []

    @staticmethod
    def from_index_(d_index):
        # Series
        s = BaseModel.from_index(Devis.table_name, d_index)

        return Devis(d_index, s.loc[[f.name for f in Devis.l_fields()]].to_dict())

    @staticmethod
    def load_db(**kwargs):

        l_fields = Devis.l_index + Devis.l_fields() + Devis.l_hfields

        # Load table
        df = BaseModel.load_db(table_name='devis', l_fields=l_fields, columns=kwargs.get('columns', None))

        return df

    @staticmethod
    def get_devis():
        df_devis = Devis.load_db(columns=['devis_id'])

        if df_devis.empty:
            return []

        return df_devis['devis_id'].unique()

    def add(self):

        l_devis = Devis.get_devis()

        # Save current contact id
        devis_id_ = self.devis_id

        if self.devis_id == '' or self.devis_id is None:
            self.devis_id = 'DV{0:0=4d}'.format(max(map(lambda x: int(x.replace('DV', '')), l_devis)) + 1)

        self.price = Devis.compute_price(
            {'hp': self.__getattribute__('heure_prod'), 'ha': self.__getattribute__('heure_autre'),
             'php': self.__getattribute__('prix_heure_prod'), 'pha':self.__getattribute__('prix_heure_autre')},
            {'ca': self.__getattribute__('coef_achat'), 'ma': self.__getattribute__('montant_achat')}
        )

        # Try to add and reset contact id if failed
        try:
            super(Devis, self).add()

        except ValueError, e:
            self.devis_id = devis_id_
            raise ValueError(e.message)

        return self
Exemple #23
0
class User(object):

    d_base = {
        '__tablename__': 'users',
        'username': Column(String(250), primary_key=True),
        'password': Column(String(250)),
        'rights': Column(String(250))
    }

    d_fields = {
        'index': [StringFields(title='Username', name='username')],
        'fields': [
            StringFields(title='Password', name='password'),
            StringFields(title='Droits',
                         name='rights',
                         l_choices=[('SADMIN', 'SADMIN'), ('UADMIN', 'UADMIN'),
                                    ('CADMIN', 'CADMIN'),
                                    ('STANDARD', 'STANDARD')],
                         multiple=True)
        ]
    }

    driver = RdbmsDriver(facile_base, d_sconfig['mysql_uri'], 'UserDB driver')

    def __init__(self, username, password, rights=None):
        self.username = username
        self.password = password
        self.rights = rights

    @staticmethod
    def declarative_base():

        if 'users' in facile_base.metadata.tables.keys():
            base_ = type('User', (object, ), User.d_base)
            base_.metatadata = facile_base.metadata

        else:
            base_ = type('User', (facile_base, ), User.d_base)

        return base_

    @staticmethod
    def from_username(username):

        # Get entry with correct username
        df = User.driver.select('users', **{'username': username})

        s = df.iloc[0]
        if not s.empty:
            return User(df.loc[0, 'username'], df.loc[0, 'password'],
                        df.loc[0, 'rights'])
        else:
            raise ValueError('username {} does not exists'.format(username))

    @staticmethod
    def from_login(username, password):

        # Get entry with correct username
        df = User.driver.select('users', **{'username': username})

        # Check password is ok !
        if not df.empty:
            if str(password) == str(df.loc[0, 'password']):
                return User.from_username(username)

            else:
                raise ValueError('password is not correct')
        else:
            raise ValueError('username {} does not exists'.format(username))

    def add(self):
        # Add User
        df_ = pd.DataFrame([[self.username, self.password, self.rights]],
                           columns=['username', 'password', 'rights'])
        self.driver.insert(df_, 'users')

    def alter(self):
        # Update user
        d_value = {
            k: self.__getattribute__(k)
            for k in ['username', 'password', 'rights']
        }
        self.driver.update_row(d_value, 'users')

    def delete(self):
        # Delete user
        d_value = {
            k: self.__getattribute__(k)
            for k in ['username', 'password', 'rights']
        }
        self.driver.delete_row(d_value, 'users')

    @staticmethod
    def control_loading(rights):

        d_control_data = {}
        df = User.driver.read_table('users')

        if rights != 'SADMIN':
            df.loc[df.rights == 'SADMIN', 'password'] = '******'

        # App 1 Table of user
        table_man = TableLoader(User.d_fields['index'],
                                User.d_fields['fields'])
        df_, d_footer, kwargs = table_man.load_full_table(df, sort=False)

        d_control_data['tableuser'] = {
            'table': {
                'df': df_.copy(),
                'd_footer': d_footer,
                'kwargs': kwargs,
                'key': 'nothing'
            },
            'rows': [('title', [{
                'content': 'title',
                'value': 'Utilisateur de la base',
                'cls': 'text-center'
            }]), ('Table', [{
                'content': 'table'
            }])],
            'rank':
            0
        }

        # App 2: form action on user
        action = StringFields(title="Action",
                              name='action',
                              l_choices=[('Ajouter', 'Ajouter'),
                                         ('Suprimer', 'Suprimer'),
                                         ('Modifier', 'modifier')])
        l_nodes = [action.sn] + [f.sn for f in User.d_fields['index']
                                 ] + [f.sn for f in User.d_fields['fields']]
        mapping = {
            'action': None,
            'username': None,
            'password': None,
            'rights': []
        }

        d_control_data['setusers'] = {
            'form': {
                'nodes': l_nodes,
                'mapping': mapping
            },
            'rows': [('title', [{
                'content': 'title',
                'value': "Modification des utilisateurs",
                'cls': 'text-center'
            }]), ('form', [{
                'content': 'form'
            }])],
            'rank':
            1
        }

        return d_control_data

    @staticmethod
    def control_process(form_data, session):

        form_data['success'] = True

        if session['rights'] != 'SADMIN' and 'SADMIN' in form_data['rights']:
            script = 'alert("Problem ! {}");'.format(
                "Vous ne pouvez pas faire d'action pour un super utilisateur")

            return script

        if form_data['action'] == 'Ajouter':
            user = User(form_data['username'], form_data['password'],
                        form_data['password'])
            try:
                user.add()
            except IndexError:
                form_data[
                    'err_msg'] = "l'utilisateur {} existe deja en base".format(
                        form_data['username'])
                form_data['success'] = False

        elif form_data['action'] == 'Modifier':
            user = User(form_data['username'], form_data['password'],
                        form_data['password'])
            try:
                user.alter()
            except IndexError:
                form_data[
                    'err_msg'] = "l'utilisateur {} n'existe pas en base".format(
                        form_data['username'])
                form_data['success'] = False

        else:
            user = User(form_data['username'], form_data['password'],
                        form_data['password'])
            try:
                user.delete()
            except IndexError:
                form_data[
                    'err_msg'] = "l'utilisateur {} n'existe pas en base".format(
                        form_data['username'])
                form_data['success'] = False

        # Get script
        if form_data['success']:
            script = 'alert(%s %s);' % \
                     ('"User: {}'.format(form_data['username']), ' {} avec succes"'.format(form_data['action']))

        else:
            script = 'alert("Problem ! {}");'.format(
                form_data.get(
                    'err_msg',
                    "Presenter vous au responsable des systemes d'information")
            )

        return script
    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 #25
0
    def l_fields(widget=False):
        if widget:
            l_fields = \
                [StringFields(title=u'Type de contact', name='type', l_choices=Contact.list('type'), table_reduce=True,
                              rank=1, multiple=True, required=True),
                 StringFields(title=u'Désignation client / fournisseur', name='designation',
                              l_choices=Contact.list('client') + Contact.list('fournisseur'), table_reduce=True, rank=2,
                              required=True),
                 StringFields(title=u'Désignation du contact', name='contact', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Description du contact', name='desc', table_reduce=True, rank=4),
                 StringFields(title=u'Adresse', name='adresse'),
                 StringFields(title=u'CS/BP', name='cs_bp'),
                 StringFields(title=u'Ville', name='ville'),
                 StringFields(title=u'Code postal', name='code_postal'),
                 StringFields(title=u'tel', name='num_tel'),
                 StringFields(title=u'E-mail', name='mail')]
        else:
            l_fields = \
                [StringFields(title=u'Type de contact', name='type', table_reduce=True, rank=1, multiple=True,
                              required=True),
                 StringFields(title=u'Désignation client / fournisseur', name='designation', table_reduce=True, rank=2,
                              required=True),
                 StringFields(title=u'Désignation du contact', name='contact', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Description du contact', name='desc', table_reduce=True, rank=4),
                 StringFields(title=u'Adresse', name='adresse'),
                 StringFields(title=u'CS/BP', name='cs_bp'),
                 StringFields(title=u'Ville', name='ville'),
                 StringFields(title=u'Code postal', name='code_postal'),
                 StringFields(title=u'tel', name='num_tel'),
                 StringFields(title=u'E-mail', name='mail')]

        return l_fields
Exemple #26
0
class Fournisseur(BaseModel):

    table_name = 'fournisseur'

    l_index = [
        StringFields(title=u'Raison sociale',
                     name='raison_social',
                     table_reduce=True,
                     rank=0,
                     required=True,
                     primary_key=True)
    ]
    l_actions = map(
        lambda x: (x.format(u'un fournisseur'), x.format(u'un fournisseur')),
        BaseModel.l_actions)
    action_field = StringFields(title='Action',
                                name='action',
                                l_choices=l_actions,
                                round=0)
    nb_step_form = 2

    @staticmethod
    def l_fields(widget=False):
        l_fields = \
            [StringFields(title=u'Adresse', name='adresse', required=True),
             StringFields(title=u'CS/BP', name='cs_bp'),
             StringFields(title=u'Ville', name='ville', ),
             StringFields(title=u'Code postal', name='code_postal'),
             StringFields(title=u'tel', name='num_tel', table_reduce=True, rank=2),
             StringFields(title=u'E-mail', name='mail', table_reduce=True, rank=3)]

        return l_fields

    @staticmethod
    def declarative_base():
        return BaseModel.declarative_base(clsname='Fournisseur',
                                          name=Fournisseur.table_name,
                                          dbcols=[
                                              f.dbcol()
                                              for f in Fournisseur.l_index +
                                              Fournisseur.l_fields()
                                          ])

    @staticmethod
    def from_index_(d_index):
        # Series
        s = BaseModel.from_index('fournisseur', d_index)

        return Fournisseur(
            d_index, s.loc[[f.name for f in Fournisseur.l_fields()]].to_dict())

    @staticmethod
    def load_db(**kwargs):

        l_fields = Fournisseur.l_index + Fournisseur.l_fields(
        ) + Fournisseur.l_hfields

        # Load table
        df = BaseModel.load_db(table_name='fournisseur',
                               l_fields=l_fields,
                               columns=kwargs.get('columns', None))

        return df

    @staticmethod
    def get_fournisseurs():
        df_fournisseur = Fournisseur.load_db(columns=['raison_social'])

        if df_fournisseur.empty:
            return []

        return df_fournisseur['raison_social'].unique()

    @staticmethod
    def form_loading(step, index=None, data=None):

        if index is not None:
            d_index = {Fournisseur.l_index[0].name: index}
        else:
            d_index = None

        form_man = FormLoader(Fournisseur.l_index,
                              Fournisseur.l_fields(widget=True))

        if step % Fournisseur.nb_step_form == 0:
            index_node = StringFields(
                title=u'Raison sociale',
                name='index',
                missing=unicode(''),
                l_choices=zip(Fournisseur.get_fournisseurs(),
                              Fournisseur.get_fournisseurs()) +
                [(u'new', u'Nouveau')],
                desc=u"En cas de modification choisir un fournisseur")
            form_man.load_init_form(Fournisseur.action_field, index_node)

        else:
            data_db = None
            if d_index is not None:
                data_db = Fournisseur.from_index_(d_index).__dict__

            form_man.load(step % Fournisseur.nb_step_form,
                          data_db=data_db,
                          data_form=data)

        return form_man.d_form_data

    @staticmethod
    def table_loading(reduced=True, type='html', full_path=None):
        # Load database
        df = Fournisseur.load_db()

        # Instantiate table manager
        table_man = TableLoader(Fournisseur.l_index,
                                Fournisseur.l_fields(),
                                limit=10,
                                type=type)

        if type == 'excel':
            # Get processed table
            df = table_man.load_full_table(df)

            # Save excel file
            writer = pd.ExcelWriter(full_path, engine='xlsxwriter')
            df.to_excel(writer, sheet_name='Feuille1', index=False)
            writer.save()

            return

        if reduced:
            df, kwargs = table_man.load_reduce_table(df)
            d_footer = None

        else:
            table_man = TableLoader(Fournisseur.l_index,
                                    Fournisseur.l_fields())
            df, d_footer, kwargs = table_man.load_full_table(df)

        return df, d_footer, kwargs
Exemple #27
0
class Facture(BaseModel):

    table_name = 'facture'
    l_index = [
        StringFields(title=u'Numéro de Facture',
                     name='facture_id',
                     widget=HiddenWidget(),
                     table_reduce=True,
                     rank=0,
                     primary_key=True)
    ]
    l_actions = map(
        lambda x: (x.format(u'une facture'), x.format(u'une facture')),
        BaseModel.l_actions)
    action_field = StringFields(title=u'Action',
                                name='action',
                                l_choices=l_actions,
                                round=0)
    nb_step_form = 2

    @staticmethod
    def l_fields(widget=False, restricted=True):
        if widget:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', l_choices=Facture.list('affaire'),
                              table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Type', name='type', l_choices=Facture.list('type'), table_reduce=True,
                              required=True),
                 StringFields(title=u'Objet', name='objet'),
                 MoneyFields(title=u'Montant facture HT', name='montant_ht', required=True),
                 FloatFields(title=u'Taux TVA', name='taux_tva', l_choices=Facture.list('tva'), required=True),
                 MoneyFields(title=u'Montant TVA', name='montant_tva', widget=HiddenWidget()),
                 MoneyFields(title=u'Montant TTC', name='montant_ttc', widget=HiddenWidget(), table_reduce=True, rank=3),
                 IntegerFields(title=u'Numéro de situation', name='situation', l_choices=Facture.list('situation'),
                               required=True),
                 DateFields(title=u'Visa', name='date_visa', missing='1970-01-01'),
                 DateFields(title=u'Encaissement', name='date_payed', missing='1970-01-01')
                 ]

            if restricted:
                l_fields[-2] = DateFields(
                    title=u'Visa',
                    name='date_visa',
                    missing='1970-01-01',
                    widget=HiddenWidget(),
                    processing_form=lambda x: pd.Timestamp(x))
                l_fields[-1] = DateFields(
                    title=u'Encaissement',
                    name='date_payed',
                    missing='1970-01-01',
                    widget=HiddenWidget(),
                    processing_form=lambda x: pd.Timestamp(x))
        else:
            l_fields = \
                [StringFields(title=u"Numéro d'affaire", name='affaire_id', table_reduce=True, rank=1, required=True),
                 StringFields(title=u'Type', name='type', table_reduce=True, required=True),
                 StringFields(title=u'Objet', name='objet', required=True),
                 MoneyFields(title=u'Montant facture HT', name='montant_ht', required=True),
                 FloatFields(title=u'Taux TVA', name='taux_tva', required=True),
                 MoneyFields(title=u'Montant TVA', name='montant_tva'),
                 MoneyFields(title=u'Montant TTC', name='montant_ttc', table_reduce=True, rank=3),
                 IntegerFields(title=u'Numero de situation', name='situation', required=True),
                 DateFields(title=u'Visa', name='date_visa', required=True),
                 DateFields(title=u'Encaissement', name='date_payed', required=True)]

        return l_fields

    @staticmethod
    def declarative_base():
        return BaseModel.declarative_base(
            clsname='Facture',
            name=Facture.table_name,
            dbcols=[f.dbcol() for f in Facture.l_index + Facture.l_fields()])

    @staticmethod
    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 []

    @staticmethod
    def from_index_(d_index):
        # Series
        s = BaseModel.from_index('facture', d_index)

        return Facture(d_index,
                       s.loc[[f.name for f in Facture.l_fields()]].to_dict())

    @staticmethod
    def load_db(**kwargs):
        l_fields = Facture.l_index + Facture.l_fields() + Facture.l_hfields

        # Load table
        df = BaseModel.load_db(table_name='facture',
                               l_fields=l_fields,
                               columns=kwargs.get('columns', None))

        return df

    @staticmethod
    def get_facture():
        df_facture = Facture.load_db(columns=['facture_id'])

        if df_facture.empty:
            return []

        return df_facture['facture_id'].unique()

    @staticmethod
    def merge_affaire(l_af):

        # Get main and sub affaire
        main = '/'.join([l_af[0].affaire_num, l_af[0].affaire_ind])
        sub = '/'.join([l_af[-1].affaire_num, l_af[-1].affaire_ind])

        # Load commande and update affaire id
        df = Facture.driver.select(Facture.table_name, **{"affaire_id": sub})
        df['affaire_id'] = main

        # Save changes
        Facture.driver.update_rows(df, Facture.table_name)

    def add(self):
        l_factures = list(
            Facture.load_db(columns=['facture_id', 'type']).values)

        # Save current facture id
        facture_id_ = self.facture_id

        if self.facture_id == '' or self.facture_id is None:
            import IPython
            IPython.embed()
            if self.type == 'facture':
                l_factures_sub = [
                    t[0] for t in l_factures if t[1] == 'facture'
                ]
                self.facture_id = 'FC{0:0=4d}'.format(
                    max(map(lambda x: int(x.replace('FC', '')),
                            l_factures_sub)) + 1)

            else:
                l_factures_sub = [
                    t[0] for t in l_factures if t[1] == 'facture'
                ]
                self.facture_id = 'AV{0:0=4d}'.format(
                    max(map(lambda x: int(x.replace('AV', '')),
                            l_factures_sub)) + 1)

                if self.montant_ht > 0:
                    self.montant_ht *= -1

        # Get taxes additionnal informations
        self.montant_ttc, self.montant_tva = Facture.get_montant(
            self.__getattribute__('montant_ht'),
            self.__getattribute__('taux_tva'))

        # Try to add and reset conatct id if failed
        try:
            super(Facture, self).add()

        except ValueError, e:
            self.facture_id = facture_id_
            raise ValueError(e.message)

        return self
Exemple #28
0
    def control_loading(rights):

        d_control_data = {}
        df = User.driver.read_table('users')

        if rights != 'SADMIN':
            df.loc[df.rights == 'SADMIN', 'password'] = '******'

        # App 1 Table of user
        table_man = TableLoader(User.d_fields['index'],
                                User.d_fields['fields'])
        df_, d_footer, kwargs = table_man.load_full_table(df, sort=False)

        d_control_data['tableuser'] = {
            'table': {
                'df': df_.copy(),
                'd_footer': d_footer,
                'kwargs': kwargs,
                'key': 'nothing'
            },
            'rows': [('title', [{
                'content': 'title',
                'value': 'Utilisateur de la base',
                'cls': 'text-center'
            }]), ('Table', [{
                'content': 'table'
            }])],
            'rank':
            0
        }

        # App 2: form action on user
        action = StringFields(title="Action",
                              name='action',
                              l_choices=[('Ajouter', 'Ajouter'),
                                         ('Suprimer', 'Suprimer'),
                                         ('Modifier', 'modifier')])
        l_nodes = [action.sn] + [f.sn for f in User.d_fields['index']
                                 ] + [f.sn for f in User.d_fields['fields']]
        mapping = {
            'action': None,
            'username': None,
            'password': None,
            'rights': []
        }

        d_control_data['setusers'] = {
            'form': {
                'nodes': l_nodes,
                'mapping': mapping
            },
            'rows': [('title', [{
                'content': 'title',
                'value': "Modification des utilisateurs",
                'cls': 'text-center'
            }]), ('form', [{
                'content': 'form'
            }])],
            'rank':
            1
        }

        return d_control_data
Exemple #29
0
    def l_fields(widget=False, **kwlist):
        if widget:
            l_fields = \
                [StringFields(title=u"Numéro de devis", name='devis_id', l_choices=Affaire.list('devis'),
                              table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Responsable affaire', name='responsable', l_choices=Affaire.list('responsable'),
                              table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Chantier', name='chantier_id', l_choices=Affaire.list('chantier', **kwlist),
                              round=2, required=True),
                 StringFields(title=u'Contact client - chantier', name='contact_chantier_client',
                              l_choices=Affaire.list('contact_chantier_client', **kwlist), round=2, required=True),
                 StringFields(title=u'Contact client - facturation', name='contact_facturation_client',
                              l_choices=Affaire.list('contact_facturation_client', **kwlist), round=2, required=True),
                 StringFields(title=u'Contact interne - chantier', name='contact_chantier_interne',
                              l_choices=Affaire.list('contact_chantier_interne', **kwlist), round=2, required=True),
                 MoneyFields(title=u'FAE', name='fae', missing=0.0, widget=HiddenWidget())]

        else:
            l_fields = \
                [StringFields(title=u"Numéro de devis", name='devis_id', table_reduce=True, rank=2, required=True),
                 StringFields(title=u'Responsable Affaire', name='responsable', table_reduce=True, rank=3, required=True),
                 StringFields(title=u'Chantier', name='chantier_id', round=2, required=True),
                 StringFields(title=u'Contact client - chantier', name='contact_chantier_client', round=2, required=True),
                 StringFields(title=u'Contact client - facturation', name='contact_facturation_client', round=2,
                              required=True),
                 StringFields(title=u'Contact interne - chantier', name='contact_chantier_interne', round=2,
                              required=True),
                 MoneyFields(title=u'FAE', name='fae', missing=0.0, widget=HiddenWidget())]

        return l_fields
Exemple #30
0
class BaseModel(object):
    table_name = ''
    l_index, l_subindex = [], []
    l_hfields = [
        StringFields(name='creation_date', title='creation_date', round=0),
        StringFields(name='maj_date', title='maj_date', round=0)
    ]
    l_actions = [u'Ajouter {}', u'Modifier {}', u'Suprimer {}']
    l_documents = []
    l_apps = []
    driver = RdbmsDriver(facile_base, d_sconfig['mysql_uri'],
                         'BaseModel driver')

    def __init__(self, d_index, d_fields, d_hfields={}, table_name=None):
        for f in self.l_index:
            self.__setattr__(f.name, d_index[f.name])

        for f in self.l_fields():
            self.__setattr__(f.name, d_fields[f.name])

        for f in self.l_hfields:
            self.__setattr__(f.name, d_hfields.get(f.name, None))

        if table_name is not None:
            self.table_name = table_name

    @staticmethod
    def l_fields():
        raise NotImplementedError

    @staticmethod
    def declarative_base(**kwargs):
        if kwargs['name'] in facile_base.metadata.tables.keys():
            base_ = type(
                kwargs['clsname'], (object, ),
                dict([('__tablename__', kwargs['name'])] + kwargs['dbcols'] +
                     [f.dbcol() for f in BaseModel.l_hfields]))
            base_.metadata = facile_base.metadata

        else:
            base_ = type(
                kwargs['clsname'], (kwargs.get('base', facile_base), ),
                dict([('__tablename__', kwargs['name'])] + kwargs['dbcols'] +
                     [f.dbcol() for f in BaseModel.l_hfields]))

        return base_

    @staticmethod
    def list(kw):
        raise NotImplementedError

    @staticmethod
    def from_index(table_name, d_index):

        # Select element of interest
        df = BaseModel.driver.select(table_name, **d_index)

        if not df.empty:
            return df.loc[df.index[0]]
        else:
            raise IndexError('index: {} does not exist'.format(d_index))

    @staticmethod
    def from_subindex(table_name, d_subindex, l_index_names):

        # Select element of interest
        df = BaseModel.driver.select(table_name, **d_subindex)

        if not df.empty:
            return {name: df.loc[df.index[0], name] for name in l_index_names}
        else:
            raise IndexError('sub index: {} does not exist'.format(d_subindex))

    @staticmethod
    def from_groupindex(table_name, d_groupindex, l_index_names):

        # Select group of interest
        df = BaseModel.driver.select(table_name, **d_groupindex)

        if not df.empty:
            return [{name: r[name]
                     for name in l_index_names} for _, r in df.iterrows()]
        else:
            return []

    @staticmethod
    def load_db(**kwargs):

        table_name, l_fields, columns = kwargs['table_name'], kwargs[
            'l_fields'], kwargs['columns']
        df = BaseModel.driver.read_table(table_name, columns=columns)

        if columns is None:
            columns = df.columns

        # Load db as df
        df = df.fillna({
            f.name: f.__dict__.get('missing', '')
            for f in l_fields if f.name in columns
        })

        df = df.transform({
            f.name: f.processing_db['download']
            for f in l_fields
            if f.name in columns and f.processing_db is not None
        })

        return df[columns]

    def add(self):
        # Update creation and maj timestamp
        self.creation_date = str(pd.Timestamp.now())
        self.maj_date = str(pd.Timestamp.now())

        # Add record and save dataframe as csv
        data = [
            self.__getattribute__(f.name)
            for f in self.l_index + self.l_fields() + self.l_hfields
        ]
        df_ = pd.DataFrame(
            [data],
            columns=[
                f.name for f in self.l_index + self.l_fields() + self.l_hfields
            ])

        # Insert value
        try:
            self.driver.insert(df_, self.table_name)
        except IndexError:
            raise IndexError('Primary key already exists')

        return self

    def alter(self):
        # Update maj timestamp
        self.maj_date = str(pd.Timestamp.now())

        # Get new values
        l_fields = self.l_index + self.l_fields() + self.l_hfields
        d_value = {f.name: self.__getattribute__(f.name) for f in l_fields}
        d_value.pop('creation_date')
        # Update value
        self.driver.update_row(d_value, self.table_name)

        return self

    def delete(self):

        # Get new values
        l_fields = self.l_index + self.l_fields() + self.l_hfields
        d_value = {f.name: self.__getattribute__(f.name) for f in l_fields}

        # Update value
        self.driver.delete_row(d_value, self.table_name)

        return self

    @staticmethod
    def control_loading():
        d_control_data = {
            'noapp': {
                'rows': [('title', [{
                    'content': 'title',
                    'value': 'Aucun controle disponible',
                    'cls': 'text-center'
                }])],
                'rank':
                0
            }
        }

        return d_control_data