Example #1
0
    def titre_annexe(client, edition, generaux, reference, titre, annexe):
        """
        création d'un titre d'annexe
        :param client: données du client concerné
        :param edition: paramètres d'édition
        :param generaux: paramètres généraux
        :param reference: référence de la facture
        :param titre: titre de l'annexe
        :param annexe: nom de l'annexe
        :return: page de titre latex de l'annexe
        """
        dic_titre = {'code_sap': Latex.echappe_caracteres(client['code_sap']), 'ref': reference, 'titre': titre,
                     'nom': Latex.echappe_caracteres(client['abrev_labo']), 'annexe': annexe,
                     'date': edition.mois_txt + " " + str(edition.annee),
                     'centre': Latex.echappe_caracteres(generaux.centre)}

        contenu = r'''
            \thispagestyle{empty}
            \begin{adjustwidth}{0cm}{}
            %(centre)s \hspace*{\fill} \thepage \\
            %(ref)s \\
            \hspace*{\fill} %(nom)s \\
            \hspace*{\fill} %(code_sap)s \\
            \end{adjustwidth}
            \begin{center}
            \Large\textsc{%(annexe)s %(date)s} \\
            \Large\textsc{%(titre)s}
            \end{center}
            \rule{\linewidth}{1pt}
             \vspace*{5mm}
            ''' % dic_titre

        return contenu
Example #2
0
    def table_points_xbmu(code_client, scl, sommes_acces, machines, users):
        """
        Points XB/M/U - Table Client Récap Bonus/MAchine/User
        :param code_client: code du client concerné
        :param scl: sommes client calculées
        :param sommes_acces: sommes des accès importés
        :param machines: machines importées
        :param users: users importés
        :return: table au format latex
        """
        if scl['somme_t_mb'] > 0:
            structure = r'''{|l|c|r|r|}'''
            legende = r'''Récapitulatif des bonus d’utilisation en heures creuses'''

            contenu = r'''
                \cline{3-4}
                \multicolumn{2}{l|}{} & \multicolumn{1}{c|}{Temps Mach.} & \multicolumn{1}{c|}{Points Bonus} \\
                \hline
                '''

            somme = sommes_acces[code_client]['machines']
            machines_utilisees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_utilisees.items()):
                for nom_machine, id_machine in sorted(mics.items()):
                    if somme[id_machine]['dhm'] > 0:
                        dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                        'hc': Outils.format_heure(somme[id_machine]['duree_hc']),
                                        'dhm': somme[id_machine]['dhm']}
                        contenu += r'''
                            \hspace{2mm} %(machine)s & HC & %(hc)s & %(dhm)s \\
                            \hline
                            ''' % dico_machine

                        utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                        for nom, upi in sorted(utilisateurs.items()):
                            for prenom, ids in sorted(upi.items()):
                                for id_user in sorted(ids):
                                    smu = somme[id_machine]['users'][id_user]
                                    if smu['duree_hc'] > 0:
                                        dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                                     'hc': Outils.format_heure(smu['duree_hc'])}
                                        contenu += r'''
                                            \hspace{5mm} %(user)s & HC & %(hc)s \hspace{5mm} & \\
                                            \hline
                                        ''' % dico_user

            dico = {'bht': scl['somme_t_mb']}
            contenu += r'''
                \multicolumn{3}{|r|}{\textbf{Total points de bonus}} & %(bht)s \\
                \hline
                ''' % dico

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #3
0
    def creation_annexes(sommes, clients, edition, livraisons, acces, machines, reservations, prestations, comptes,
                         dossier_annexe, plateforme, prefixe, coefprests, coefmachines, generaux, garde):
        """
        création des annexes techniques
        :param sommes: sommes calculées
        :param clients: clients importés
        :param edition: paramètres d'édition
        :param livraisons: livraisons importées
        :param acces: accès importés
        :param machines: machines importées
        :param reservations: réservations importées
        :param prestations: prestations importées
        :param comptes: comptes importés
        :param dossier_annexe: nom du dossier dans lequel enregistrer les annexes
        :param plateforme: OS utilisé
        :param prefixe: prefixe de nom des annexes
        :param coefprests: coefficients prestations importés
        :param coefmachines: coefficients machines importés
        :param generaux: paramètres généraux
        :param garde: titre page de garde
        """

        if sommes.calculees == 0:
            info = "Vous devez d'abord faire toutes les sommes avant de pouvoir créer les annexes"
            print(info)
            Outils.affiche_message(info)
            return

        for code_client in sommes.sommes_clients.keys():
            contenu = Latex.entete(plateforme)
            contenu += r'''\usepackage[margin=10mm, includefoot]{geometry}
                \usepackage{multirow}
                \usepackage{longtable}
                \usepackage{dcolumn}
                \usepackage{changepage}
                \usepackage[scriptsize]{caption}

                \begin{document}
                \renewcommand{\arraystretch}{1.5}
                '''
            contenu += r'''
                \vspace*{8cm}
                \begin{adjustwidth}{5cm}{}
                \Large\textsc{''' + garde + r'''}\newline\newline'''
            nom = Latex.echappe_caracteres(clients.donnees[code_client]['abrev_labo'])
            code_sap = clients.donnees[code_client]['code_sap']

            contenu += code_client + " - " + code_sap + " - " + nom + r'''\newpage
                \end{adjustwidth}'''
            contenu += Annexes.contenu_client(sommes, clients, code_client, edition, livraisons, acces, machines,
                                              reservations, prestations, comptes, coefprests, coefmachines, generaux)
            contenu += r'''\end{document}'''

            nom = prefixe + str(edition.annee) + "_" + Outils.mois_string(edition.mois) + "_" + \
                  str(edition.version) + "_" + code_client

            Latex.creer_latex_pdf(nom, contenu, dossier_annexe)
Example #4
0
    def externaldocument (self, dict):
        # .aux document needed to cross-ref with xr
        auxfile = dict["arg"] + ".aux"
        texfile = dict["arg"] + ".tex"

        # Ignore the dependency if no tex source found
        if not(os.path.isfile(texfile)):
            msg.log(_("file %s is required by xr package but not found")\
                    % texfile, pkg="xr")
            return

        # Ask to compile the related .tex file to have the .aux 
        texdep = Latex(self.env)
        texdep.set_source(texfile)
        texdep.batch = self.doc.batch
        texdep.encoding = self.doc.encoding
        texdep.draft_only = True # Final output not required here
        for m in self.texmodules:
            texdep.modules.register(m)
        # Load other modules from source, except xr to avoid loops
        texdep.prepare(exclude_mods=["xr-hyper"])

        # Add the .aux as an expected input for compiling the doc
        self.doc.sources[auxfile] = texdep
        msg.log(_(
            "dependency %s added for external references") % auxfile, pkg="xr")
Example #5
0
    def table_prix_lvr_jd(code_client, id_compte, intitule_compte, sco, sommes_livraisons, generaux):
        """
        Prix LVR J/D - Table Compte Récap Prestations livrées/code D
        :param code_client: code du client concerné
        :param id_compte: id du compte concerné
        :param intitule_compte: intitulé du compte concerné
        :param sco: sommes compte calculées
        :param sommes_livraisons: sommes des livraisons importées
        :param generaux: paramètres généraux
        :return: table au format latex
        """

        if code_client in sommes_livraisons and id_compte in sommes_livraisons[code_client]:
            somme = sommes_livraisons[code_client][id_compte]
            structure = r'''{|l|r|c|r|r|r|}'''
            legende = r'''Consommables et autres prestations'''
            contenu_prests = ""
            for article in generaux.articles_d3:
                if article.code_d in somme and sco['sommes_cat_m'][article.code_d] > 0:
                    if contenu_prests != "":
                        contenu_prests += r'''
                            \multicolumn{6}{c}{} \\
                            '''

                    contenu_prests += r'''
                        \hline
                        \multicolumn{1}{|l|}{
                        \textbf{''' + intitule_compte + " - " + Latex.echappe_caracteres(article.intitule_long) + r'''
                        }} & \multicolumn{1}{c|}{Quantité} & Unité & \multicolumn{1}{c|}{P.U.}
                        & \multicolumn{1}{c|}{Montant} & \multicolumn{1}{c|}{Rabais} \\
                        \hline
                        '''
                    for no_prestation, sip in sorted(somme[article.code_d].items()):
                        if sip['montant'] > 0:
                            dico_prestations = {'nom': Latex.echappe_caracteres(sip['nom']),
                                                'num': no_prestation,
                                                'quantite': "%.1f" % sip['quantite'],
                                                'unite': Latex.echappe_caracteres(sip['unite']),
                                                'pn': Outils.format_2_dec(sip['pn']),
                                                'montant': Outils.format_2_dec(sip['montant']),
                                                'rabais': Outils.format_2_dec(sip['rabais'])}
                            contenu_prests += r'''
                                %(num)s - %(nom)s & \hspace{5mm} %(quantite)s & %(unite)s & %(pn)s & %(montant)s
                                & %(rabais)s  \\
                                \hline
                                ''' % dico_prestations
                    dico_prestations = {'montant': Outils.format_2_dec(sco['sommes_cat_m'][article.code_d]),
                                        'rabais': Outils.format_2_dec(sco['sommes_cat_r'][article.code_d])}
                    contenu_prests += r'''
                        \multicolumn{4}{|r|}{Total} & %(montant)s & %(rabais)s  \\
                        \hline
                        ''' % dico_prestations
            return Latex.tableau(contenu_prests, structure, legende)
        else:
            return ""
Example #6
0
    def table_prix_cae_jk(code_client, id_compte, intitule_compte, sco, sommes_acces, categories):
        """
        Prix CAE J/K - Table Compte Récap Procédés/Catégorie Machine
        :param code_client: code du client concerné
        :param id_compte: id du compte concerné
        :param intitule_compte: intitulé du compte concerné
        :param sco: sommes compte calculées
        :param sommes_acces: sommes des accès importés
        :param categories: catégories importées
        :return: table au format latex
        """

        if code_client in sommes_acces and id_compte in sommes_acces[code_client]['comptes'] and sco['somme_j_mk'] > 0:

            structure = r'''{|l|c|c|r|r|}'''
            legende = r'''Services'''
            contenu = r'''
                \hline
                \textbf{''' + intitule_compte + r'''} & Unité & Quantité & \multicolumn{1}{c|}{PU} &
                 \multicolumn{1}{c|}{Montant}   \\
                \hline
                '''

            for cat, som_cat in sorted(sommes_acces[code_client]['categories'][id_compte].items()):

                for id_categorie, cats in sorted(som_cat.items()):
                    montant = cats['mk']
                    unite = categories.donnees[id_categorie]['unite']
                    if unite == 'hh_mm':
                        quantite = Outils.format_heure(cats['quantite'])
                    else:
                        quantite = cats['quantite']
                    if montant > 0:
                        dico_cat = {'intitule': Latex.echappe_caracteres(categories.donnees[id_categorie]['intitule']),
                                    'pk': Outils.format_2_dec(cats['pk']),
                                    'unite': Latex.echappe_caracteres(unite),
                                    'quantite': quantite,
                                    'mk': Outils.format_2_dec(montant)}
                        contenu += r'''
                            %(intitule)s & %(unite)s & %(quantite)s & %(pk)s & %(mk)s  \\
                            \hline
                            ''' % dico_cat

            dico_cat = {'mkj': Outils.format_2_dec(sco['somme_j_mk'])}

            contenu += r'''
                \multicolumn{4}{|r|}{Total} & %(mkj)s \\
                \hline
                ''' % dico_cat

            return Latex.tableau(contenu, structure, legende)
        else:
            return ""
Example #7
0
    def __init__(self):
        # The actual workers
        self.maker = Maker()
        self.tex = Latex(self.maker)
        self.maker.dep_append(self.tex)

        # What to do
        self.backend = "pdftex"
        self.format = "pdf"
        self.index_style = ""
        self.batch = 1
        self.encoding = "latin-1"
        self.texpost = ""
        self.options = ""
Example #8
0
    def table_prix_xf(scl, generaux, filtre, contenu_prix_xf):
        """
        Prix XF - Table Client Récap Postes de la facture
        :param scl: sommes client calculées
        :param generaux: paramètres généraux
        :param filtre: si nul pour code n
        :param contenu_prix_xf: contenu généré de la table
        :return: table au format latex
        """

        brut = scl['rm'] + scl['somme_t_mm'] + scl['em']
        for cat, tt in scl['sommes_cat_m'].items():
            brut += tt
        if scl['somme_t'] > 0 or (filtre == "NON" and brut > 0):
            structure = r'''{|c|l|r|r|r|}'''
            legende = r'''Récapitulatif des postes de la facture'''

            dico = {'emom': Outils.format_2_dec(scl['em']), 'emor': Outils.format_2_dec(scl['er']),
                    'emo': Outils.format_2_dec(scl['e']), 'resm': Outils.format_2_dec(scl['rm']),
                    'resr': Outils.format_2_dec(scl['rr']), 'res': Outils.format_2_dec(scl['r']),
                    'int_emo': Latex.echappe_caracteres(generaux.articles[0].intitule_long),
                    'int_res': Latex.echappe_caracteres(generaux.articles[1].intitule_long),
                    'p_emo': generaux.poste_emolument, 'p_res': generaux.poste_reservation}

            contenu = r'''
                \hline
                N. Poste & Poste & \multicolumn{1}{c|}{Montant} & \multicolumn{1}{c|}{Rabais}
                & \multicolumn{1}{c|}{Total} \\
                \hline'''
            if scl['em'] > 0 and not (filtre == "OUI" and scl['e'] == 0):
                contenu += r'''
                    %(p_emo)s & %(int_emo)s & %(emom)s & %(emor)s & %(emo)s \\
                    \hline''' % dico
            if scl['rm'] > 0 and not (filtre == "OUI" and scl['r'] == 0):
                contenu += r'''
                    %(p_res)s & %(int_res)s & %(resm)s & %(resr)s & %(res)s \\
                    \hline
                    ''' % dico

            contenu += contenu_prix_xf

            contenu += r'''\multicolumn{4}{|r|}{Total}
                & ''' + Outils.format_2_dec(scl['somme_t']) + r'''\\
                \hline
                '''
            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #9
0
    def ligne_tableau(article, poste, net, rabais, consommateur, edition):
        """
        retourne une ligne de tableau html

        :param article: Une instance de la classe generaux.Article
        :param poste: indice de poste
        :param net: montant net
        :param rabais: rabais sur le montant
        :param consommateur: consommateur
        :param edition: paramètres d'édition
        :return: ligne de tableau html
        """
        montant = net - rabais
        date_livraison = str(edition.dernier_jour) + "." + Outils.mois_string(
            edition.mois) + "." + str(edition.annee)
        description = article.code_d + " : " + article.code_sap
        dico_tab = {
            'poste': poste,
            'date': date_livraison,
            'descr': description,
            'texte': article.texte_sap,
            'nom': Latex.echappe_caracteres(consommateur),
            'unit': article.unite,
            'quantity': article.quantite,
            'unit_p': "%.2f" % net,
            'discount': "%.2f" % rabais,
            'net': "%.2f" % montant
        }
        ligne = r'''<tr>
            <td> %(poste)s </td><td> %(date)s </td><td> %(nom)s </td><td> %(descr)s <br /> %(texte)s </td>
            <td> %(unit)s </td><td id="toright"> %(quantity)s </td><td id="toright"> %(unit_p)s </td>
            <td id="toright"> %(discount)s </td><td id="toright"> %(net)s </td>
            </tr>
            ''' % dico_tab
        return ligne
Example #10
0
    def ligne_facture(generaux, article, poste, net, rabais, op_centre,
                      consommateur, edition):
        """
        retourne une ligne de facturation formatée

        :param generaux: paramètres généraux
        :param article: Une instance de la classe generaux.Article
        :param poste: indice de poste
        :param net: montant net
        :param rabais: rabais sur le montant
        :param op_centre: centre d'opération
        :param consommateur: consommateur
        :param edition: paramètres d'édition
        :return: ligne de facturation formatée
        """
        net = "%.2f" % net
        rabais = "%.2f" % rabais
        if rabais == 0:
            rabais = ""
        code_op = generaux.code_t + op_centre + article.code_d
        date_livraison = str(edition.annee) + Outils.mois_string(
            edition.mois) + str(edition.dernier_jour)

        return [
            poste, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
            "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
            article.code_sap, "", article.quantite, article.unite,
            article.type_prix, net, article.type_rabais, rabais,
            date_livraison, generaux.centre_financier, "", generaux.fonds, "",
            "", code_op, "", "", "", article.texte_sap,
            Latex.echappe_caracteres(consommateur)
        ]
Example #11
0
    def ligne_tableau(article, poste, net, rabais, consommateur, edition):
        """
        retourne une ligne de tableau html

        :param article: Une instance de la classe generaux.Article
        :param poste: indice de poste
        :param net: montant net
        :param rabais: rabais sur le montant
        :param consommateur: consommateur
        :param edition: paramètres d'édition
        :return: ligne de tableau html
        """
        montant = net - rabais
        date_livraison = str(edition.dernier_jour) + "." + Outils.mois_string(edition.mois) + "." + str(edition.annee)
        description = article.code_d + " : " + article.code_sap
        dico_tab = {'poste': poste, 'date': date_livraison, 'descr': description,
                    'texte': article.texte_sap, 'nom': Latex.echappe_caracteres(consommateur),
                    'unit': article.unite, 'quantity': article.quantite,
                    'unit_p': "%.2f" % net, 'discount': "%.2f" % rabais, 'net': "%.2f" % montant}
        ligne = r'''<tr>
            <td> %(poste)s </td><td> %(date)s </td><td> %(nom)s </td><td> %(descr)s <br /> %(texte)s </td>
            <td> %(unit)s </td><td id="toright"> %(quantity)s </td><td id="toright"> %(unit_p)s </td>
            <td id="toright"> %(discount)s </td><td id="toright"> %(net)s </td>
            </tr>
            ''' % dico_tab
        return ligne
Example #12
0
    def table_prix_ja(sco, generaux):
        """
        Prix JA - Table Compte Récap Articles
        :param sco: sommes compte calculées
        :param generaux: paramètres généraux
        :return: table au format latex
        """

        structure = r'''{|l|r|r|r|}'''
        legende = r'''Récapitulatif des articles du projet'''

        contenu = r'''
            \cline{2-4}
            \multicolumn{1}{r|}{} & \multicolumn{1}{c|}{Montant} & \multicolumn{1}{c|}{Rabais}
            & \multicolumn{1}{c|}{Net} \\
            \hline'''

        if sco['somme_j_mm'] > 0:
            dico = {'mm': Outils.format_2_dec(sco['somme_j_mm']), 'mr': Outils.format_2_dec(sco['somme_j_mr']),
                    'mj': Outils.format_2_dec(sco['mj']),
                    'int_proc': Latex.echappe_caracteres(generaux.articles[2].intitule_long)}
            contenu += r'''
                %(int_proc)s & %(mm)s & %(mr)s & %(mj)s \\
                \hline
                ''' % dico

        total = sco['mj']
        for article in generaux.articles_d3:
            total += sco['tot_cat'][article.code_d]
            if sco['sommes_cat_m'][article.code_d]:
                dico = {'intitule': Latex.echappe_caracteres(article.intitule_long),
                        'cmj': Outils.format_2_dec(sco['sommes_cat_m'][article.code_d]),
                        'crj': Outils.format_2_dec(sco['sommes_cat_r'][article.code_d]),
                        'cj': Outils.format_2_dec(sco['tot_cat'][article.code_d])}
                contenu += r'''
                %(intitule)s & %(cmj)s & %(crj)s & %(cj)s \\
                \hline
                ''' % dico

        contenu += r'''\multicolumn{3}{|r|}{Total} & ''' + Outils.format_2_dec(total) + r'''\\
        \hline
        '''

        return Latex.tableau(contenu, structure, legende)
Example #13
0
    def section(client, generaux, reference, titre):
        """
        création d'un début de section non-visible
        :param client: données du client concerné
        :param generaux: paramètres généraux
        :param reference: référence de la facture
        :param titre: titre de la section
        :return: section latex
        """
        dic_section = {'code_sap': Latex.echappe_caracteres(client['code_sap']),
                       'nom': Latex.echappe_caracteres(client['abrev_labo']), 'ref': reference, 'titre': titre,
                       'centre': Latex.echappe_caracteres(generaux.centre)}

        section = r'''
            \fakesection{%(centre)s \\ %(ref)s \\ %(titre)s}
            {%(code_sap)s - %(nom)s \\}
            ''' % dic_section

        return section
Example #14
0
    def entete(edition):
        """
        création de l'entête latex
        :param edition: paramètres d'édition
        :return: entête latex
        """

        entete = Latex.entete()
        entete += r'''
            \usepackage[margin=12mm, includehead, includefoot]{geometry}
            \usepackage{multirow}
            \usepackage{graphicx}
            \usepackage{longtable}
            \usepackage{dcolumn}
            \usepackage{changepage}
            \usepackage[scriptsize]{caption}
            \captionsetup[table]{position=bottom}
            \usepackage{fancyhdr}\usepackage{float}
            \restylefloat{table}

            '''

        if edition.filigrane != "":
            entete += r'''
                \usepackage{draftwatermark}
                \SetWatermarkLightness{0.8}
                \SetWatermarkAngle{45}
                \SetWatermarkScale{2}
                \SetWatermarkFontSize{2cm}
                \SetWatermarkText{''' + edition.filigrane[:15] + r'''}
                '''

        entete += r'''
            \pagestyle{fancy}

            \fancyhead{}
            \fancyfoot{}

            \renewcommand{\headrulewidth}{0pt}
            \renewcommand{\footrulewidth}{0pt}
            \renewcommand{\arraystretch}{1.5}

            \fancyhead[L]{\leftmark}
            \fancyhead[R]{\thepage \\ \rightmark}

            \newcommand{\fakesection}[2]{
                \markboth{#1}{#2}
            }

            \begin{document}
            '''

        return entete
Example #15
0
    def table_prix_xaj(scl, generaux, contenu_prix_xaj):
        """
        Prix XA/J - Table Client Récap Articles/Compte
        :param scl: sommes client calculées
        :param generaux: paramètres généraux
        :param contenu_prix_xaj: contenu généré de la table
        :return: table au format latex
        """

        structure = r'''{|l|l|r|r|'''
        legende = r'''Récapitulatif des projets'''

        contenu = r'''
            \hline
            Projet & Type & \multicolumn{1}{c|}{Procédés}'''

        for article in generaux.articles_d3:
            structure += r'''r|'''
            contenu += r''' & \multicolumn{1}{c|}{
            ''' + Latex.echappe_caracteres(article.intitule_court) + r'''}'''
        structure += r'''}'''
        contenu += r'''& \multicolumn{1}{c|}{Total} \\
            \hline
            '''

        contenu += contenu_prix_xaj

        dico = {'procedes': Outils.format_2_dec(scl['mt']),
                'total': Outils.format_2_dec((scl['somme_t']-scl['r']-scl['e']))}

        contenu += r'''Total article & & %(procedes)s''' % dico

        for categorie in generaux.codes_d3():
            contenu += r''' & ''' + Outils.format_2_dec(scl['tot_cat'][categorie])

        contenu += r'''& %(total)s \\
            \hline
            ''' % dico

        return Latex.long_tableau(contenu, structure, legende)
Example #16
0
    def ligne_liv(livraison):
        """
        création d'une ligne de tableau pour une livraison
        :param livraison: livraison particulière
        :return: ligne de tableau latex
        """
        total = livraison['montant'] - livraison['rabais_r']
        dico = {
            'date': Latex.echappe_caracteres(livraison['date_livraison']),
            'prestation': Latex.echappe_caracteres(livraison['designation']),
            'quantite': livraison['quantite'],
            'unite': Latex.echappe_caracteres(livraison['unite']),
            'rapport': "%.2f" % livraison['prix_unit_client'],
            'montant': "%.2f" % livraison['montant'],
            'rabais': "%.2f" % livraison['rabais_r'],
            'total': "%.2f" % total,
            'id': livraison['id_livraison'],
            'responsable': Latex.echappe_caracteres(livraison['responsable']),
            'commande': Latex.echappe_caracteres(livraison['date_commande']),
            'remarque': Latex.echappe_caracteres(livraison['remarque'])
        }

        return r'''\multirow{2}{*}{%(date)s} & %(prestation)s & %(quantite)s & %(unite)s & %(rapport)s & %(montant)s &
            %(rabais)s & %(total)s \\
            \cline{2-8}
             & \multicolumn{7}{l|}{Commande: %(commande)s; N. livraison: %(id)s; Resp: %(responsable)s; Remarque:
             %(remarque)s} \\
             \hline
             ''' % dico, total
Example #17
0
    def __init__(self):
        # The actual workers
        self.maker = Maker()
        self.tex = Latex(self.maker)
        self.maker.dep_append(self.tex)

        # What to do
        self.backend = "pdftex"
        self.format = "pdf"
        self.index_style = ""
        self.batch = 1
        self.encoding = "latin-1"
        self.texpost = ""
Example #18
0
 def ligne_tableau(self, article, poste, net, rabais, consommateur, edition):
     montant = net - rabais
     date_livraison = str(edition.dernier_jour) + "." + Outils.mois_string(edition.mois) + "." + str(edition.annee)
     description = article.code_d + " : " + article.code_sap
     dico_tab = {'poste': poste, 'date': date_livraison, 'descr': description,
                 'texte': article.texte_sap, 'nom': Latex.echappe_caracteres(consommateur),
                 'unit': article.unite, 'quantity': article.quantite,
                 'unit_p': "%.2f" % net, 'discount': "%.2f" % rabais, 'net': "%.2f" % montant}
     ligne = r'''<tr>
         <td> %(poste)s </td><td> %(date)s </td><td> %(nom)s </td><td> %(descr)s <br /> %(texte)s </td>
         <td> %(unit)s </td><td id="toright"> %(quantity)s </td><td id="toright"> %(unit_p)s </td>
         <td id="toright"> %(discount)s </td><td id="toright"> %(net)s </td>
         </tr>
         ''' % dico_tab
     return ligne
Example #19
0
    def table_tps_m_cae_xmu(code_client, acces, contenu_cae_xmu):
        """
        Tps_M CAE X/M/U - Table Client Récap Temps mach avec pénalités /Machine/User
        :param code_client: code du client concerné
        :param acces: accès importés
        :param contenu_cae_xmu: contenu généré pour cette table
        :return: table au format latex
        """

        if code_client in acces.sommes and contenu_cae_xmu != "":
            structure = r'''{|l|c|c|}'''
            legende = r'''Récapitulatif des utilisations machines par utilisateur'''
            contenu = r'''
                \cline{2-3}
                \multicolumn{1}{c|}{} & HP & HC \\
                \hline'''

            contenu += contenu_cae_xmu

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #20
0
    def ligne_liv(livraison):
        """
        création d'une ligne de tableau pour une livraison
        :param livraison: livraison particulière
        :return: ligne de tableau latex
        """
        total = livraison['montant'] - livraison['rabais_r']
        dico = {'date': Latex.echappe_caracteres(livraison['date_livraison']),
                'prestation': Latex.echappe_caracteres(livraison['designation']),
                'quantite': livraison['quantite'], 'unite': Latex.echappe_caracteres(livraison['unite']),
                'rapport': "%.2f" % livraison['prix_unit_client'], 'montant': "%.2f" % livraison['montant'],
                'rabais': "%.2f" % livraison['rabais_r'], 'total': "%.2f" % total, 'id': livraison['id_livraison'],
                'responsable': Latex.echappe_caracteres(livraison['responsable']),
                'commande': Latex.echappe_caracteres(livraison['date_commande']),
                'remarque': Latex.echappe_caracteres(livraison['remarque'])}

        return r'''\multirow{2}{*}{%(date)s} & %(prestation)s & %(quantite)s & %(unite)s & %(rapport)s & %(montant)s &
            %(rabais)s & %(total)s \\
            \cline{2-8}
             & \multicolumn{7}{l|}{Commande: %(commande)s; N. livraison: %(id)s; Resp: %(responsable)s; Remarque:
             %(remarque)s} \\
             \hline
             ''' % dico, total
Example #21
0
    def table_prix_jdmu(code_client, id_compte, intitule_compte, sco, sommes_acces, machines, users):
        """
        Prix JD/M/U - Table Compte Déductions HC (Rabais) par Machine
        :param code_client: code du client concerné
        :param id_compte: id du compte concerné
        :param intitule_compte: intitulé du compte concerné
        :param sco: sommes compte calculées
        :param sommes_acces: sommes des accès importés
        :param machines: machines importées
        :param users: users importés
        :return: table au format latex
        """

        if sco['somme_j_dhi'] > 0 and code_client in sommes_acces and id_compte in sommes_acces[code_client]['comptes']:
            structure = r'''{|l|c|r|r|}'''
            legende = r'''Rabais d’utilisation de machines en heures creuses'''
            contenu = r'''
                \hline
                \multicolumn{2}{|l|}{\textbf{''' + intitule_compte + r'''}} & \multicolumn{1}{c|}{Temps Mach.}
                 & \multicolumn{1}{c|}{Rabais (CHF)} \\
                \hline
                '''

            somme = sommes_acces[code_client]['comptes'][id_compte]
            machines_utilisees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_utilisees.items()):
                for nom_machine, id_machine in sorted(mics.items()):
                    if somme[id_machine]['dhi'] > 0:
                        dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                        'hc': Outils.format_heure(somme[id_machine]['duree_hc']),
                                        'dhi': Outils.format_2_dec(somme[id_machine]['dhi'])}
                        contenu += r'''
                            \hspace{2mm} %(machine)s & HC & %(hc)s & %(dhi)s \\
                            \hline
                            ''' % dico_machine

                        utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                        for nom, upi in sorted(utilisateurs.items()):
                            for prenom, ids in sorted(upi.items()):
                                for id_user in sorted(ids):
                                    smu = somme[id_machine]['users'][id_user]
                                    if smu['duree_hc'] > 0:
                                        dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                                     'hc': Outils.format_heure(smu['duree_hc'])}
                                        contenu += r'''
                                            \hspace{5mm} %(user)s & HC & %(hc)s \hspace{5mm} & \\
                                            \hline
                                        ''' % dico_user

            dico = {'rabais_d': Outils.format_2_dec(sco['somme_j_dhi_d']),
                    'rabais': Outils.format_2_dec(sco['somme_j_dhi'])}

            contenu += r'''
                \multicolumn{3}{|r|}{Arrondi} & %(rabais_d)s \\
                \hline
                \multicolumn{3}{|r|}{Total} & %(rabais)s \\
                \hline
                ''' % dico

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #22
0
    def contenu_tps_m_cae_xmu(code_client, scl, sommes_acces, machines, users, comptes):
        """
        contenu Tps_M CAE X/M/U - Table Client Récap Temps mach avec pénalités /Machine/User
        :param code_client: code du client concerné
        :param scl: sommes client calculées
        :param sommes_acces: sommes des accès importés
        :param machines: machines importées
        :param users: users importés
        :param comptes: comptes importés
        :return: contenu
        """

        contenu = ""
        if code_client in sommes_acces:
            somme = sommes_acces[code_client]['machines']
            machines_utilisees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_utilisees.items()):
                for nom_machine, id_machine in sorted(mics.items()):
                    if id_machine in scl['res']:
                        pur_hp = somme[id_machine]['pur_hp']
                        pur_hc = somme[id_machine]['pur_hc']
                        tx_hp = machines.donnees[id_machine]['tx_occ_eff_hp']
                        tx_hc = machines.donnees[id_machine]['tx_occ_eff_hc']
                        if (pur_hc > 0 and tx_hc > 0) or (pur_hp > 0 and tx_hp > 0):
                            dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                            'hp': Outils.format_heure(somme[id_machine]['duree_hp']),
                                            'hc': Outils.format_heure(somme[id_machine]['duree_hc'])}
                            contenu += r'''
                               \textbf{%(machine)s} & \hspace{5mm} %(hp)s & \hspace{5mm} %(hc)s \\
                                \hline
                                ''' % dico_machine

                            utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                            for nom, upi in sorted(utilisateurs.items()):
                                for prenom, ids in sorted(upi.items()):
                                    for id_user in sorted(ids):
                                        smu = somme[id_machine]['users'][id_user]
                                        dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                                     'hp': Outils.format_heure(smu['duree_hp']),
                                                     'hc': Outils.format_heure(smu['duree_hc'])}
                                        contenu += r'''
                                            \hspace{5mm} %(user)s & %(hp)s & %(hc)s \\
                                            \hline
                                            ''' % dico_user

                                        comptes_utilises = Outils.comptes_in_somme(smu['comptes'], comptes)

                                        for id_compte, num_compte in sorted(comptes_utilises.items(), key=lambda x: x[1]):
                                            smuc = smu['comptes'][id_compte]
                                            compte = comptes.donnees[id_compte]
                                            intitule_compte = Latex.echappe_caracteres(compte['numero']
                                                                                       + " - " + compte['intitule'])
                                            dico_compte = {'compte': intitule_compte,
                                                           'hp': Outils.format_heure(smuc['duree_hp']),
                                                           'hc': Outils.format_heure(smuc['duree_hc'])}
                                            contenu += r'''
                                                \hspace{10mm} %(compte)s & %(hp)s \hspace{5mm} & %(hc)s \hspace{5mm} \\
                                                \hline
                                                ''' % dico_compte
        return contenu
Example #23
0
                                 verification)
    acces.calcul_montants(machines, categprix, clients, verification, couts,
                          comptes)

    sommes = Sommes(verification, generaux)
    sommes.calculer_toutes(livraisons, reservations, acces, clients, machines)

    for donnee in paramannexe.donnees:
        donnee['chemin'] = Outils.chemin(
            [dossier_enregistrement, donnee['dossier']], generaux)
        Outils.existe(donnee['chemin'], True)
        donnee['lien'] = Outils.lien_dossier([dossier_lien, donnee['dossier']],
                                             generaux)

    # faire les annexes avant la facture, que le ticket puisse vérifier leur existence
    if Latex.possibles():
        Annexes.annexes(sommes, clients, edition, livraisons, acces, machines,
                        reservations, comptes, paramannexe, generaux, users,
                        couts, docpdf)

    Outils.copier_dossier("./reveal.js/", "js", dossier_enregistrement)
    Outils.copier_dossier("./reveal.js/", "css", dossier_enregistrement)
    facture_prod = Facture()
    f_html_sections = facture_prod.factures(sommes, dossier_destination,
                                            edition, generaux, clients,
                                            comptes, paramannexe)

    prod2qual = Prod2Qual(dossier_source)
    if prod2qual.actif:
        facture_qual = Facture(prod2qual)
        generaux_qual = Generaux(dossier_source, prod2qual)
Example #24
0
    def annexes(consolidation, plateforme, subgeneraux, subedition,
                dossier_annexe):
        """
        création des annexes de subsides
        :param consolidation: classe de consolidation des données des bilans
        :param plateforme: OS utilisé
        :param subgeneraux: paramètres généraux
        :param subedition: paramètres d'édition
        :param dossier_annexe: nom du dossier dans lequel enregistrer le dossier des annexes
        """
        for code_client, dcl in consolidation.clients.items():
            code_client = Latex.echappe_caracteres(code_client)

            contenu = Latex.entete(plateforme)
            contenu += r'''
                \usepackage[margin=10mm, includehead]{geometry}
                \usepackage{changepage}
                \usepackage{graphicx}
                \usepackage{longtable}
                \usepackage{dcolumn}
                \usepackage[scriptsize]{caption}
                \usepackage{fancyhdr}
                '''

            if subedition.filigrane != "":
                contenu += r'''
                    \usepackage{draftwatermark}
                    \SetWatermarkLightness{0.8}
                    \SetWatermarkAngle{45}
                    \SetWatermarkScale{2}
                    \SetWatermarkFontSize{2cm}
                    \SetWatermarkText{''' + subedition.filigrane[:15] + r'''}
                    '''

            contenu += r'''
                \pagestyle{fancy}

                \fancyhead{}
                \fancyfoot{}

                \renewcommand{\headrulewidth}{0pt}
                \renewcommand{\footrulewidth}{0pt}

                \fancyhead[L]{\leftmark \\ \rightmark}
                \fancyhead[R]{\thepage}

                \newcommand{\fakesection}[2]{
                    \markboth{#1}{#2}
                }
                
                \begin{document}
                \renewcommand{\arraystretch}{1.5}
                '''
            reference = "SUBS" + str(subedition.annee_fin_general)[2:] + \
                        Outils.mois_string(subedition.mois_fin_general) + "." + code_client

            contenu += r'''
                \begin{titlepage}
                \vspace*{8cm}
                \begin{adjustwidth}{5cm}{}
                \Large\textsc{Annexes subsides \newline Subsidies Appendices}\newline
                \Large\textsc{''' + reference + r'''}\newline\newline\newline
                '''

            debut = Outils.mois_nom(subedition.mois_debut_general) + " " + str(
                subedition.annee_debut_general)
            fin = Outils.mois_nom(subedition.mois_fin_general) + " " + str(
                subedition.annee_fin_general)
            dic_entete = {
                'code': code_client,
                'code_sap': Latex.echappe_caracteres(dcl['sap']),
                'nom': Latex.echappe_caracteres(dcl['abrev']),
                'debut': debut,
                'fin': fin
            }

            contenu += r'''Client %(code)s - %(code_sap)s - %(nom)s \newline
                 %(debut)s - %(fin)s
                \end{adjustwidth}
                \end{titlepage}    
                \clearpage
                ''' % dic_entete
            contenu += Annexes.contenu_client(code_client, consolidation,
                                              subgeneraux, subedition)
            contenu += r'''\end{document}'''

            nom = "subside_" + str(subedition.annee_fin_general) + "_" + \
                  Outils.mois_string(subedition.mois_fin_general) + "_" + code_client

            Latex.creer_latex_pdf(nom, contenu, dossier_annexe)
Example #25
0
def fermion_propagator():
    """ Calculate expression for first-order corrected fermion propagator. """

    latex = Latex()

    # 1. Write out amplitude  TODO include regulator terms
    m = []

    phase = 0  # Power of i
    const = []  # List of constants (as a product)
    metrics = []  # List of metrics (as a product)
    integrals = []  # List of Integral objects
    numers = []  # List of Terms in numerator (as a sum of products)
    denoms = []  # List of Terms in denominator

    def latex_add():
        s = ""
        s += ["", "i", "-", "-i"][phase % 4]  # Phase
        s += " ".join([t.latex() for t in const])  # Const
        s += " ".join([t.latex() for t in metrics])  # Metrics
        s += " ".join([t.latex() for t in integrals])  # Integrals
        n = " + ".join([" ".join([t.latex() for t in p]) for p in numers])
        d = " ".join(["(" + t.latex() + ")" for t in denoms])  # Denoms
        s += "\\frac{{ 1 }}{{ {0} }}".format(d)
        s += "\\left( {0} \\right)".format(n)
        latex.add(s)

    def sop_mult(sop1, sop2):
        """ Multiply sum of products """
        if sop1 == []:
            return multiplicand
        else:
            lst = []
            for prod1 in sop1:
                for prod2 in sop2:
                    lst.append(prod1 + prod2)
            return lst

    e = C("e")

    # 1. Write out amplitude

    # S_F(p)
    phase += 1
    ind = "\\sigma_1"

    multiplicand = [[Gamma(ind), Sub("p", ind)], [C("m")]]
    numers = sop_mult(numers, multiplicand)
    denoms.append(Term("p^2 - m^2 + i\\epsilon"))

    # int dk
    integrals.append(Integral("k", norm=True))

    # ie gamma mu
    ind = "\\mu"
    phase += 1
    const.append(e)
    multiplicand = [[Gamma(ind)]]
    numers = sop_mult(numers, multiplicand)

    # S_F(p - k)
    phase += 1
    ind = "\\sigma_2"
    multiplicand = [[Gamma(ind), Sub("p", ind)], [Gamma(ind),
                                                  Sub("-k", ind)], [C("m")]]
    numers = sop_mult(numers, multiplicand)
    denoms.append(Term("(p - k)^2 - m^2 + i\\epsilon"))

    # ie gamma nu
    ind = "\\nu"
    phase += 1
    const.append(e)
    multiplicand = [[Gamma(ind)]]
    numers = sop_mult(numers, multiplicand)

    # S_F(p)
    phase += 1
    ind = "\\sigma_1"
    multiplicand = [[Gamma(ind), Sub("p", ind)], [C("m")]]
    numers = sop_mult(numers, multiplicand)
    denoms.append(Term("p^2 - m^2 + i\\epsilon"))

    # D_{\mu, \nu}(k)
    phase += 3
    metrics.append(Metric("\\mu", "\\nu"))
    denoms.append(Term("k^2 + i\\epsilon"))

    latex_add()

    # Parse denominators
    n = len(denoms)
    const.append(Term(str(factorial(n - 1))))
    for i in range(n):
        a = Term("0")
        b = Term("1" + "".join([" - z_{0}".format(j + 1) for j in range(i)]))
        integrals.append(
            Integral("z_{0}".format(i + 1), norm=True, limits=(a, b)))
    denoms = [
        Term("\\left[" + " + ".join([
            "({0})z_{1}".format(d.latex(), i + 1) for i, d in enumerate(denoms)
        ]) + "\\right]^{0}".format(n))
    ]

    latex_add()

    latex.render()
Example #26
0
class LatexBuilder:
    """
    Main (g)rubber wrapper hiding all the internals and compiling the
    required tex file.
    """
    def __init__(self):
        # The actual workers
        self.maker = Maker()
        self.tex = Latex(self.maker)
        self.maker.dep_append(self.tex)

        # What to do
        self.backend = "pdftex"
        self.format = "pdf"
        self.index_style = ""
        self.batch = 1
        self.encoding = "latin-1"
        self.texpost = ""
        self.options = ""

    def set_format(self, format):
        # Just record it
        self.format = format

    def set_backend(self, backend):
        self.backend = backend

    def set_index_style(self, index_style):
        self.index_style = index_style

    def compile(self, source):
        self.tex.batch = self.batch
        self.tex.encoding = self.encoding
        self.tex.set_source(source)
        if self.options:
            self.tex.opts += shlex.split(self.options)

        # Load the modules needed to produce the expected output format
        if (self.format == "pdf"):
            if (self.backend == "pdftex"):
                self.tex.modules.register("pdftex")
            elif (self.backend == "xetex"):
                self.tex.modules.register("xetex")
            else:
                self.tex.modules.register("dvips")
                self.tex.modules.register("ps2pdf")
        elif (self.format == "ps"):
            self.tex.modules.register("dvips")

        # Now load other the modules required to compile this file
        self.tex.prepare()

        # Set the index style
        if self.index_style and self.tex.modules.has_key("makeidx"):
            idx = self.tex.modules["makeidx"]
            idx.style = self.index_style

        # Let's go...
        rc = self.maker.make()
        if rc != 0:
            raise OSError("%s compilation failed" % self.tex.program)

        # Post process script to call?
        if not (self.texpost):
            return

        os.environ["LATEX"] = self.tex.program
        rc = subprocess.call([self.texpost, source], stdout=msg.stdout)
        if rc == 1:
            return
        if rc != 0:
            raise OSError("%s texpost failed" % self.texpost)

        rc = self.maker.make(force=1)
        if rc != 0:
            raise OSError("%s post compilation failed" % self.tex.program)

    def clean(self):
        self.tex.clean()
        self.reinit()

    def reinit(self):
        self.tex.reinit()
        self.maker.reinit()
        self.maker.dep_append(self.tex)

    def print_errors(self):
        msg.display_all(self.tex.get_errors(), writer=msg.write_stderr)

    def print_misschars(self):
        # Show the characters not handled by fonts
        self.tex.print_misschars()
Example #27
0
    def ligne_cae(cae, machine, coefmachine):
        """
        création d'une ligne de tableau pour un accès
        :param cae: accès particulier
        :param machine: machine concernée
        :param coefmachine: coefficients machine concernée
        :return: ligne de tableau latex
        """

        login = Latex.echappe_caracteres(cae['date_login']).split()
        temps = login[0].split('-')
        date = temps[0]
        for pos in range(1, len(temps)):
            date = temps[pos] + '.' + date
        if len(login) > 1:
            heure = login[1]
        else:
            heure = ""

        mai_hp = round(cae['duree_machine_hp']/60 * cae['pum'], 2)
        mai_hc = round(cae['duree_machine_hc']/60 * cae['pum'], 2)
        dsi_hp = round(cae['duree_machine_hp']/60 * coefmachine['coef_d'] * machine['d_h_machine_d'], 2)
        dsi_hc = round(cae['duree_machine_hc']/60 * coefmachine['coef_d'] * machine['d_h_machine_d'], 2)
        dhi = cae['dhi']
        moi_hp = round(cae['duree_operateur_hp']/60 * cae['puo_hp'], 2)
        moi_hc = round(cae['duree_operateur_hc']/60 * cae['puo_hc'], 2)
        m_hp = mai_hp + moi_hp - dsi_hp
        m_hc = mai_hc + moi_hc - dsi_hc - dhi

        dico = {'date': date, 'heure': heure,
                'machine': Latex.echappe_caracteres(cae['nom_machine']),
                'operateur': Latex.echappe_caracteres(cae['nom_op']),
                'rem_op': Latex.echappe_caracteres(cae['remarque_op']),
                'rem_staff': Latex.echappe_caracteres(cae['remarque_staff']),
                'tm_hp': Outils.format_heure(cae['duree_machine_hp']),
                'to_hp': Outils.format_heure(cae['duree_operateur_hp']),
                'tm_hc': Outils.format_heure(cae['duree_machine_hc']),
                'to_hc': Outils.format_heure(cae['duree_operateur_hc']),
                'pum': cae['pum'], 'puo_hp': cae['puo_hp'], 'puo_hc': cae['puo_hc'], 'mai_hp': "%.2f" % mai_hp,
                'mai_hc': "%.2f" % mai_hc, 'dsi_hp': Outils.format_si_nul(dsi_hp),
                'dsi_hc': Outils.format_si_nul(dsi_hc), 'dhi_hp': '-', 'dhi_hc': Outils.format_si_nul(dhi),
                'moi_hp': "%.2f" % moi_hp, 'moi_hc': "%.2f" % moi_hc, 'm_hp': "%.2f" % m_hp, 'm_hc': "%.2f" % m_hc}

        nb = 0
        if (cae['duree_machine_hp'] > 0) or (cae['duree_operateur_hp'] > 0):
            nb += 1

        if (cae['duree_machine_hc'] > 0) or (cae['duree_operateur_hc'] > 0):
            nb += 1

        if nb == 0:
            return "", [0, 0, 0, 0, 0]

        if (cae['remarque_staff'] != "") or (cae['remarque_op'] != ""):
            nb += 1

        if nb == 1:
            ligne = r'''%(date)s & %(heure)s''' % dico
        else:
            ligne = r'''\multirow{''' + str(nb) + r'''}{*}{%(date)s} & \multirow{''' % dico
            ligne += str(nb) + r'''}{*}{%(heure)s}''' % dico

        nb = 0
        if (cae['duree_machine_hp'] > 0) or (cae['duree_operateur_hp'] > 0):
            ligne += r''' & %(machine)s & HP & %(tm_hp)s & %(to_hp)s & %(pum)s & %(puo_hp)s & %(mai_hp)s &
                %(dsi_hp)s & %(dhi_hp)s & %(moi_hp)s & %(m_hp)s \\
                ''' % dico
            nb += 1

        if (cae['duree_machine_hc'] > 0) or (cae['duree_operateur_hc'] > 0):
            if nb > 0:
                ligne += r'''& &'''
            else:
                ligne += r'''& %(machine)s ''' % dico
            ligne += r''' & HC & %(tm_hc)s & %(to_hc)s & %(pum)s & %(puo_hc)s & %(mai_hc)s &
                %(dsi_hc)s & %(dhi_hc)s & %(moi_hc)s & %(m_hc)s \\
                ''' % dico

        if (cae['remarque_staff'] != "") or (cae['remarque_op'] != ""):
            ligne += r'''\cline{3-13}
                &  & \multicolumn{11}{l|}{%(operateur)s ; %(rem_op)s ; %(rem_staff)s}\\
                ''' % dico

        ligne += r'''\hline
            '''
        return ligne, [(mai_hp + mai_hc), (dsi_hp + dsi_hc), dhi, (moi_hp + moi_hc), (m_hp + m_hc)]
Example #28
0
    def contenu_client(sommes, clients, code_client, edition, livraisons, acces, machines, reservations, prestations,
                       comptes, coefprests, coefmachines, generaux):
        """
        création du contenu de l'annexe pour un client
        :param sommes: sommes calculées
        :param clients: clients importés
        :param code_client: code du client pour l'annexe
        :param edition: paramètres d'édition
        :param livraisons: livraisons importées
        :param acces: accès importés
        :param machines: machines importées
        :param reservations: réservations importées
        :param prestations: prestations importées
        :param comptes: comptes importés
        :param coefprests: coefficients prestations importés
        :param coefmachines: coefficients machines importés
        :param generaux: paramètres généraux
        :return: contenu de l'annexe du client
        """

        contenu = ""

        scl = sommes.sommes_clients[code_client]
        client = clients.donnees[code_client]
        sca = sommes.sommes_categories[code_client]
        intitule_client = code_client + " - " + Latex.echappe_caracteres(client['abrev_labo'])

        structure_recap_compte = r'''{|l|l|r|r|'''
        contenu_recap_compte = r'''
            \hline
            Compte & Catégorie & \multicolumn{1}{l|}{Procédés}'''

        for categorie in generaux.codes_d3():
            structure_recap_compte += r'''r|'''
            contenu_recap_compte += r''' & \multicolumn{1}{l|}{
            ''' + Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie)) + r'''}'''

        structure_recap_compte += r'''}'''
        legende_recap_compte = r'''Récapitulatif des comptes pour client ''' + intitule_client
        contenu_recap_compte += r'''& \multicolumn{1}{l|}{Total cpte} \\
            \hline
            '''

        structure_recap_eligibles = r'''{|l|c|c|c|c|c|c|c|c|}'''
        legende_recap_eligibles = r'''Coûts procédés éligibles des comptes pour client ''' + intitule_client
        contenu_recap_eligibles = r'''
            \hline
            Compte & Coûts A & Coûts B & Coûts C & Coûts U1 & Coûts U2 & Coûts U3 & Coûts MO & Coûts CO \\
            \hline
            '''

        client_comptes = sommes.sommes_comptes[code_client]
        contenu_compte = ""

        for id_compte in sorted(client_comptes.keys()):
            # ## COMPTE

            compte = comptes.donnees[id_compte]
            intitule_compte = id_compte + " - " + Latex.echappe_caracteres(compte['intitule'])
            dico_nom = {'labo': Latex.echappe_caracteres(client['abrev_labo']),
                        'utilisateur': Latex.echappe_caracteres(compte['intitule']),
                        'date': edition.mois_txt + " " + str(edition.annee)}
            contenu_compte += r'''
                \clearpage
                %(labo)s - %(utilisateur)s - %(date)s
                ''' % dico_nom

            # ## RES
            structure_res = r'''{|l|l|l|l|l|l|}'''
            dico_res = {'compte': intitule_compte}
            contenu_res = r'''
                \hline
                \multicolumn{3}{|l|}{%(compte)s} & & \multicolumn{2}{l|}{hh:mm} \\
                \hline
                Date & Heure & Equipement & & slot & fact. \\
                \hline
                ''' % dico_res
            nombre_res = 0
            legende_res = r'''Récapitulatif Réservations : ''' + intitule_compte

            res_proj = reservations.reservations_pour_compte(id_compte, code_client)
            for res in res_proj:
                nombre_res += 1
                ligne = Annexes.ligne_res(res)
                contenu_res += ligne

            contenu_rsv = ""
            if nombre_res > 0:
                contenu_rsv = Latex.long_tableau(contenu_res, structure_res, legende_res)
            # ## res

            structure_recap_projet = r'''{|l|r|r|'''
            contenu_recap_projet = r'''
                \hline
                Projet & \multicolumn{1}{l|}{Procédés} '''
            for categorie in generaux.codes_d3():
                structure_recap_projet += r'''r|'''
                contenu_recap_projet += r''' & \multicolumn{1}{l|}{
                ''' + Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie)) + r'''}'''
            structure_recap_projet += r'''}'''
            legende_recap_projet = r'''Récapitulatif compte ''' + intitule_compte
            contenu_recap_projet += r''' & \multicolumn{1}{l|}{Total projet} \\
                \hline
                '''
            contenu_projet = ""

            if code_client in sommes.sommes_projets:
                if id_compte in sommes.sommes_projets[code_client]:
                    print(code_client, id_compte)
                    client_compte_projet = sommes.sommes_projets[code_client][id_compte]

                    for num_projet in sorted(client_compte_projet.keys()):
                        # ## PROJET
                        sp = sommes.sommes_projets[code_client][id_compte][num_projet]
                        intitule_projet = num_projet + " - " + Latex.echappe_caracteres(sp['intitule'])

                        dico_recap_projet = {'num': intitule_projet, 'procede': "%.2f" % sp['mp']}

                        total = sp['mp']
                        contenu_recap_projet += r'''
                            \hline
                            %(num)s & %(procede)s''' % dico_recap_projet
                        for categorie in generaux.codes_d3():
                            total += sp['tot_cat'][categorie]
                            contenu_recap_projet += r''' & ''' + "%.2f" % sp['tot_cat'][categorie]
                        dico_recap_projet['total'] = "%.2f" % total

                        contenu_recap_projet += r''' & %(total)s \\
                            \hline
                            ''' % dico_recap_projet

                        ## CAE
                        structure_cae = r'''{|l|l|l|c|c|c|c|c|c|c|c|c|c|}'''
                        dico_cae = {'compte': intitule_compte, 'projet': intitule_projet}
                        contenu_cae = r'''
                            \hline
                            \multicolumn{3}{|l|}{%(compte)s / %(projet)s} & & \multicolumn{2}{c|}{hh:mm} &
                            \multicolumn{2}{c|}{CHF/h} & Montant & \multicolumn{2}{c|}{Déductions} & Montant & Montant \\
                            \cline{1-8}
                            \cline{10-11}
                            Date & Heure & Equipement & & mach. & oper. & mach. & MO & machine &
                            spé. & HC & MO & net \\
                            \hline
                            ''' % dico_cae
                        nombre_cae = 0
                        legende_cae = r'''Récapitulatif Utilisation machines : ''' + intitule_compte + r''' / ''' +\
                                      intitule_projet

                        cae_proj = acces.acces_pour_projet(num_projet, id_compte, code_client)
                        resultats = [0, 0, 0, 0, 0]
                        for cae in cae_proj:
                            nombre_cae += 1
                            machine = machines.donnees[cae['id_machine']]
                            coefmachine = coefmachines.donnees[client['id_classe_tarif'] + machine['categorie']]
                            ligne, resultat = Annexes.ligne_cae(cae, machine, coefmachine)
                            resultats[0] += resultat[0]
                            resultats[1] += resultat[1]
                            resultats[2] += resultat[2]
                            resultats[3] += resultat[3]
                            resultats[4] += resultat[4]
                            contenu_cae += ligne

                        contenu_cae += r'''
                            \multicolumn{8}{|r|}{Total} & ''' + Outils.format_si_nul(resultats[0]) + r'''
                            & ''' + Outils.format_si_nul(resultats[1]) + r'''
                            & ''' + Outils.format_si_nul(resultats[2]) + r'''
                            & ''' + Outils.format_si_nul(resultats[3]) + r'''
                            & ''' + Outils.format_si_nul(resultats[4]) + r''' \\
                            \hline
                            '''

                        if nombre_cae > 0:
                            contenu_projet += Latex.long_tableau(contenu_cae, structure_cae, legende_cae)
                        ## cae

                        # ## LIV
                        structure_liv = r'''{|l|l|l|l|r|r|r|r|}'''
                        dico_liv = {'compte': intitule_compte, 'projet': intitule_projet}
                        contenu_liv = r'''
                            \hline
                            \multicolumn{2}{|l|}{%(compte)s / %(projet)s} & & & & & &  \\
                            \hline
                            Date livr. & Désignation & Q & Unité & \multicolumn{1}{l|}{PU} & \multicolumn{1}{l|}{Montant}
                            & \multicolumn{1}{l|}{Rabais} & \multicolumn{1}{l|}{Total} \\
                            \hline
                            ''' % dico_liv
                        nombre_liv = 0
                        legende_liv = r'''Récapitulatif Livraisons : ''' + intitule_compte + r''' / ''' + intitule_projet

                        liv_proj_cat = livraisons.livraisons_pour_projet_par_categorie(num_projet, id_compte, code_client,
                                                                                       prestations)
                        resultats = 0
                        for categorie in generaux.codes_d3():
                            if categorie in liv_proj_cat:
                                livs = liv_proj_cat[categorie]
                                for liv in livs:
                                    nombre_liv += 1
                                    ligne, resultat = Annexes.ligne_liv(liv)
                                    resultats += resultat
                                    contenu_liv += ligne

                        contenu_liv += r'''
                            \multicolumn{7}{|r|}{Total} & ''' + Outils.format_si_nul(resultats) + r'''\\
                            \hline
                            '''

                        if nombre_liv > 0:
                            contenu_projet += Latex.long_tableau(contenu_liv, structure_liv, legende_liv)
                        # ## liv

                        # ## projet

            sco = sommes.sommes_comptes[code_client][id_compte]

            ligne = r'''\hline
                Total article & ''' + "%.2f" % sco['mj']

            sj = sco['mj']

            for categorie in generaux.codes_d3():
                ligne += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]
                sj += sco['tot_cat'][categorie]

            ligne += r''' & ''' + "%.2f" % sj
            ligne += r'''\\
                \hline
                '''

            contenu_recap_projet += ligne

            contenu_compte += Latex.tableau(contenu_recap_projet, structure_recap_projet, legende_recap_projet)

            dico_recap_compte = {'compte': intitule_compte, 'type': compte['categorie'], 'procede': "%.2f" % sco['mj'],
                                 'total': "%.2f" % sj}

            contenu_recap_compte += r'''%(compte)s & %(type)s & %(procede)s ''' \
                                    % dico_recap_compte

            for categorie in generaux.codes_d3():
                contenu_recap_compte += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]

            contenu_recap_compte += r'''& %(total)s \\
                    \hline
                    ''' % dico_recap_compte

            u1 = sco['somme_j_ai']
            u2 = u1 + sco['somme_j_bi']
            u3 = u2 + sco['somme_j_ci']
            couts_co = 0
            for cat, tt in sco['tot_cat'].items():
                couts_co += tt

            dico_recap_eligibles = {'compte': intitule_compte, 'couts_a': "%.2f" % sco['somme_j_ai'],
                                    'couts_mo': "%.2f" % sco['somme_j_oi'], 'couts_b': "%.2f" % sco['somme_j_bi'],
                                    'couts_c': "%.2f" % sco['somme_j_ci'], 'u1': "%.2f" % u1, 'u2': "%.2f" % u2,
                                    'u3': "%.2f" % u3, 'couts_co': "%.2f" % couts_co}

            contenu_recap_eligibles += r'''%(compte)s & %(couts_a)s & %(couts_b)s & %(couts_c)s &
                %(u1)s & %(u2)s & %(u3)s & %(couts_mo)s & %(couts_co)s \\
                \hline
                ''' % dico_recap_eligibles

            structure_recap_poste = r'''{|l|r|r|r|}'''
            legende_recap_poste = r'''Récapitulatif postes pour compte ''' + intitule_compte

            dico_recap_poste = {'maij': "%.2f" % sco['somme_j_mai'], 'moij': "%.2f" % sco['somme_j_moi'],
                                'mrj': "%.2f" % sco['somme_j_mr'], 'mj': "%.2f" % sco['mj']}

            contenu_recap_poste = r'''
                \hline
                Compte : ''' + intitule_compte + r''' & \multicolumn{1}{l|}{Montant} & \multicolumn{1}{l|}{Rabais}
                & \multicolumn{1}{l|}{Total} \\
                \hline
                Machine & %(maij)s & \multirow{2}{*}{%(mrj)s} & \multirow{2}{*}{%(mj)s} \\
                \cline{1-2}
                Main d'oeuvre & %(moij)s &  &  \\
                \hline
                ''' % dico_recap_poste

            for categorie in generaux.codes_d3():
                contenu_recap_poste += Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie))
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['sommes_cat_m'][categorie]
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['sommes_cat_r'][categorie]
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]
                contenu_recap_poste += r''' \\
                    \hline
                    '''

            contenu_compte += Latex.tableau(contenu_recap_poste, structure_recap_poste, legende_recap_poste)

            if nombre_res > 0:
                contenu_compte += contenu_rsv

            machines_utilisees = {}
            somme_res_compte = {}
            if code_client in reservations.sommes:
                if id_compte in reservations.sommes[code_client]['comptes']:
                    somme_res_compte = reservations.sommes[code_client]['comptes'][id_compte]
                    for key in somme_res_compte.keys():
                        machines_utilisees[key] = {'machine': machines.donnees[key]['nom']}
            somme_cae_compte = {}
            if code_client in acces.sommes:
                if id_compte in acces.sommes[code_client]:
                    somme_cae_compte = acces.sommes[code_client][id_compte]
                    for key in somme_cae_compte.keys():
                        if key not in machines_utilisees:
                            machines_utilisees[key] = {'machine': machines.donnees[key]['nom']}

            if len(machines_utilisees) > 0:
                structure_stat_machines = r'''{|l|c|c|c|c|c|c|r|}'''
                legende_stat_machines = r'''Statistiques de réservation/utilisation par machine : ''' + intitule_compte
                contenu_stat_machines = r'''
                    \hline
                    Equipement & & Slot rés. & Slot ann. & Taux & Utilisation minimale & Machine & Pénalités [h] \\
                    \hline
                    '''

                for machine_t in sorted(machines_utilisees.items(), key=lambda k_v: k_v[1]['machine']):
                    machine = machine_t[1]
                    id_machine = machine_t[0]

                    taux_hp = machines.donnees[id_machine]['tx_occ_eff_hp']
                    taux_hc = machines.donnees[id_machine]['tx_occ_eff_hc']
                    duree_hp = 0
                    duree_hc = 0
                    res_hp = 0
                    res_hc = 0
                    ann_hp = 0
                    ann_hc = 0
                    if id_machine in somme_cae_compte:
                        duree_hp = somme_cae_compte[id_machine]['duree_hp']
                        duree_hc = somme_cae_compte[id_machine]['duree_hc']
                    if id_machine in somme_res_compte:
                        res_hp = somme_res_compte[id_machine]['res_hp']
                        res_hc = somme_res_compte[id_machine]['res_hc']
                        ann_hp = somme_res_compte[id_machine]['ann_hp']
                        ann_hc = somme_res_compte[id_machine]['ann_hc']

                    min_hp = (res_hp + ann_hp) * taux_hp / 100
                    min_hc = (res_hc + ann_hc) * taux_hc / 100

                    pen_hp = min_hp - duree_hp
                    pen_hc = min_hc - duree_hc

                    dico_stat_machines = {
                        'machine': Latex.echappe_caracteres(machine['machine']),
                        'res_hp': Outils.format_heure(res_hp), 'res_hc': Outils.format_heure(res_hc),
                        'ann_hp': Outils.format_heure(ann_hp), 'ann_hc': Outils.format_heure(ann_hc),
                        'duree_hp': Outils.format_heure(duree_hp), 'duree_hc': Outils.format_heure(duree_hc),
                        'taux_hp': str(int(taux_hp)) + '\%', 'taux_hc': str(int(taux_hc)) + '\%',
                        'min_hp': Outils.format_heure(min_hp), 'min_hc': Outils.format_heure(min_hc),
                        'pen_hp': "%.1f" % round(pen_hp/60, 1), 'pen_hc': "%.1f" % round(pen_hc/60, 1)}

                    if res_hp > 0 or ann_hp or duree_hp:
                        contenu_stat_machines += r'''%(machine)s & HP &  %(res_hp)s & %(ann_hp)s & %(taux_hp)s &
                            %(min_hp)s & %(duree_hp)s & %(pen_hp)s \\
                            \hline
                            ''' % dico_stat_machines
                    if res_hc > 0 or ann_hc or duree_hc:
                        contenu_stat_machines += r'''%(machine)s & HC &  %(res_hc)s & %(ann_hc)s & %(taux_hc)s &
                            %(min_hc)s & %(duree_hc)s & %(pen_hc)s \\
                            \hline
                            ''' % dico_stat_machines

                contenu_compte += Latex.tableau(contenu_stat_machines, structure_stat_machines,
                                                legende_stat_machines)

            contenu_compte += contenu_projet
            # ## compte

        dic_entete = {'code': code_client, 'code_sap': client['code_sap'],
                      'nom': Latex.echappe_caracteres(client['abrev_labo']),
                      'date': edition.mois_txt + " " + str(edition.annee)}
        entete = r'''
            %(code)s - %(code_sap)s - %(nom)s - %(date)s
            ''' % dic_entete

        contenu += entete

        structure_recap_poste_cl = r'''{|l|r|r|r|}'''
        legende_recap_poste_cl = r'''Récapitulatif postes pour client ''' + intitule_client

        dico_recap_poste_cl = {'emom': "%.2f" % scl['em'], 'emor': "%.2f" % scl['er'], 'emo': "%.2f" % scl['e'],
                               'resm': "%.2f" % scl['rm'], 'resr': "%.2f" % scl['rr'], 'res': "%.2f" % scl['r'],
                               'mat': "%.2f" % scl['mat'], 'stmr': "%.2f" % scl['somme_t_mr'], 'mt': "%.2f" % scl['mt'],
                               'mot': "%.2f" % scl['mot']}

        contenu_recap_poste_cl = r'''
            \hline
             & \multicolumn{1}{l|}{Montant} & \multicolumn{1}{l|}{Rabais} & \multicolumn{1}{l|}{Total} \\
            \hline
            Emolument & %(emom)s & %(emor)s & %(emo)s \\
            \hline
            Frais de réservation & %(resm)s & %(resr)s & %(res)s \\
            \hline
            Machine & %(mat)s & \multirow{2}{*}{%(stmr)s} & \multirow{2}{*}{%(mt)s} \\
            \cline{1-2}
            Main d'oeuvre & %(mot)s & & \\
            \hline
            ''' % dico_recap_poste_cl

        for categorie in generaux.codes_d3():
            contenu_recap_poste_cl += Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie))
            contenu_recap_poste_cl += r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['sommes_cat_m'][categorie] + r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['sommes_cat_r'][categorie] + r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['tot_cat'][categorie] + r''' \\
                \hline
                '''

        contenu += Latex.tableau(contenu_recap_poste_cl, structure_recap_poste_cl, legende_recap_poste_cl)

        dico_emolument = {'emb':  "%.2f" % client['emol_base_mens'], 'ef':  "%.2f" % client['emol_fixe'],
                          'pente': client['coef'], 'tot_eq_r': "%.2f" % scl['r'],
                          'tot_eq_m': "%.2f" % (scl['mt']-scl['mot']), 'tot_eq': "%.2f" % scl['somme_eq'],
                          'rabais': "%.2f" % scl['er']}

        structure_emolument = r'''{|r|r|l|r|r|r|r|}'''
        legende_emolument = r'''Emolument pour client ''' + intitule_client
        contenu_emolument = r'''
            \hline
            \multicolumn{1}{|l|}{Emolument de base} & \multicolumn{1}{l|}{Emolument fixe} & Pente
            & \multicolumn{1}{l|}{Total EQ R} & \multicolumn{1}{l|}{Total EQ M} & \multicolumn{1}{l|}{Total EQ} &
            \multicolumn{1}{l|}{Rabais émolument} \\
            \hline
            %(emb)s & %(ef)s & %(pente)s & %(tot_eq_r)s & %(tot_eq_m)s & %(tot_eq)s & %(rabais)s \\
            \hline
            ''' % dico_emolument

        contenu += Latex.tableau(contenu_emolument, structure_emolument, legende_emolument)

        if scl['r'] > 0:
            structure_frais_client = r'''{|l|c|r|r|r|}'''
            legende_frais_client = r'''Frais de réservation/utilisation par machine pour client : ''' + intitule_client
            contenu_frais_client = r'''
                    \hline
                    Equipement & & Pénalités [h] & PU & Montant \\
                    \hline
                    '''
            machines_utilisees = {}
            for key in scl['res']:
                machines_utilisees[key] = {'machine': machines.donnees[key]['nom']}

            for machine_t in sorted(machines_utilisees.items(), key=lambda k_v: k_v[1]['machine']):
                machine = machine_t[1]
                id_machine = machine_t[0]
                som_m = scl['res'][id_machine]
                if som_m['pen_hp'] > 0 or som_m['pen_hc'] > 0:

                    dico_frais_client = {
                        'machine': Latex.echappe_caracteres(machine['machine']),
                        'pen_hp': "%.1f" % som_m['pen_hp'], 'pen_hc': "%.1f" % som_m['pen_hc'],
                        'mont_hp': Outils.format_si_nul(som_m['m_hp']), 'mont_hc': Outils.format_si_nul(som_m['m_hc']),
                        'pu_hp': Outils.format_si_nul(reservations.sommes[code_client]['machines'][id_machine]['pu_hp']),
                        'pu_hc': Outils.format_si_nul(reservations.sommes[code_client]['machines'][id_machine]['pu_hc'])}

                    if som_m['pen_hp'] > 0:
                        contenu_frais_client += r'''%(machine)s & HP &  %(pen_hp)s & %(pu_hp)s & %(mont_hp)s \\
                            \hline
                            ''' % dico_frais_client

                    if som_m['pen_hc'] > 0:
                        contenu_frais_client += r'''%(machine)s & HC &  %(pen_hc)s & %(pu_hc)s & %(mont_hc)s \\
                            \hline
                            ''' % dico_frais_client

            contenu_frais_client += r'''
                \multicolumn{4}{|r|}{Total} & ''' + Outils.format_si_nul(scl['r']) + r'''\\
                \hline
                '''

            contenu += Latex.tableau(contenu_frais_client, structure_frais_client, legende_frais_client)

        dico_recap_compte = {'procedes': "%.2f" % scl['mt'], 'total': "%.2f" % (scl['somme_t']-scl['r'])}

        contenu_recap_compte += r'''Total article & & %(procedes)s''' % dico_recap_compte

        for categorie in generaux.codes_d3():
            contenu_recap_compte += r''' & ''' + "%.2f" % scl['tot_cat'][categorie]

        contenu_recap_compte += r'''& %(total)s \\
                \hline
                ''' % dico_recap_compte

        contenu += Latex.tableau(contenu_recap_compte, structure_recap_compte, legende_recap_compte)

        u1 = scl['somme_t_ai']
        u2 = u1 + scl['somme_t_bi']
        u3 = u2 + scl['somme_t_ci']
        tot_co = 0
        for cat, tt in scl['tot_cat'].items():
            tot_co += tt
        dico_recap_eligibles = {'ait': "%.2f" % scl['somme_t_ai'], 'moit': "%.2f" % scl['somme_t_oi'],
                                'bit': "%.2f" % scl['somme_t_bi'], 'cit': "%.2f" % scl['somme_t_ci'], 'u1': "%.2f" % u1,
                                'u2': "%.2f" % u2, 'u3': "%.2f" % u3, 'coit': "%.2f" % tot_co}

        contenu_recap_eligibles += r'''Total article & %(ait)s & %(bit)s & %(cit)s & %(u1)s & %(u2)s &
            %(u3)s & %(moit)s & %(coit)s \\
            \hline
            ''' % dico_recap_eligibles

        contenu += Latex.tableau(contenu_recap_eligibles, structure_recap_eligibles, legende_recap_eligibles)

        structure_recap_cat_cl = r'''{|l|r|r|r|}'''
        legende_recap_cat_cl = r'''Détail par catégorie pour client ''' + intitule_client

        dico_recap_cat_cl = {'mmk1': '0.00', 'mrk1': '0.00', 'mk1': '0.00', 'mmk2': '0.00', 'mrk2': '0.00',
                             'mk2': '0.00', 'mmk3': '0.00', 'mrk3': '0.00', 'mk3': '0.00', 'mmk4': '0.00',
                             'mrk4': '0.00', 'mk4': '0.00', 'mm': "%.2f" % scl['somme_t_mm'],
                             'mr': "%.2f" % scl['somme_t_mr'], 'mt': "%.2f" % scl['mt']}

        if '1' in sca:
            dico_recap_cat_cl['mmk1'] = "%.2f" % sca['1']['somme_k_mm']
            dico_recap_cat_cl['mrk1'] = "%.2f" % sca['1']['somme_k_mr']
            dico_recap_cat_cl['mk1'] = "%.2f" % sca['1']['mk']
        if '2' in sca:
            dico_recap_cat_cl['mmk2'] = "%.2f" % sca['2']['somme_k_mm']
            dico_recap_cat_cl['mrk2'] = "%.2f" % sca['2']['somme_k_mr']
            dico_recap_cat_cl['mk2'] = "%.2f" % sca['2']['mk']
        if '3' in sca:
            dico_recap_cat_cl['mmk3'] = "%.2f" % sca['3']['somme_k_mm']
            dico_recap_cat_cl['mrk3'] = "%.2f" % sca['3']['somme_k_mr']
            dico_recap_cat_cl['mk3'] = "%.2f" % sca['3']['mk']
        if '4' in sca:
            dico_recap_cat_cl['mmk4'] = "%.2f" % sca['4']['somme_k_mm']
            dico_recap_cat_cl['mrk4'] = "%.2f" % sca['4']['somme_k_mr']
            dico_recap_cat_cl['mk4'] = "%.2f" % sca['4']['mk']

        contenu_recap_cat_cl = r'''
            \hline
             & \multicolumn{1}{l|}{Montant} & \multicolumn{1}{l|}{Rabais} & \multicolumn{1}{l|}{Total} \\
            \hline
            Coût procédés (catégorie Utilisateur) & %(mmk1)s & %(mrk1)s & %(mk1)s \\
            \hline
            Coût procédés (catégorie Etudiant en projet Master) & %(mmk2)s & %(mrk2)s & %(mk2)s \\
            \hline
            Coût procédés (catégorie Etudiant en projet Semestre) & %(mmk3)s & %(mrk3)s & %(mk3)s \\
            \hline
            Coût procédés (catégorie Client) & %(mmk4)s & %(mrk4)s & %(mk4)s \\
            \hline
            Total & %(mm)s & %(mr)s & %(mt)s \\
            \hline
            ''' % dico_recap_cat_cl

        contenu += Latex.tableau(contenu_recap_cat_cl, structure_recap_cat_cl, legende_recap_cat_cl)

        contenu += contenu_compte

        return contenu
Example #29
0
    def annexes(sommes, clients, edition, livraisons, acces, machines,
                reservations, comptes, paramannexe, generaux, users,
                categories, docpdf):
        """
        création des annexes
        :param sommes: sommes calculées
        :param clients: clients importés
        :param edition: paramètres d'édition
        :param livraisons: livraisons importées
        :param acces: accès importés
        :param machines: machines importées
        :param reservations: réservations importées
        :param comptes: comptes importés
        :param paramannexe: paramètres d'annexe
        :param generaux: paramètres généraux
        :param users: users importés
        :param categories: catégories importées
        :param docpdf: paramètres d'ajout de document pdf
        """

        if sommes.calculees == 0:
            info = "Vous devez d'abord faire toutes les sommes avant de pouvoir créer les annexes"
            Outils.affiche_message(info)
            return

        for code_client, scl in sommes.sommes_clients.items():
            code_client = Latex.echappe_caracteres(code_client)
            client = clients.donnees[code_client]
            nature = Latex.echappe_caracteres(
                generaux.code_ref_par_code_n(client['nature']))
            av_hc = Latex.echappe_caracteres(
                generaux.avantage_hc_par_code_n(client['nature']))
            reference = nature + str(edition.annee)[2:] + Outils.mois_string(
                edition.mois) + "." + code_client
            if edition.version > 0:
                reference += "-" + str(edition.version)

            filtre = generaux.filtrer_article_nul_par_code_n(client['nature'])

            contenu_prix_xaj = ""
            contenu_prix_xf = ""
            inc_fact = 1

            contenu_prix_lvr_xdj_tab = {}
            for article in generaux.articles_d3:
                contenu_prix_lvr_xdj_tab[article.code_d] = ""

            contenu_projets = ""
            contenu_details = ""

            todo = {}
            for donnee in paramannexe.donnees:
                if generaux.code_ref_par_code_n(client['nature']) == "INT":
                    todo[donnee['nom']] = donnee['int']
                elif client['mode'] == "MAIL":
                    todo[donnee['nom']] = donnee['ext_mail']
                else:
                    todo[donnee['nom']] = donnee['ext_postal']

            if code_client in sommes.sommes_comptes:
                comptes_utilises = Outils.comptes_in_somme(
                    sommes.sommes_comptes[code_client], comptes)

                for id_compte, num_compte in sorted(comptes_utilises.items(),
                                                    key=lambda x: x[1]):
                    id_compte = Latex.echappe_caracteres(id_compte)

                    # ## COMPTE

                    sco = sommes.sommes_comptes[code_client][id_compte]
                    compte = comptes.donnees[id_compte]
                    intitule_compte = Latex.echappe_caracteres(
                        compte['numero'] + " - " + compte['intitule'])

                    # ## ligne Prix XF - Table Client Récap Postes de la facture

                    if sco['c1'] > 0 and not (filtre == "OUI"
                                              and sco['c2'] == 0):
                        poste = inc_fact * 10
                        intitule = Latex.echappe_caracteres(
                            intitule_compte + " - " +
                            generaux.articles[2].intitule_long)

                        if sco['somme_j_mm'] > 0 and not (filtre == "OUI"
                                                          and sco['mj'] == 0):
                            dico_prix_xf = {
                                'intitule': intitule,
                                'poste': str(poste),
                                'mm': Outils.format_2_dec(sco['somme_j_mm']),
                                'mr': Outils.format_2_dec(sco['somme_j_mr']),
                                'mj': Outils.format_2_dec(sco['mj'])
                            }
                            contenu_prix_xf += r'''
                                %(poste)s & %(intitule)s & %(mm)s  & %(mr)s & %(mj)s \\
                                \hline
                                ''' % dico_prix_xf
                            poste += 1

                        for article in generaux.articles_d3:
                            categorie = article.code_d
                            if sco['sommes_cat_m'][categorie] > 0 and not (
                                    filtre == "OUI"
                                    and sco['tot_cat'][article.code_d] == 0):
                                intitule = Latex.echappe_caracteres(
                                    intitule_compte + " - " +
                                    article.intitule_long)
                                dico_prix_xf = {
                                    'intitule':
                                    intitule,
                                    'poste':
                                    str(poste),
                                    'mm':
                                    Outils.format_2_dec(
                                        sco['sommes_cat_m'][article.code_d]),
                                    'mr':
                                    Outils.format_2_dec(
                                        sco['sommes_cat_r'][article.code_d]),
                                    'mj':
                                    Outils.format_2_dec(
                                        sco['tot_cat'][article.code_d])
                                }
                                contenu_prix_xf += r'''
                                    %(poste)s & %(intitule)s & %(mm)s  & %(mr)s & %(mj)s \\
                                    \hline
                                    ''' % dico_prix_xf
                                poste += 1

                        inc_fact += 1

                    # ## ligne Prix XA/J - Table Client Récap Articles/Compte

                    total = sco['mj']
                    dico_prix_xaj = {
                        'compte': intitule_compte,
                        'type':
                        Latex.echappe_caracteres(compte['type_subside']),
                        'procede': Outils.format_2_dec(sco['mj'])
                    }

                    ligne = r'''%(compte)s & %(type)s & %(procede)s ''' % dico_prix_xaj

                    for categorie in generaux.codes_d3():
                        total += sco['tot_cat'][categorie]
                        ligne += r''' & ''' + Outils.format_2_dec(
                            sco['tot_cat'][categorie])

                    if total > 0:
                        dico_prix_xaj['total'] = Outils.format_2_dec(total)
                        ligne += r'''& %(total)s \\
                            \hline
                            ''' % dico_prix_xaj
                        contenu_prix_xaj += ligne

                    # ## ligne Prix LVR X/D/J - Table Client Récap Prestations livr./code D/Compte

                    if code_client in livraisons.sommes and id_compte in livraisons.sommes[
                            code_client]:
                        for article in generaux.articles_d3:
                            if article.code_d in livraisons.sommes[
                                    code_client][id_compte]:
                                if contenu_prix_lvr_xdj_tab[
                                        article.code_d] == "":
                                    contenu_prix_lvr_xdj_tab[
                                        article.code_d] = r'''
                                        \cline{2-4}
                                        \multicolumn{1}{c}{} & \multicolumn{3}{|c|}{
                                        ''' + Latex.echappe_caracteres(
                                            article.intitule_long) + r'''} \\
                                        \hline
                                        Compte & Montant & Rabais & Montant net \\
                                        \hline
                                        '''
                                dico_prest_client = {
                                    'intitule':
                                    intitule_compte,
                                    'cmj':
                                    Outils.format_2_dec(
                                        sco['sommes_cat_m'][article.code_d]),
                                    'crj':
                                    Outils.format_2_dec(
                                        sco['sommes_cat_r'][article.code_d]),
                                    'cj':
                                    Outils.format_2_dec(
                                        sco['tot_cat'][article.code_d])
                                }
                                contenu_prix_lvr_xdj_tab[
                                    article.code_d] += r'''
                                %(intitule)s & %(cmj)s & %(crj)s & %(cj)s \\
                                \hline
                                ''' % dico_prest_client

                    # ##

                    ann_pro_titre = "Récapitulatif du projet : " + intitule_compte
                    contenu_projets += Annexes.titre_annexe(
                        client, edition, generaux, reference, ann_pro_titre,
                        "Annexe facture")
                    contenu_projets += Annexes.section(client, generaux,
                                                       reference,
                                                       ann_pro_titre)

                    contenu_projets += TablesAnnexes.table_prix_ja(
                        sco, generaux)
                    contenu_projets += TablesAnnexes.table_prix_cae_jk(
                        code_client, id_compte, intitule_compte, sco,
                        acces.sommes, categories)
                    contenu_projets += TablesAnnexes.table_prix_lvr_jd(
                        code_client, id_compte, intitule_compte, sco,
                        livraisons.sommes, generaux)
                    if av_hc == "RABAIS":
                        contenu_projets += TablesAnnexes.table_prix_jdmu(
                            code_client, id_compte, intitule_compte, sco,
                            acces.sommes, machines, users)
                    contenu_projets += r'''\clearpage'''

                    ann_det_titre = "Annexe détaillée du projet : " + intitule_compte
                    contenu_details += Annexes.titre_annexe(
                        client, edition, generaux, reference, ann_det_titre,
                        "Annexe facture")
                    contenu_details += Annexes.section(client, generaux,
                                                       reference,
                                                       ann_det_titre)
                    contenu_details += TablesAnnexes.table_tps_cae_jkmu(
                        code_client, id_compte, intitule_compte, users,
                        machines, categories, acces)
                    if code_client in livraisons.sommes and id_compte in livraisons.sommes[
                            code_client]:
                        contenu_details += TablesAnnexes.table_qte_lvr_jdu(
                            code_client, id_compte, intitule_compte, generaux,
                            livraisons, users)
                    contenu_details += r'''\clearpage'''

                    # ## compte

            contenu_cae_xmu = TablesAnnexes.contenu_tps_m_cae_xmu(
                code_client, scl, acces.sommes, machines, users, comptes)

            suffixe = "_" + str(edition.annee) + "_" + Outils.mois_string(
                edition.mois) + "_"
            suffixe += str(edition.version) + "_" + code_client

            # ## Début des tableaux

            pdfs_annexes = {}

            if scl['somme_t'] > 0:
                if todo['Annexe-client'] != "NO":
                    contenu_annexe_client = Annexes.entete(edition)
                    contenu_annexe_client += Annexes.titre_annexe(
                        client, edition, generaux, reference,
                        "Récapitulatif pour le client", "Annexe facture")
                    contenu_annexe_client += Annexes.section(
                        client, generaux, reference,
                        "Récapitulatif pour le client")

                    contenu_annexe_client += TablesAnnexes.table_prix_xf(
                        scl, generaux, filtre, contenu_prix_xf)
                    contenu_annexe_client += TablesAnnexes.table_prix_xaj(
                        scl, generaux, contenu_prix_xaj)
                    if av_hc == "BONUS":
                        contenu_annexe_client += TablesAnnexes.table_points_xbmu(
                            code_client, scl, acces.sommes, machines, users)
                    contenu_annexe_client += TablesAnnexes.table_prix_xrmu(
                        code_client, scl, reservations.sommes, machines, users)
                    contenu_annexe_client += r'''\end{document}'''
                    Latex.creer_latex_pdf('Annexe-client' + suffixe,
                                          contenu_annexe_client)
                    pdfs_annexes['Annexe-client'] = [
                        'Annexe-client' + suffixe + ".pdf"
                    ]

                if not contenu_projets == "" and todo['Annexe-projets'] != "NO":
                    contenu_annexe_projets = Annexes.entete(edition)
                    contenu_annexe_projets += contenu_projets
                    contenu_annexe_projets += r'''\end{document}'''
                    Latex.creer_latex_pdf('Annexe-projets' + suffixe,
                                          contenu_annexe_projets)
                    pdfs_annexes['Annexe-projets'] = [
                        'Annexe-projets' + suffixe + ".pdf"
                    ]

                if todo['Annexe-détails'] != "NO":
                    contenu_details_2 = ""
                    if code_client in reservations.sommes or contenu_cae_xmu != "":
                        contenu_details_2 += Annexes.titre_annexe(
                            client, edition, generaux, reference,
                            "Annexe détaillée des pénalités de réservation",
                            "Annexe facture")
                        contenu_details_2 += Annexes.section(
                            client, generaux, reference,
                            "Annexe détaillée des pénalités de réservation")
                        contenu_details_2 += TablesAnnexes.table_tps_penares_xmu(
                            code_client, scl, acces.sommes,
                            reservations.sommes, machines, users)
                        contenu_details_2 += TablesAnnexes.table_tps_m_cae_xmu(
                            code_client, acces, contenu_cae_xmu)
                        contenu_details_2 += TablesAnnexes.table_tps_res_xmu(
                            code_client, reservations, machines, users)
                    if not contenu_details == "" or not contenu_details_2 == "":
                        contenu_annexe_details = Annexes.entete(edition)
                        contenu_annexe_details += contenu_details
                        contenu_annexe_details += contenu_details_2
                        contenu_annexe_details += r'''\end{document}'''
                        Latex.creer_latex_pdf('Annexe-détails' + suffixe,
                                              contenu_annexe_details)
                        pdfs_annexes['Annexe-détails'] = [
                            'Annexe-détails' + suffixe + ".pdf"
                        ]

                if docpdf is not None and todo['Annexe-pièces'] != "NO":
                    pdfs = docpdf.pdfs_pour_client(client, 'Annexe-pièces')
                    if pdfs is not None and len(pdfs) > 0:
                        nom_pdf = 'Annexe-pièces' + suffixe
                        pieces = [nom_pdf + '.pdf']
                        texte = ""
                        for pos, docs in sorted(pdfs.items()):
                            for doc in docs:
                                texte += str(pos) + r''' \hspace*{5cm} 
                                    ''' + Latex.echappe_caracteres(
                                    doc['nom']) + r'''
                                     \\ 
                                    '''
                                pieces.append(doc['chemin'])
                        contenu_annexe_pieces = Annexes.entete(edition)
                        contenu_annexe_pieces += Annexes.titre_annexe(
                            client, edition, generaux, reference,
                            "Documents contractuels et informatifs",
                            "Annexe facture")
                        contenu_annexe_pieces += Annexes.section(
                            client, generaux, reference,
                            "Documents contractuels et informatifs")
                        contenu_annexe_pieces += texte
                        contenu_annexe_pieces += r'''\end{document}'''
                        Latex.creer_latex_pdf(nom_pdf, contenu_annexe_pieces)
                        pdfs_annexes['Annexe-pièces'] = pieces

            if docpdf is not None and todo['Annexe-interne'] != "NO":
                pdfs = docpdf.pdfs_pour_client(client, 'Annexe-interne')
                if pdfs is not None and len(pdfs) > 0:
                    nom_pdf = 'Annexe-interne-anntemp'
                    pieces = [nom_pdf + '.pdf']
                    texte = ""
                    for pos, docs in sorted(pdfs.items()):
                        for doc in docs:
                            texte += str(pos) + r''' \hspace*{5cm} 
                                ''' + Latex.echappe_caracteres(
                                doc['nom']) + r'''
                                 \\ 
                                '''
                            pieces.append(doc['chemin'])
                    contenu_annexe_interne_a = Annexes.entete(edition)
                    contenu_annexe_interne_a += Annexes.titre_annexe(
                        client, edition, generaux, reference,
                        "Documents contractuels et informatifs",
                        "Annexe interne")
                    contenu_annexe_interne_a += Annexes.section(
                        client, generaux, reference,
                        "Annexe interne / Documents contractuels et informatifs"
                    )
                    contenu_annexe_interne_a += texte
                    contenu_annexe_interne_a += r'''\end{document}'''
                    Latex.creer_latex_pdf(nom_pdf, contenu_annexe_interne_a)
                    pdfs_annexes['Annexe-interne'] = pieces

            for donnee in paramannexe.donnees:
                if donnee['nom'] in pdfs_annexes:
                    if len(pdfs_annexes[donnee['nom']]) > 1:
                        Latex.concatenation_pdfs(donnee['nom'] + suffixe,
                                                 pdfs_annexes[donnee['nom']])
                    Latex.finaliser_pdf(donnee['nom'] + suffixe,
                                        donnee['chemin'])
                    if donnee['nom'] == 'Annexe-projets':
                        lignes = RecaProjet.creation_lignes(
                            edition, sommes.sommes_comptes[code_client],
                            client, generaux, acces, livraisons, comptes,
                            categories)
                        RecaProjet.recap(donnee['dossier_pdf'],
                                         donnee['nom'] + suffixe, lignes)

            files = [f for f in os.listdir('.') if os.path.isfile(f)]
            for f in files:
                if f.endswith('anntemp.pdf'):
                    os.unlink(f)
Example #30
0
    def table_prix_xrmu(code_client, scl, sommes_reservations, machines, users):
        """
        Prix XR/M/U - Table Client Récap Pénalités Réservations/Machine/user
        :param code_client: code du client concerné
        :param scl: sommes client calculées
        :param sommes_reservations: sommes des réservations importées
        :param machines: machines importées
        :param users: users importés
        :return: table au format latex
        """
        if scl['rm'] > 0:
            structure = r'''{|l|c|c|r|r|}'''
            legende = r'''Récapitulatif des pénalités de réservation'''

            contenu = r'''
                \cline{3-5}
                \multicolumn{2}{l|}{} & \multicolumn{1}{c|}{Pénalités} & \multicolumn{1}{c|}{PU} 
                & \multicolumn{1}{c|}{Montant} \\
                \cline{3-5}
                \multicolumn{2}{l|}{} & \multicolumn{1}{c|}{Durée} & \multicolumn{1}{c|}{CHF/h} 
                & \multicolumn{1}{c|}{CHF} \\
                \hline
                '''

            somme = sommes_reservations[code_client]

            machines_reservees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_reservees.items()):
                for nom_machine, id_machine in sorted(mics.items()):
                    scm = scl['res'][id_machine]
                    contenu_hp = ""
                    contenu_hc = ""
                    dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                    'duree_hp': Outils.format_heure(scm['tot_hp']),
                                    'pu_hp': Outils.format_2_dec(somme[id_machine]['pu_hp']),
                                    'montant_hp': Outils.format_2_dec(scm['mont_hp']),
                                    'duree_hc': Outils.format_heure(scm['tot_hc']),
                                    'pu_hc': Outils.format_2_dec(somme[id_machine]['pu_hc']),
                                    'montant_hc': Outils.format_2_dec(scm['mont_hc'])}
                    if scm['mont_hp'] > 0:
                        contenu_hp += r'''
                                %(machine)s & HP & %(duree_hp)s & %(pu_hp)s  & %(montant_hp)s \\
                                \hline
                                ''' % dico_machine

                    if scm['mont_hc'] > 0:
                        contenu_hc += r'''
                                %(machine)s & HC & %(duree_hc)s & %(pu_hc)s  & %(montant_hc)s \\
                                \hline
                                ''' % dico_machine

                    utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                    for nom, upi in sorted(utilisateurs.items()):
                        for prenom, ids in sorted(upi.items()):
                            for id_user in sorted(ids):
                                smu = scm['users'][id_user]
                                dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                             'duree_hp': Outils.format_heure(smu['tot_hp']),
                                             'duree_hc': Outils.format_heure(smu['tot_hc'])}
                                if scm['mont_hp'] > 0 and smu['tot_hp'] > 0:
                                    contenu_hp += r'''
                                            \hspace{5mm} %(user)s & HP & %(duree_hp)s \hspace{5mm} & & \\
                                            \hline
                                            ''' % dico_user

                                if scm['mont_hc'] > 0 and smu['tot_hc'] > 0:
                                    contenu_hc += r'''
                                            \hspace{5mm} %(user)s & HC & %(duree_hc)s \hspace{5mm} & & \\
                                            \hline
                                            ''' % dico_user
                    contenu += contenu_hp
                    contenu += contenu_hc

            dico = {'penalite_d': Outils.format_2_dec(scl['rm_d']),
                    'penalite': Outils.format_2_dec(scl['rm']),
                    'rabais': Outils.format_2_dec(scl['rr']),
                    'total': Outils.format_2_dec(scl['r'])}

            contenu += r'''
                \multicolumn{4}{|r|}{Arrondi} & %(penalite_d)s \\
                \hline
                \multicolumn{4}{|r|}{Total} & %(penalite)s \\
                \hline
                \multicolumn{4}{|r|}{Rabais} & %(rabais)s \\
                \hline
                \multicolumn{4}{|r|}{\textbf{Total à payer}} & %(total)s \\
                \hline
                ''' % dico

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #31
0
    def table_tps_res_xmu(code_client, reservations, machines, users):
        """
        Tps RES X/M/U - Table Client Détail Temps Réservations/Machine/User
        :param code_client: code du client concerné
        :param reservations: réservations importées
        :param machines: machines importées
        :param users: users importés
        :return: table au format latex
        """

        if code_client in reservations.sommes:
            structure = r'''{|c|c|c|c|c|}'''
            legende = r'''Détail des réservations machines par utilisateur'''
            contenu = r'''
                \cline{4-5}
                \multicolumn{3}{c}{} & \multicolumn{2}{|c|}{Durée réservée} \\
                \cline{4-5}
                \multicolumn{3}{c|}{} & HP & HC \\
                \hline
                '''

            somme = reservations.sommes[code_client]

            machines_reservees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_reservees.items()):
                for nom_machine, id_machine in sorted(mics.items()):

                    dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                    'hp': Outils.format_heure(somme[id_machine]['res_hp']),
                                    'hc': Outils.format_heure(somme[id_machine]['res_hc'])}
                    contenu += r'''
                            \multicolumn{3}{|l|}{\textbf{%(machine)s}} & \hspace{5mm} %(hp)s &
                            \hspace{5mm} %(hc)s \\
                            \hline
                            ''' % dico_machine

                    utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                    for nom, upi in sorted(utilisateurs.items()):
                        for prenom, ids in sorted(upi.items()):
                            for id_user in sorted(ids):
                                smu = somme[id_machine]['users'][id_user]
                                dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                             'hp': Outils.format_heure(smu['res_hp']),
                                             'hc': Outils.format_heure(smu['res_hc'])}
                                contenu += r'''
                                        \multicolumn{3}{|l|}{\hspace{5mm} %(user)s} & %(hp)s & %(hc)s \\
                                        \hline
                                        ''' % dico_user
                                for p1 in smu['data']:
                                    res = reservations.donnees[p1]
                                    login = Latex.echappe_caracteres(res['date_debut']).split()
                                    temps = login[0].split('-')
                                    date = temps[0]
                                    for p2 in range(1, len(temps)):
                                        date = temps[p2] + '.' + date
                                    if len(login) > 1:
                                        heure = login[1]
                                    else:
                                        heure = ""

                                    sup = ""
                                    if res['date_suppression'] != "":
                                        sup = "Supprimé le : " + res['date_suppression']
                                    dico_pos = {'date': date, 'heure': heure, 'sup': Latex.echappe_caracteres(sup),
                                                'hp': Outils.format_heure(res['duree_fact_hp']),
                                                'hc': Outils.format_heure(res['duree_fact_hc'])}
                                    contenu += r'''
                                                \hspace{10mm} %(date)s & %(heure)s & %(sup)s & %(hp)s \hspace{5mm} &
                                                 %(hc)s \hspace{5mm} \\
                                                \hline
                                            ''' % dico_pos

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #32
0
    # print(bullpen)
    # for table in standings:
    #     print(table)
    # print(ahistory)
    # print(hhistory)
    # print(bat_df)
    # print(pit_df)
    # print(era_df)
    # print(rel_df)
    # print(hr_df)
    # print(elo)
    # print(pitcher_history)
    # print(last_week_bullpen)
    # print(series_table)

    l = Latex("{}-{}.tex".format(args.team, args.date))
    l.header()
    l.title(summary)

    l.start_table('lcclrrrrrrrrr')
    l.add_headers(['Team', 'R/L', '#', 'Name', 'war', 'w', 'l', 'era', 'ip', 'k/9', 'bb/9', 'hr/9', 'gb%'])
    l.add_rows(summary['pit_df'], ['', '', '{:.0f}', '', '{:.1f}', '{:.0f}', '{:.0f}', '{:.2f}', '{:.1f}', '{:.2f}', '{:.2f}', '{:.2f}', '{:.2f}'])
    l.end_table()

    l.add_space('.5cm')
    l.start_multicol(2)
    l.add_text(summary['preview'])
    l.end_multicol()

    l.add_section("{} Lineup".format(away))
    l.start_table('lcclrcrrrrr')
Example #33
0
    def ligne_res(res):
        """
        création d'une ligne de tableau pour une réservation
        :param res: réservation particulière
        :return: ligne de tableau latex
        """
        login = Latex.echappe_caracteres(res['date_debut']).split()
        temps = login[0].split('-')
        date = temps[0]
        for pos in range(1, len(temps)):
            date = temps[pos] + '.' + date
        if len(login) > 1:
            heure = login[1]
        else:
            heure = ""

        dico = {'date': date, 'heure': heure,
                'machine': Latex.echappe_caracteres(res['nom_machine']),
                'reserve': Latex.echappe_caracteres(res['date_reservation']),
                'supprime': Latex.echappe_caracteres(res['date_suppression']),
                'shp': Outils.format_heure(res['duree_hp']), 'shc': Outils.format_heure(res['duree_hc']),
                'fhp': Outils.format_heure(res['duree_fact_hp']), 'fhc': Outils.format_heure(res['duree_fact_hc'])}

        nb = 0
        if res['duree_fact_hp'] > 0:
            nb += 1

        if res['duree_fact_hc'] > 0:
            nb += 1

        if nb == 0:
            return ""

        if res['date_suppression'] != "":
            nb += 1

        if nb == 1:
            ligne = r'''%(date)s & %(heure)s''' % dico
        else:
            ligne = r'''\multirow{''' + str(nb) + r'''}{*}{%(date)s} & \multirow{''' % dico
            ligne += str(nb) + r'''}{*}{%(heure)s}''' % dico

        nb = 0
        if res['duree_fact_hp'] > 0:
            ligne += r''' & %(machine)s & HP & %(shp)s & %(fhp)s\\
                ''' % dico
            nb += 1

        if res['duree_fact_hc'] > 0:
            if nb > 0:
                ligne += r'''& &'''
            else:
                ligne += r'''& %(machine)s ''' % dico
            ligne += r''' & HC & %(shc)s & %(fhc)s \\
                ''' % dico

        if res['date_suppression'] != "":
            ligne += r'''\cline{3-6}
                &  & \multicolumn{4}{l|}{Supprimé le : %(supprime)s} \\
                ''' % dico

        ligne += r'''\hline
            '''

        return ligne
Example #34
0
    def table_tps_cae_jkmu(code_client, id_compte, intitule_compte, users, machines, categories, acces):
        """
        Tps CAE J/K/M/U - Table Compte Détail Temps CAE/Catégorie Machine/Machine/User
        :param code_client: code du client concerné
        :param id_compte: id du compte concerné
        :param intitule_compte: intitulé du compte concerné
        :param users: users importés
        :param machines: machines importées
        :param categories: catégories importées
        :param acces: accès importés
        :return: table au format latex
        """

        if code_client in acces.sommes and id_compte in acces.sommes[code_client]['comptes']:
            structure = r'''{|l|l|l|c|c|c|}'''
            legende = r'''Détails des utilisations machines'''

            contenu = r'''
                \hline
                \multicolumn{3}{|l|}{\multirow{2}{*}{\scriptsize{\textbf{''' + intitule_compte + r'''}}}}
                & \multicolumn{2}{c|}{Machine} & Main d'oeuvre \\
                \cline{4-6}
                \multicolumn{3}{|l|}{} & HP & HC &  \\
                \hline
                '''

            somme = acces.sommes[code_client]['comptes'][id_compte]
            som_cat = acces.sommes[code_client]['categories'][id_compte]['machine']

            machines_utilisees = Outils.machines_in_somme(somme, machines)

            for id_categorie, mics in sorted(machines_utilisees.items()):
                dico_cat = {'hp': Outils.format_heure(som_cat[id_categorie]['duree_hp']),
                            'hc': Outils.format_heure(som_cat[id_categorie]['duree_hc']),
                            'mo': Outils.format_heure(som_cat[id_categorie]['mo'])}
                contenu += r'''
                    \multicolumn{3}{|l|}
                    {\textbf{''' + Latex.echappe_caracteres(categories.donnees[id_categorie]['intitule']) + r'''}} &
                     \hspace{5mm} %(hp)s & \hspace{5mm} %(hc)s &
                     \hspace{5mm} %(mo)s \\
                    \hline''' % dico_cat

                for nom_machine, id_machine in sorted(mics.items()):

                    dico_machine = {'machine': Latex.echappe_caracteres(nom_machine),
                                    'hp': Outils.format_heure(somme[id_machine]['duree_hp']),
                                    'hc': Outils.format_heure(somme[id_machine]['duree_hc']),
                                    'mo': Outils.format_heure(somme[id_machine]['mo'])}
                    contenu += r'''
                        \multicolumn{3}{|l|}{\hspace{2mm} \textbf{%(machine)s}} & \hspace{3mm} %(hp)s & 
                        \hspace{3mm} %(hc)s & \hspace{3mm} %(mo)s \\
                        \hline
                        ''' % dico_machine

                    utilisateurs = Outils.utilisateurs_in_somme(somme[id_machine]['users'], users)

                    for nom, upi in sorted(utilisateurs.items()):
                        for prenom, ids in sorted(upi.items()):
                            for id_user in sorted(ids):
                                smu = somme[id_machine]['users'][id_user]
                                dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                             'hp': Outils.format_heure(smu['duree_hp']),
                                             'hc': Outils.format_heure(smu['duree_hc']),
                                             'mo': Outils.format_heure(smu['mo'])}
                                contenu += r'''
                                    \multicolumn{3}{|l|}{\hspace{5mm} %(user)s} & %(hp)s & %(hc)s & %(mo)s \\
                                    \hline
                                ''' % dico_user
                                for p1 in smu['data']:
                                    cae = acces.donnees[p1]
                                    login = Latex.echappe_caracteres(cae['date_login']).split()
                                    temps = login[0].split('-')
                                    date = temps[0]
                                    for p2 in range(1, len(temps)):
                                        date = temps[p2] + '.' + date
                                    if len(login) > 1:
                                        heure = login[1]
                                    else:
                                        heure = ""

                                    rem = ""
                                    if id_user != cae['id_op']:
                                        op = users.donnees[cae['id_op']]
                                        rem += "op : " + op['nom'] + " " + op['prenom']
                                    if cae['remarque_op'] != "":
                                        if rem != "":
                                            rem += "; "
                                        rem += "rem op : " + cae['remarque_op']
                                    if cae['remarque_staff'] != "":
                                        if rem != "":
                                            rem += "; "
                                        rem += "rem CMi : " + cae['remarque_staff']

                                    dico_pos = {'date': date, 'heure': heure,
                                                'rem': Latex.echappe_caracteres(rem),
                                                'hp': Outils.format_heure(cae['duree_machine_hp']),
                                                'hc': Outils.format_heure(cae['duree_machine_hc']),
                                                'mo': Outils.format_heure(cae['duree_operateur'])}
                                    contenu += r'''
                                        \hspace{10mm} %(date)s & %(heure)s & \parbox{5cm}{%(rem)s}
                                        & %(hp)s \hspace{5mm} & %(hc)s \hspace{5mm} & %(mo)s \hspace{5mm} \\
                                        \hline
                                    ''' % dico_pos

            return Latex.long_tableau(contenu, structure, legende)
        else:
            return ""
Example #35
0
def calculate(config_str, internal_momenta):
    """ Calculate expression for configuration. """

    latex = Latex()

    ################################################
    ########     CONSTRUCT AMPLITUDE      ##########
    ################################################

    try:
        internal_momenta = internal_momenta.split()
        config, amp = make_amplitude(config_str, internal_momenta)
    except:
        raise ParseException("Error while parsing.")

    # Render
    latex.add_text("\\section*{Raw amplitude}")
    amp.latex_add(latex)
    if RENDER_ALL:
        latex.render()

    ################################################
    ########   SIMPLIFY NUMERATOR         ##########
    ################################################

    amp.numer = amp.numer.expand()

    # Render
    latex.add_text("\\section*{Simplified numerator}")
    amp.latex_add(latex)
    if RENDER_ALL:
        latex.render()

    ################################################
    ########      FEYNMAN'S TRICK         ##########
    ################################################

    denom_ = []
    for arg in amp.denom.args:
        if type(arg) == sy.Pow:
            base, power = arg.args
            for _ in range(power):
                denom_.append(base)
        else:
            denom_.append(arg)

    n = len(denom_)
    amp.const *= gamma(n)

    zs = [sy.Symbol("{{ z_{{ {0} }} }}".format(i + 1)) for i in range(n)]
    amp.denom = sum([d * z for (d, z) in zip(denom_, zs)]).expand()**n
    for i, z in enumerate(zs):
        a = 0
        b = 1 - sum(zs[:i])
        amp.integrals_zs.append((z, a, b))

    # Render
    latex.add_text("\\section*{Feynman parameterization}")
    latex.add_text("Here, we perform the following expansion:")
    latex.add_text("""$$
    \\frac{1}{A_1} \\cdots \\frac{1}{A_n} = (n-1)! \\int\\limits_0^1 dz_1
                                                   \\int\\limits_0^{1-z_1} dz_2
                                                   \\cdots
                                                   \\int\\limits_0^{1-z_1-\\cdots-z_{n-1}} dz_n
                                                   \\frac{1}{(z_1 A_1 + \\cdots + z_n A_n)^n}
    $$""")
    latex.add_text(
        "We use this form because a single denominator raised to a power can be simplified with the Golden Integral."
    )
    amp.latex_add(latex)
    if RENDER_ALL:
        latex.render()

    ################################################
    ######## SPLIT NUMERATOR INTO TERMS   ##########
    ################################################
    amps = []
    for numer_ in sy.Add.make_args(amp.numer):
        amp_ = amp.copy()
        amp_.numer = numer_
        amps.append(amp_)

    # Render
    latex.add_text("\\section*{Expanded numerator}")
    latex.add_text(
        "We split the numerator into additive terms, to process individually.  The following is a list of such terms:"
    )
    for amp_ in amps:
        amp_.latex_add(latex)
    if RENDER_ALL:
        latex.render()

    ################################################
    ########     EVAL. INTERNAL MOMENTA   ##########
    ################################################

    # TODO evaluate internal momenta integrals
    # At this point we stop with numer and denom and combine them into
    # one expression, `inner`, which is a sum of fractions.
    # TODO update this comment

    # Render an explanation
    latex.add_text("\\section*{{Golden Integral}}")
    latex.add_text("We resolve internal momentas with this transformation:")
    latex.add_text("""
    $$\\int \\frac{d^d q}{(2 \pi)^d} \\frac{(q^2)^a}{(q^2 + D)^b} = i \\frac{\\Gamma (b-a-\\frac{1}{2}d) \\Gamma (a + \\frac{1}{2} d)}{(4 \\pi)^{d/2} \\Gamma(b) \\Gamma(\\frac{1}{2}d)} D^{-(b-a-d/2)}$$
    """)
    latex.add_text(
        "After this section, all internal momenta should disappear.  We will now resolve each term in a queue.  Each term may produce additional terms, which are pushed to the back of the queue and resolved later."
    )

    integrated_amps = []

    #for i, amp_ in enumerate(amps):
    i = 0
    while len(amps) > 0:
        # Pop off one amplitude
        amp_ = amps[0]
        amps = amps[1:]
        i += 1

        latex.add_text(
            "\\section*{{Evaluating internal momenta in this term ({0} terms left)}}"
            .format(len(amps)))
        amp_.latex_add(latex)
        if RENDER_ALL:
            latex.render()

        # Find an internal momenta
        if len(amp_.integrals_internal) > 0:
            (k, _, _) = amp_.integrals_internal[0]
            latex.add_text("Integrating over ${0}$\\\\".format(k))

            # TODO cleanup weird namespacing
            k_down_dummy = Momentum(k, "DUMMY", 0)
            k_up_dummy = Momentum(k, "DUMMY", 1)
            k2_dummy = k_down_dummy * k_up_dummy

            # Decompose denominator
            # denom = denom_nopow ^ b
            denom_nopow, b = amp_.denom.args[0], amp_.denom.args[1]

            # Completing the square
            # Denominator is always quadratic in momenta
            G = denom_nopow  # aliasing for convenience

            latex.add_text("Completing the square\\")

            A = G.collect(k2_dummy).coeff(k2_dummy)
            G = sy.simplify(G - A * k2_dummy)
            B_up = G.collect(k_down_dummy).coeff(k_down_dummy)
            B_down = G.collect(k_up_dummy).coeff(k_up_dummy)
            B = B_up + Amplitude.flip_variant(B_down)
            G = sy.simplify(G - B_up * k_down_dummy - B_down * k_up_dummy)
            C = G
            D = -(B_up * Amplitude.flip_variant(B_up)) / (4 * A) + C

            latex.add("A = " + latex.get(A))
            latex.add("B = " + latex.get(B))
            latex.add("C = " + latex.get(C))
            """ 
                The denominator is in the form:

                    A k^2 + Bk + C

                We define a new variable, q, such that

                    q = A^(1/2) k + B / (2 A^(1/2))

                and replace k:

                    k = q / A^(1/2) - B / (2A)
                    d^d k = (1 / A^(1/2)) d^d q

                The substitution k -> q yields:

                    A k^2 + Bk + C |-> q^2 + D

                where we define D = C - B^2 / (4A)
            """

            # Prepare to replace numerator
            k_name = k
            q_name = "q_{0}".format(len(amp_.qs) + 1)  # TODO sloppy af
            amp_.qs.append(q_name)

            q_up = Momentum(q_name, "DUMMY", 1)
            q_down = Momentum(q_name, "DUMMY", 0)

            any_name = sy.Wild("a")
            any_ind = sy.Wild("b")
            any_variant = sy.Wild("c")

            any_B_up = B_up.replace(Momentum(any_name, "DUMMY", any_variant),
                                    Momentum(any_name, any_ind, any_variant))
            any_B_down = Amplitude.flip_variant(any_B_up)

            # Actually replace numerator
            amp_.numer = amp_.numer.replace(
                Momentum(k_name, any_ind, 1),
                Momentum(q_name, any_ind, 1) / (A**0.5) - any_B_up / (2 * A))

            amp_.numer = amp_.numer.replace(
                Momentum(k_name, any_ind, 0),
                Momentum(q_name, any_ind, 0) / (A**0.5) - any_B_down / (2 * A))

            amp_.numer = sy.simplify(amp_.numer)

            # Replace denominator
            amp_.denom = (q_down * q_up + D)**b

            # Replace integral
            # TODO replace integral
            amp_.integrals_internal[0] = (q_name, _, _)
            amp_.numer /= A**0.5

            latex.add_text("After ${0} \\to {1}$ substitutions".format(
                k_name, q_name))
            amp_.latex_add(latex)
            if RENDER_ALL:
                latex.render()

            # Expand the numerator into different amplitudes and multiply them
            # back in the end
            amps__ = []
            for numer in sy.Add.make_args(amp_.numer.expand()):
                new_amp = amp_.copy()
                new_amp.numer = numer
                amps__.append(new_amp)

            # Render
            latex.add_text(
                "\\section*{{Expanding numerator into {0} term(s)}}".format(
                    len(amps__)))
            for amp__ in amps__:
                amp__.latex_add(latex)
            if RENDER_ALL:
                latex.render()

            # Finish q_name integration for each amplitude separately
            for amp__ in amps__:
                prod = sy.Mul.make_args(amp__.numer)

                # Get k-vectors
                # TODO Figure out a way to collect qs nicely
                qs = [
                    q for q in prod
                    if isinstance(q, Momentum) and q.args[0].name == q_name
                ]

                latex.add_text("\\subsection*{Integrating this term:}")
                amp__.latex_add(latex)
                latex.add_text(
                    "Found {0} q-vector terms in the numerator.\\\\".format(
                        len(qs)))

                # Simplify q vectors

                # Ward identity for odd tensors
                if len(qs) % 2 == 1:
                    # TODO integral evaluates to zero
                    latex.add_text("Term vanishes due to Ward identity\\\\")
                    amp__.const = 0
                    continue

                if len(qs) > 0:
                    # TODO convert higher-order even tensor integral to
                    #      scalar integral
                    pass
                else:
                    # TODO Assume a = 0 for now
                    # This is obviously wrong in general but will be easier
                    # to fix with a good test case
                    a = 0

                    # Golden integral
                    #c, a = term.as_coeff_exponent(sy.Symbol(k2))
                    c_ = sy.I * gamma(b - a -
                                      (4 - EPS) / 2) * gamma(a + (4 + EPS) / 2)
                    c_ /= gamma(b)
                    c_ /= (4 * sy.pi)**2
                    # Part of the Golden integral d^q factor
                    c_ *= (2 * sy.pi)**4
                    amp__.const *= c_

                    amp__.denom = D**(b - a - 2
                                      )  # TODO generalize to d-dimensions
                    # with 2 -> D / 2

                    # Add to amps if nonzero
                    amps.append(amp__)

                    # Remove internal integral
                    amp__.integrals_internal = amp__.integrals_internal[1:]

                    # Render
                    latex.add_text("Apply golden integral")
                    amp__.latex_add(latex)
                if RENDER_ALL:
                    latex.render()
        else:
            integrated_amps.append(amp_)

        ## Compress inners by term
        #inners_dict = {}
        #for (c_, expr_) in amp.inners:
        #    if expr_ not in inners_dict:
        #        inners_dict[expr_] = 0
        #    inners_dict[expr_] += c_
        #amp.inners = [(v, k) for (k, v) in inners_dict.items()]
        #amp.latex_add2(latex)

    amps = integrated_amps

    latex.add_text("\\section*{Final amplitudes after momenta integration}")
    for amp_ in amps:
        amp_.latex_add(latex)

    if RENDER_ALL:
        latex.render()

    ##########################################
    ########  CUTOFF INTEGRATIONS   ##########
    ##########################################
    latex.add_text("\\section*{Integrating cutoffs}")
    latex.add_text(
        "Here we integrate all $t$-variables, which represent the upper and lower cutoffs."
    )
    uv = sy.Symbol(config["Lamb"])

    integrated_amps = []

    for amp_ in amps:
        latex.add_text("\\subsection*{Integrating this term}")
        amp_.latex_add(latex)

        expr_ = 1 / amp_.denom

        latex.add_text("Denominator only")
        latex.add(latex.get(expr_))
        if RENDER_ALL:
            latex.render()

        # Integrate cutoffs
        for (t, a, b) in amp_.integrals_cutoffs:
            # Integrate w.r.t. cutoff
            expr_ = sy.integrate(expr_, (t, a, b))

            latex.add_text("Integrating wrt ${0}$...".format(t))
            latex.add(latex.get(expr_))
            if RENDER_ALL:
                latex.render()

            # Collecting highest order term
            old_expr = expr_
            while True:
                old_expr = expr_

                expr_ = sy.expand_log(expr_, force=True)
                expr_ = get_highest_log_term(expr_, uv)
                expr_ = sy.simplify(expr_)

                if old_expr == expr_:
                    # No more changes
                    break

            latex.add_text("Keeping only highest order term...")
            latex.add(latex.get(expr_))
            if RENDER_ALL:
                latex.render()

            amp_.numer *= expr_
            amp_.denom = 1

        amp_.integrals_cutoffs = []
        integrated_amps.append(amp_)

    amps = integrated_amps

    ######################################
    ########   Z INTEGRATIONS   ##########
    ######################################
    latex.add_text("\\section*{Integrating $z$-variables}")
    latex.add_text(
        "Here we integrate all $z$-variables, the Feynman parameters.")

    integrated_amps = []

    for amp_ in amps:
        latex.add_text("\\subsection*{Integrating this term}")
        amp_.latex_add(latex)

        # Integrate cutoffs
        expr_ = amp_.numer

        for (z, a, b) in amp_.integrals_zs[::-1]:
            # Integrate w.r.t. cutoff
            # Rationalize decimal powers first, or sympy breaks
            expr_ = sy.nsimplify(expr_, tolerance=0.001, rational=True)
            expr_ = sy.integrate(expr_, (z, a, b))

            latex.add_text("Integrating wrt ${0}$...".format(z))
            latex.add(latex.get(expr_))
            if RENDER_ALL:
                latex.render()

        amp_.numer = expr_
        amp_.integrals_zs = []

        integrated_amps.append(amp_)

    amps = integrated_amps

    latex.add_text(
        "\\section*{Final amplitudes after $z$-variable integration}")
    for amp_ in amps:
        amp_.latex_add(latex)

    if RENDER_ALL:
        latex.render()

    ################################################
    ########  EVALUATE SPINS AND GAMMAS   ##########
    ################################################

    latex.add_text("\\section*{Evaluating spins and gamma matrices}")
    #latex.add_text("TODO jk do it yourself you slags, here's the sum, have fun.  Don't forget to take traces/multiply by -1 for internal fermion loops.")
    latex.add_text("TODO.  Here's the sum for now:")

    latex.add("\\; + \\;".join([amp_.get_latex(latex) for amp_ in amps]))

    if RENDER_ALL:
        latex.render()

    ################################################
    ########            RENDER            ##########
    ################################################

    #amp.latex_add2(latex)
    latex.render()

    return "\\; + \\;".join([amp_.get_latex(latex) for amp_ in amps])
Example #36
0
    def contenu_client(code_client, consolidation, subgeneraux, subedition):
        """
        création du contenu de l'annexe pour un client
        :param code_client: code du client pour l'annexe
        :param consolidation: classe de consolidation des données des bilans
        :param subgeneraux: paramètres généraux
        :param subedition: paramètres d'édition
        """

        contenu = ""

        client = consolidation.clients[code_client]
        reference = "SUBS" + str(subedition.annee_fin_general)[2:] + \
                    Outils.mois_string(subedition.mois_fin_general) + "." + code_client

        debut = Outils.mois_nom(subedition.mois_debut_general) + " " + str(
            subedition.annee_debut_general)
        fin = Outils.mois_nom(subedition.mois_fin_general) + " " + str(
            subedition.annee_fin_general)
        dic_section = {
            'code': code_client,
            'code_sap': Latex.echappe_caracteres(client['sap']),
            'nom': Latex.echappe_caracteres(client['abrev']),
            'ref': reference,
            'date_debut': debut,
            'date_fin': fin
        }

        contenu += r'''
            \fakesection{%(ref)s \hspace*{4cm} Client %(code)s - %(code_sap)s - %(nom)s - %(date_debut)s - %(date_fin)s}
            {}
            ''' % dic_section

        contenu_recap_compte = ""
        contenu_detail_compte = ""
        inc_4 = 0
        taille_d3 = len(subgeneraux.articles_d3)

        numbers = {}
        for id_compte, compte in client['comptes'].items():
            numbers[id_compte] = compte['num_compte']

        for id_compte, num_compte in sorted(numbers.items(),
                                            key=lambda x: x[1]):
            compte = client['comptes'][id_compte]

            # ## COMPTE

            # ## ligne 3
            if compte['subs'] > 0:
                dico_recap_compte = {
                    'numero': num_compte,
                    'intitule': Latex.echappe_caracteres(compte['intitule']),
                    'code': Latex.echappe_caracteres(compte['id_sub']),
                    'type_s': Latex.echappe_caracteres(compte['type_s']),
                    'type_p': Latex.echappe_caracteres(compte['type_p']),
                    'montant': Outils.format_2_dec(compte['subs'])
                }
                contenu_recap_compte += r'''
                    %(numero)s & %(intitule)s & %(code)s & %(type_s)s & %(type_p)s & %(montant)s \\
                    \hline
                      ''' % dico_recap_compte

            # ## partie 4

            if compte['subs'] > 0:
                dico_detail_compte = {
                    'taille': (4 + taille_d3),
                    'numero': num_compte,
                    'intitule': Latex.echappe_caracteres(compte['intitule']),
                    'type': Latex.echappe_caracteres(compte['type'])
                }
                if inc_4 > 0:
                    contenu_detail_compte += r'''
                        \multicolumn{%(taille)s}{c}{} \\ \noalign{\penalty-5000}
                          ''' % dico_detail_compte
                else:
                    inc_4 = 1
                contenu_detail_compte += r'''
                    \hline
                    \multicolumn{%(taille)s}{|c|}{%(numero)s - %(intitule)s - %(type)s} \\*
                    \hline
                    Année & Mois & \multicolumn{1}{c|}{Coûts Procédés} 
                      ''' % dico_detail_compte

                for article in subgeneraux.articles_d3:
                    contenu_detail_compte += r''' & \multicolumn{1}{c|}{
                        ''' + Latex.echappe_caracteres(
                        article.intitule_court) + r'''}'''

                for a, annee in sorted(compte['annees'].items()):
                    for m, mois in sorted(annee['mois'].items()):
                        dico = {
                            'annee': a,
                            'mois': m,
                            'mj': Outils.format_2_dec(mois['mj'])
                        }
                        contenu_detail_compte += r'''\\*
                            \hline
                            %(annee)s & %(mois)s & %(mj)s
                            ''' % dico
                        for d3 in subgeneraux.codes_d3():
                            contenu_detail_compte += r''' & ''' + Outils.format_2_dec(
                                mois[d3 + 'j'])

                dico_detail_compte = {
                    'm_mois': compte['m_mois'],
                    'm_compte': compte['m_compte'],
                    'mt': Outils.format_2_dec(compte['mt']),
                    'mt_p': Outils.format_2_dec(compte['mt_p']),
                    's-mt': Outils.format_2_dec(compte['s-mt'])
                }

                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Total période} & %(mt)s
                    ''' % dico_detail_compte
                for d3 in subgeneraux.codes_d3():
                    contenu_detail_compte += r''' &
                    ''' + Outils.format_2_dec(compte[d3 + 't'])

                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Plafond par mois} & %(m_mois)s
                    ''' % dico_detail_compte
                for d3 in subgeneraux.codes_d3():
                    contenu_detail_compte += r''' &
                    ''' + Outils.format_2_dec(compte[d3 + '_mois'])

                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Total des montants plafonnés} & %(mt_p)s
                    ''' % dico_detail_compte
                for d3 in subgeneraux.codes_d3():
                    contenu_detail_compte += r''' &
                    ''' + Outils.format_2_dec(compte[d3 + 't_p'])

                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Plafond par compte} & %(m_compte)s
                    ''' % dico_detail_compte
                for d3 in subgeneraux.codes_d3():
                    contenu_detail_compte += r''' &
                    ''' + Outils.format_2_dec(compte[d3 + '_compte'])

                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Subsides} & %(s-mt)s
                    ''' % dico_detail_compte
                for d3 in subgeneraux.codes_d3():
                    contenu_detail_compte += r''' &
                    ''' + Outils.format_2_dec(compte['s-' + d3 + 't'])

                dico_detail_compte = {
                    'taille': (2 + len(subgeneraux.articles_d3)),
                    'subs': Outils.format_2_dec(compte['subs'])
                }
                contenu_detail_compte += r'''\\*
                    \hline
                    \multicolumn{2}{|l|}{Total subsides} & \multicolumn{%(taille)s}{r|}{%(subs)s} \\ 
                    \hline
                    ''' % dico_detail_compte

        # ## 1

        structure_total = r'''{|c|l|l|r|}'''
        contenu_total = r'''
            \hline
            Code OP & \multicolumn{1}{c|}{Poste} & \multicolumn{1}{c|}{Prestation} & \multicolumn{1}{c|}{Montant} \\
            \hline
            '''
        base = client['nature'] + str(subedition.annee_fin_general)[2:] + \
               Outils.mois_string(subedition.mois_fin_general)
        if client['bonus'] > 0:
            poste = Latex.echappe_caracteres(
                subgeneraux.article_t_indice('2').texte_t_long)
            prestation = Latex.echappe_caracteres(
                subgeneraux.articles[0].intitule_long)
            op = subgeneraux.article_t_indice(
                '2').code_t + base + subgeneraux.articles[0].code_d
            dico = {
                'op': op,
                'poste': poste,
                'prestation': prestation,
                'montant': Outils.format_2_dec(client['bonus'])
            }
            contenu_total += r'''
                %(op)s & %(poste)s & %(prestation)s & %(montant)s \\
                \hline
                ''' % dico
        for t3, client_t3 in sorted(client['codes'].items()):
            poste = subgeneraux.article_t(t3).texte_t_long
            if client_t3['sm'] > 0:
                prestation = Latex.echappe_caracteres(
                    subgeneraux.articles[0].intitule_long)
                op = t3 + base + subgeneraux.articles[0].code_d
                dico = {
                    'op': op,
                    'poste': poste,
                    'prestation': prestation,
                    'montant': Outils.format_2_dec(client_t3['sm'])
                }
                contenu_total += r'''
                    %(op)s & %(poste)s & %(prestation)s & %(montant)s \\
                    \hline
                    ''' % dico
            for article in subgeneraux.articles_d3:
                if client_t3['s' + article.code_d] > 0:
                    prestation = Latex.echappe_caracteres(
                        article.intitule_long)
                    op = t3 + base + article.code_d
                    dico = {
                        'op':
                        op,
                        'poste':
                        poste,
                        'prestation':
                        prestation,
                        'montant':
                        Outils.format_2_dec(client_t3['s' + article.code_d])
                    }
                    contenu_total += r'''
                        %(op)s & %(poste)s & %(prestation)s & %(montant)s \\
                        \hline
                        ''' % dico
        total = Outils.format_2_dec(client['subs'] + client['bonus'])
        contenu_total += r'''
            \multicolumn{3}{|r|}{TOTAL} & ''' + total + r''' \\
            \hline
            '''

        legende_total = r'''Table 1 - Récapitulatif des bonus et subsides'''

        contenu += Latex.tableau(contenu_total, structure_total, legende_total)

        # ## 2

        if client['bonus'] > 0:
            structure_bonus = r'''{|c|c|l|r|}'''
            contenu_bonus = r'''
                \hline
                Année & Mois & \multicolumn{1}{c|}{Code} & \multicolumn{1}{c|}{Montant} \\
                \hline
                '''

            for a, annee in sorted(client['annees'].items()):
                for m, mois in sorted(annee['mois'].items()):
                    code = Latex.echappe_caracteres(
                        subgeneraux.article_t_indice('2').texte_t_court)
                    dico = {
                        'annee': a,
                        'mois': m,
                        'bj': mois['bj'],
                        'code': code
                    }
                    contenu_bonus += r'''
                        %(annee)s & %(mois)s & %(code)s & %(bj)s \\
                        \hline
                        ''' % dico

            contenu_bonus += r'''
                \multicolumn{3}{|r|}{TOTAL} & ''' + str(
                client['bonus']) + r''' \\
                \hline
                '''

            legende_bonus = r'''Table 2 - Bonus d'utilisation en heures creuses'''

            contenu += Latex.tableau(contenu_bonus, structure_bonus,
                                     legende_bonus)
        else:
            contenu += Latex.tableau_vide(
                r'''Table 2 vide : Pas de bonus d'utilisation en heures creuses'''
            )

        if client['subs'] > 0:

            # ## 3

            structure_recap = r'''{|r|l|l|l|l|r|}'''
            contenu_recap = r'''
                \hline
                \multicolumn{1}{|c|}{N. compte} & \multicolumn{1}{c|}{Intitulé compte} & \multicolumn{1}{c|}{Code} & 
                \multicolumn{1}{c|}{Type Subsides} & \multicolumn{1}{c|}{Type projet} & \multicolumn{1}{c|}{Montant} \\
                \hline
                '''
            contenu_recap += contenu_recap_compte
            contenu_recap += r'''
                \multicolumn{5}{|r|}{TOTAL} & ''' + Outils.format_2_dec(
                client['subs']) + r''' \\
                \hline
                '''

            legende_recap = r'''Table 3 - Récapitulatif des subsides par compte'''

            contenu += Latex.tableau(contenu_recap, structure_recap,
                                     legende_recap)

            # ## 4

            structure_detail = r'''{|>{\centering}p{1.5cm}|c|r|r|'''
            for i in range(taille_d3):
                structure_detail += r'''r|'''
            structure_detail += r'''}'''

            legende_detail = r'''Table 4 - Détail des subsides'''

            contenu += Latex.long_tableau(contenu_detail_compte,
                                          structure_detail, legende_detail)

        else:
            contenu += Latex.tableau_vide(
                r'''Table 3 vide : Pas de subsides''')

        return contenu
Example #37
0
    def contenu_client(sommes, clients, code_client, edition, livraisons, acces, machines, reservations, prestations,
                       comptes, coefprests, coefmachines, generaux):
        """
        création du contenu de l'annexe pour un client
        :param sommes: sommes calculées
        :param clients: clients importés
        :param code_client: code du client pour l'annexe
        :param edition: paramètres d'édition
        :param livraisons: livraisons importées
        :param acces: accès importés
        :param machines: machines importées
        :param reservations: réservations importées
        :param prestations: prestations importées
        :param comptes: comptes importés
        :param coefprests: coefficients prestations importés
        :param coefmachines: coefficients machines importés
        :param generaux: paramètres généraux
        :return: contenu de l'annexe du client
        """

        contenu = ""

        scl = sommes.sommes_clients[code_client]
        client = clients.donnees[code_client]
        sca = sommes.sommes_categories[code_client]
        intitule_client = code_client + " - " + Latex.echappe_caracteres(client['abrev_labo'])

        structure_recap_compte = r'''{|l|l|r|r|r|'''
        contenu_recap_compte = r'''
            \hline
            Compte & Catégorie & \multicolumn{1}{l|}{Plafonné} & \multicolumn{1}{l|}{Non Plaf.}'''

        for categorie in generaux.codes_d3():
            structure_recap_compte += r'''r|'''
            contenu_recap_compte += r''' & \multicolumn{1}{l|}{
            ''' + Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie)) + r'''}'''

        structure_recap_compte += r'''}'''
        legende_recap_compte = r'''Récapitulatif des comptes pour client ''' + intitule_client
        contenu_recap_compte += r'''& \multicolumn{1}{l|}{Total cpte} \\
            \hline
            '''

        client_comptes = sommes.sommes_comptes[code_client]
        contenu_compte = ""

        for id_compte in sorted(client_comptes.keys()):
            # ## COMPTE

            co = comptes.donnees[id_compte]
            intitule_compte = id_compte + " - " + Latex.echappe_caracteres(co['intitule'])
            dico_nom = {'labo': Latex.echappe_caracteres(client['abrev_labo']),
                        'utilisateur': Latex.echappe_caracteres(co['intitule']),
                        'date': edition.mois_txt + " " + str(edition.annee)}
            contenu_compte += r'''
                \clearpage
                %(labo)s - %(utilisateur)s - %(date)s
                ''' % dico_nom

            structure_recap_projet = r'''{|l|r|r|r|'''
            contenu_recap_projet = r'''
                \hline
                Projet & \multicolumn{1}{l|}{Plafonné} & \multicolumn{1}{l|}{Non Plaf.} '''
            for categorie in generaux.codes_d3():
                structure_recap_projet += r'''r|'''
                contenu_recap_projet += r''' & \multicolumn{1}{l|}{
                ''' + Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie)) + r'''}'''
            structure_recap_projet += r'''}'''
            legende_recap_projet = r'''Récapitulatif compte ''' + intitule_compte
            contenu_recap_projet += r''' & \multicolumn{1}{l|}{Total projet} \\
                \hline
                '''
            client_compte_projet = sommes.sommes_projets[code_client][id_compte]
            contenu_projet = ""

            for num_projet in sorted(client_compte_projet.keys()):
                # ## PROJET
                sp = sommes.sommes_projets[code_client][id_compte][num_projet]
                intitule_projet = num_projet + " - " + Latex.echappe_caracteres(sp['intitule'])

                machines_utilisees = {}

                dico_recap_projet = {'num': intitule_projet, 'plafond': "%.2f" % sp['somme_p_pm'],
                                     'non_plafond': "%.2f" % sp['somme_p_nm']}

                total = sp['somme_p_pm'] + sp['somme_p_nm']

                contenu_recap_projet += r'''
                    \hline
                    %(num)s & %(plafond)s & %(non_plafond)s''' % dico_recap_projet
                for categorie in generaux.codes_d3():
                    total += sp['tot_cat'][categorie]
                    contenu_recap_projet += r''' & ''' + "%.2f" % sp['tot_cat'][categorie]
                dico_recap_projet['total'] = "%.2f" % total

                contenu_recap_projet += r''' & %(total)s \\
                    \hline
                    ''' % dico_recap_projet

                # ## CAE
                structure_cae = r'''{|l|l|l|l|l|l||r|r|r||r|r|r|}'''
                dico_cae = {'compte': intitule_compte, 'projet': intitule_projet}
                contenu_cae = r'''
                    \hline
                    \multicolumn{3}{|l|}{%(compte)s / %(projet)s} & & \multicolumn{2}{l||}{hh:mm} &
                    \multicolumn{3}{l||}{CHF/h} & \multicolumn{3}{l|}{CHF} \\
                    \hline
                    Date & Heure & Equipement & & mach. & oper. & \multicolumn{1}{l|}{P} & \multicolumn{1}{l|}{NP}
                    & \multicolumn{1}{l||}{OP} & \multicolumn{1}{l|}{P} & \multicolumn{1}{l|}{NP}
                    & \multicolumn{1}{l|}{OP} \\
                    \hline
                    ''' % dico_cae
                nombre_cae = 0
                legende_cae = r'''Récapitulatif Utilisation machines : ''' + intitule_compte + r''' / ''' +\
                              intitule_projet

                cae_proj = acces.acces_pour_projet(num_projet, id_compte, code_client)
                resultats = [0, 0, 0]
                for cae in cae_proj:
                    nombre_cae += 1
                    if cae['id_machine'] not in machines_utilisees:
                        machines_utilisees[cae['id_machine']] = {'machine': cae['nom_machine'], 'usage_hp': 0,
                                                                 'reservation_hp': 0, 'facture_hp': 0, 'usage_hc': 0,
                                                                 'reservation_hc': 0, 'facture_hc': 0}
                    machines_utilisees[cae['id_machine']]['usage_hp'] += cae['duree_machine_hp']
                    machines_utilisees[cae['id_machine']]['usage_hc'] += cae['duree_machine_hc']
                    machine = machines.donnees[cae['id_machine']]
                    coefmachine = coefmachines.donnees[client['id_classe_tarif'] + machine['categorie']]
                    ligne, resultat = Annexes.ligne_cae(cae, machine, coefmachine)
                    resultats[0] += resultat[0]
                    resultats[1] += resultat[1]
                    resultats[2] += resultat[2]
                    contenu_cae += ligne

                contenu_cae += r'''
                    \multicolumn{9}{|r||}{Total} & ''' + Outils.format_si_nul(resultats[0]) + r'''
                    & ''' + Outils.format_si_nul(resultats[1]) + r'''
                    & ''' + Outils.format_si_nul(resultats[2]) + r''' \\
                    \hline
                    '''

                if nombre_cae > 0:
                    contenu_projet += Latex.long_tableau(contenu_cae, structure_cae, legende_cae)
                # ## cae

                # ## RES
                structure_res = r'''{|l|l|l|l|l|l||r|r||r|r|}'''
                dico_res = {'compte': intitule_compte, 'projet': intitule_projet}
                contenu_res = r'''
                    \hline
                    \multicolumn{3}{|l|}{%(compte)s / %(projet)s} & & \multicolumn{2}{l||}{hh:mm} &
                    \multicolumn{2}{l||}{CHF/h} & \multicolumn{2}{l|}{CHF} \\
                    \hline
                    Date & Heure & Equipement & & slot & fact. & \multicolumn{1}{l|}{P} & \multicolumn{1}{l||}{NP}
                    & \multicolumn{1}{l|}{P} & \multicolumn{1}{l|}{NP} \\
                    \hline
                    ''' % dico_res
                nombre_res = 0
                legende_res = r'''Récapitulatif Réservations : ''' + intitule_compte + r''' / ''' + intitule_projet

                res_proj = reservations.reservations_pour_projet(num_projet, id_compte, code_client)
                resultats = [0, 0]
                for res in res_proj:
                    nombre_res += 1
                    if res['id_machine'] not in machines_utilisees:
                        machines_utilisees[res['id_machine']] = {'machine': res['nom_machine'], 'usage_hp': 0,
                                                                 'reservation_hp': 0, 'facture_hp': 0, 'usage_hc': 0,
                                                                 'reservation_hc': 0, 'facture_hc': 0}
                    machines_utilisees[res['id_machine']]['reservation_hp'] += res['duree_hp']
                    machines_utilisees[res['id_machine']]['reservation_hc'] += res['duree_hc']
                    machines_utilisees[res['id_machine']]['facture_hp'] += res['duree_fact_hp']
                    machines_utilisees[res['id_machine']]['facture_hc'] += res['duree_fact_hc']
                    ligne, resultat = Annexes.ligne_res(res, machines.donnees[res['id_machine']])
                    resultats[0] += resultat[0]
                    resultats[1] += resultat[1]
                    contenu_res += ligne

                contenu_res += r'''
                    \multicolumn{8}{|r||}{Total} & ''' + Outils.format_si_nul(resultats[0]) + r'''
                    & ''' + Outils.format_si_nul(resultats[1]) + r'''\\
                    \hline
                    '''

                if nombre_res > 0:
                    contenu_projet += Latex.long_tableau(contenu_res, structure_res, legende_res)
                # ## res

                # ## LIV
                structure_liv = r'''{|l|l|l|l|r|r|r|r|}'''
                dico_liv = {'compte': intitule_compte, 'projet': intitule_projet}
                contenu_liv = r'''
                    \hline
                    \multicolumn{2}{|l|}{%(compte)s / %(projet)s} & & & & & &  \\
                    \hline
                    Date livr. & Désignation & Q & Unité & \multicolumn{1}{l|}{PU} & \multicolumn{1}{l|}{Montant}
                    & \multicolumn{1}{l|}{Rabais} & \multicolumn{1}{l|}{Total} \\
                    \hline
                    ''' % dico_liv
                nombre_liv = 0
                legende_liv = r'''Récapitulatif Livraisons : ''' + intitule_compte + r''' / ''' + intitule_projet

                liv_proj_cat = livraisons.livraisons_pour_projet_par_categorie(num_projet, id_compte, code_client,
                                                                               prestations)
                resultats = 0
                for categorie in generaux.codes_d3():
                    if categorie in liv_proj_cat:
                        livs = liv_proj_cat[categorie]
                        for liv in livs:
                            nombre_liv += 1
                            ligne, resultat = Annexes.ligne_liv(liv)
                            resultats += resultat
                            contenu_liv += ligne

                contenu_liv += r'''
                    \multicolumn{7}{|r|}{Total} & ''' + Outils.format_si_nul(resultats) + r'''\\
                    \hline
                    '''

                if nombre_liv > 0:
                    contenu_projet += Latex.long_tableau(contenu_liv, structure_liv, legende_liv)
                # ## liv

                if nombre_cae > 0 or nombre_res > 0:
                    structure_stat_machines = r'''{|l|l|l|l|l|}'''
                    legende_stat_machines = r'''Statistiques de réservation/utilisation par machine : ''' + \
                                            intitule_compte + r''' / ''' + intitule_projet
                    contenu_stat_machines = r'''
                        \hline
                        Equipement & & Utilisation & Res. Slot & Res. Effect. \\
                        \hline
                        '''

                    for machine_t in sorted(machines_utilisees.items(), key=lambda k_v: k_v[1]['machine']):
                        machine = machine_t[1]
                        dico_stat_machines = {
                            'machine': Latex.echappe_caracteres(machine['machine']),
                            'usage_hp': Outils.format_heure(machine['usage_hp']),
                            'reservation_hp': Outils.format_heure(machine['reservation_hp']),
                            'facture_hp': Outils.format_heure(machine['facture_hp']),
                            'usage_hc': Outils.format_heure(machine['usage_hc']),
                            'reservation_hc': Outils.format_heure(machine['reservation_hc']),
                            'facture_hc': Outils.format_heure(machine['facture_hc'])}
                        if machine['facture_hp'] > 0 or \
                                machine['reservation_hp'] or machine['usage_hp']:
                            contenu_stat_machines += r'''%(machine)s & HP &  %(usage_hp)s & %(reservation_hp)s & %(facture_hp)s \\
                            \hline
                            ''' % dico_stat_machines
                        if machine['facture_hc'] > 0 or \
                                machine['reservation_hc'] or machine['usage_hc']:
                            contenu_stat_machines += r'''%(machine)s & HC & %(usage_hc)s & %(reservation_hc)s & %(facture_hc)s \\
                            \hline
                            ''' % dico_stat_machines

                    contenu_projet += Latex.tableau(contenu_stat_machines, structure_stat_machines,
                                                    legende_stat_machines)

                # ## projet

            sco = sommes.sommes_comptes[code_client][id_compte]

            dico_recap_projet = {'plafond': "%.2f" % sco['somme_j_pm'], 'non_plafond': "%.2f" % sco['somme_j_nm'],
                                 'prj': "%.2f" % sco['prj'], 'nrj': "%.2f" % sco['nrj'], 'pj': "%.2f" % sco['pj'],
                                 'nj': "%.2f" % sco['nj']}

            ligne1 = r'''\hline
                Montant article & %(plafond)s & %(non_plafond)s''' % dico_recap_projet
            ligne2 = r'''Plafonnement & %(prj)s & %(nrj)s''' % dico_recap_projet
            ligne3 = r'''Total article & %(pj)s & %(nj)s''' % dico_recap_projet

            sj = sco['pj'] + sco['nj']

            for categorie in generaux.codes_d3():
                ligne1 += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]
                ligne2 += r''' & '''
                ligne3 += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]
                sj += sco['tot_cat'][categorie]

            dico_recap_projet['sj'] = "%.2f" % sj
            ligne1 += r''' & \\
                \hline
                '''
            ligne2 += r''' & \\
                \hline
                '''
            ligne3 += r''' & %(sj)s\\
                \hline
                ''' % dico_recap_projet

            contenu_recap_projet += ligne1 + ligne2 + ligne3

            contenu_compte += Latex.tableau(contenu_recap_projet, structure_recap_projet, legende_recap_projet)

            dico_recap_compte = {'compte': intitule_compte, 'type': co['categorie'], 'plafond': "%.2f" % sco['pj'],
                                 'non_plafond': "%.2f" % sco['nj'], 'total': "%.2f" % sj}

            contenu_recap_compte += r'''%(compte)s & %(type)s & %(plafond)s & %(non_plafond)s ''' \
                                    % dico_recap_compte

            for categorie in generaux.codes_d3():
                contenu_recap_compte += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]

            contenu_recap_compte += r'''& %(total)s \\
                    \hline
                    ''' % dico_recap_compte

            structure_recap_poste = r'''{|l|r|r|r|}'''
            legende_recap_poste = r'''Récapitulatif postes pour compte ''' + intitule_compte

            dico_recap_poste = {'spu': "%.2f" % sco['somme_j_pu'], 'prj': "%.2f" % sco['prj'],
                                'pj': "%.2f" % sco['pj'], 'spv': "%.2f" % sco['somme_j_pv'],
                                'squ': "%.2f" % sco['somme_j_qu'], 'nrj': "%.2f" % sco['nrj'],
                                'nj': "%.2f" % sco['nj'], 'sqv': "%.2f" % sco['somme_j_qv'],
                                'som': "%.2f" % sco['somme_j_om']}

            contenu_recap_poste = r'''
                \hline
                Compte : ''' + intitule_compte + r''' & \multicolumn{1}{l|}{Montant} & \multicolumn{1}{l|}{Rabais}
                & \multicolumn{1}{l|}{Total} \\
                \hline
                Montant utilisation Machine P & %(spu)s & \multirow{2}{*}{%(prj)s} & \multirow{2}{*}{%(pj)s} \\
                \cline{1-2}
                Montant réservation Machine P & %(spv)s &  & \\
                \hline
                Montant utilisation Machine NP & %(squ)s & \multirow{3}{*}{%(nrj)s} & \multirow{3}{*}{%(nj)s} \\
                \cline{1-2}
                Montant réservation Machine NP & %(sqv)s &  &  \\
                \cline{1-2}
                Montant Main d'oeuvre & %(som)s &  &  \\
                \hline
                ''' % dico_recap_poste

            for categorie in generaux.codes_d3():
                contenu_recap_poste += Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie))
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['sommes_cat_m'][categorie]
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['sommes_cat_r'][categorie]
                contenu_recap_poste += r''' & ''' + "%.2f" % sco['tot_cat'][categorie]
                contenu_recap_poste += r''' \\
                    \hline
                    '''

            contenu_compte += Latex.tableau(contenu_recap_poste, structure_recap_poste, legende_recap_poste)
            contenu_compte += contenu_projet
            # ## compte

        dic_entete = {'code': code_client, 'code_sap': client['code_sap'],
                      'nom': Latex.echappe_caracteres(client['abrev_labo']),
                      'date': edition.mois_txt + " " + str(edition.annee)}
        entete = r'''
            %(code)s - %(code_sap)s - %(nom)s - %(date)s
            ''' % dic_entete

        contenu += entete

        dic_emo = {'emb':  "%.2f" % client['emol_base_mens'], 'ef':  "%.2f" % client['emol_fixe'],
                   'pente': client['coef'], 'tot_eq_p': "%.2f" % scl['pt'], 'tot_eq_np': "%.2f" % scl['qt'],
                   'tot_eq': "%.2f" % scl['somme_eq'], 'rabais': "%.2f" % scl['er']}

        structure_emolument = r'''{|r|r|l|r|r|r|r|}'''
        legende_emolument = r'''Emolument pour client ''' + intitule_client
        contenu_emolument = r'''
            \hline
            \multicolumn{1}{|l|}{Emolument de base} & \multicolumn{1}{l|}{Emolument fixe} & Pente
            & \multicolumn{1}{l|}{Total EQ P} & \multicolumn{1}{l|}{Total EQ NP} & \multicolumn{1}{l|}{Total EQ}
            & \multicolumn{1}{l|}{Rabais émolument} \\
            \hline
            %(emb)s & %(ef)s & %(pente)s & %(tot_eq_p)s & %(tot_eq_np)s & %(tot_eq)s & %(rabais)s \\
            \hline
            ''' % dic_emo

        contenu += Latex.tableau(contenu_emolument, structure_emolument, legende_emolument)

        dico_recap_compte = {'plafond': "%.2f" % scl['pt'], 'non_plafond': "%.2f" % scl['nt'],
                             'total': "%.2f" % scl['somme_t']}

        contenu_recap_compte += r'''Total article & & %(plafond)s & %(non_plafond)s''' % dico_recap_compte

        for categorie in generaux.codes_d3():
            contenu_recap_compte += r''' & ''' + "%.2f" % scl['tot_cat'][categorie]

        contenu_recap_compte += r'''& %(total)s \\
                \hline
                ''' % dico_recap_compte

        contenu += Latex.tableau(contenu_recap_compte, structure_recap_compte, legende_recap_compte)

        structure_recap_poste_cl = r'''{|l|r|r|r|}'''
        legende_recap_poste_cl = r'''Récapitulatif postes pour client ''' + intitule_client

        dico_recap_poste_cl = {'kpm1': '0.00', 'kprj1': '0.00', 'pk1': '0.00', 'kpm2': '0.00', 'kprj2': '0.00',
                               'pk2': '0.00', 'kpm3': '0.00', 'kprj3': '0.00', 'pk3': '0.00', 'kpm4': '0.00',
                               'kprj4': '0.00', 'pk4': '0.00',
                               'tpm': "%.2f" % scl['somme_t_pm'], 'tprj': "%.2f" % scl['somme_t_prj'],
                               'pt': "%.2f" % scl['pt'], 'tqm': "%.2f" % scl['somme_t_qm'],
                               'nt': "%.2f" % scl['nt'], 'tnrj': "%.2f" % scl['somme_t_nrj'],
                               'tom': "%.2f" % scl['somme_t_om']}

        if '1' in sca:
            dico_recap_poste_cl['kpm1'] = "%.2f" % sca['1']['somme_k_pm']
            dico_recap_poste_cl['kprj1'] = "%.2f" % sca['1']['somme_k_prj']
            dico_recap_poste_cl['pk1'] = "%.2f" % sca['1']['pk']
        if '2' in sca:
            dico_recap_poste_cl['kpm2'] = "%.2f" % sca['2']['somme_k_pm']
            dico_recap_poste_cl['kprj2'] = "%.2f" % sca['2']['somme_k_prj']
            dico_recap_poste_cl['pk2'] = "%.2f" % sca['2']['pk']
        if '3' in sca:
            dico_recap_poste_cl['kpm3'] = "%.2f" % sca['3']['somme_k_pm']
            dico_recap_poste_cl['kprj3'] = "%.2f" % sca['3']['somme_k_prj']
            dico_recap_poste_cl['pk3'] = "%.2f" % sca['3']['pk']
        if '4' in sca:
            dico_recap_poste_cl['kpm4'] = "%.2f" % sca['4']['somme_k_pm']
            dico_recap_poste_cl['kprj4'] = "%.2f" % sca['4']['somme_k_prj']
            dico_recap_poste_cl['pk4'] = "%.2f" % sca['4']['pk']

        contenu_recap_poste_cl = r'''
            \hline
             & \multicolumn{1}{l|}{Montant} & \multicolumn{1}{l|}{Rabais} & \multicolumn{1}{l|}{Total} \\
            \hline
            Machine P (catégorie 1 : Utilisateur) & %(kpm1)s & %(kprj1)s & %(pk1)s \\
            \hline
            Machine P (catégorie 2 : Etudiant en projet Master) & %(kpm2)s & %(kprj2)s & %(pk2)s \\
            \hline
            Machine P (catégorie 3 : Etudiant en projet Semestre) & %(kpm3)s & %(kprj3)s & %(pk3)s \\
            \hline
            Machine P (catégorie 4 : Client) & %(kpm4)s & %(kprj4)s & %(pk4)s \\
            \hline
            Machine P (total des catégories) & %(tpm)s & %(tprj)s & %(pt)s \\
            \hline
            Machine NP & %(tqm)s & \multirow{2}{*}{%(tnrj)s} & \multirow{2}{*}{%(nt)s} \\
            \cline{1-2}
            Main d'oeuvre & %(tom)s & & \\
            \hline
            ''' % dico_recap_poste_cl

        for categorie in generaux.codes_d3():
            contenu_recap_poste_cl += Latex.echappe_caracteres(coefprests.obtenir_noms_categories(categorie))
            contenu_recap_poste_cl += r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['sommes_cat_m'][categorie] + r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['sommes_cat_r'][categorie] + r''' & '''
            contenu_recap_poste_cl += "%.2f" % scl['tot_cat'][categorie] + r''' \\
                \hline
                '''

        contenu += Latex.tableau(contenu_recap_poste_cl, structure_recap_poste_cl, legende_recap_poste_cl)
        contenu += contenu_compte

        return contenu
Example #38
0
def fermion_propagator():
    """ Calculate expression for first-order corrected fermion propagator. """

    latex = Latex()

    # 1. Write out amplitude  TODO include regulator terms
    m = []

    ind = "\sigma_1"
    sum_terms = [Sub("p", ind), C("m")]
    m.append(Frac(Prod([Sum(sum_terms), Gamma(ind)]), Term("p^2 - m^2 + i\\epsilon")))

    m.append(Integral("k", norm=True))
    m.append(I())
    m.append(C("e"))
    m.append(Term("\\gamma^\\mu"))

    ind = "\sigma_2"
    sum_terms = [Sub("p", ind), Sub("(-k)", ind), C("m")]
    m.append(Frac(Prod([Sum(sum_terms), Gamma(ind)]), Term("(p - k)^2 - m^2 + i\\epsilon")))
    m.append(I())
    m.append(C("e"))
    m.append(Term("\\gamma^\\nu"))
    m.append(Term("D_{\\mu \\nu}(k)"))

    ind = "\sigma_3"
    sum_terms = [Sub("p", ind), C("m")]
    m.append(Frac(Prod([Sum(sum_terms), Gamma(ind)]), Term("p^2 - m^2 + i\\epsilon")))

    latex.add(" ".join([t.latex() for t in m]))

    # 2. Use Feynman parameterization to rewrite propagators
    m_ = []
    ds = []
    for term in m:
        if term.is_fraction():
            # TODO
            m_.append(term.numer)
            ds.append(term.denom)
        else:
            m_.append(term)

    # Integrals
    for i, d in enumerate(ds):
        a = Term("0")
        b = Term("1" + "".join([" - z_{0}".format(j + 1) for j in range(i)]))
        m_.append(Integral("z_{0}".format(i+1), norm=True, limits=(a, b)))

    # Frac
    denom = ""
    denom += "\\left["
    ds_ = []
    for i, d in enumerate(ds):
        ds_.append("\\left(" + d.latex() + "\\right) " + "z_{0}".format(i + 1))
    denom += " + ".join(ds_)
    denom += "\\right]"
    denom += "^{0}".format(len(ds))
    frac = Frac(Term("1"), Term(denom))
    m_.append(frac)

    m = m_
    latex.add(" ".join([t.latex() for t in m]))

    # 3. Distribute numerators (p + m) ish terms
    # 4. Solve each internal momenta integral
    # 5. Move terms independent of z's to left
    # 6. Groan.  Solve.
    # 7. Solve remaining integrals, contract metrics, etc.
    # 8. (OPTIONAL) Evaluate traces for non-Abelian theories.

    latex.render()
Example #39
0
    def ligne_cae(cae, machine, coefmachine):
        """
        création d'une ligne de tableau pour un accès
        :param cae: accès particulier
        :param machine: machine concernée
        :param coefmachine: coefficients machine concernée
        :return: ligne de tableau latex
        """

        t1 = machine['t_h_machine_hp_p'] * coefmachine['coef_p']
        t2 = machine['t_h_machine_hp_np'] * coefmachine['coef_np']
        t3 = machine['t_h_operateur_hp_mo'] * coefmachine['coef_mo']
        t4 = machine['t_h_machine_hc_p'] * coefmachine['coef_p']
        t5 = machine['t_h_machine_hc_np'] * coefmachine['coef_np']
        t6 = machine['t_h_operateur_hc_mo'] * coefmachine['coef_mo']

        p1 = round(t1 * cae['duree_machine_hp'] / 60, 2)
        p2 = round(t2 * cae['duree_machine_hp'] / 60, 2)
        p3 = round(t3 * cae['duree_operateur_hp'] / 60, 2)
        p4 = round(t4 * cae['duree_machine_hc'] / 60, 2)
        p5 = round(t5 * cae['duree_machine_hc'] / 60, 2)
        p6 = round(t6 * cae['duree_operateur_hc'] / 60, 2)
        login = Latex.echappe_caracteres(cae['date_login']).split()
        temps = login[0].split('-')
        date = temps[0]
        for pos in range(1, len(temps)):
            date = temps[pos] + '.' + date
        if len(login) > 1:
            heure = login[1]
        else:
            heure = ""

        dico = {'date': date, 'heure': heure,
                'machine': Latex.echappe_caracteres(cae['nom_machine']),
                'operateur': Latex.echappe_caracteres(cae['nom_op']),
                'rem_op': Latex.echappe_caracteres(cae['remarque_op']),
                'rem_staff': Latex.echappe_caracteres(cae['remarque_staff']),
                'deq_hp': Outils.format_heure(cae['duree_machine_hp']),
                'dmo_hp': Outils.format_heure(cae['duree_operateur_hp']),
                'deq_hc': Outils.format_heure(cae['duree_machine_hc']),
                'dmo_hc': Outils.format_heure(cae['duree_operateur_hc']),
                't1': "%d" % t1, 't2': "%d" % t2, 't3': "%d" % t3, 't4': "%d" % t4, 't5': "%d" % t5, 't6': "%d" % t6,
                'p1': Outils.format_si_nul(p1), 'p2': Outils.format_si_nul(p2), 'p3': Outils.format_si_nul(p3),
                'p4': Outils.format_si_nul(p4), 'p5': Outils.format_si_nul(p5), 'p6': Outils.format_si_nul(p6)}

        nb = 0
        if (cae['duree_machine_hp'] > 0) or (cae['duree_operateur_hp'] > 0):
            nb += 1

        if (cae['duree_machine_hc'] > 0) or (cae['duree_operateur_hc'] > 0):
            nb += 1

        if nb == 0:
            return "", [0, 0, 0]

        if (cae['remarque_staff'] != "") or (cae['remarque_op'] != ""):
            nb += 1

        if nb == 1:
            ligne = r'''%(date)s & %(heure)s''' % dico
        else:
            ligne = r'''\multirow{''' + str(nb) + r'''}{*}{%(date)s} & \multirow{''' % dico
            ligne += str(nb) + r'''}{*}{%(heure)s}''' % dico

        nb = 0
        if (cae['duree_machine_hp'] > 0) or (cae['duree_operateur_hp'] > 0):
            ligne += r''' & %(machine)s & HP & %(deq_hp)s & %(dmo_hp)s & %(t1)s & %(t2)s & %(t3)s &
                %(p1)s & %(p2)s & %(p3)s \\
                ''' % dico
            nb += 1

        if (cae['duree_machine_hc'] > 0) or (cae['duree_operateur_hc'] > 0):
            if nb > 0:
                ligne += r'''& &'''
            else:
                ligne += r'''& %(machine)s ''' % dico
            ligne += r''' & HC & %(deq_hc)s & %(dmo_hc)s & %(t4)s & %(t5)s & %(t6)s &
                %(p4)s & %(p5)s & %(p6)s \\
                ''' % dico

        if (cae['remarque_staff'] != "") or (cae['remarque_op'] != ""):
            ligne += r'''\cline{3-12}
                &  & \multicolumn{10}{l|}{%(operateur)s ; %(rem_op)s ; %(rem_staff)s}\\
                ''' % dico

        ligne += r'''\hline
            '''
        return ligne, [(p1 + p4), (p2 + p5), (p3 + p6)]
Example #40
0
    def table_qte_lvr_jdu(code_client, id_compte, intitule_compte, generaux, livraisons, users):
        """
        Qté LVR J/D/U - Table Compte Détail Quantités livrées/Prestation (code D)/User
        :param code_client: code du client concerné
        :param id_compte: id du compte concerné
        :param intitule_compte: intitulé du compte concerné
        :param generaux: paramètres généraux
        :param livraisons: livraisons importées
        :param users: users importés
        :return: table au format latex
        """

        structure = r'''{|l|c|c|c|}'''
        legende = r'''Détails des prestations livrées'''

        contenu = r'''
            '''
        i = 0
        somme = livraisons.sommes[code_client][id_compte]
        for article in generaux.articles_d3:
            if article.code_d in somme:
                if i == 0:
                    i += 1
                else:
                    contenu += r'''\multicolumn{4}{c}{} \\
                        '''
                contenu += r'''
                    \hline
                    \multicolumn{1}{|l|}{
                    \textbf{''' + intitule_compte + " - " + Latex.echappe_caracteres(article.intitule_long) + r'''
                    }} & Quantité & Unité & Rabais \\
                    \hline
                    '''
                for no_prestation, sip in sorted(somme[article.code_d].items()):
                    dico_prestations = {'nom': Latex.echappe_caracteres(sip['nom']),
                                        'num': no_prestation,
                                        'quantite': "%.1f" % sip['quantite'],
                                        'unite': Latex.echappe_caracteres(sip['unite']),
                                        'rabais': Outils.format_2_dec(sip['rabais'])}
                    contenu += r'''
                        %(num)s - %(nom)s & \hspace{5mm} %(quantite)s & %(unite)s
                        & \hspace{5mm} %(rabais)s \\
                        \hline
                        ''' % dico_prestations

                    utilisateurs = Outils.utilisateurs_in_somme(sip['users'], users)

                    for nom, upi in sorted(utilisateurs.items()):
                        for prenom, ids in sorted(upi.items()):
                            for id_user in sorted(ids):
                                spu = sip['users'][id_user]
                                dico_user = {'user': Latex.echappe_caracteres(nom + " " + prenom),
                                             'quantite': "%.1f" % spu['quantite'],
                                             'unite': Latex.echappe_caracteres(sip['unite']),
                                             'rabais': Outils.format_2_dec(spu['rabais'])}
                                contenu += r'''
                                    \hspace{5mm} %(user)s & %(quantite)s & %(unite)s & %(rabais)s \\
                                    \hline
                                ''' % dico_user

                                for pos in spu['data']:
                                    liv = livraisons.donnees[pos]
                                    rem = ""
                                    dl = ""
                                    if liv['remarque'] != "":
                                        rem = "; Remarque : " + liv['remarque']
                                    if liv['date_livraison'] != "":
                                        dl = "Dt livraison: " + liv['date_livraison'] + ";"
                                    op = users.donnees[liv['id_operateur']]
                                    dico_pos = {'date_liv': Latex.echappe_caracteres(dl),
                                                'quantite': "%.1f" % liv['quantite'],
                                                'rabais': Outils.format_2_dec(liv['rabais_r']),
                                                'id': Latex.echappe_caracteres(liv['id_livraison']),
                                                'unite': Latex.echappe_caracteres(sip['unite']),
                                                'responsable': Latex.echappe_caracteres(op['prenom'] + " " + op['nom']),
                                                'commande': Latex.echappe_caracteres(liv['date_commande']),
                                                'remarque': Latex.echappe_caracteres(rem)}
                                    contenu += r'''
                                        \hspace{10mm} %(date_liv)s N. livraison: %(id)s
                                        & %(quantite)s \hspace{5mm} & %(unite)s & %(rabais)s \hspace{5mm} \\
        
                                        \hspace{10mm} \scalebox{.8}{Commande: %(commande)s;
                                        Resp: %(responsable)s%(remarque)s} & & & \\
                                        \hline
                                    ''' % dico_pos

        return Latex.long_tableau(contenu, structure, legende)
Example #41
0
    def ligne_res(res, machine):
        """
        création d'une ligne de tableau pour une réservation
        :param res: réservation particulière
        :param machine: machine concernée
        :return: ligne de tableau latex
        """
        p7 = round(machine['t_h_reservation_hp_p'] * res['duree_fact_hp'] / 60, 2)
        p8 = round(machine['t_h_reservation_hp_np'] * res['duree_fact_hp'] / 60, 2)
        p9 = round(machine['t_h_reservation_hc_p'] * res['duree_fact_hc'] / 60, 2)
        p10 = round(machine['t_h_reservation_hc_np'] * res['duree_fact_hc'] / 60, 2)
        login = Latex.echappe_caracteres(res['date_debut']).split()
        temps = login[0].split('-')
        date = temps[0]
        for pos in range(1, len(temps)):
            date = temps[pos] + '.' + date
        if len(login) > 1:
            heure = login[1]
        else:
            heure = ""

        dico = {'date': date, 'heure': heure,
                'machine': Latex.echappe_caracteres(res['nom_machine']),
                'reserve': Latex.echappe_caracteres(res['date_reservation']),
                'supprime': Latex.echappe_caracteres(res['date_suppression']),
                'shp': Outils.format_heure(res['duree_hp']), 'shc': Outils.format_heure(res['duree_hc']),
                'fhp': Outils.format_heure(res['duree_fact_hp']), 'fhc': Outils.format_heure(res['duree_fact_hc']),
                't7': "%d" % machine['t_h_reservation_hp_p'], 't8': "%d" % machine['t_h_reservation_hp_np'],
                't9': "%d" % machine['t_h_reservation_hc_p'], 't10': "%d" % machine['t_h_reservation_hc_np'],
                'p7': Outils.format_si_nul(p7), 'p8': Outils.format_si_nul(p8), 'p9': Outils.format_si_nul(p9),
                'p10': Outils.format_si_nul(p10)}

        nb = 0
        if res['duree_fact_hp'] > 0:
            nb += 1

        if res['duree_fact_hc'] > 0:
            nb += 1

        if nb == 0:
            return "", [0, 0]

        if res['date_suppression'] != "":
            nb += 1

        if nb == 1:
            ligne = r'''%(date)s & %(heure)s''' % dico
        else:
            ligne = r'''\multirow{''' + str(nb) + r'''}{*}{%(date)s} & \multirow{''' % dico
            ligne += str(nb) + r'''}{*}{%(heure)s}''' % dico

        nb = 0
        if res['duree_fact_hp'] > 0:
            ligne += r''' & %(machine)s & HP & %(shp)s & %(fhp)s & %(t7)s & %(t8)s & %(p7)s & %(p8)s \\
                ''' % dico
            nb += 1

        if res['duree_fact_hc'] > 0:
            if nb > 0:
                ligne += r'''& &'''
            else:
                ligne += r'''& %(machine)s ''' % dico
            ligne += r''' & HC & %(shc)s & %(fhc)s & %(t9)s & %(t10)s & %(p9)s & %(p10)s \\
                ''' % dico

        if res['date_suppression'] != "":
            ligne += r'''\cline{3-10}
                &  & \multicolumn{8}{l|}{Supprimé le : %(supprime)s} \\
                ''' % dico

        ligne += r'''\hline
            '''

        return ligne, [(p7 + p9), (p8 + p10)]
Example #42
0
annexes_techniques = "annexes_techniques"
dossier_annexes_techniques = Outils.chemin_dossier([dossier_enregistrement, annexes_techniques], plateforme, generaux)
lien_annexes_techniques = Outils.lien_dossier([dossier_lien, annexes_techniques], plateforme, generaux)

facture_prod = Facture()
facture_prod.factures(sommes, dossier_destination, edition, generaux, clients, comptes,
                      lien_annexes, lien_annexes_techniques, annexes, annexes_techniques)

prod2qual = Prod2Qual(dossier_source)
if prod2qual.actif:
    facture_qual = Facture(prod2qual)
    generaux_qual = Generaux(dossier_source, prod2qual)
    facture_qual.factures(sommes, dossier_destination, edition, generaux_qual, clients, comptes,
                          lien_annexes, lien_annexes_techniques, annexes, annexes_techniques)

if Latex.possibles():
    Annexes.annexes_techniques(sommes, clients, edition, livraisons, acces, machines, reservations, prestations,
                               comptes, dossier_annexes_techniques, plateforme, coefprests, coefmachines, generaux)
    Annexes.annexes(sommes, clients, edition, livraisons, acces, machines, reservations, prestations, comptes,
                    dossier_annexes, plateforme, coefprests, coefmachines, generaux)

BilanMensuel.bilan(dossier_destination, edition, sommes, clients, generaux, acces,
                   reservations, livraisons, comptes)

for fichier in [acces.nom_fichier, clients.nom_fichier, coefmachines.nom_fichier, coefprests.nom_fichier,
                  comptes.nom_fichier, livraisons.nom_fichier, machines.nom_fichier, prestations.nom_fichier,
                  reservations.nom_fichier, generaux.nom_fichier, edition.nom_fichier]:
    dossier_destination.ecrire(fichier, dossier_source.lire(fichier))

Outils.affiche_message("OK !!!")
Example #43
0
class LatexBuilder:
    """
    Main (g)rubber wrapper hiding all the internals and compiling the
    required tex file.
    """
    def __init__(self):
        # The actual workers
        self.maker = Maker()
        self.tex = Latex(self.maker)
        self.maker.dep_append(self.tex)

        # What to do
        self.backend = "pdftex"
        self.format = "pdf"
        self.index_style = ""
        self.batch = 1
        self.encoding = "latin-1"
        self.texpost = ""

    def set_format(self, format):
        # Just record it
        self.format = format

    def set_backend(self, backend):
        self.backend = backend

    def set_index_style(self, index_style):
        self.index_style = index_style

    def compile(self, source):
        self.tex.batch = self.batch
        self.tex.encoding = self.encoding
        self.tex.set_source(source)

        # Load the modules needed to produce the expected output format
        if (self.format == "pdf"):
            if (self.backend == "pdftex"):
                self.tex.modules.register("pdftex")
            elif (self.backend == "xetex"):
                self.tex.modules.register("xetex")
            else:
                self.tex.modules.register("dvips")
                self.tex.modules.register("ps2pdf")
        elif (self.format == "ps"):
            self.tex.modules.register("dvips")

        # Now load other the modules required to compile this file
        self.tex.prepare()

        # Set the index style
        if self.index_style and self.tex.modules.has_key("makeidx"):
            idx = self.tex.modules["makeidx"]
            idx.style = self.index_style

        # Let's go...
        rc = self.maker.make()
        if rc != 0:
            raise OSError("%s compilation failed" % self.tex.program)

        # Post process script to call?
        if not(self.texpost):
            return

        os.environ["LATEX"] = self.tex.program
        rc = subprocess.call([self.texpost, source], stdout=msg.stdout)
        if rc == 1:
            return
        if rc != 0:
            raise OSError("%s texpost failed" % self.texpost)

        rc = self.maker.make(force=1)
        if rc != 0:
            raise OSError("%s post compilation failed" % self.tex.program)

    def clean(self):
        self.tex.clean()
        self.reinit()

    def reinit(self):
        self.tex.reinit()
        self.maker.reinit()
        self.maker.dep_append(self.tex)

    def print_errors(self):
        msg.display_all(self.tex.get_errors(), writer=msg.write_stderr)