Beispiel #1
0
            private static Analytics.GlobalStatisticsPerYear <Firma.Statistics.RegistrSmluv> CalculateGlobalRankPerYear_UradySmlouvy(
                int?obor    = null,
                int?threads = null,
                Action <string> logOutputFunc = null, Action <ActionProgressData> progressOutputFunc = null
                )
            {
                obor = obor ?? 0;
                var    icos    = Firmy.GlobalStatistics.VsechnyUrady(logOutputFunc, progressOutputFunc);
                object lockObj = new object();
                List <Analytics.StatisticsSubjectPerYear <Firma.Statistics.RegistrSmluv> > data =
                    new List <Analytics.StatisticsSubjectPerYear <Firma.Statistics.RegistrSmluv> >();

                Devmasters.Batch.Manager.DoActionForAll <string>(icos,
                                                                 (Func <string, ActionOutputData>)(
                                                                     ico =>
                {
                    var stat = Firmy.Get(ico)?.StatistikaRegistruSmluv(obor.Value);
                    if (stat != null)
                    {
                        lock (lockObj)
                        {
                            data.Add(stat);
                        }
                    }
                    return(new Devmasters.Batch.ActionOutputData());
                }), logOutputFunc, progressOutputFunc, true, maxDegreeOfParallelism: threads, prefix: $"CalculateGlobalRankPerYear_UradySmlouvy_{obor.Value} ");

                return(new Analytics.GlobalStatisticsPerYear <Firma.Statistics.RegistrSmluv>(
                           Analytics.Consts.RegistrSmluvYearsList,
                           data,
                           m => m.PocetSmluv >= 10
                           ));
            }
Beispiel #2
0
            public GenericSponzorItem(FirmaEvent fe)
            {
                this.Name       = Firmy.GetJmeno(fe.ICO);
                this.Amount     = fe.AddInfoNum ?? 0;
                this.SubjectUrl = Firmy.Get(fe.ICO).GetUrlOnWebsite(false);
                this.Strana     = fe.AddInfo;

                //transaction
                if (!string.IsNullOrEmpty(fe.Zdroj) && fe.Zdroj.ToLower().StartsWith("https://www.hlidacstatu.cz/ucty/transakce/"))
                {
                    //https://www.hlidacstatu.cz/ucty/transakce/7CCEEC74486A0B58A13DE15369B3CE74
                    var res = HlidacStatu.Lib.ES.Manager.GetESClient_Ucty()
                              .Get <HlidacStatu.Lib.Data.TransparentniUcty.BankovniPolozka>(fe.Zdroj.ToLower().Replace("https://www.hlidacstatu.cz/ucty/transakce/", ""));
                    if (res.Found)
                    {
                        this.Transaction    = res.Source;
                        this.TransactionUrl = this.Transaction.GetUrl(false);
                        this.Date           = this.Transaction.Datum;
                    }
                }
                if (this.Transaction == null)
                {
                    this.Date = fe.DatumOd ?? fe.Created;
                }
            }
        public string ToHtml(string itemTemplate = "{0}")
        {
            string kohoSponzoroval = JmenoPrijemce();

            if (string.IsNullOrWhiteSpace(kohoSponzoroval))
            {
                // nevime
                return("");
            }

            var kdySponzoroval = DarovanoDne.HasValue ? $"v roce {DarovanoDne?.Year}" : "v neznámém datu";

            var hodnotaDaruKc = Util.RenderData.NicePrice(Hodnota ?? 0, html: true);
            var dar           = (Typ == (int)TypDaru.FinancniDar) ?
                                $"částkou {hodnotaDaruKc}" :
                                $"nepeněžním darem ({Popis}) v hodnotě {hodnotaDaruKc}";
            var zdroj = string.IsNullOrWhiteSpace(this.Zdroj) ? "" :
                        $"(<a target=\"_blank\" href=\"{Zdroj}\"><span class=\"glyphicon glyphicon-link\" aria-hidden=\"true\"></span>zdroj</a>)";

            if (Typ == (int)TypDaru.DarFirmy)
            {
                return(string.Format(itemTemplate, $"Člen statut. orgánu ve firmě {Firmy.GetJmeno(IcoDarce)} sponzorující {kohoSponzoroval} {kdySponzoroval}, hodnota daru {hodnotaDaruKc}"));
            }

            return(string.Format(itemTemplate, $"Sponzor {kohoSponzoroval} {kdySponzoroval} {dar} {zdroj}"));
        }
Beispiel #4
0
        public static IEnumerable <(string idDotace, string ico, int ageInDays)> CompanyAgeDuringSubsidy()
        {
            var dotSer = new Dotace.DotaceService();

            foreach (var dotace in dotSer.YieldAllDotace())
            {
                bool missingEssentialData = string.IsNullOrWhiteSpace(dotace.Prijemce?.Ico) ||
                                            !dotace.DatumPodpisu.HasValue;

                if (missingEssentialData)
                {
                    continue;
                }

                Firma firma = Firmy.Get(dotace.Prijemce.Ico);

                if (firma.PatrimStatu()) //nechceme státní firmy
                {
                    continue;
                }

                if (!firma.Datum_Zapisu_OR.HasValue) //nechceme firmy s chybějící hodnotou data zapisu do OR
                {
                    continue;
                }

                var companyAgeInDays = (dotace.DatumPodpisu.Value - firma.Datum_Zapisu_OR.Value).Days;

                yield return(idDotace : dotace.IdDotace, ico : firma.ICO, ageInDays : companyAgeInDays);
            }
        }
Beispiel #5
0
        public void Recalculate()
        {
            var resMinDate = Smlouva.Search.SimpleSearch("ico:" + this.Ico, 1, 1, Smlouva.Search.OrderResult.DateSignedAsc, platnyZaznam: true);

            if (resMinDate.Total > 0)
            {
                DateTime firstSmlouva = resMinDate.Results.First().datumUzavreni;
                DateTime zalozena     = Firmy.Get(this.Ico).Datum_Zapisu_OR ?? new DateTime(1990, 1, 1);
                this.PocetDni_k_PrvniSmlouve = (int)((firstSmlouva - zalozena).TotalDays);
            }
        }
Beispiel #6
0
        public static string GetJmeno(string ico)
        {
            var f = Firmy.Get(ico);

            if (f.Valid)
            {
                return(f.Jmeno);
            }
            else
            {
                return("(neznámé)");
            }
        }
Beispiel #7
0
                private static VZ Create(string ico)
                {
                    Firma f = Firmy.Get(ico);

                    if (f.Valid == false)
                    {
                        return(nullObj);
                    }
                    else
                    {
                        return(Create(f));
                    }
                }
Beispiel #8
0
 private Firma gf()
 {
     if (firma == null)
     {
         lock (lo)
         {
             if (firma == null)
             {
                 firma = Firmy.Get(this.ico);
             }
         }
     }
     return(firma);
 }
Beispiel #9
0
 public string PrintName(bool html = false)
 {
     switch (Type)
     {
         case NodeType.Person:
             return Osoby.GetById.Get(Convert.ToInt32(Id))?.FullNameWithYear(html) ?? "(neznámá osoba)";
         case NodeType.Company:
         default:
             return Firmy.GetJmeno(Id);
             //if (f.Valid)
             //    return f.Jmeno;
             //else
             //    return "(neznámá firma)";
     }
 }
Beispiel #10
0
            public string PrintName(bool html = false)
            {
                switch (Type)
                {
                case NodeType.Person:
                    return(Osoby.GetById.Get(Convert.ToInt32(Id))?.FullNameWithYear(html) ?? "(neznámá osoba)");

                case NodeType.Company:
                default:
                    var f = Firmy.Get(Id);
                    if (f.Valid)
                    {
                        return(f.Jmeno);
                    }
                    else
                    {
                        return("(neznámá firma)");
                    }
                }
            }
Beispiel #11
0
        public bool JeSmlouva_S_VazbouNaPolitiky(Relation.AktualnostType aktualnost)
        {
            var icos = ico_s_VazbouPolitik;

            if (aktualnost == Relation.AktualnostType.Nedavny)
            {
                icos = ico_s_VazbouPolitikNedavne;
            }
            if (aktualnost == Relation.AktualnostType.Aktualni)
            {
                icos = ico_s_VazbouPolitikAktualni;
            }
            Firma f = null;

            if (this.platnyZaznam)
            {
                f = Firmy.Get(this.Platce.ico);
                if (f.Valid && !f.PatrimStatu())
                {
                    if (!string.IsNullOrEmpty(this.Platce.ico) && icos.Contains(this.Platce.ico))
                    {
                        return(true);
                    }
                }

                foreach (var ss in this.Prijemce)
                {
                    f = Firmy.Get(ss.ico);
                    if (f.Valid && !f.PatrimStatu())
                    {
                        if (!string.IsNullOrEmpty(ss.ico) && icos.Contains(ss.ico))
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Beispiel #12
0
            public static RegistrSmluv Calculate(Osoba o, Data.Relation.AktualnostType aktualnost, int?obor)
            {
                RegistrSmluv res = new RegistrSmluv();

                res.OsobaNameId = o.NameId;
                res.Aktualnost  = aktualnost;
                res.Obor        = (Smlouva.SClassification.ClassificationsTypes?)obor;

                Dictionary <string, StatisticsSubjectPerYear <Smlouva.Statistics.Data> > statni = new Dictionary <string, StatisticsSubjectPerYear <Smlouva.Statistics.Data> >();
                Dictionary <string, StatisticsSubjectPerYear <Smlouva.Statistics.Data> > soukr  = new Dictionary <string, StatisticsSubjectPerYear <Smlouva.Statistics.Data> >();

                var perIcoStat = o.AktualniVazby(aktualnost)
                                 .Where(v => !string.IsNullOrEmpty(v.To?.UniqId) &&
                                        v.To.Type == HlidacStatu.Lib.Data.Graph.Node.NodeType.Company)
                                 .Select(v => v.To)
                                 .Distinct(new HlidacStatu.Lib.Data.Graph.NodeComparer())
                                 .Select(f => Firmy.Get(f.Id))
                                 .Where(f => f.Valid == true)
                                 .Select(f => new { f = f, ss = f.StatistikaRegistruSmluv(obor) });


                foreach (var it in perIcoStat)
                {
                    if (it.f.PatrimStatu())
                    {
                        statni.Add(it.f.ICO, it.ss);
                    }
                    else
                    {
                        soukr.Add(it.f.ICO, it.ss);
                    }
                }
                res.StatniFirmy   = statni;
                res.SoukromeFirmy = soukr;

                return(res);
            }
        public static AnalysisCalculation.VazbyFiremNaUradyStat UradyObchodujiciSFirmami_s_vazbouNaPolitiky(Relation.AktualnostType aktualnost, bool showProgress = false)
        {
            HlidacStatu.Lib.Data.AnalysisCalculation.VazbyFiremNaPolitiky vazbyNaPolitiky = null;
            List <Lib.Data.FirmaEvent> sponzorujiciFirmy = null;

            QueryContainer qc = null;

            switch (aktualnost)
            {
            case HlidacStatu.Lib.Data.Relation.AktualnostType.Aktualni:
                vazbyNaPolitiky = StaticData.FirmySVazbamiNaPolitiky_aktualni_Cache.Get();
                qc = new QueryContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>().Term(t => t.Field(f => f.SVazbouNaPolitikyAktualni).Value(true));
                sponzorujiciFirmy = StaticData.SponzorujiciFirmy_Nedavne.Get();
                break;

            case HlidacStatu.Lib.Data.Relation.AktualnostType.Nedavny:
                vazbyNaPolitiky = StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get();
                qc = new QueryContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>().Term(t => t.Field(f => f.SVazbouNaPolitikyNedavne).Value(true));
                sponzorujiciFirmy = StaticData.SponzorujiciFirmy_Nedavne.Get();
                break;

            case HlidacStatu.Lib.Data.Relation.AktualnostType.Neaktualni:
            case HlidacStatu.Lib.Data.Relation.AktualnostType.Libovolny:
                vazbyNaPolitiky = StaticData.FirmySVazbamiNaPolitiky_vsechny_Cache.Get();
                qc = new QueryContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>().Term(t => t.Field(f => f.SVazbouNaPolitiky).Value(true));
                sponzorujiciFirmy = StaticData.SponzorujiciFirmy_Vsechny.Get();
                break;
            }


            Func <int, int, Nest.ISearchResponse <Lib.Data.Smlouva> > searchFunc = null;

            searchFunc = (size, page) =>
            {
                return(Lib.ES.Manager.GetESClient().Search <Lib.Data.Smlouva>(a => a
                                                                              .Size(size)
                                                                              .From(page * size)
                                                                              .Source(m => m.Excludes(e => e.Field(o => o.Prilohy)))
                                                                              .Query(q => qc)
                                                                              .Scroll("5m")
                                                                              ));
            };


            //TODO predelat z projeti vsech smluv na hledani pres vsechna ICO  v RS, vybrani statnich firem,
            //a dohlednai jejich statistiky vuci jednotlivym ostatnim firmam v RS
            Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > > uradyStatni = new Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > >();
            Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > > uradySoukr  = new Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > >();
            object lockObj = new object();

            Lib.ES.SearchTools.DoActionForQuery <Lib.Data.Smlouva>(Lib.ES.Manager.GetESClient(), searchFunc,
                                                                   (hit, param) =>
            {
                Lib.Data.Smlouva s = hit.Source;
                List <string> icos = new List <string>();
                try
                {
                    var objednatelIco = s.Platce.ico;
                    if (!string.IsNullOrEmpty(objednatelIco))
                    {
                        Firma ff = Firmy.Get(objednatelIco);
                        if (!ff.Valid || !ff.PatrimStatu())
                        {
                            goto end;
                        }

                        //vsichni prijemci smlouvy statniho subjektu
                        icos.AddRange(s.Prijemce.Select(m => m.ico).Where(m => !string.IsNullOrEmpty(m)).Distinct());

                        lock (lockObj)
                        {
                            foreach (var ico in icos)
                            {
                                if (vazbyNaPolitiky.SoukromeFirmy.ContainsKey(ico) || sponzorujiciFirmy.Any(m => m.ICO == ico))
                                {
                                    if (!uradySoukr.ContainsKey(objednatelIco))
                                    {
                                        uradySoukr.Add(objednatelIco, new Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > >());
                                        uradySoukr[objednatelIco].Ico = objednatelIco;
                                    }
                                    uradySoukr[objednatelIco].Add(1, s.CalculatedPriceWithVATinCZK);
                                    if (!uradySoukr[objednatelIco].Detail.Any(m => m.Item == ico))
                                    {
                                        uradySoukr[objednatelIco].Detail.Add(new Analysis.BasicData <string>()
                                        {
                                            Item = ico, CelkemCena = s.CalculatedPriceWithVATinCZK, Pocet = 1
                                        });
                                    }
                                    else
                                    {
                                        var item = uradySoukr[objednatelIco].Detail.First(m => m.Item == ico);
                                        item.Add(1, s.CalculatedPriceWithVATinCZK);
                                    }
                                }
                                else if (vazbyNaPolitiky.StatniFirmy.ContainsKey(ico))
                                {
                                    if (!uradyStatni.ContainsKey(objednatelIco))
                                    {
                                        uradyStatni.Add(objednatelIco, new Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > >());
                                        uradyStatni[objednatelIco].Ico = objednatelIco;
                                    }
                                    uradyStatni[objednatelIco].Add(1, s.CalculatedPriceWithVATinCZK);
                                    if (!uradyStatni[objednatelIco].Detail.Any(m => m.Item == ico))
                                    {
                                        uradyStatni[objednatelIco].Detail.Add(new Analysis.BasicData <string>()
                                        {
                                            Item = ico, CelkemCena = s.CalculatedPriceWithVATinCZK, Pocet = 1
                                        });
                                    }
                                    else
                                    {
                                        var item = uradyStatni[objednatelIco].Detail.First(m => m.Item == ico);
                                        item.Add(1, s.CalculatedPriceWithVATinCZK);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    HlidacStatu.Util.Consts.Logger.Error("ERROR UradyObchodujiciSFirmami_s_vazbouNaPolitiky", e);
                }

                end:
                return(new Devmasters.Core.Batch.ActionOutputData()
                {
                    CancelRunning = false, Log = null
                });
            }, null,
                                                                   showProgress ? Devmasters.Core.Batch.Manager.DefaultOutputWriter : (Action <string>)null,
                                                                   showProgress ? new Devmasters.Core.Batch.ActionProgressWriter().Write : (Action <ActionProgressData>)null
                                                                   , true
                                                                   , prefix: "UradyObchodujiciSFirmami_s_vazbouNaPolitiky " + aktualnost.ToNiceDisplayName()
                                                                   );


            AnalysisCalculation.VazbyFiremNaUradyStat ret = new VazbyFiremNaUradyStat();
            ret.SoukromeFirmy = uradySoukr
                                .Where(m => m.Value.Pocet > 0)
                                .Select(kv => kv.Value)
                                .OrderByDescending(o => o.Pocet);

            return(ret);
        }
        public static Tuple <VazbyFiremNaUradyStat, VazbyFiremNaUradyStat> UradyObchodujiciSFirmami_NespolehlivymiPlatciDPH(bool showProgress = false)
        {
            var nespolehliveFirmy = StaticData.NespolehlivyPlatciDPH.Get();

            Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > > uradyData
                = new Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > >();

            Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > > nespolehliveFirmyKontrakty
                = new Dictionary <string, Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > > >();

            var lockObj = new object();

            Devmasters.Core.Batch.Manager.DoActionForAll <NespolehlivyPlatceDPH>(nespolehliveFirmy.Values,
                                                                                 (nf) =>
            {
                var nespolehlivaFirma = Firmy.Get(nf.Ico);
                var ico     = nf.Ico;
                var smlouvy = SimpleSmlouvyForIco(ico, nf.FromDate);
                foreach (var s in smlouvy)
                {
                    var allIco = new List <string>(
                        s.Prijemce.Select(m => m.ico).Where(p => !string.IsNullOrEmpty(p))
                        );
                    allIco.Add(s.Platce.ico);
                    var urady = allIco.Select(i => Firmy.Get(i)).Where(f => f.PatrimStatu());

                    foreach (var urad in urady)
                    {
                        lock (lockObj)
                        {
                            if (!uradyData.ContainsKey(urad.ICO))
                            {
                                uradyData.Add(urad.ICO, new Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > >()
                                {
                                    Item = urad.ICO
                                });
                            }
                            uradyData[urad.ICO].Add(1, s.CalculatedPriceWithVATinCZK);
                            if (!uradyData[urad.ICO].Detail.Any(m => m.Item == ico))
                            {
                                uradyData[urad.ICO].Detail.Add(new Analysis.BasicData <string>()
                                {
                                    Item = ico, CelkemCena = s.CalculatedPriceWithVATinCZK, Pocet = 1
                                });
                            }
                            else
                            {
                                var item = uradyData[urad.ICO].Detail.First(m => m.Item == ico);
                                item.Pocet++;
                                item.CelkemCena += s.CalculatedPriceWithVATinCZK;
                            }

                            //--------------
                            if (!nespolehliveFirmyKontrakty.ContainsKey(ico))
                            {
                                nespolehliveFirmyKontrakty.Add(ico, new Analysis.BasicDataForSubject <List <Analysis.BasicData <string> > >());
                                nespolehliveFirmyKontrakty[ico].Ico = ico;
                            }
                            nespolehliveFirmyKontrakty[ico].Add(1, s.CalculatedPriceWithVATinCZK);
                            if (!nespolehliveFirmyKontrakty[ico].Detail.Any(m => m.Item == urad.ICO))
                            {
                                nespolehliveFirmyKontrakty[ico].Detail.Add(new Analysis.BasicData <string>()
                                {
                                    Item = urad.ICO, CelkemCena = s.CalculatedPriceWithVATinCZK, Pocet = 1
                                });
                            }
                            else
                            {
                                var item = nespolehliveFirmyKontrakty[ico].Detail.First(m => m.Item == urad.ICO);
                                item.Add(1, s.CalculatedPriceWithVATinCZK);
                            }
                        }
                    }
                }

                return(new ActionOutputData());
            },
                                                                                 showProgress ? Devmasters.Core.Batch.Manager.DefaultOutputWriter : (Action <string>)null,
                                                                                 showProgress ? new Devmasters.Core.Batch.ActionProgressWriter().Write : (Action <ActionProgressData>)null,
                                                                                 !System.Diagnostics.Debugger.IsAttached);

            VazbyFiremNaUradyStat ret = new VazbyFiremNaUradyStat();

            ret.StatniFirmy = uradyData
                              .Where(m => m.Value.Pocet > 0)
                              .Select(kv => kv.Value)
                              .OrderByDescending(o => o.Pocet)
                              .ToList();

            VazbyFiremNaUradyStat retNespolehliveFirmy = new VazbyFiremNaUradyStat();

            retNespolehliveFirmy.SoukromeFirmy = nespolehliveFirmyKontrakty
                                                 .Where(m => m.Value.Pocet > 0)
                                                 .Select(kv => kv.Value)
                                                 .OrderByDescending(o => o.Pocet)
                                                 .ToList();

            return(new Tuple <VazbyFiremNaUradyStat, VazbyFiremNaUradyStat>(ret, retNespolehliveFirmy));
        }
Beispiel #15
0
            private static Zatrideni.Item[] GetSubjektyDirect(StatniOrganizaceObor obor)
            {
                string[] icos = null;
                string   sql  = "";

                switch (obor)
                {
                case StatniOrganizaceObor.Vse:
                    icos = GetAllSubjektyFromRPP();
                    break;

                case StatniOrganizaceObor.Zdravotni_ustavy:
                case StatniOrganizaceObor.Hasicsky_zachranny_sbor:
                case StatniOrganizaceObor.Krajske_hygienicke_stanice:
                case StatniOrganizaceObor.Krajska_statni_zastupitelstvi:
                case StatniOrganizaceObor.Krajske_soudy:
                case StatniOrganizaceObor.Soudy:
                case StatniOrganizaceObor.Statutarni_mesta:
                case StatniOrganizaceObor.Verejne_vysoke_skoly:
                case StatniOrganizaceObor.Krajska_reditelstvi_policie:
                case StatniOrganizaceObor.Statni_fondy:
                case StatniOrganizaceObor.OSSZ:
                case StatniOrganizaceObor.Kraje_Praha:
                case StatniOrganizaceObor.Zdravotni_pojistovny:
                case StatniOrganizaceObor.Katastralni_urady:
                case StatniOrganizaceObor.Ministerstva:
                case StatniOrganizaceObor.Organizacni_slozky_statu:
                case StatniOrganizaceObor.Dalsi_ustredni_organy_statni_spravy:
                case StatniOrganizaceObor.Celni_urady:
                case StatniOrganizaceObor.Financni_urady:
                case StatniOrganizaceObor.Konzervatore:
                case StatniOrganizaceObor.Mestske_casti_Prahy:
                case StatniOrganizaceObor.OVM_pro_evidenci_skutecnych_majitelu:
                case StatniOrganizaceObor.Obce_III_stupne:
                    icos = GetSubjektyFromRPP((int)obor);
                    break;

                case StatniOrganizaceObor.Vsechny_ustredni_organy_statni_spravy:
                    icos = GetSubjektyFromRPP((int)StatniOrganizaceObor.Dalsi_ustredni_organy_statni_spravy)
                           .Concat(GetSubjektyFromRPP((int)StatniOrganizaceObor.Ministerstva))
                           .ToArray();
                    break;

                case StatniOrganizaceObor.Nemocnice:
                    sql  = @"select distinct ico from (
select f.ICO from Firma f where Jmeno like N'%nemocnice%' and f.IsInRS = 1
union
select distinct f.ico
    from Firma_NACE fn
    join firma f on f.ICO = fn.ICO
    where (nace like '861%' or NACE like '862%') and f.IsInRS = 1
    and f.Kod_PF not in (105, 101, 801, 601)
								
) as f
where f.ICO not in ('70876606','70994226','45274649','05243793','64203450','25916092','60800691','08297517','00212423')";
                    icos = GetSubjektyFromSQL(sql);
                    break;

                case StatniOrganizaceObor.Velke_nemocnice:
                    icos = "00064165,00064173,00064203,00098892,00159816,00179906,00669806,00843989,25488627,26365804,27283933,27661989,65269705,27283518,26000202,00023736,00023884,27256391,61383082,27256537,00023001,27520536,26068877,47813750,00064211,00209805,27660915,00635162,27256456,00090638,00092584,00064190"
                           .Split(',');
                    break;

                case StatniOrganizaceObor.Fakultni_nemocnice:
                    icos = "65269705,00179906,00669806,00098892,00843989,00064165,00064203,00159816,00064173"
                           .Split(',');
                    break;

                case StatniOrganizaceObor.Krajske_spravy_silnic:
                    icos = "00066001,00090450,70947023,70946078,72053119,00080837,70971641,27502988,00085031,70932581,70960399,00095711,26913453,03447286,25396544,60733098"
                           .Split(',');
                    break;

                case StatniOrganizaceObor.Dopravni_podniky:
                    icos = "05792291,25095251,25136046,25137280,00005886,25166115,25164538,25220683,29099846,61058238,48364282,62240935,64053466,06231292,62242504,25013891,47311975,00079642,06873031,25267213,63217066,25512897,25508881,00100790,47676639,05724252,64610250,61974757,60730153"
                           .Split(',');
                    break;

                case StatniOrganizaceObor.Technicke_sluzby:
                    sql  = @"select ico from Firma f where Jmeno like N'technické služby%' and f.IsInRS = 1";
                    icos = GetSubjektyFromSQL(sql);
                    break;

                case StatniOrganizaceObor.Domov_duchodcu:
                    sql  = @"select ico from Firma f where Jmeno like N'%domov důchodců%' and f.IsInRs = 1";
                    icos = GetSubjektyFromSQL(sql);
                    break;

                case StatniOrganizaceObor.Vyjimky_RS:

                    // Poslanecká sněmovna, Senát, Kancelář prezidenta republiky, Ústavní soud, Nejvyšší kontrolní úřad,
                    //Kancelář veřejného ochránce práv a Úřad Národní rozpočtové rady
                    //CNB
                    icos = new string[] { "00006572", "63839407", "48136000", "48513687", "49370227", "70836981", "05553539", "48136450" };
                    break;

                case StatniOrganizaceObor.Ostatni:
                    icos = new string[] { };
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                bool removeKraj = false;

                switch (obor)
                {
                case StatniOrganizaceObor.Ostatni:
                case StatniOrganizaceObor.Zdravotni_pojistovny:
                case StatniOrganizaceObor.Fakultni_nemocnice:
                case StatniOrganizaceObor.Krajska_statni_zastupitelstvi:
                case StatniOrganizaceObor.Krajske_soudy:
                case StatniOrganizaceObor.Kraje_Praha:
                case StatniOrganizaceObor.Mestske_casti_Prahy:
                case StatniOrganizaceObor.OSSZ:
                case StatniOrganizaceObor.Ministerstva:
                case StatniOrganizaceObor.Organizacni_slozky_statu:
                case StatniOrganizaceObor.Vsechny_ustredni_organy_statni_spravy:
                case StatniOrganizaceObor.Dalsi_ustredni_organy_statni_spravy:
                case StatniOrganizaceObor.Financni_urady:
                case StatniOrganizaceObor.Vyjimky_RS:
                case StatniOrganizaceObor.Verejne_vysoke_skoly:
                case StatniOrganizaceObor.Konzervatore:
                case StatniOrganizaceObor.Krajske_spravy_silnic:
                case StatniOrganizaceObor.OVM_pro_evidenci_skutecnych_majitelu:
                    removeKraj = true;
                    break;

                default:
                    break;
                }

                if (icos.Count() == 0)
                {
                    return new Item[] { }
                }
                ;
                else
                {
                    var ret = new System.Collections.Generic.List <Item>();

                    Devmasters.Batch.Manager.DoActionForAll <string>(icos.Select(m => m.Trim()).Distinct(),
                                                                     ic =>
                    {
                        var f = Firmy.Get(ic);

                        if (f.PatrimStatu())
                        {
                            lock (_getSubjektyDirectLock)
                            {
                                if (!ret.Any(ff => ff.Ico == f.ICO))
                                {
                                    ret.Add(new Item()
                                    {
                                        Ico    = f.ICO,
                                        Jmeno  = f.Jmeno,
                                        KrajId = removeKraj ? "" : f.KrajId,
                                        Kraj   = removeKraj ? "" : CZ_Nuts.Nace2Kraj(f.KrajId, "(neznamý)")
                                    });
                                }
                            }
                        }
                        return(new Devmasters.Batch.ActionOutputData());
                    }, !System.Diagnostics.Debugger.IsAttached);

                    return(ret.ToArray());
                }
            }
Beispiel #16
0
        public static IEnumerable <IcoSmlouvaMinMax> GetFirmyCasovePodezreleZalozene(Action <string> logOutputFunc = null, Action <ActionProgressData> progressOutputFunc = null)
        {
            HlidacStatu.Util.Consts.Logger.Debug("GetFirmyCasovePodezreleZalozene - getting all ico");
            var allIcos = Lib.Data.External.FirmyDB.AllIcoInRS();
            Dictionary <string, AnalysisCalculation.IcoSmlouvaMinMax> firmy = new Dictionary <string, AnalysisCalculation.IcoSmlouvaMinMax>();
            object lockFirmy = new object();
            var    client    = HlidacStatu.Lib.ES.Manager.GetESClient();
            AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva> aggs = new AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>()
                                                                                 .Min("minDate", m => m
                                                                                      .Field(f => f.datumUzavreni)
                                                                                      );


            HlidacStatu.Util.Consts.Logger.Debug("GetFirmyCasovePodezreleZalozene - getting first smlouva for all ico from ES");
            Devmasters.Batch.Manager.DoActionForAll <string, object>(allIcos,
                                                                     (ico, param) =>
            {
                Firma ff = Firmy.Get(ico);
                if (Firma.IsValid(ff))
                {
                    if (ff.PatrimStatu()) //statni firmy tam nechci
                    {
                        return(new Devmasters.Batch.ActionOutputData()
                        {
                            CancelRunning = false, Log = null
                        });
                    }
                    else
                    {
                        var res = HlidacStatu.Lib.Data.Smlouva.Search.SimpleSearch("ico:" + ico, 0, 0, HlidacStatu.Lib.Data.Smlouva.Search.OrderResult.FastestForScroll, aggs, exactNumOfResults: true);
                        if (res.ElasticResults.Aggregations.Count > 0)
                        {
                            var epoch = ((Nest.ValueAggregate)res.ElasticResults.Aggregations.First().Value).Value;
                            if (epoch.HasValue)
                            {
                                var mindate = Devmasters.DT.Util.FromEpochTimeToUTC((long)epoch / 1000);

                                lock (lockFirmy)
                                {
                                    if (firmy.ContainsKey(ico))
                                    {
                                        if (firmy[ico].minUzavreni.HasValue == false)
                                        {
                                            firmy[ico].minUzavreni = mindate;
                                        }
                                        else if (firmy[ico].minUzavreni.Value > mindate)
                                        {
                                            firmy[ico].minUzavreni = mindate;
                                        }
                                    }
                                    else
                                    {
                                        firmy.Add(ico, new AnalysisCalculation.IcoSmlouvaMinMax()
                                        {
                                            ico         = ico,
                                            minUzavreni = Devmasters.DT.Util.FromEpochTimeToUTC((long)epoch / 1000)
                                        });
                                    }
                                    if (ff.Datum_Zapisu_OR.HasValue)
                                    {
                                        firmy[ico].vznikIco = ff.Datum_Zapisu_OR.Value;
                                        firmy[ico].jmeno    = ff.Jmeno;
                                    }
                                }
                            }
                        }
                    }
                }
                return(new Devmasters.Batch.ActionOutputData()
                {
                    CancelRunning = false, Log = null
                });
            },
                                                                     null,
                                                                     logOutputFunc ?? Devmasters.Batch.Manager.DefaultOutputWriter,
                                                                     progressOutputFunc ?? new Devmasters.Batch.ActionProgressWriter(0.1f).Write,
                                                                     true
                                                                     );


            //List<string> privateCompanyIcos = new List<string>();
            ////filter statni firmy && add vznik

            //Devmasters.Batch.Manager.DoActionForAll<string, object>(firmy.Keys,
            //(ico, param) =>
            //{
            //    Firma ff = Firmy.Get(ico);
            //    if (Firma.IsValid(ff))
            //    {
            //        if (ff.PatrimStatu()) //statni firmy tam nechci
            //        {
            //            return new Devmasters.Batch.ActionOutputData() { CancelRunning = false, Log = null };
            //        }
            //        else
            //        {
            //            if (ff.Datum_Zapisu_OR.HasValue)
            //            {
            //                firmy[ico].vznikIco = ff.Datum_Zapisu_OR.Value;
            //                firmy[ico].jmeno = ff.Jmeno;
            //                privateCompanyIcos.Add(ico);
            //            }
            //        }
            //    }

            //    return new Devmasters.Batch.ActionOutputData() { CancelRunning = false, Log = null };
            //},
            //null,
            //Devmasters.Batch.Manager.DefaultOutputWriter,
            //new Devmasters.Batch.ActionProgressWriter(1f).Write,
            //true, maxDegreeOfParallelism: 5
            //);

            HlidacStatu.Util.Consts.Logger.Debug("GetFirmyCasovePodezreleZalozene - filter with close dates");

            DateTime minDate = new DateTime(1990, 01, 01);
            var      badF    = firmy
                               .Select(m => m.Value)
                               .Where(f => f.minUzavreni > minDate)
                               .Where(f => f.days.HasValue && f.days.Value < 60)
                               .OrderBy(f => f.days.Value)
                               .ToArray();

            //.Take(100)

            HlidacStatu.Util.Consts.Logger.Debug($"GetFirmyCasovePodezreleZalozene - returning {badF.Count()} records.");

            return(badF);
        }
Beispiel #17
0
 public static IEnumerable <Firma> FindAllInMemory(string query, int limit)
 {
     return(FindAllIco(query, limit)
            .Select(m => Firmy.Get(m)));
 }
Beispiel #18
0
        public static IEnumerable <Osoba> GetPolitikByQueryFromFirmy(string jmeno, int maxNumOfResults = 50, IEnumerable <string> alreadyFoundFirmyIcos = null)
        {
            var res = new Osoba[] { };

            var firmy = alreadyFoundFirmyIcos;

            if (firmy == null)
            {
                firmy = Firma.Search.FindAllIco(jmeno, maxNumOfResults * 10);
            }

            if (firmy != null && firmy.Count() > 0)
            {
                Dictionary <int, int> osoby = new Dictionary <int, int>();
                bool skipRest = false;
                foreach (var fico in firmy)
                {
                    if (StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy.ContainsKey(fico))
                    {
                        foreach (var osobaId in StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy[fico])
                        {
                            if (osoby.ContainsKey(osobaId))
                            {
                                osoby[osobaId]++;
                            }
                            else
                            {
                                osoby.Add(osobaId, 1);
                            }

                            if (osoby.Count > maxNumOfResults)
                            {
                                skipRest = true;
                                break;
                            }
                        }
                    }

                    if (skipRest == false)
                    {
                        var fvazby = Firmy.Get(fico).AktualniVazby(Relation.AktualnostType.Nedavny);
                        foreach (var fv in fvazby)
                        {
                            if (fv.To.Type == Graph.Node.NodeType.Company)
                            {
                                int osobaId = Convert.ToInt32(fv.To.Id);
                                if (osoby.ContainsKey(osobaId))
                                {
                                    osoby[osobaId]++;
                                }
                                else
                                {
                                    osoby.Add(osobaId, 1);
                                }
                            }
                            if (osoby.Count > maxNumOfResults)
                            {
                                skipRest = true;
                                break;
                            }

                            if (skipRest == false && StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy.ContainsKey(fv.To.Id))
                            {
                                foreach (var osobaId in StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy[fv.To.Id])
                                {
                                    if (osoby.ContainsKey(osobaId))
                                    {
                                        osoby[osobaId]++;
                                    }
                                    else
                                    {
                                        osoby.Add(osobaId, 1);
                                    }
                                    if (osoby.Count > maxNumOfResults)
                                    {
                                        skipRest = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                res = osoby
                      .OrderByDescending(o => o.Value)
                      .Take(maxNumOfResults - res.Length)
                      .Select(m => Osoby.GetById.Get(m.Key))
                      .Where(m => m != null)
                      .Where(m => m.IsValid())   //not empty (nullObj from OsobaCache)
                      .ToArray();
            }
            return(res);
        }
Beispiel #19
0
            public static Lib.Data.Search.GeneralResult <Firma> SimpleSearch(string query, int page, int size)
            {
                List <Firma> found = new List <Firma>();

                string modifQ = Lib.Searching.SimpleQueryCreator
                                .GetSimpleQuery(query, new Searching.Rules.IRule[] { new Searching.Rules.Firmy_OVMKategorie() })
                                .FullQuery();

                string[] specifiedIcosInQuery = Devmasters.RegexUtil.GetRegexGroupValues(modifQ, @"(ico\w{0,11}\: \s? (?<ic>\d{3,8}))", "ic");
                if (specifiedIcosInQuery != null && specifiedIcosInQuery.Length > 0)
                {
                    foreach (var ic in specifiedIcosInQuery.Skip((page - 1) * size).Take(size))
                    {
                        Firma f = Firmy.Get(ic);
                        if (f.Valid)
                        {
                            ///nalezene ICO
                            found.Add(f);
                        }
                    }
                    if (found.Count() > 0)
                    {
                        return new Data.Search.GeneralResult <Firma>(query, specifiedIcosInQuery.Count(), found, size, true)
                               {
                                   Page = page
                               }
                    }
                    ;
                }



                //
                modifQ = Regex.Replace(modifQ, "(ico:|icoprijemce:|icoplatce:|icododavatel:|icozadavatel:)", "ico:", regexQueryOption);

                modifQ = Regex.Replace(modifQ, "(jmenoPrijemce:|jmenoPlatce:|jmenododavatel:|jmenozadavatel:)", "jmeno:", regexQueryOption);

                //modifQ = System.Text.RegularExpressions.Regex.Replace(modifQ, "\\s(AND|OR)\\s", " ", regexQueryOption);

                page = page - 1;
                if (page < 0)
                {
                    page = 0;
                }

                if (page * size >= MaxResultWindow) //elastic limit
                {
                    page = 0; size = 0;             //return nothing
                }


                var qc = GetSimpleQuery(query);
                //var qc = new QueryContainerDescriptor<Lib.Data.Smlouva>()
                //    .QueryString(qs => qs
                //        .Query(modifQ)
                //        .DefaultOperator(Operator.And)
                //    );

                ISearchResponse <FirmaInElastic> res = null;

                try
                {
                    res = ES.Manager.GetESClient_Firmy()
                          .Search <FirmaInElastic>(s => s
                                                   .Size(size)
                                                   .From(page * size)
                                                   .TrackTotalHits(size == 0 ? true : (bool?)null)
                                                   .Query(q => qc)
                                                   );

                    if (res.IsValid)
                    {
                        foreach (var i in res.Hits)
                        {
                            found.Add(Firmy.Get(i.Source.Ico));
                        }
                        return(new Data.Search.GeneralResult <Firma>(query, res.Total, found, size, true)
                        {
                            Page = page
                        });
                    }
                    else
                    {
                        Lib.ES.Manager.LogQueryError <FirmaInElastic>(res, query);
                        return(new Data.Search.GeneralResult <Firma>(query, 0, found, size, false)
                        {
                            Page = page
                        });
                    }
                }
                catch (Exception e)
                {
                    if (res != null && res.ServerError != null)
                    {
                        Lib.ES.Manager.LogQueryError <FirmaInElastic>(res, query);
                    }
                    else
                    {
                        HlidacStatu.Util.Consts.Logger.Error("", e);
                    }
                    throw;
                }
                //return new Data.Search.GeneralResult<Firma>(query, 0, found, size, false) { Page = page };
            }
Beispiel #20
0
        private static string PrintFlatRelations(Graph.MergedEdge parent, int level, IEnumerable <Graph.Edge> relations, TiskEnum typ,
                                                 List <string> renderedIds, bool withStats = true, string highlightSubjId = null)
        {
            int    space     = 2;
            string horizLine = "--"; //new string('\u2500',2);
            string vertLine  = "|";  //new string('\u2502',1);
            string cross     = "+";  //new string('\u251C', 1);

            if (renderedIds == null)
            {
                renderedIds = new List <string>();
            }

            var rels = relations
                       .Where(m =>
                              (
                                  (parent != null && m.From?.UniqId == parent.To?.UniqId)
                                  ||
                                  (parent == null && !relations.Any(r => r.To?.UniqId == m.From?.UniqId)) //do root urovne pridej vazby, ktere jsou sirotci bez parenta
                              )
                              )
                       .Distinct()
                       .GroupBy(k => new { id = k.To.UniqId, type = k.To.Type }, (k, v) =>
            {
                Graph.MergedEdge withChildren = Graph.Edge.MergeSameEdges(v);
                if (withChildren == null)
                {
                    withChildren = new Graph.MergedEdge(v.First());
                }

                return(withChildren);
            })
                       .OrderBy(m => m.To.PrintName())
                       .ToArray();

            if (rels.Count() == 0)
            {
                return(string.Empty);
            }

            StringBuilder     sb       = new StringBuilder(512);
            List <Graph.Edge> deepRels = new List <Graph.Edge>();

            switch (typ)
            {
            case TiskEnum.Text:
                break;

            case TiskEnum.Html:
            case TiskEnum.Checkbox:
                sb.AppendLine("<ul>");
                break;

            case TiskEnum.Json:
                break;
            }
            for (int i = 0; i < rels.Count(); i++)
            {
                var rel = rels[i];
                if (renderedIds.Contains(rel.To.UniqId))
                {
                    continue;
                }

                var last = i == (rels.Count() - 1);
                Analytics.StatisticsSubjectPerYear <Data.Smlouva.Statistics.Data> stat = null;
                if (withStats && rel.To.Type == Graph.Node.NodeType.Company)
                {
                    stat = Firmy.Get(rel.To.Id).StatistikaRegistruSmluv(); //new Analysis.SubjectStatistic(rel.To.Id);
                }
                string subjId   = rel.To.Type == Graph.Node.NodeType.Company ? rel.To.Id : "Osoba";
                string subjName = rel.To.PrintName();
                renderedIds.Add(rel.To.UniqId);
                switch (typ)
                {
                case TiskEnum.Text:
                    sb.AppendLine(string.Concat(Enumerable.Repeat(vertLine + new string(' ', space), level + 1)));
                    sb.Append(
                        string.Concat(
                            Enumerable.Repeat(
                                vertLine + new string(' ', space)
                                , (level))
                            )
                        );
                    if (rel.To.Highlighted)
                    {
                        subjName = string.Format("!!{0}!!", subjName);
                    }

                    sb.AppendFormat("{0}{1}:{2} {3}\n",
                                    cross + horizLine + " ",
                                    subjId,
                                    subjName,
                                    rel.Doba()
                                    );
                    sb.Append(PrintFlatRelations(rel, level + 1, relations, typ, renderedIds, withStats));
                    break;

                case TiskEnum.Html:
                    if (withStats && stat != null)
                    {
                        sb.AppendFormat("<li class='{3} {6}'><a href='/subjekt/{0}'>{0}:{1}</a>{7}; {4}, celkem {5}. {2}</li>",
                                        subjId,
                                        subjName,
                                        PrintFlatRelations(rel, level + 1, relations, typ, renderedIds, withStats),
                                        last ? "" : "connect",
                                        Devmasters.Lang.Plural.Get(stat.Summary().PocetSmluv, Util.Consts.csCulture, "{0} smlouva", "{0} smlouvy", "{0} smluv"),
                                        Smlouva.NicePrice(stat.Summary().CelkovaHodnotaSmluv, html: true, shortFormat: true),
                                        "aktualnost" + ((int)rel.Aktualnost).ToString(),
                                        (rel.Aktualnost < AktualnostType.Aktualni) ? rel.Doba(format: "/{0}/") : string.Empty
                                        );
                    }
                    else
                    {
                        sb.AppendFormat("<li class='{3} {4}'><a href='/subjekt/{0}'><span class=''>{0}:{1}</span></a>{5}.  {2}</li>",
                                        subjId,
                                        subjName,
                                        PrintFlatRelations(rel, level + 1, relations, typ, renderedIds, withStats),
                                        last ? "" : "connect",
                                        "aktualnost" + ((int)rel.Aktualnost).ToString(),
                                        (rel.Aktualnost < AktualnostType.Aktualni) ? rel.Doba(format: "/{0}/") : string.Empty,
                                        (!string.IsNullOrEmpty(highlightSubjId) && subjId == highlightSubjId) ? "highlighted" : ""
                                        );
                    }

                    break;

                case TiskEnum.Checkbox:
                    sb.AppendFormat(@"<li class=""{0} {1}""><input type=""checkbox"" name=""ico"" value=""{2}"" /> <span><b>{2}</b> {3}</span>{4}</li>"
                                    , (last ? "" : "connect"),
                                    ("aktualnost" + ((int)rel.Aktualnost).ToString()),
                                    subjId, subjName,
                                    PrintFlatRelations(rel, level + 1, relations, typ, renderedIds, withStats)
                                    );

                    break;

                case TiskEnum.Json:
                    break;
                }
            }
            switch (typ)
            {
            case TiskEnum.Text:
                break;

            case TiskEnum.Html:
            case TiskEnum.Checkbox:
                sb.AppendLine("</ul>");
                break;

            case TiskEnum.Json:
                break;
            }

            return(sb.ToString());
        }
        public string JmenoPrijemce()
        {
            bool prijemceJeFirma = !string.IsNullOrWhiteSpace(IcoPrijemce);

            if (prijemceJeFirma)
            {
                var zkratkyStran = StaticData.ZkratkyStran_cache.Get();
                return(zkratkyStran.TryGetValue(IcoPrijemce, out string nazev) ? nazev : Firmy.GetJmeno(IcoPrijemce));
            }

            bool prijemcejeOsoba = OsobaIdPrijemce != null && OsobaIdPrijemce > 0;

            if (prijemcejeOsoba)
            {
                return(Osoby.GetById.Get(OsobaIdPrijemce.Value).FullName());
                //return Osoba.GetByInternalId(OsobaIdPrijemce.Value).FullName();
            }

            //todo: log corrupted data
            return("");
        }
Beispiel #22
0
        public InfoFact[] InfoFacts()
        {
            lock (lockInfoObj)
            {
                if (_infofacts == null)
                {
                    List <InfoFact> f = new List <InfoFact>();

                    string hlavni = $"Smlouva mezi {Devmasters.Core.TextUtil.ShortenText(this.Platce.nazev, 60)} a "
                                    + $"{Devmasters.Core.TextUtil.ShortenText(this.Prijemce.First().nazev, 60)}";
                    if (this.Prijemce.Count() == 0)
                    {
                        hlavni += $".";
                    }
                    else if (this.Prijemce.Count() == 1)
                    {
                        hlavni += $" a 1 dalším.";
                    }
                    else if (this.Prijemce.Count() > 1)
                    {
                        hlavni += $" a {this.Prijemce.Count() - 1} dalšími.";
                    }
                    hlavni += (this.CalculatedPriceWithVATinCZK == 0
                        ? " Hodnota smlouvy je utajena."
                        : " Hodnota smlouvy je " + HlidacStatu.Util.RenderData.ShortNicePrice(this.CalculatedPriceWithVATinCZK, html: true));

                    f.Add(new InfoFact(hlavni, InfoFact.ImportanceLevel.Summary));

                    //sponzori
                    foreach (var subj in this.Prijemce.Union(new HlidacStatu.Lib.Data.Smlouva.Subjekt[] { this.Platce }))
                    {
                        var firma = HlidacStatu.Lib.Data.Firmy.Get(subj.ico);
                        if (firma.Valid && firma.IsSponzor() && firma.JsemSoukromaFirma())
                        {
                            f.Add(new InfoFact(
                                      $"{firma.Jmeno}: " +
                                      firma.Description(true, m => m.Type == (int)HlidacStatu.Lib.Data.FirmaEvent.Types.Sponzor, itemDelimeter: ", ", numOfRecords: 2)
                                      , InfoFact.ImportanceLevel.Medium)
                                  );
                        }
                    }

                    //issues
                    if (this.IsPartOfRegistrSmluv() && this.znepristupnenaSmlouva() == false &&
                        this.Issues != null && this.Issues.Any(m => m.Public && m.Public && m.Importance != HlidacStatu.Lib.Issues.ImportanceLevel.NeedHumanReview))
                    {
                        int count = 0;
                        foreach (var iss in this.Issues.Where(m => m.Public && m.Importance != HlidacStatu.Lib.Issues.ImportanceLevel.NeedHumanReview)
                                 .OrderByDescending(m => m.Importance))
                        {
                            if (this.znepristupnenaSmlouva() && iss.IssueTypeId == -1) //vypis pouze info o znepristupneni
                            {
                                count++;
                                f.Add(new InfoFact(
                                          $"<b>{iss.Title}</b><br/><small>{iss.TextDescription}</small>"
                                          , InfoFact.ImportanceLevel.High)
                                      );
                            }
                            else if (iss.Public && iss.Importance != HlidacStatu.Lib.Issues.ImportanceLevel.NeedHumanReview)
                            {
                                count++;
                                string importance = "";
                                switch (iss.Importance)
                                {
                                case Lib.Issues.ImportanceLevel.NeedHumanReview:
                                case Lib.Issues.ImportanceLevel.Ok:
                                case Lib.Issues.ImportanceLevel.Formal:
                                    importance = "";
                                    break;

                                case Lib.Issues.ImportanceLevel.Minor:
                                case Lib.Issues.ImportanceLevel.Major:
                                    importance = "Nedostatek: ";
                                    break;

                                case Lib.Issues.ImportanceLevel.Fatal:
                                    importance = "Vážný nedostatek: ";
                                    break;

                                default:
                                    break;
                                }
                                f.Add(
                                    new InfoFact(
                                        $"<b>{importance}{(string.IsNullOrEmpty(importance) ? iss.Title : iss.Title.ToLower())}</b><br/><small>{iss.TextDescription}</small>"
                                        , InfoFact.ImportanceLevel.Medium)
                                    );
                            }

                            if (count >= 2)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        f.Add(new InfoFact("Žádné nedostatky u smlouvy jsme nenalezli.", InfoFact.ImportanceLevel.Low));
                    }


                    //politici
                    foreach (var ss in this.Prijemce)
                    {
                        if (!string.IsNullOrEmpty(ss.ico) && HlidacStatu.Lib.StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy.ContainsKey(ss.ico))
                        {
                            var politici = StaticData.FirmySVazbamiNaPolitiky_nedavne_Cache.Get().SoukromeFirmy[ss.ico];
                            if (politici.Count > 0)
                            {
                                var sPolitici = Osoby.GetById.Get(politici[0]).FullNameWithYear();
                                if (politici.Count == 2)
                                {
                                    sPolitici = sPolitici + " a " + Osoby.GetById.Get(politici[1]).FullNameWithYear();
                                }
                                else if (politici.Count == 3)
                                {
                                    sPolitici = sPolitici
                                                + ", "
                                                + Osoby.GetById.Get(politici[1]).FullNameWithYear()
                                                + " a "
                                                + Osoby.GetById.Get(politici[2]).FullNameWithYear();
                                }
                                else if (politici.Count > 3)
                                {
                                    sPolitici = sPolitici
                                                + ", "
                                                + Osoby.GetById.Get(politici[1]).FullNameWithYear()
                                                + ", "
                                                + Osoby.GetById.Get(politici[2]).FullNameWithYear()
                                                + " a další";
                                }
                                f.Add(new InfoFact($"V dodavateli {Firmy.GetJmeno(ss.ico)} se "
                                                   + Devmasters.Core.Lang.Plural.Get(politici.Count()
                                                                                     , " angažuje jedna politicky angažovaná osoba - "
                                                                                     , " angažují {0} politicky angažované osoby - "
                                                                                     , " angažuje {0} politicky angažovaných osob - ")
                                                   + sPolitici + "."
                                                   , InfoFact.ImportanceLevel.Medium)
                                      );
                            }
                        }
                    }

                    _infofacts = f.OrderByDescending(o => o.Level).ToArray();
                }
            }
            return(_infofacts);
        }
        public static VazbyFiremNaPolitiky LoadFirmySVazbamiNaPolitiky(Relation.AktualnostType aktualnostVztahu, bool showProgress = false)
        {
            Dictionary <string, List <int> > pol_SVazbami             = new Dictionary <string, List <int> >();
            Dictionary <string, List <int> > pol_SVazbami_StatniFirmy = new Dictionary <string, List <int> >();

            Devmasters.Core.Batch.Manager.DoActionForAll <Osoba>(StaticData.Politici.Get(),
                                                                 (p) =>
            {
                var vazby = p.AktualniVazby(aktualnostVztahu);
                if (vazby != null && vazby.Count() > 0)
                {
                    foreach (var v in vazby)
                    {
                        if (!string.IsNullOrEmpty(v.To.Id))
                        {
                            //check if it's GovType company
                            Firma f = Firmy.Get(v.To.Id);
                            //if (f == null)
                            //{
                            //    f = External.GovData.FromIco(v.To.Id);
                            //    if (f == null)
                            //        continue; //unknown company, skip
                            //}
                            if (!Firma.IsValid(f))
                            {
                                continue; //unknown company, skip
                            }
                            if (f.PatrimStatu())
                            {
                                //Gov Company
                                if (pol_SVazbami_StatniFirmy.ContainsKey(v.To.Id))
                                {
                                    var pol = pol_SVazbami_StatniFirmy[v.To.Id];
                                    if (!pol.Any(m => m == p.InternalId))
                                    {
                                        pol.Add(p.InternalId);
                                    }
                                }
                                else
                                {
                                    pol_SVazbami_StatniFirmy.Add(v.To.Id, new List <int>());
                                    pol_SVazbami_StatniFirmy[v.To.Id].Add(p.InternalId);
                                }
                            }
                            else
                            {
                                //private company
                                if (pol_SVazbami.ContainsKey(v.To.Id))
                                {
                                    var pol = pol_SVazbami[v.To.Id];
                                    if (!pol.Any(m => m == p.InternalId))
                                    {
                                        pol.Add(p.InternalId);
                                    }
                                }
                                else
                                {
                                    pol_SVazbami.Add(v.To.Id, new List <int>());
                                    pol_SVazbami[v.To.Id].Add(p.InternalId);
                                }
                            }
                        }
                    }
                }
                return(new Devmasters.Core.Batch.ActionOutputData()
                {
                    CancelRunning = false, Log = null
                });
            },
                                                                 showProgress ? Devmasters.Core.Batch.Manager.DefaultOutputWriter : (Action <string>)null,
                                                                 showProgress ? new Devmasters.Core.Batch.ActionProgressWriter().Write : (Action <ActionProgressData>)null,
                                                                 false
                                                                 , prefix: "LoadFirmySVazbamiNaPolitiky " + aktualnostVztahu.ToNiceDisplayName()
                                                                 );

            return(new VazbyFiremNaPolitiky()
            {
                SoukromeFirmy = pol_SVazbami, StatniFirmy = pol_SVazbami_StatniFirmy
            });
        }
        public static IEnumerable <IcoSmlouvaMinMax> GetFirmyCasovePodezreleZalozene(Action <string> logOutputFunc = null, Action <ActionProgressData> progressOutputFunc = null)
        {
            var allIcos = Lib.Data.External.FirmyDB.AllIcoInRS();
            Dictionary <string, AnalysisCalculation.IcoSmlouvaMinMax> firmy = new Dictionary <string, AnalysisCalculation.IcoSmlouvaMinMax>();
            object lockFirmy = new object();
            var    client    = HlidacStatu.Lib.ES.Manager.GetESClient();
            AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva> aggs = new AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>()
                                                                                 .Min("minDate", m => m
                                                                                      .Field(f => f.datumUzavreni)
                                                                                      );


            Devmasters.Core.Batch.Manager.DoActionForAll <string, object>(allIcos,
                                                                          (ico, param) =>
            {
                var res = HlidacStatu.Lib.ES.SearchTools.SimpleSearch("ico:" + ico, 0, 0, HlidacStatu.Lib.ES.SearchTools.OrderResult.FastestForScroll, aggs);
                if (res.Result.Aggregations.Count > 0)
                {
                    var epoch = ((Nest.ValueAggregate)res.Result.Aggregations.First().Value).Value;
                    if (epoch.HasValue)
                    {
                        var mindate = Devmasters.Core.DateTimeUtil.FromEpochTimeToUTC((long)epoch / 1000);

                        lock (lockFirmy)
                        {
                            if (firmy.ContainsKey(ico))
                            {
                                if (firmy[ico].minUzavreni.HasValue == false)
                                {
                                    firmy[ico].minUzavreni = mindate;
                                }
                                else if (firmy[ico].minUzavreni.Value > mindate)
                                {
                                    firmy[ico].minUzavreni = mindate;
                                }
                            }
                            else
                            {
                                firmy.Add(ico, new AnalysisCalculation.IcoSmlouvaMinMax()
                                {
                                    ico         = ico,
                                    minUzavreni = Devmasters.Core.DateTimeUtil.FromEpochTimeToUTC((long)epoch / 1000)
                                });
                            }
                        }
                    }
                }

                return(new Devmasters.Core.Batch.ActionOutputData()
                {
                    CancelRunning = false, Log = null
                });
            },
                                                                          null,
                                                                          logOutputFunc ?? Devmasters.Core.Batch.Manager.DefaultOutputWriter,
                                                                          progressOutputFunc ?? new Devmasters.Core.Batch.ActionProgressWriter(0.1f).Write,
                                                                          true
                                                                          );


            List <string> privateCompanyIcos = new List <string>();

            //filter statni firmy && add vznik

            Devmasters.Core.Batch.Manager.DoActionForAll <string, object>(firmy.Keys,
                                                                          (ico, param) =>
            {
                Firma ff = Firmy.Get(ico);
                if (Firma.IsValid(ff))
                {
                    if (ff.PatrimStatu()) //statni firmy tam nechci
                    {
                        return(new Devmasters.Core.Batch.ActionOutputData()
                        {
                            CancelRunning = false, Log = null
                        });
                    }
                    else
                    {
                        if (ff.Datum_Zapisu_OR.HasValue)
                        {
                            firmy[ico].vznikIco = ff.Datum_Zapisu_OR.Value;
                            firmy[ico].jmeno    = ff.Jmeno;
                            privateCompanyIcos.Add(ico);
                        }
                    }
                }

                return(new Devmasters.Core.Batch.ActionOutputData()
                {
                    CancelRunning = false, Log = null
                });
            },
                                                                          null,
                                                                          Devmasters.Core.Batch.Manager.DefaultOutputWriter,
                                                                          new Devmasters.Core.Batch.ActionProgressWriter(1f).Write,
                                                                          true, maxDegreeOfParallelism: 5
                                                                          );


            DateTime minDate = new DateTime(1990, 01, 01);
            var      badF    = firmy
                               .Where(kv => privateCompanyIcos.Contains(kv.Key))
                               .Select(m => m.Value)
                               .Where(f => f.minUzavreni > minDate)
                               .Where(f => f.days.HasValue && f.days.Value < 60)
                               .OrderBy(f => f.days.Value);

            //.Take(100)

            return(badF);
        }
Beispiel #25
0
            public static List <string> VsechnyUrady(
                Action <string> logOutputFunc = null,
                Action <ActionProgressData> progressOutputFunc = null,
                int?threads = null)
            {
                if (_vsechnyUrady != null)
                {
                    return(_vsechnyUrady);
                }
                else
                {
                    lock (_vsechnyUradyLock)
                    {
                        if (_vsechnyUrady != null)
                        {
                            return(_vsechnyUrady);
                        }


                        var icos = new List <string>();

                        HlidacStatu.Util.Consts.Logger.Info($"Loading ALL ICOS");

                        icos.AddRange(StaticData.KrajskeUradyCache.Get().Select(m => m.ICO));
                        icos.AddRange(StaticData.MinisterstvaCache.Get().Select(m => m.ICO));
                        // krajske technicke sluzby
                        icos.AddRange("00066001,00090450,70947023,70946078,72053119,00080837,70971641,27502988,00085031,70932581,70960399,00095711,26913453,03447286,25396544,60733098".Split(','));
                        //velke nemocnice
                        icos.AddRange("00064165,00064173,00064203,00098892,00159816,00179906,00669806,00843989,25488627,26365804,27283933,27661989,65269705,27283518,26000202,00023736,00023884,27256391,61383082,27256537,00023001,27520536,26068877,47813750,00064211,00209805,27660915,00635162,27256456,00090638,00092584,00064190".Split(','));
                        //fakultni nemocnice
                        icos.AddRange("00064165,00064173,00064203,00098892,00159816,00179906,00669806,00843989,25488627,26365804,27283933,27661989,65269705,27283518,26000202,00023736,00023884,27256391,61383082,27256537,00023001,27520536,26068877,47813750,00064211,00209805,27660915,00635162,27256456,00090638,00092584,00064190".Split(','));

                        //CEZ, CPost, CD,
                        icos.AddRange("45274649,47114983,70994226".Split(','));
                        icos.AddRange(Firma.StatniFirmyICO);

                        icos.AddRange(Lib.DirectDB
                                      .GetList <string>("select distinct ico from firma where status =1 and Kod_PF in (301,302,312,313,314,325,331,352,353,361,362,381,382,521,771,801,804,805)")
                                      );

                        icos.AddRange(StaticData.StatutarniMestaAllCache.Get().Select(m => m.ICO));
                        //velka mesta
                        string velkamesta = "00064581,00081531,00266094,00254657,00262978,44992785,00845451,00274046,00075370,00262978,00299308,00244732,00283924";
                        icos.AddRange(velkamesta.Split(','));

                        icos.AddRange(Firma.Zatrideni.Subjekty(Firma.Zatrideni.StatniOrganizaceObor.Vse).Select(m => m.Ico));

                        //nejvice utajujici smluvni strany
                        HlidacStatu.Util.Consts.Logger.Info($"Loading ICOS utajujici smluvni strany");
                        AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva> aggs = new AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>()
                                                                                             .Terms("perIco", m => m
                                                                                                    .Field("platce.ico")
                                                                                                    .Size(2500)
                                                                                                    .Order(o => o.Descending("_count"))
                                                                                                    );

                        var res = HlidacStatu.Lib.Data.Smlouva.Search.SimpleSearch("(issues.issueTypeId:18 OR issues.issueTypeId:12)", 1, 0,
                                                                                   HlidacStatu.Lib.Data.Smlouva.Search.OrderResult.FastestForScroll, aggs, platnyZaznam: true);

                        foreach (Nest.KeyedBucket <object> val in ((BucketAggregate)res.ElasticResults.Aggregations["perIco"]).Items)
                        {
                            var ico = (string)val.Key;
                            var f   = Firmy.Get(ico);
                            if (f.PatrimStatu())
                            {
                                if (HlidacStatu.Lib.Analysis.ACore.GetBasicStatisticForICO(ico)
                                    .Data.Any(m => m.Value.Pocet > Lib.Analysis.KorupcniRiziko.Consts.MinSmluvPerYear)
                                    )
                                {
                                    icos.Add(ico);
                                }
                            }
                            else
                            {
                            }
                        }

                        //nejvice utajujici ceny
                        HlidacStatu.Util.Consts.Logger.Info($"Loading ICOS utajujici ceny");
                        aggs = new AggregationContainerDescriptor <HlidacStatu.Lib.Data.Smlouva>()
                               .Terms("perIco", m => m
                                      .Field("platce.ico")
                                      .Size(2500)
                                      .Order(o => o.Descending("_count"))
                                      );

                        res = HlidacStatu.Lib.Data.Smlouva.Search.SimpleSearch("(issues.issueTypeId:100)", 1, 0,
                                                                               HlidacStatu.Lib.Data.Smlouva.Search.OrderResult.FastestForScroll, aggs, platnyZaznam: true);

                        foreach (Nest.KeyedBucket <object> val in ((BucketAggregate)res.ElasticResults.Aggregations["perIco"]).Items)
                        {
                            var ico = (string)val.Key;
                            var f   = Firmy.Get(ico);
                            if (f.PatrimStatu())
                            {
                                if (HlidacStatu.Lib.Analysis.ACore.GetBasicStatisticForICO(ico)
                                    .Data.Any(m => m.Value.Pocet > Lib.Analysis.KorupcniRiziko.Consts.MinSmluvPerYear)
                                    )
                                {
                                    icos.Add(ico);
                                }
                            }
                            else
                            {
                                if (System.Diagnostics.Debugger.IsAttached)
                                {
                                    //System.Diagnostics.Debugger.Break();
                                    Console.WriteLine("excl:" + f.Jmeno);
                                }
                            }
                        }



                        HlidacStatu.Util.Consts.Logger.Info("Dohledani podrizenych organizaci");
                        //podrizene organizace
                        var allIcos = new System.Collections.Concurrent.ConcurrentBag <string>();

                        Devmasters.Batch.Manager.DoActionForAll <string>(icos.Distinct().ToArray(),
                                                                         (i) =>
                        {
                            var fk = Firmy.Get(i);
                            allIcos.Add(i);
                            foreach (var pic in fk.IcosInHolding(Relation.AktualnostType.Aktualni))
                            {
                                allIcos.Add(pic);
                            }
                            ;

                            return(new Devmasters.Batch.ActionOutputData());
                        },
                                                                         logOutputFunc,
                                                                         progressOutputFunc,
                                                                         true, maxDegreeOfParallelism: threads);


                        icos          = allIcos.ToList();
                        _vsechnyUrady = icos
                                        .Select(i => HlidacStatu.Util.ParseTools.NormalizeIco(i))
                                        .Distinct()
                                        .ToList();
                    }
                }
                return(_vsechnyUrady);
            }