public PagamentoRitenutaDTO GetByDomainEntity(PagamentoRitenuta item)
 {
     try
     {
         return setDto(item);
     }
     catch (Exception ex)
     {
         log4net.MDC.Set("user", Gipasoft.Security.Login.Instance.CurrentLogin().LoginName);
         _log.Error("Errore nel caricamento dei pagamenti delle ritenute: " +  Gipasoft.Library.Utility.GetMethodDescription() + " - id:" + item.ID.ToString(), ex);
         throw ex;
     }
 }
        public void SetMovimentiRitenuta(PagamentoRitenuta fileRitenuta, string descrizioneAddebitoInteressi, string descrizioneAddebitoSanzioni)
        {
            try
            {
                var numeroRiga = 0;
                var causale = _daoFactory.GetCausaleContabileDao().GetByCodice("VR");
                var lista = new Dictionary<Esercizio, TestataMovimentoContabile>(fileRitenuta.Pagamenti.Count);

                foreach (var pag in fileRitenuta.Pagamenti)
                {
                    try
                    {
                        // ------------------------------------------------
                        // Testata
                        // ------------------------------------------------
                        TestataMovimentoContabile testata;

                        var esercizi = (from es in _daoFactory.GetEsercizioDao().GetByCondominio(pag.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento)
                                        where es.Gestione == GestioneEsercizioEnum.Ordinario && es.DataApertura <= fileRitenuta.Data.GetValueOrDefault() && es.DataChiusura >= fileRitenuta.Data.GetValueOrDefault()
                                        select es).ToList();

                        if (esercizi.Count() > 1)
                        {
                            var eserciziId = esercizi.Aggregate(string.Empty, (current, es) => current + (" id:" + es.ID + " descrizione:" + es.Descrizione + " - "));
                            _log.WarnFormat("Uno o più esercizi ordinari si sovrappongono - {0} - condominio:{1} - esercizi:{2}", Utility.GetMethodDescription(), pag.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento.ID, eserciziId);
                        }
                        var esercizio = esercizi.FirstOrDefault() ?? pag.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento;

                        if (lista.ContainsKey(esercizio))
                            testata = lista[esercizio];
                        else
                        {
                            var message = IsAllowDataRegistrazione(new List<int> { esercizio.CondominioRiferimento.ID }, esercizio, fileRitenuta.Data.GetValueOrDefault());
                            if (message.Count == 0)
                            {
                                testata = new TestataMovimentoContabile(esercizio, fileRitenuta.Data, TipoTestataMovimentoContabileEnum.Automatica, null);
                                _daoFactory.GetTestataMovimentoContabileDao().SaveOrUpdate(testata);
                                lista.Add(esercizio, testata);
                            }
                            else
                            {
                                var ex = new InvalidDataException(string.Format("La data di registrazione {0} non è valida", fileRitenuta.Data));
                                _log.ErrorFormat("Data di registrazione non valida - {0} - data:{1} - pagamento:{2} - esercizio:{3}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, pag.ID , esercizio.ID);
                                throw ex;
                            }
                        }

                        var spesa = pag.ScadenzaRiferimento.SpesaRiferimento;
                        var firstDettaglio = spesa.Dettagli.FirstOrDefault();
                        TestataMovimentoContabile testataFattura = null;
                        if (firstDettaglio != null)
                        {
                            var firstMovimento = firstDettaglio.Movimenti.FirstOrDefault();
                            if (firstMovimento != null)
                                testataFattura = firstMovimento.Testata;
                        }
                        
                        // ------------------------------------------------
                        // Interessi per Ravvedimento Operoso
                        // ------------------------------------------------
                        if (pag.RitenutaAcconto.ImportoInteressi > 0)
                        {
                            if (testataFattura != null && !testataFattura.AperturaBilancio)
                            {
                                var importo = spesa.Dettagli.SelectMany(item => item.Movimenti).Sum(item => item.Importo.GetValueOrDefault());
                                foreach (var dettaglio in spesa.Dettagli)
                                {
                                    try
                                    {
                                        foreach (var movimento in dettaglio.Movimenti)
                                        {
                                            try
                                            {
                                                var importoMovimento = movimento.GetImportoConSegno().GetValueOrDefault();
                                                if (movimento.ContoRiferimento.Tipo == TipoContoEconomicoEnum.Patrimoniale)
                                                    importoMovimento = importoMovimento * -1;

                                                var interesseCompetenza = pag.RitenutaAcconto.ImportoInteressi.GetValueOrDefault();
                                                if (spesa.ImportoLordo != 0)
                                                    interesseCompetenza = (pag.RitenutaAcconto.ImportoInteressi.GetValueOrDefault() * importoMovimento) / importo;
                                                else
                                                {
                                                    _log.WarnFormat("Trovata spesa con importo lordo a 0 - {0} - spesa:{1} - data:{2} - movimento:{3} - pagamento:{4} - file ritenuta:{5}", Utility.GetMethodDescription(), spesa.ID, fileRitenuta.Data, movimento.ID, pag.ID, fileRitenuta.ID);
                                                }

                                                var movimentoInteresse = new MovimentoContabile(testata, causale, numeroRiga, movimento.ContoRiferimento, interesseCompetenza, "D")
                                                {
                                                    SottoContoRiferimento = movimento.SottoContoRiferimento,
                                                    FornitoreRiferimento = movimento.FornitoreRiferimento,
                                                    Descrizione = descrizioneAddebitoInteressi.Replace("<DescrizioneSpesa>", movimento.GetDescrizione()),
                                                    TipoInteresseSanzione = TipoInteresseSanzioneEnum.Interesse,
                                                    PagamentoInteresseSanzione = pag
                                                };

                                                // TODO: Da verificare per i problemi riscontrati con interessi e sanzioni
                                                // "Interessi ravv. operoso - " + movimento.GetDescrizione();
                                                _ripartizioneService.CloneRipartizioneByMovimento(movimentoInteresse, movimento);

                                                _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoInteresse);

                                            }
                                            catch (Exception ex)
                                            {
                                                _log.ErrorFormat("Errore inaspettato nella funzione - (SINGOLO MOVIMENTO INTERESSE) - {0} - data:{1} - movimento:{2} - pagamento:{3} - file ritenuta:{4}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, movimento.ID, pag.ID, fileRitenuta.ID);
                                                throw;
                                            }
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        _log.ErrorFormat("Errore inaspettato nella funzione - (SINGOLO DETTAGLIO INTERESSE) - {0} - data:{1} - dettaglio:{2} - pagamento:{3} - file ritenuta:{4}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, dettaglio.ID, pag.ID, fileRitenuta.ID);
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                numeroRiga++;
                                var sottoContoInteressiSanzioni = _daoFactory.GetSottoContoDao().GetInteressiSanzioniByEsercizio(testata.EsercizioRiferimento.ID, testata.EsercizioRiferimento.CondominioRiferimento.ID);
                                if (sottoContoInteressiSanzioni != null)
                                {
                                    var movimentoInteresse = new MovimentoContabile(testata, causale, numeroRiga, sottoContoInteressiSanzioni.ContoRiferimento, pag.RitenutaAcconto.ImportoInteressi.GetValueOrDefault(), "D")
                                    {
                                        SottoContoRiferimento = sottoContoInteressiSanzioni,
                                        FornitoreRiferimento = spesa.FornitoreRiferimento,
                                        Descrizione = "Interesse versamento ritenuta"
                                    };

                                    _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoInteresse);
                                }
                                else
                                {
                                    pag.RitenutaAcconto.ImportoInteressi = null;
                                }
                            }

                        }

                        // ------------------------------------------------
                        // Sanzione per Ravvedimento Operoso
                        // ------------------------------------------------
                        if (pag.RitenutaAcconto.ImportoSanzione > 0)
                        {
                            if (testataFattura != null && !testataFattura.AperturaBilancio)
                            {
                                var importo = spesa.Dettagli.SelectMany(item => item.Movimenti).Sum(item => item.Importo.GetValueOrDefault());
                                foreach (var dettaglio in spesa.Dettagli)
                                {
                                    try
                                    {
                                        foreach (var movimento in dettaglio.Movimenti)
                                        {
                                            try
                                            {
                                                var importoMovimento = movimento.GetImportoConSegno().GetValueOrDefault();
                                                if (movimento.ContoRiferimento.Tipo == TipoContoEconomicoEnum.Patrimoniale)
                                                    importoMovimento = importoMovimento * -1;

                                                var sanzioneCompetenza = pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault();
                                                if (spesa.ImportoLordo != 0)
                                                    sanzioneCompetenza = (pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault() * importoMovimento) / importo;
                                                else
                                                {
                                                    _log.WarnFormat("Trovata spesa con importo lordo a 0 - (SANZIONE) - {0} - spesa:{1} - data:{2} - movimento:{3} - pagamento:{4} - file ritenuta:{5}", Utility.GetMethodDescription(), spesa.ID, fileRitenuta.Data, movimento.ID, pag.ID, fileRitenuta.ID);
                                                }

                                                var movimentoSanzione = new MovimentoContabile(testata, causale, numeroRiga, movimento.ContoRiferimento, sanzioneCompetenza, "D")
                                                {
                                                    SottoContoRiferimento = movimento.SottoContoRiferimento,
                                                    FornitoreRiferimento = movimento.FornitoreRiferimento,
                                                    Descrizione = descrizioneAddebitoSanzioni.Replace("<DescrizioneSpesa>", movimento.GetDescrizione()),
                                                    TipoInteresseSanzione = TipoInteresseSanzioneEnum.Sanzione,
                                                    PagamentoInteresseSanzione = pag
                                                };
                                                //"Sanzione ravv. operoso - " + movimento.GetDescrizione();
                                                _ripartizioneService.CloneRipartizioneByMovimento(movimentoSanzione, movimento);

                                                _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoSanzione);

                                            }
                                            catch (Exception ex)
                                            {
                                                _log.ErrorFormat("Errore inaspettato nella funzione - (SINGOLO MOVIMENTO INTERESSE) - {0} - data:{1} - movimento:{2} - pagamento:{3} - file ritenuta:{4}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, movimento.ID, pag.ID, fileRitenuta.ID);
                                                throw;
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        _log.ErrorFormat("Errore inaspettato nella funzione - (SINGOLO DETTAGLIO RAVVEDIMENTO) - {0} - data:{1} - dettaglio:{2} - pagamento:{3} - file ritenuta:{4}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, dettaglio.ID, pag.ID, fileRitenuta.ID);
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                numeroRiga++;
                                var sottoContoInteressiSanzioni = _daoFactory.GetSottoContoDao().GetInteressiSanzioniByEsercizio(testata.EsercizioRiferimento.ID, testata.EsercizioRiferimento.CondominioRiferimento.ID);
                                if (sottoContoInteressiSanzioni != null)
                                {
                                    var movimentoSanzione = new MovimentoContabile(testata, causale, numeroRiga, sottoContoInteressiSanzioni.ContoRiferimento, pag.RitenutaAcconto.ImportoSanzione, "D")
                                    {
                                        SottoContoRiferimento = sottoContoInteressiSanzioni,
                                        FornitoreRiferimento = spesa.FornitoreRiferimento,
                                        Descrizione = "Sanzione versamento ritenuta"
                                    };

                                    _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoSanzione);
                                }
                                else
                                {
                                    pag.RitenutaAcconto.ImportoSanzione = 0;
                                }
                            }
                        }

                        // ------------------------------------------------
                        // Ritenuta
                        // ------------------------------------------------
                        numeroRiga++;
                        var movimentoPatrimoniale = new MovimentoContabile(testata, causale, numeroRiga, _daoFactory.GetContoDao().GetByCodice(esercizio.ID, esercizio.CondominioRiferimento.ID, _pianoContiService.GetCodiceContoRitenuta()), pag.RitenutaAcconto.Importo, "D")
                        {
                            FornitoreRiferimento = pag.ScadenzaRiferimento.SpesaRiferimento.FornitoreRiferimento,
                            Descrizione = "Versamento Ritenuta " + pag.GetDescrizione()
                        };
                        _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoPatrimoniale);

                        // ------------------------------------------------
                        // BANCA
                        // ------------------------------------------------
                        numeroRiga++;
                        var movimentoBancario = new MovimentoContabile(testata, causale, numeroRiga, _daoFactory.GetContoDao().GetByCodice(esercizio.ID, esercizio.CondominioRiferimento.ID, _pianoContiService.GetCodiceContoBancario()), pag.RitenutaAcconto.ImportoConInteressi + pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault(), "A")
                        {
                            FornitoreRiferimento = movimentoPatrimoniale.FornitoreRiferimento,
                            Descrizione = movimentoPatrimoniale.Descrizione,
                            ContoCorrenteBancario = esercizio.CondominioRiferimento.DatiBancariPrincipale
                        };
                        _daoFactory.GetMovimentoContabileDao().SaveOrUpdate(movimentoBancario);

                        pag.RitenutaAcconto.MovimentoContabilePagamento = movimentoBancario;

                        setMovimentoArrotondamento(testata, causale, null);
                    }
                    catch (Exception ex)
                    {
                        _log.ErrorFormat("Errore inaspettato nella funzione - (SINGOLO PAGAMENTO) - {0} - data:{1} - pagamento:{2} - fileRitenuta:{3}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, pag.ID, fileRitenuta.ID);
                        throw;
                    }

                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato nella funzione - {0} - data:{1} - fileRitenuta:{2}", ex, Utility.GetMethodDescription(), fileRitenuta.Data, fileRitenuta.ID);
                throw;
            }
        }
Esempio n. 3
0
        public byte[] EsecuzionePagamenti(PagamentoRitenuta ritenuta, bool testataPerCondominio, bool mittenteCondominio, DateTime dataVersamento)
        {
            _testata = ritenuta;
            byte[] bytes = null;

            try
            {
                // =============================================================================================
                // Compilo il modulo PDF
                // =============================================================================================
                var modulo = RitenutaModuloPDFResources.ResourceManager.GetObject("F24_" + dataVersamento.Year);
                if (modulo != null)
                {
                    var listaPagamenti = ordinaDisposizioni(new List<Pagamento>(_testata.Pagamenti));

                    // Per ogni condominio creo un modulo
                    var moduliCondomini = new List<byte[]>();
                    foreach (var condominio in listaPagamenti.Keys)
                    {
                        var iban = condominio.DatiBancariPrincipale.Iban;
                        if (!string.IsNullOrEmpty(iban) && iban.StartsWith("IT"))
                            iban = iban.Substring(2);

                        // Intestazione
                        var datiF24 = new DatiModelloF24
                        {
                            CodiceFiscaleCondominio = condominio.CodiceFiscale,
                            ComuneCondominio = condominio.Indirizzo.Comune.Descrizione,
                            IbanCondominio = iban,
                            IndirizzoCondominio = condominio.Indirizzo.Indirizzo + condominio.Indirizzo.Civico,
                            ProvinciaCondominio = condominio.Indirizzo.Comune.ProvinciaAppartenenza.Codice,
                            DataVersamento = dataVersamento.ToShortDateString()
                        };

                        if (dataVersamento.Year == 2014)
                            datiF24.IbanCondominio = datiF24.IbanCondominio.Substring(2);

                        var nomeCondominio = condominio.Descrizione;
                        if (nomeCondominio.Length > 70)
                        {
                            datiF24.NomeCondominio = nomeCondominio.Substring(0, 70);
                            datiF24.NomeCondominio2 = nomeCondominio.Substring(71);
                        }
                        else
                            datiF24.NomeCondominio = nomeCondominio;

                        // Dati Banca
                        var banca = _daoFactory.GetAbiCabDao().GetByAbiCab(condominio.DatiBancariPrincipale.Abi, condominio.DatiBancariPrincipale.Cab);
                        datiF24.NomeBancaDelega = banca.DescrizioneAbi;
                        datiF24.NomeAgenziaDelega = banca.DescrizioneCab;
                        datiF24.ProvinciaAgenziaDelega = banca.Provincia;

                        var progressivoTributo = 0;
                        var totaleDebito = 0m;
                        var totaleCredito = 0m;
                        foreach (var kvp in listaPagamenti[condominio])
                        {
                            progressivoTributo++;
                            decimal? importoADebito = (from pag in kvp.Value
                                                       where pag.RitenutaAcconto.Importo != null && pag.RitenutaAcconto.Importo > 0
                                                       select pag).Sum(pag => Math.Round(pag.RitenutaAcconto.ImportoConInteressi, 2));
                            setImporto(kvp.Key, importoADebito.GetValueOrDefault(), progressivoTributo, datiF24);

                            // Eventuali sanzioni
                            var importoSanzione = kvp.Value.Sum(pag => Math.Round(pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault(), 2));
                            if (importoSanzione > 0)
                            {
                                progressivoTributo++;
                                setImporto("8906¥" + kvp.Key.Split('¥')[1], importoSanzione, progressivoTributo, datiF24);
                            }

                            totaleDebito += importoADebito.GetValueOrDefault() + importoSanzione;
                        }

                        datiF24.TotaleImportoADebito = totaleDebito.ToString("#0.00");
                        datiF24.TotaleImporto = datiF24.TotaleImportoADebito;

                        var xmlMappingFile = RitenutaModuloPDFResources.ResourceManager.GetObject(string.Format("F24_FieldMapping_{0}", dataVersamento.Year));
                        if (xmlMappingFile == null)
                            xmlMappingFile = RitenutaModuloPDFResources.ResourceManager.GetObject("F24_FieldMapping");

                        moduliCondomini.Add(FillForm.FillStream(datiF24, (byte[])modulo, Library.Conversione.ToString(xmlMappingFile), false, true));
                    }

                    // Merge di tutte le pagine
                    if (moduliCondomini.Count > 0)
                    {
                        try
                        {
                            var pdfmerge = new PdfMerge();
                            bytes = pdfmerge.Merge(moduliCondomini, true);
                        }
                        catch (Exception ex)
                        {
                            _log.ErrorFormat("Errore nel merge dei moduli - {0} - ritenuta:{1} - azienda:{2}", ex, Library.Utility.GetMethodDescription(), ritenuta.ID, ritenuta.AziendaID);                            
                            throw;
                        }
                    }
                }


                return bytes;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione del file CBI delle ritenute - F24. - {0} - ritenuta:{1}", ex, Library.Utility.GetMethodDescription(), ritenuta.ID);
                _notifier.Notify("Si sono verificati problemi inaspettati durante la creazione del file CBI delle ritenute - F24." + Environment.NewLine + "Controllare il log per ulteriori dettagli.");
                return bytes;
            }

        }
Esempio n. 4
0
        private void writeCodaEF(PagamentoRitenuta testata, string abi, Condominio cond, int numeroDeleghe, decimal importoTotale, int numeroRighe, bool mittenteCondominio, TextWriter sw)
        {
            try
            {
                var sb = new StringBuilder(120);

                var azienda = _daoFactory.GetAziendaDao().GetById(testata.AziendaID.GetValueOrDefault(), false);

                // Tipo Record
                sb.Append(" EF");

                // Codice SIA azienda mittente (studio) o condominio in funzione della scelta dell'operatore
                sb.Append(mittenteCondominio ? cond.CodiceSIA : azienda.CodiceSIA);

                // Codice ABI Banca passiva (ordinante cioè ABI della banca del condominio)
                sb.Append(abi.Trim().PadLeft(5, '0'));

                // data creazione
                sb.Append(convertData(DateTime.Today));

                // nome supporto - riferimento Disposizione
                sb.Append(getNomeSupporto(cond).PadLeft(20, '0'));

                // campo a disposizione
                sb.Append(string.Empty.PadLeft(6));

                // ----------------------------------------
                // Riepilogo
                // ----------------------------------------
                // numero deleghe
                sb.Append(numeroDeleghe.ToString(CultureInfo.InvariantCulture).PadLeft(7, '0'));

                // totale importi positivi
                sb.Append(convertImporto(importoTotale));

                // totale importi negativi
                sb.Append(string.Empty.PadLeft(15, '0'));

                // numero totale righe flusso
                sb.Append(numeroRighe.ToString(CultureInfo.InvariantCulture).PadLeft(7, '0'));

                // filler
                sb.Append(string.Empty.PadLeft(24));

                // divisa
                sb.Append("E");

                // filler
                sb.Append(string.Empty.PadLeft(6));

                sw.WriteLine(sb.ToString());
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione della testata del file cbi per F24 - PAGAMENTI - {0} - abi:{1} - azienda:{2}", ex, Library.Utility.GetMethodDescription(), abi, _testata != null ? _testata.AziendaID.ToString() : "<NULL>");
                throw;
            }
        }
Esempio n. 5
0
        // Pagamento
        private decimal writeMovimento5001(PagamentoRitenuta testata, List<Pagamento> pagamenti, Condominio condominio, bool mittenteCondominio, int numeroDelega, StreamWriter sw)
        {
            try
            {
                var sb = new StringBuilder(120);

                // ---------------------------------------
                // Calcolo importi
                // ---------------------------------------
                decimal? importoADebito = (from pag in pagamenti
                                           where pag.RitenutaAcconto.Importo != null && pag.RitenutaAcconto.Importo > 0
                                           select pag).Sum(pag => (Math.Round(pag.RitenutaAcconto.ImportoConInteressi, 2) + Math.Round(pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault(), 2)));
                decimal? importoACredito = (from pag in pagamenti
                                            where pag.RitenutaAcconto.Importo != null && pag.RitenutaAcconto.Importo < 0
                                            select pag).Sum(pag => (Math.Round(pag.RitenutaAcconto.ImportoConInteressi, 2))) * -1;

                // Tipo Record
                sb.Append(" 50");

                // Numero Disposizione
                sb.Append(numeroDelega.ToString(CultureInfo.InvariantCulture).PadLeft(7, '0'));

                // Sub Tipo Record
                sb.Append("01");

                // --------------------------------------------------------------------
                // Banca Passiva (Banca del condominio)
                // --------------------------------------------------------------------
                // ABI
                sb.Append(condominio.DatiBancariPrincipale.Abi.PadLeft(5, '0'));
                // CAB
                sb.Append(condominio.DatiBancariPrincipale.Cab.PadLeft(5, '0'));
                // Conto Corrente
                sb.Append(condominio.DatiBancariPrincipale.ContoCorrente.PadLeft(12, '0'));
                // Conto Corrente
                sb.Append(condominio.DatiBancariPrincipale.Cin);

                // --------------------------------------------------------------------
                // Saldo
                // --------------------------------------------------------------------
                decimal saldo = 0;
                saldo += importoADebito.GetValueOrDefault();
                saldo -= importoACredito.GetValueOrDefault();
                if (saldo < 0)
                    saldo = saldo * -1;
                // Importo Saldo
                sb.Append(convertImporto(saldo));

                // flag firmatario
                sb.Append("0");
                
                // filler
                sb.Append(string.Empty.PadLeft(2));

                // Codice fiscale del titolare del conto di addebito: condominio se mittente è il condominio ..... 
                if (mittenteCondominio)
                {
                    sb.Append(condominio.CodiceFiscale.PadRight(16));

                    // Titolare del conto di addebito (condominio)
                    sb.Append("2");
                }
                // .... altrimenti lo studio
                else
                {
                    sb.Append(condominio.Azienda.CodiceFiscale.PadRight(16));

                    // Titolare del conto di addebito (studio)
                    sb.Append("3");
                }

                // data pagamento
                var dataPagamento = _dataVersamento;
                if (testata.Data != null)
                    dataPagamento = testata.Data.Value;
                sb.Append(dataPagamento.ToString("yyyyMMdd"));

                // Importo a credito compensato
                sb.Append(convertImporto(importoACredito));

                // filler
                sb.Append(string.Empty.PadLeft(2));

                // tipo codice individuale
                sb.Append("3");

                // In futuro qui avremo codice paese e check digit dell'IBAN

                // filler
                sb.Append(string.Empty.PadLeft(24));

                sw.WriteLine(sb.ToString());

                return saldo;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione della testata del file cbi per F24 - PAGAMENTI - {0} - condominio:{1} - azienda:{2}", ex, Library.Utility.GetMethodDescription(), condominio != null ? condominio.ID.ToString() : "<NULL>", _testata != null ? _testata.AziendaID.ToString() : "<NULL>");
                throw;
            }        
        }
Esempio n. 6
0
        // Domicilio Fiscale / Altri dati della Delega 
        private void writeRiga20(PagamentoRitenuta testata, Condominio condominio, TextWriter sw, int numeroDelega)
        {
            try
            {
                var sb = new StringBuilder(120);

                // Tipo Record
                sb.Append(" 20");

                // Numero Delega
                sb.Append(numeroDelega.ToString(CultureInfo.InvariantCulture).PadLeft(7, '0'));

                // --------------------------------------------------------------------
                // Indirizzo del soggetto indicato nella delega F24 (condominio)
                // --------------------------------------------------------------------
                // Comune
                var comune = Library.Conversione.ToInvioTelematico(condominio.Indirizzo.Comune.Descrizione);
                if (comune.Length > 25)
                    comune = comune.Substring(0, 25);
                sb.Append(comune.PadRight(25));

                // Provincia
                sb.Append(condominio.Indirizzo.Comune.ProvinciaAppartenenza.Codice.PadRight(2));

                // Indirizzo
                var indirizzo = Library.Conversione.ToInvioTelematico(condominio.Indirizzo.Indirizzo);
                if (indirizzo.Length > 35)
                    indirizzo = indirizzo.Substring(0, 35);
                sb.Append(indirizzo.PadRight(35));

                // data pagamento
                var dataPagamento = _dataVersamento;
                if (testata.Data != null)
                    dataPagamento = testata.Data.Value;
                sb.Append(dataPagamento.ToString("yyyyMMdd"));

                // Flag anno imposta
                sb.Append("0");

                // Secondo codice fiscale
                sb.Append(string.Empty.PadLeft(16));

                // Codice Identificativo
                sb.Append(string.Empty.PadLeft(2));

                // filler
                sb.Append(string.Empty.PadLeft(21));

                sw.WriteLine(sb.ToString());
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione della testata del file cbi per F24 - {0} - condominio:{1} - azienda:{2}", ex, Library.Utility.GetMethodDescription(), condominio != null ? condominio.ID.ToString() : "<NULL>", _testata != null ? _testata.AziendaID.ToString() : "<NULL>");
                throw;
            }
        }
Esempio n. 7
0
        private void writeTestataF4(PagamentoRitenuta testata, string codiceAbi, Condominio cond, bool mittenteCondominio, StreamWriter sw)
        {
            try
            {
                var sb = new StringBuilder(120);

                var azienda = _daoFactory.GetAziendaDao().GetById(testata.AziendaID.GetValueOrDefault(), false);

                // Tipo Record
                sb.Append(" F4");

                // Codice SIA azienda mittente (studio) o condominio in funzione della scelta dell'operatore
                sb.Append(mittenteCondominio ? cond.CodiceSIA : azienda.CodiceSIA);

                // Codice ABI Banca passiva (ordinante cioè ABI della banca del condominio)
                sb.Append(codiceAbi.Trim().PadLeft(5, '0'));

                // data creazione
                sb.Append(convertData(DateTime.Today));

                // nome supporto - riferimento Disposizione
                sb.Append(getNomeSupporto(cond).PadLeft(20, '0'));

                // campo a disposizione
                sb.Append(string.Empty.PadLeft(6));

                // filler
                sb.Append(string.Empty.PadLeft(59));

                // Tipo Flusso
                sb.Append("2");
                // Qualificatore Flusso
                sb.Append("$");
                // Soggetto Veicolatore Flusso (codice sia studio)
                sb.Append(azienda.CodiceSIA);

                // filler
                sb.Append(string.Empty.PadLeft(2));

                // divisa
                sb.Append("E");

                // filler
                sb.Append(string.Empty.PadLeft(1));

                // campo non utilizzabile
                sb.Append(string.Empty.PadLeft(5));

                sw.WriteLine(sb.ToString());
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante la creazione della testata del file cbi per F24 - {0} - condominio:{1} - azienda:{2}", ex, Library.Utility.GetMethodDescription(), cond != null ? cond.ID.ToString() : "<NULL>", _testata != null ? _testata.AziendaID.ToString() : "<NULL>");
                throw;
            }
        }
Esempio n. 8
0
        public byte[] EsecuzionePagamenti(PagamentoRitenuta ritenuta, bool testataPerCondominio, bool mittenteCondominio, DateTime dataVersamento)
        {
            _testata = ritenuta;
            _dataVersamento = dataVersamento;
            var abi = string.Empty;
            byte[] bytes = null;
            StreamWriter sw = null;
            try
            {
                if (!testataPerCondominio)
                    mittenteCondominio = false;

                var fileName = Path.GetTempPath() + "\\" + Guid.NewGuid();
                if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
                    fileName = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory + "\\" + Guid.NewGuid();
                if (File.Exists(fileName))
                    File.Delete(fileName);

                // =============================================================================================
                // Creo il file
                // =============================================================================================
                using (sw = File.CreateText(fileName))
                {
                    int numeroRighe = 1;
                    int numeroDelega = 0;
                    decimal importoTotale = 0;

                    if (!testataPerCondominio)
                    {
                        // Creo le riga di testa
                        numeroRighe = 1;
                        numeroDelega = 0;
                        importoTotale = 0;

                        var groupByAbi = (from item in _testata.Pagamenti
                                          group item by item.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento.DatiBancariPrincipale.Abi into pagamentiPerAbi
                                          select pagamentiPerAbi).ToList();
                        var count1 = groupByAbi.Count();
                        abi = count1 == 1 ? groupByAbi.Single().First().ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento.DatiBancariPrincipale.Abi : _daoFactory.GetAziendaDao().GetById(_testata.AziendaID.GetValueOrDefault(), false).BancaRiferimentoRitenuta.ID.Abi;

                        writeTestataF4(_testata, abi, null, mittenteCondominio, sw);
                    }
                    var listaPagamenti = ordinaDisposizioni(new List<Pagamento>(_testata.Pagamenti));

                    foreach (var condominio in listaPagamenti.Keys)
                    {
                        if (testataPerCondominio)
                        {
                            // Creo le riga di testa
                            numeroRighe = 1;
                            numeroDelega = 0;
                            importoTotale = 0;
                            writeTestataF4(_testata, condominio.DatiBancariPrincipale.Abi, condominio, mittenteCondominio, sw);
                        }

                        numeroDelega++;
                        writeRiga10(condominio, sw, numeroDelega);
                        numeroRighe++;
                        writeRiga20(ritenuta, condominio, sw, numeroDelega);
                        numeroRighe++;

                        var progressivoTributo = 0;
                        foreach (var kvp in listaPagamenti[condominio])
                        {
                            numeroRighe++;
                            progressivoTributo++;
                            writeMovimento4001(kvp.Value, kvp.Key, numeroDelega, progressivoTributo, sw);

                            // Eventuali sanzioni
                            var importoSanzione= kvp.Value.Sum(pag => Math.Round(pag.RitenutaAcconto.ImportoSanzione.GetValueOrDefault(), 2));
                            if (importoSanzione > 0)
                            {
                                numeroRighe++;
                                progressivoTributo++;
                                writeMovimento4001(importoSanzione, null, getKeySanzione("8906", kvp.Key), numeroDelega, progressivoTributo, sw);
                            }
                        }

                        var pagamentiPerCondominio = mergeDisposizioni(listaPagamenti[condominio]);

                        numeroRighe++;
                        var saldo = writeMovimento4002(pagamentiPerCondominio, numeroDelega, sw);
                        
                        _log.DebugFormat("Creazione file ritenute per banca - {0} - condominio:{1} - importoSaldo:{2}", Library.Utility.GetMethodDescription(), condominio.ID, saldo);

                        numeroRighe++;
                        importoTotale += writeMovimento5001(ritenuta, pagamentiPerCondominio, condominio, mittenteCondominio, numeroDelega, sw);
                        numeroRighe++;
                        writeMovimento5002(_testata.AziendaID.GetValueOrDefault(), condominio, mittenteCondominio, numeroDelega, sw);
                        numeroRighe++;
                        writeMovimento5003(_testata.AziendaID.GetValueOrDefault(), numeroDelega, sw);

                        if (testataPerCondominio)
                        {
                            numeroRighe++;
                            writeCodaEF(_testata, condominio.DatiBancariPrincipale.Abi, condominio, numeroDelega, importoTotale, numeroRighe, mittenteCondominio, sw);
                        }

                    }

                    if (!testataPerCondominio)
                    {
                        numeroRighe++;
                        writeCodaEF(_testata, abi, null, numeroDelega, importoTotale, numeroRighe, mittenteCondominio, sw);
                    }
                }

                _notifier.Notify("Il file delle ritenute F24 è stato correttamente creato.");

                var infile = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                bytes = new byte[infile.Length];
                infile.Read(bytes, 0, bytes.Length);

                ritenuta.ContenutoFile = Library.Conversione.ToString(bytes);

                return bytes;
            }
            catch (Exception ex)
            {
                _log.FatalFormat("Errore inaspettato durante la creazione del file CBI delle ritenute - F24 - {0}", ex, Library.Utility.GetMethodDescription());
                _notifier.Notify("Si sono verificati problemi inaspettati durante la creazione del file CBI delle ritenute - F24." + Environment.NewLine + "Controllare il log per ulteriori dettagli.");
                return bytes;
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
Esempio n. 9
0
        public string AddVersamentoRitenutaEccesso(int idPagamento, decimal importo, decimal importoInteressi, decimal importoSanzione, DateTime dataPagamento, int idConto, int? idSottoConto, string descrizione, string descrizioneAddebitoInteressi, string descrizioneAddebitoSanzioni)
        {
            try
            {
                var anomalie = string.Empty;

                if (!string.IsNullOrEmpty(descrizione) && descrizione.Trim().Length > 500)
                    descrizione = descrizione.Trim().Substring(0, 500);

                var pagamento = _daoFactory.GetPagamentoDao().Find(idPagamento, false);
                var conto = _daoFactory.GetContoDao().Find(idConto, false);

                if (pagamento != null && conto != null)
                {
                    // Se il versamento in eccesso è già presente devo annullare i relativi movimenti contabili
                    PagamentoRitenuta pagamentoRitenuta = null;
                    if (pagamento.RitenutaAccontoEccesso != null && pagamento.RitenutaAccontoEccesso.Importo > 0)
                    {
                        pagamentoRitenuta = pagamento.RitenutaAccontoEccesso.TestataRiferimento;
                        _movimentiContabilitaService.DeleteMovimento(pagamento.RitenutaAccontoEccesso.MovimentoContabilePagamento.ID);
                    }

                    pagamento.RitenutaAccontoEccesso = new Ritenuta(importo)
                    {
                        ImportoInteressi = importoInteressi,
                        ImportoSanzione = importoSanzione,
                        DataPagamentoRitenuta = dataPagamento
                    };

                    if (pagamentoRitenuta == null)
                    {
                        pagamentoRitenuta = new PagamentoRitenuta(pagamento.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento.Azienda.ID, descrizione, dataPagamento, true, TipoVersamentoF24Enum.Immediato);
                        pagamentoRitenuta.Pagamenti.Add(pagamento);
                        _daoFactory.GetPagamentoRitenutaDao().SaveOrUpdate(pagamentoRitenuta);
                    }
                    else
                    {
                        pagamentoRitenuta.Descrizione = descrizione;
                        pagamentoRitenuta.Data = dataPagamento;
                    }

                    pagamento.RitenutaAccontoEccesso.Stato = StatoRitenutaEnum.Pagata;
                    pagamento.RitenutaAccontoEccesso.TestataRiferimento = pagamentoRitenuta;

                    pagamentoRitenuta.TestataContabile = _movimentiContabilitaService.SetMovimentiRitenuta(pagamento,pagamento.RitenutaAccontoEccesso, conto, idSottoConto, dataPagamento, descrizione, descrizioneAddebitoInteressi, descrizioneAddebitoSanzioni, null);
                }
                return anomalie;
            }
            catch(Exception ex)
            {
                
                _log.Fatal("Errore inaspettato durante l'inserimento della ritenuta in eccesso - " + Utility.GetMethodDescription() + " - idPagamento " + idPagamento + " - importo:" + importo + " - importoInteressi:" + importoInteressi + " - importoSanzione:" + importoSanzione + " - dataPagamento:" + dataPagamento + " - idConto:" + idConto + " - idSottoConto:" + idSottoConto.GetValueOrDefault() + " - descrizione:" + descrizione + " - descrizioneAddebitoInteressi:" + descrizioneAddebitoInteressi + " - descrizioneAddebitoSanzioni:" + descrizioneAddebitoSanzioni, ex);
                throw; 
            }
        }
Esempio n. 10
0
        public string PagamentoRitenuta(Pagamento pagamento, DateTime dataPagamento, Conto conto, int? idSottoconto, string descrizione, decimal? importo, decimal? importoInteressi, decimal? importoSanzione)
        {
            try
            {
                var anomalie = string.Empty; 
                if (Conversione.IsSqlSmallDateTime(dataPagamento))
                {
                    if (!string.IsNullOrEmpty(descrizione) && descrizione.Trim().Length > 500)
                        descrizione = descrizione.Trim().Substring(0, 500);

                    var pagamentoRitenuta = new PagamentoRitenuta(pagamento.ScadenzaRiferimento.SpesaRiferimento.EsercizioRiferimento.CondominioRiferimento.Azienda.ID, descrizione, dataPagamento, true, TipoVersamentoF24Enum.Immediato);
                    pagamentoRitenuta.Pagamenti.Add(pagamento);
                    _daoFactory.GetPagamentoRitenutaDao().SaveOrUpdate(pagamentoRitenuta);

                    if (importoInteressi != null)
                        pagamento.RitenutaAcconto.ImportoInteressi = importoInteressi.Value;

                    if (importoSanzione != null)
                        pagamento.RitenutaAcconto.ImportoSanzione = importoSanzione.Value;

                    pagamento.RitenutaAcconto.Stato = StatoRitenutaEnum.Pagata;
                    pagamento.RitenutaAcconto.TestataRiferimento = pagamentoRitenuta;
                    pagamentoRitenuta.TestataContabile = _movimentiContabilitaService.SetMovimentiRitenuta(pagamento, pagamento.RitenutaAcconto, conto, idSottoconto, dataPagamento, descrizione, null, null, importo);
                }
                else
                {
                    _log.WarnFormat("La data di pagamento della ritenuta non è corretta - {0} - pagamento:{1} - importo:{2} - dataPagamento:{3:d} - conto:{4} - idSottoconto:{5} - descrizione:{6}", Utility.GetMethodDescription(), pagamento.ID, importo, dataPagamento, conto.ID, idSottoconto.GetValueOrDefault(), descrizione);
                }

                return anomalie;
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Errore inaspettato durante l'inserimento pagamento della ritenuta - {0} - pagamento:{1} - importo:{2} - dataPagamento:{3:d} - conto:{4} - idSottoconto:{5} - descrizione:{6}", ex, Utility.GetMethodDescription(), pagamento.ID, importo, dataPagamento, conto.ID, idSottoconto.GetValueOrDefault(), descrizione);
                throw; 
            }
        }
Esempio n. 11
0
        public byte[] CreateRitenute(int idAzienda, IList<RitenutaAccontoDTO> lista, DateTime dataPagamento, string descrizione, string descrizioneAddebitoInteressi, string descrizioneAddebitoSanzioni, bool mittenteCondominio, bool testataPerCondominio, TipoVersamentoF24Enum tipoVersamento)
        {
            var fileRitenuta = new PagamentoRitenuta(idAzienda, descrizione, dataPagamento, false, tipoVersamento);
            _daoFactory.GetPagamentoRitenutaDao().SaveOrUpdate(fileRitenuta);
            decimal importoTotaleRitenuta = 0;
            decimal importoTotaleInteressi = 0;
            decimal importoTotaleSanzione = 0;
            foreach (var ritenuta in lista)
            {
                var pagamentoRiferimento = _daoFactory.GetPagamentoDao().Find(ritenuta.IdPagamento.GetValueOrDefault(), true);
                if(pagamentoRiferimento != null)
                {
                    pagamentoRiferimento.RitenutaAcconto.TestataRiferimento = fileRitenuta;
                    fileRitenuta.Pagamenti.Add(pagamentoRiferimento);
                    pagamentoRiferimento.RitenutaAcconto.Stato = StatoRitenutaEnum.Pagata;
                    pagamentoRiferimento.RitenutaAcconto.ImportoInteressi = ritenuta.ImportoInteressi;
                    pagamentoRiferimento.RitenutaAcconto.ImportoSanzione = ritenuta.ImportoSanzione;
                    importoTotaleRitenuta += ritenuta.ImportoRitenuta.GetValueOrDefault();
                    importoTotaleInteressi += ritenuta.ImportoInteressi.GetValueOrDefault();
                    importoTotaleSanzione += ritenuta.ImportoSanzione.GetValueOrDefault();
                }
            }

            fileRitenuta.ImportoRitenuta = importoTotaleRitenuta;
            fileRitenuta.ImportoInteressi = importoTotaleInteressi;
            fileRitenuta.ImportoSanzione = importoTotaleSanzione;

            var fileBody = _esecuzioneRitenuta.EsecuzionePagamenti(fileRitenuta, testataPerCondominio, mittenteCondominio, dataPagamento);
            if (fileBody != null)
            {
                // Se richiesto il modulo PDF salvo il modulo come documento
                if(tipoVersamento == TipoVersamentoF24Enum.PDF)
                {
                    var fileName = string.Format("Modulo F24 del {0}-{1}-{2}", dataPagamento.Day, dataPagamento.Month, dataPagamento.Year);
                    var documentMessage = _documentService.SaveDocument(fileBody, fileName, ".pdf", null, idAzienda);
                    if(documentMessage.Documento != null)
                    {
                        var checksum = documentMessage.Documento.Checksum;
                        var moduloPdf = new Documento(checksum, fileName, ".pdf", "ModuloF24", false, _daoFactory.GetAziendaDao().GetById(idAzienda, false)) { PagamentoRitenuta = fileRitenuta };
                        _daoFactory.GetDocumentoDao().SaveOrUpdate(moduloPdf);
                    }
                }

                _movimentiContabilitaService.SetMovimentiRitenuta(fileRitenuta, descrizioneAddebitoInteressi, descrizioneAddebitoSanzioni);
                return fileBody;
            }
            _persistenceContext.RollbackAndCloseSession(Security.Login.Instance.CurrentLogin().LoginName);
            _persistenceContext.BeginTransaction(Security.Login.Instance.CurrentLogin().LoginName, IsolationLevel.ReadUncommitted);

            return null;
        }
        //public int? ManageDomainEntity(PianoRatealeDTO dto)
        //{
        //    try
        //    {
        //        return this.manage(dto).ID;
        //    }
        //    catch (Exception ex)
        //    {
        //        log4net.MDC.Set("user", Gipasoft.Security.Login.Instance.CurrentLogin().LoginName);
        //        _log.Error("Errore nel caricamento del piano rateale: Gipasoft.Business.Sfera.Repository.PianoRatealeRepository.ManageDomainEntity() - id:" + dto.ID.ToString(), ex);
        //        throw ex;
        //    }
        //}

        #endregion Public Methods

        #region Private Methods

        private PagamentoRitenutaDTO setDto(PagamentoRitenuta item)
        {
            PagamentoRitenutaDTO dto = new PagamentoRitenutaDTO()
            {
                Data = item.Data,
                Descrizione = item.Descrizione,
                ID = item.ID,
                IdAzienda = item.AziendaID.GetValueOrDefault(),
                ImportoInteressi = item.ImportoInteressi,
                ImportoRitenuta = item.ImportoRitenuta,
                ImportoSanzione = item.ImportoSanzione,
                IsDeleteAllow = item.IsDeleteAllow(),
                Version = item.Version,
                FrequentlyAccessed = item.FrequentlyAccessed,
                IsFittizio = item.IsFittizio
            };

            // Dettaglio Pagamenti
            dto.Pagamenti = new List<PagamentoListaRitenutaDTO>(item.Pagamenti.Count);
            PagamentoFatturaRepository rep = new PagamentoFatturaRepository();
            foreach (Pagamento pagamento in item.Pagamenti)
            {
                dto.Pagamenti.Add(rep.GetByDomainEntity(pagamento));
            }

            return dto;
        }
Esempio n. 13
0
 public virtual IUpdatableBusinessEntity Copy()
 {
     var ritenuta = new PagamentoRitenuta(AziendaID.GetValueOrDefault(), "<DA MODIFICARE>", Data, IsFittizio, TipoVersamentoF24);
     return ritenuta;
 }