Exemplo n.º 1
0
    def translate(self, label=False):
        # begin translate
        self.pageProperties = Sla2pdfUtils.pageProFunc(self.slaDocumentTag())
        self.canvas = Canvas(filename = self.slafile + '.pdf', pagesize=(self.pageProperties[0][8],self.pageProperties[0][7]))
        # Page's table
        reiter = False
        self.pdfPage = 0
        tablepropertys = self.findTablesProperties()
        iteratable = self.getIteratableGroups(tablepropertys)
        for self.pdfPage in xrange(0, self.numPages):
            print("PAGINA", self.pdfPage, "DI", self.numPages)
            if label:
                group = tablepropertys[self.pdfPage].keys()[0]
                tabpro = tablepropertys[self.pdfPage][group]
                reiter = True
                # Closing pages (elements of the same page must be near)
                if "noGroup" in group and tabpro["pfile"] != "":
                    self.drawImage(group=group, tabpro=tabpro)  # IMMAGINE
                elif "noGroup" in group and tabpro["pfile"] == "":
                    self.drawTable(group=group, monocell=True,
                                   tabpro=tabpro)  # MONOCELLA
                else:
                    self.drawTable(group=group, reiter=reiter,
                                   tabpro=tabpro)  # TABELLA
                self.canvas.saveState()
                self.canvas.showPage()
            else:
                for tableproperty in tablepropertys:
                    for group in tableproperty.keys():
                        if self.pbar:
                            pbar(self.pbar,pulse=True,text="GEN STAMPA ATTENDERE 2 di 2")
                        tabpro = tableproperty[group]
                        try:
                            group= group.strip().split('%%%')[0]
                        except:
                            group= group.strip()
                        if group in iteratable:
                            colu = int(tabpro['columns'])
        #                    tabpro['iterproper'] = tabpro['parasobj'][colu:(colu*2)]
                            reiter = True
                        n_cells = int(tabpro['n_cells'])
                        # Closing pages (elements of the same page must be near)
                        if "noGroup" in group and tabpro["pfile"] != "" :
                            self.drawImage(group=group, tabpro=tabpro) # IMMAGINE
                        elif "noGroup" in group  and tabpro["pfile"] == "":
                            self.drawTable(group =group, monocell=True, tabpro=tabpro)# MONOCELLA
                        else:
                            self.drawTable(group =group, reiter = reiter, tabpro = tabpro) # TABELLA
                self.canvas.saveState()
                self.canvas.showPage()
        self.canvas.save()
        # temporary pdf file is removed immediately
        filename = self.slafile + '.pdf'

        f = file(filename, 'rb')
        result = f.read()
        f.close()
#        os.remove(filename)
        return result
Exemplo n.º 2
0
    def duplicateElement(self, pages):
        """ Duplica TUTTI gli oggetti da una pagina all'altra """
#        pages = len(self.slaPage())
        adesso = self.slaPageObjects()
        for j in xrange(1, pages):
            for pageObject in adesso:
                if self.pbar:
                    pbar(self.pbar, pulse=True, text="GEN.STAMPA ATTENDERE 1 DI 2")
                # Creating dictionary attributes pageobject
                attributes = pageObject.items()
                dictionary = {}
                for attr in attributes:
                    dictionary[attr[0]] = attr[1]

                # Applying attributes
                app = pageObject.makeelement('PAGEOBJECT', dictionary)
                # Creating dictionary attributes itext of the pageobject
                itexts = pageObject.findall('ITEXT')
                for itext in itexts:
                    attributes = itext.items()
                    dictionary = {}
                    for attrr in attributes:
                        dictionary[attrr[0]] = attrr[1]
                    ElementTree.SubElement(app, 'ITEXT', dictionary)
                trails = pageObject.findall('trail')
                for trai in trails:
                    attributes = trai.items()
                    dictTrai = {}
                    for attrrr in attributes:
                        dictTrai[attrrr[0]] = attrrr[1]
                    ElementTree.SubElement(app, 'trail', dictTrai)

                paras = pageObject.findall('para')
                for para in paras:
                    attributes = para.items()
                    dictPara = {}
                    for attrrr in attributes:
                        dictPara[attrrr[0]] = attrrr[1]
                    ElementTree.SubElement(app, 'para', dictPara)

                pageItemAttributes = pageObject.findall('pageItemAttributes')
                ElementTree.SubElement(app, 'pageItemAttributes')
                # Number page
                inigroup = str(app.get('GROUPS')).strip()
                if inigroup:
                    nuovogruppo = (j+1)*(str(inigroup)+"%%%"+str(inigroup))
                    app.set('GROUPS',str(nuovogruppo))
                app.set('OwnPage', str(j))
                # Coordinates
                initial = app.get('YPOS')
                app.set('YPOS', str( j * (float(self.pageHeight) + float(self.borderTop)) + float(initial)))
                self.slaDocumentTag().append(app)
def ricerca_movimenti_spedizione(daos, progress=None):
    tipi_ddt_figlio = ['DDT vendita', 'DDT vendita diretta']

    res = []

    for doc in daos:
        if progress:
            pbar(progress, parziale=daos.index(doc), totale=len(daos), text="Attendere...", noeta=True)
        if doc.operazione in tipi_ddt_figlio:
            doc._padre = get_padre(doc.id)
            res.append(doc)

    if progress:
        pbar(progress, stop=True)

    return res
def chiusura_ordini(progress=None):
    da_data = datetime.date(int(workingYear), 1, 1)
    ordini = session.query(TestataDocumento).filter(TestataDocumento.data_documento >= da_data,
                                                    TestataDocumento.operazione == 'Ordine da cliente',
                                                    TestataDocumento.documento_saldato == False).all()

    for doc in ordini:
        if controlla_quantita(doc):
            # controllo delle quantità tra ordine e DDT
            # quelle del DDT >= or < qta +3 quelle dell'ordine
            doc.totale_pagato = doc.totale_sospeso
            doc.totale_sospeso = 0
            doc.documento_saldato = True
            session.commit()
            self.filter.refresh()
        if progress:
            pbar(progress, parziale=ordini.index(doc), totale=len(ordini), text="Attendere...", noeta=True)

    if progress:
        pbar(progress, stop=True)
Exemplo n.º 5
0
def to_pdf(daos, output, anag=None):
    PDF_WORKING_DIR = tempfile.mkdtemp()
    i = 1
    if anag:
        anag.pbar_anag_complessa.show()
    for dao in daos:
        if anag:
            utils.pbar(anag.pbar_anag_complessa, parziale=daos.index(dao), totale=len(daos), text="GEN STAMPE MULTIPLE",
                       noeta=False)
        if dao.__class__.__name__ == 'TestataDocumento':
            dao.totali

        with file(os.path.join(PDF_WORKING_DIR, '%s.pdf' % str(int(i) + 10000)), 'wb') as f:
            f.write(_to_pdf(dao))
        i += 1

    merger = PdfFileMerger()
    filesPdf = glob.glob(os.path.join(PDF_WORKING_DIR, '*.pdf'))
    filesPdf.sort()
    for infile in filesPdf:
        if anag:
            utils.pbar(anag.pbar_anag_complessa, parziale=filesPdf.index(infile), totale=len(filesPdf),
                       text="UNIONE PDF", noeta=False)
        merger.append(fileobj=file(infile, 'rb'))

    merger.write(output)
    merger.close()
    if anag:
        utils.pbar(anag.pbar_anag_complessa, stop=True)
        anag.pbar_anag_complessa.set_property("visible", False)
Exemplo n.º 6
0
 def recordToCSV(self, record):
     """ TODO: Aggiungere i campi obbligatori"""
     #if self.separatore_combobox.get_active_text() =="" or self.separatore_combobox.get_active_text() == None:
         #obligatoryField(self.getTopLevel(), self.separatore_combobox, msg="Separatatore Campo obbligatorio")
     #if self.stringa_combobox.get_active_text() =="" or self.stringa_combobox.get_active_text() ==None:
         #obligatoryField(self.getTopLevel(), self.stringa_combobox,msg="Separatatore Testo obbligatorio")
     tempFileCsv = Environment.tempDir+"tempCSV"
     tree_iter = self.separatore_combobox.get_active_iter()
     if tree_iter != None:
         modell = self.separatore_combobox.get_model()
         if modell[tree_iter][0] =="":
             obligatoryField(self.getTopLevel(), self.separatore_combobox)
         else:
             separatore = modell[tree_iter][0] or ";"
     tree_iter = self.stringa_combobox.get_active_iter()
     if tree_iter != None:
         modell = self.stringa_combobox.get_model()
         if modell[tree_iter][0] =="":
             obligatoryField(self.getTopLevel(), self.stringa_combobox)
         else:
             stringa = modell[tree_iter][0] or '"'
     Environment.pg2log.info("SEPARATORE: "+ (separatore or ""))
     Environment.pg2log.info("STRINGA: "+ (stringa or ""))
     spamWriter = csv.writer(open(tempFileCsv, 'wb'), delimiter=separatore or ";",
                             quotechar=stringa or '"', quoting=csv.QUOTE_MINIMAL)
     model = self.modello_treeview.get_model()
     campilist = []
     for m in model:
         if m[0] == True:
             campilist.append(m[1])
     if self.primariga_check.get_active():
         spamWriter.writerow(campilist)
     for r in record:
         row = []
         for camp in campilist:
             row.append(getattr(r,camp))
         spamWriter.writerow(row)
         pbar(self.generic_progressbar,parziale=record.index(r)+1,totale=len(record))
     pbar(self.generic_progressbar,stop=True)
def ricerca_movimenti_spedizione(da_data, al_data, progress=None):
    tipi_ddt_figlio = ['DDT vendita', 'DDT vendita diretta']
    # Tutti i documenti (ordini) non saldati dall'inizio dell'anno
    ordini = session.query(TestataDocumento).filter(TestataDocumento.data_documento >= da_data,
                                                    TestataDocumento.operazione == 'Ordine da cliente',
                                                    TestataDocumento.documento_saldato == False).all()
    res = []

    for ordine in ordini:
        if progress:
            pbar(progress, parziale=ordini.index(ordine), totale=len(ordini),
                text="Attendere...", noeta=True)
        # ottengo tutti i figli di questo ordine
        figli = get_figli(ordine.id)
        for figlio in figli:
            if figlio.operazione in tipi_ddt_figlio:
                figlio._padre = get_padre(figlio.id)
                res.append(figlio)

    if progress:
        pbar(progress, stop=True)

    return res
Exemplo n.º 8
0
def fixRigaMovimentoTable(pbar_wid=None):

    a = SetConf().select(key="fix_riga_movimento", section="General")
    if a and a[0].value =="False":
        rmfall = session.query(RigaMovimentoFornitura.id_articolo, RigaMovimentoFornitura.id_fornitura, RigaMovimentoFornitura.id_riga_movimento_acquisto).distinct().all()
        #print "RMFALL", rmfall
        num = len(rmfall)
        for riga in rmfall:
            if pbar:
                pbar(pbar_wid,parziale=rmfall.index(riga), totale=num, text="MIGRAZIONE TABELLA LOTTI ACQUISTO", noeta=False)
            #print "riga", riga
            print "RESIDUI DA GESTIRE ACQ", num - rmfall.index(riga)
            rmf = RigaMovimentoFornitura().select(idArticolo=riga[0], idRigaMovimentoAcquisto=riga[2], idFornitura=riga[1], batchSize=None)
            if rmf:
                for r in rmf:
                    if r.id_riga_movimento_vendita:
                        a = RigaMovimentoFornitura()
                        a.id_articolo = r.id_articolo
                        a.id_riga_movimento_vendita = r.id_riga_movimento_vendita
                        a.id_fornitura = r.id_fornitura
                        session.add(a)
                    if rmf.index(r) == 0:
                        a = RigaMovimentoFornitura()
                        a.id_articolo = r.id_articolo
                        a.id_riga_movimento_acquisto = r.id_riga_movimento_acquisto
                        a.id_fornitura = r.id_fornitura
                        session.add(a)
                    session.delete(r)
                        #session.add(r)
        session.commit()
        print " FINITO ACQ"
        rmfall2 = session.query(RigaMovimentoFornitura.id_riga_movimento_vendita).distinct().all()
        #print rmfall2
        num2 = len(rmfall2)
        for riga2 in rmfall2:
            if pbar_wid:
                pbar(pbar_wid,parziale=rmfall2.index(riga2), totale=num2, text="MIGRAZIONE TABELLA LOTTI VENDITA", noeta=False)
            print "RESIDUI DA GESTIRE VEN", num2 - rmfall2.index(riga2)
            if riga2[0] is not None:
                rmf2 = RigaMovimentoFornitura().select(idRigaMovimentoVendita=riga2[0], batchSize=None)
                #print "RMFFFFFFFFFFFFFFFFFFF", rmf2
                for ff in rmf2[1:]:
                    if ff.id_riga_movimento_acquisto is None:
                        session.delete(ff)
                session.commit()
        if pbar_wid:
            pbar(pbar_wid,stop=True)
        c = SetConf().select(key="fix_riga_movimento", section="General")
        c[0].value = str(True)
        session.add(c[0])
        session.commit()
        if pbar_wid:
            pbar_wid.set_property("visible",False)
        print "FATTO IL FIX"
    else:
        print "NIENTE DA FIXARE"
Exemplo n.º 9
0
    def analizza(self, data_inizio=None, data_fine=None, pageData=None):
        if not data_inizio:
            messageError(msg='Inserire una data d\'inizio periodo.')
            return 0
        if not data_fine:
            data_inizio_, data_fine = dataInizioFineMese(data_inizio)

        documenti = TestataDocumento().select(complexFilter=(and_(or_(TestataDocumento.operazione=='Fattura differita vendita', TestataDocumento.operazione=='Fattura accompagnatoria'), TestataDocumento.data_documento.between(data_inizio, data_fine))), batchSize=None)

        if not documenti:
            messageInfo(msg="Nessun risultato.")
            return 0

        righe = []

        buff = self.recordIB()

        i = 0
        totale_importi = Decimal(0)

        for documento in documenti:

            if self.progressbar:
                pbar(self.progressbar, parziale=i, totale=len(documenti))

            ope = leggiOperazione(documento.operazione)
            if ope:
                if ope['tipoPersonaGiuridica'] != 'cliente':
                    continue

            banca = None
            if documento.id_banca:
                banca = leggiBanca(documento.id_banca)
            else:
                continue

            cli = leggiCliente(documento.id_cliente)
            cli_ente = Cliente().getRecord(id=documento.id_cliente)
            cod_fisc_piva = ''
            if cli_ente:
                cod_fisc_piva = cli_ente.codice_fiscale or cli_ente.partita_iva
            else:
                cod_fisc_piva = documento.codice_fiscale_cliente
            debitore = Debitore(cod_fisc_piva, banca['abi'], banca['cab'])
            debitore.descrizione[0] = ''
            if cli['ragioneSociale']:
                debitore.descrizione[0] = cli['ragioneSociale']
            else:
                debitore.descrizione[0] = cli['cognome'] + ' ' + cli['nome']
            debitore.indirizzo = documento.indirizzo_cliente
            debitore.CAP = documento.cap_cliente
            debitore.provincia = documento.provincia_cliente
            debitore.comune = documento.localita_cliente

            for scadenza in documento.scadenze:
                if pagamentoLookup(scadenza.pagamento):

                    row = "%s N. %s a %s del %s \nImporto: %s data scadenza: %s" % (documento.operazione,
                                                     documento.numero,
                                                     documento.intestatario,
                                                     dateToString(documento.data_documento),
                                                     # scadenza.pagamento,
                                                     mN(scadenza.importo, 2),
                                                     dateToString(scadenza.data)
                                                     )

                    progressivo = i + 1
                    totale_importi += scadenza.importo
                    buff += self.record14(progressivo, scadenza.data, scadenza.importo, debitore)
                    buff += self.record20(progressivo)
                    buff += self.record30(progressivo, debitore)
                    buff += self.record40(progressivo, debitore)
                    buff += self.record50(progressivo, debitore, row.replace('\n', ''))
                    buff += self.record51(progressivo, progressivo)
                    buff += self.record70(progressivo)

                    riga = {
                        'destinatario': debitore.descrizione[0],
                        'indirizzo': debitore.indirizzo,
                        'CAP': debitore.CAP,
                        'comune': debitore.comune,
                        'provincia': debitore.provincia,
                        'cod_fisc_piva': cod_fisc_piva,
                        'banca_abi': banca['abi'],
                        'banca_cab': banca['cab'],
                        'importo': scadenza.importo,
                        'data_scadenza': scadenza.data,
                        'rif_debito': row
                    }
                    righe.append(riga)

                    i = i + 1

        buff += self.recordEF(i, totale_importi)

        pageData['righe'] = righe
        pageData['totale_importi'] = totale_importi
        pageData['disposizioni'] = i

        if self.progressbar:
            pbar(self.progressbar, stop=True)

        self._buffer = buff
Exemplo n.º 10
0
def do_send_mail(daos, anag=None, formato='pdf'):
    if anag:
        anag.pbar_anag_complessa.show()
    # recupera informazioni account posta elettronica
    try:
        account_email = session.query(AccountEmail).filter_by(id_azienda=azienda, preferito=True).one()
    except:  # NoResultFound
        raise NoAccountEmailFound("Nessun account email configurato")

    password = ''
    if keyring:
        password = keyring.get_password('promogest2', account_email.username)
    else:
        from promogest.lib.utils import inputPasswordDialog

        password = inputPasswordDialog()

    s = None
    if account_email.cripto_SSL:
        try:
            s = smtplib.SMTP_SSL(account_email.server_smtp, port=account_email.porta_smtp)
            time.sleep(1)
            s.login(account_email.username, password or '')
        except:
            raise NetworkError('Errore di connessione al server di posta in uscita.')
    else:
        try:
            s = smtplib.SMTP(account_email.server_smtp)
            time.sleep(1)
            s.starttls()
            time.sleep(1)
            s.login(account_email.username, password or '')
        except:
            raise NetworkError('Errore di connessione al server di posta in uscita.')
    del password

    progressivo = 1
    for dao in daos:
        if not dao.id_cliente:
            continue

        # recupera email destinatario
        destinatario = dao.CLI.email_pec or dao.CLI.email_principale
        if not destinatario:
            continue

        if anag:
            utils.pbar(anag.pbar_anag_complessa,
                       parziale=daos.index(dao), totale=len(daos),
                       text="INVIO EMAIL MULTIPLO", noeta=False)

        # genera il documento
        path = resolve_save_file_path(ext=formato)
        mymode = 'wb'
        if formato == 'xml':
            mymode = 'w'
        with open(path, mode=mymode) as fp:
            if formato == 'pdf':
                fp.write(_to_pdf(dao))
            elif formato == 'xml':
                fp.write(to_fatturapa(dao, progressivo=progressivo))


        # prepara il messaggio email con allegato
        outer = MIMEMultipart()
        outer.set_charset('UTF-8')
        outer['Subject'] = account_email.oggetto
        outer['To'] = formataddr((destinatario, destinatario))
        outer['From'] = formataddr((account_email.indirizzo, account_email.indirizzo))
        ctype, encoding = mimetypes.guess_type(path)
        maintype, subtype = ctype.split('/', 1)
        fp = open(path, 'rb')
        msg = MIMEBase(maintype, subtype)
        msg.set_payload(fp.read())
        fp.close()
        encoders.encode_base64(msg)
        msg.add_header('Content-Disposition', 'attachment', filename=basename(path))
        outer.attach(msg)
        text_msg = MIMEText(account_email.body + '\n' + account_email.firma)
        outer.attach(text_msg)
        try:
            s.sendmail(account_email.indirizzo, [destinatario], outer.as_string())
        except:
            raise NetworkError('Invio fattura a "{0}" non riuscito.'.format(destinatario))
        progressivo += 1
        time.sleep(5)
    if s:
        s.quit()
    if anag:
        utils.pbar(anag.pbar_anag_complessa, stop=True)
        anag.pbar_anag_complessa.set_property("visible", False)
Exemplo n.º 11
0
    def fillDocument(self):
        """ Replacing tags with real values """
        self.gruppi = self.findTablesProperties()
        iteranti = self.getIteratableGroups(self.gruppi)
        self.pageObjects = self.slaPageObjects()
        iterator = 0
        while iterator < self.lenPageObjects():
            if self.pbar:
                pbar(self.pbar,pulse=True,text="GENERAZIONE STAMPA ATTENDERE %s") %(str(iterator))
            pageObject = self.pageObjects[iterator]
            isTableItem = pageObject.get('isTableItem')
            isGroupControl = pageObject.get('isGroupControl')
            pageNumber = int(pageObject.get('OwnPage')) + 1
            group = str(pageObject.get('GROUPS')).strip()
            itexts = pageObject.findall('ITEXT')
            try:
                group= group.strip().split('%%%')[0]
            except:
                group = group
            pfile = pageObject.get('PFILE')
            if (pfile != ''):
                iterator += 1
                continue
            if group:
                actualGroup = group
                if str(actualGroup).strip() not in iteranti:
                    # Replacing non-iterator tags

                    for itext in itexts:
                        ch = itext.get('CH')
                        tags = Sla2pdfUtils.findTags(ch)
                        #print "Stampo il tag", tags
                        if tags is not None:
                            tagsKeys = tags.keys()
                            #print "Dizionario dei tags tagsKeys",  tagsKeys
                            for tagkey in tagsKeys:
                                if tagkey.replace(' ', '') == '':
                                    continue
                                #try:
                                resolvedTag = ''
                                function = tags[tagkey]['function']
                                parameter = tags[tagkey]['parameter']
                                if "X" in parameter:
                                    parameter = parameter.split("X")
                                if tagkey == 'currentPage':
                                    value = pageNumber
                                elif tagkey == 'totalPage':
                                    value = self.pagesNumber
                                elif tagkey in self.timeTags:
                                    value = Sla2pdfUtils.getNowValue(tagkey)
                                else:
                                    if self.cycle <= (len(self.objects) - 1):
                                        try:
                                            value = self.objects[self.cycle][tagkey] or ''
                                        except:
                                            if "destinazione_merce" in tagkey:
                                                if tagkey == "destinazione_merce":
                                                    value = self.daos.DM.denominazione or ""
                                                elif tagkey == "indirizzo_destinazione_merce":
                                                    value = self.daos.DM.indirizzo
                                                elif tagkey == "localita_destinazione_merce":
                                                    value = self.daos.DM.localita or ""
                                                elif tagkey == "cap_destinazione_merce":
                                                    value = self.daos.DM.cap or ""
                                                elif tagkey == "provincia_destinazione_merce":
                                                    value = self.daos.DM.provincia or ""
                                            #else:
                                                #try:

                                    else:
                                        value = ''
                                # Function
                                if function in self.formatFunctions:
                                    resolvedTag = uu(self.callFunction(function, value, parameter))
                                else:
                                    resolvedTag = uu(value)
                                ch = ch.replace(tags[tagkey]['completeTag'], resolvedTag)
                                  # Save itext
                                try:
                                    if value.count('€') >1:
                                        value = value.replace('€', '', 1)
                                except:
                                    pass
                                itext.set('CH', ch)

                else:
                    if isGroupControl == '1':
                        iterator += 1
                        continue
                    for itext in itexts:
                        ch = str(itext.get('CH'))
                        if '<<' in ch and '>>' in ch:
                            while (ch.find('<<') > -1) and (ch.find('>>') > -1):
                                arrayIndex = int(ch[ch.find('<<')+2:ch.find('>>')])
                                ch = ch.replace(('<<%d>>' % arrayIndex), '')
                        else:
                            arrayIndex = -1
                        tags = Sla2pdfUtils.findTags(ch)
                        if tags is not None:
                            for k in tags.keys():
                                if k.replace(' ', '') == '':
                                    continue
                                #try:
                                resolvedTag = ''
                                function = tags[k]['function']
                                parameter = tags[k]['parameter']
                                if k == 'currentPage':
                                    value = pageNumber
                                elif k == 'totalPage':
                                    value = self.pagesNumber
                                elif k in self.timeTags:
                                    value = Sla2pdfUtils.getNowValue(k)
                                else:
                                    indexN = k.find('(n)')
                                    if '(n)' in k:
                                        indexNP = k.find('(n).')
                                        if '(n).' in k:
                                            arrayName = k[:indexNP]
                                            tagName = k[indexNP+4:]
                                            if self.cycle <= (len(self.objects) - 1):
                                                if arrayIndex <= (len(self.objects[self.cycle][arrayName]) - 1):
                                                    arraySource = self.objects[self.cycle][arrayName][arrayIndex]

                                                    if SHOWZERORIGA == True:
                                                        value = arraySource[tagName]
                                                    else:
                                                        value = arraySource[tagName] or ""
                                                else:
                                                    value = ''
                                            else:
                                                value = ''
                                        else:
                                            tagName = k[:indexN]
                                            if arrayIndex <= (len(self.objects) - 1):
                                                arraySource = self.objects[arrayIndex]
                                                if SHOWZEROTOTALI:
                                                    value = str(arraySource[tagName])
                                                else:
                                                    value = arraySource[tagName] or ''
                                            else:
                                                value = ''
                                    else:
                                        if self.cycle <= (len(self.objects) - 1):
                                            value = self.objects[self.cycle][k] or ''
                                        else:
                                            value = ''
                                # Function
#                                print "FUCTION", function, value, parameter
                                if function in self.formatFunctions:
                                    resolvedTag = uu(self.callFunction(function, value, parameter))
                                else:
                                    resolvedTag = uu(value)
                                ch = ch.replace(tags[k]['completeTag'], resolvedTag)
                                try:
                                    if value.count('€') >1:
                                        value = value.replace('€', '', 1)
                                except:
                                    pass
                                itext.set('CH', ch)
            iterator += 1
def ricerca_forniture(fornitore, dataInizio, dataFine, progress=None):
    if not (fornitore or dataInizio or dataFine):
        return None

    data = {}
    totale_acq = 0
    totale_ven = 0
    totale_qta_acq = 0
    totale_qta_ven = 0

    id_articoli_forniture = session.query(Fornitura.id_articolo) \
            .distinct(Fornitura.id_articolo) \
            .filter(Fornitura.id_fornitore==fornitore.id) \
            .filter(Fornitura.data_fornitura>datetime.date(dataInizio.year,1,1)) \
            .all()
    # + datetime.timedelta(days=1)
    for id_articol in id_articoli_forniture:
        id_articolo = id_articol[0]
        res = session.query(Riga, RigaMovimento, TestataMovimento) \
                .join(RigaMovimento, TestataMovimento) \
                .filter(Riga.id_articolo==id_articolo) \
                .filter(TestataMovimento.data_movimento.between(dataInizio, dataFine)) \
                .all()

        for item in res:
            riga, rigamov, testmov = item
            if testmov.id_fornitore and testmov.id_cliente:
                continue
            elif testmov.id_fornitore:
                if str(id_articolo) not in data:
                    data[str(id_articolo)] = {'QTAACQ': riga.quantita * riga.moltiplicatore,
                                             'TOTACQ': rigamov.totaleRiga,
                                             'DAO_ART': riga.arti,
                                             'DAO_RIGAMOV': rigamov,
                                             'QTAVEN': 0, 'TOTVEN': 0}
                else:
                    data[str(id_articolo)]['QTAACQ'] += riga.quantita * riga.moltiplicatore
                    data[str(id_articolo)]['TOTACQ'] += rigamov.totaleRiga
                totale_acq += rigamov.totaleRiga
                totale_qta_acq += riga.quantita * riga.moltiplicatore

            elif testmov.id_cliente:
                if str(id_articolo) not in data:
                    data[str(id_articolo)] = {'QTAVEN': riga.quantita * riga.moltiplicatore,
                                             'TOTVEN': rigamov.totaleRiga,
                                             'DAO_ART': riga.arti,
                                             'DAO_RIGAMOV': rigamov,
                                             'QTAACQ': 0, 'TOTACQ': 0}
                else:
                    data[str(id_articolo)]['QTAVEN'] += riga.quantita * riga.moltiplicatore
                    data[str(id_articolo)]['TOTVEN'] += rigamov.totaleRiga
                totale_ven += rigamov.totaleRiga
                totale_qta_ven += riga.quantita * riga.moltiplicatore


        if progress:
            from promogest.lib.utils import pbar
            pbar(progress, parziale=id_articoli_forniture.index(id_articol),
                totale=len(id_articoli_forniture),
                text="Controllo documenti...", noeta=True)

    return data, {'totale_qta_acq': totale_qta_acq,
            'totale_qta_ven': totale_qta_ven,
            'totale_ven': totale_ven,
            'totale_acq': totale_acq}
def ricerca_forniture_lotti(fornitore, daData, aData, progress=None):
    data = {}

    if not fornitore:
        return None

    forniture = Fornitura().select(idFornitore=fornitore.id,
        daDataFornitura=daData,
        aDataFornitura=aData,
        batchSize=None)

    tot_a = 0
    tot_v = 0
    totale_qta_acq = 0
    totale_qta_ven = 0
    for fornitura in forniture:

        righe_mf = RigaMovimentoFornitura().select(idFornitura=fornitura.id)

        mov_acq = [riga_mf.rigamovacq for riga_mf in righe_mf if riga_mf.rigamovacq]

        for riga_mov in mov_acq:
            if not riga_mov:
                continue
            id_articolo = riga_mov.rig.id_articolo
            if str(id_articolo) not in data:
                data[str(id_articolo)] = {'QTAACQ': riga_mov.rig.quantita * riga_mov.rig.moltiplicatore,
                                         'TOTACQ': riga_mov.totaleRiga,
                                         'DAO_ART': riga_mov.rig.arti,
                                         'DAO_RIGAMOV': riga_mov,
                                         'QTAVEN': 0, 'TOTVEN': 0}
            else:
                data[str(id_articolo)]['QTAACQ'] += riga_mov.rig.quantita * riga_mov.rig.moltiplicatore
                data[str(id_articolo)]['TOTACQ'] += riga_mov.totaleRiga
            tot_a += riga_mov.totaleRiga
            totale_qta_acq += riga_mov.rig.quantita * riga_mov.rig.moltiplicatore

        mov_ven = [riga_mf.rigamovven for riga_mf in righe_mf if riga_mf.rigamovven]

        for riga_mov in mov_ven:
            if not riga_mov:
                continue
            id_articolo = riga_mov.rig.id_articolo
            if str(id_articolo) not in data:
                data[str(id_articolo)] = {'QTAVEN': riga_mov.rig.quantita * riga_mov.rig.moltiplicatore,
                                         'TOTVEN': riga_mov.totaleRiga,
                                         'DAO_ART': riga_mov.rig.arti,
                                         'DAO_RIGAMOV': riga_mov,
                                         'QTAACQ': 0, 'TOTACQ': 0}
            else:
                data[str(id_articolo)]['QTAVEN'] += riga_mov.rig.quantita * riga_mov.rig.moltiplicatore
                data[str(id_articolo)]['TOTVEN'] += riga_mov.totaleRiga
            tot_v += riga_mov.totaleRiga
            totale_qta_ven += riga_mov.rig.quantita * riga_mov.rig.moltiplicatore

        if progress:
            from promogest.lib.utils import pbar
            pbar(progress, parziale=forniture.index(fornitura), totale=len(forniture),
                text="Attendere...", noeta=True)

    return data, {'totale_qta_acq': totale_qta_acq,
            'totale_qta_ven': totale_qta_ven,
            'totale_ven': tot_v,
            'totale_acq': tot_a}