public string WriteToPath(HkpvReport report, string path, bool asJson, bool compressed = true)
        {
            var filename = Path.Combine(path, GetFileName(report, asJson, compressed));

            WriteToFile(report, filename, asJson, compressed);
            return(filename);
        }
Example #2
0
        private void Save(HkpvReport report)
        {
            if (_authContext?.Principal == null)
            {
                _logger.LogError("Not logged in");
                throw new Exception("Not logged in");
            }

            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                var institutionId = this.GetRowId("Institutions", report.Institution.Id, connection);
                var lastInfo      = GetLast(report.Institution.Id, institutionId, connection);

                var info = HkpvReportInfo.Create(report, lastInfo?.Id ?? -1, lastInfo?.Created ?? DateTime.Now);

                if (lastInfo != null && info.Equals(lastInfo))
                {
                    _logger.LogInformation("Report already exits. Skip saving.");
                    return;
                }

                this.SaveReport(connection, report, info, institutionId);
            }
        }
Example #3
0
        private void SaveReport(SqlConnection connection, HkpvReport report, HkpvReportInfo info, int institutionId)
        {
            using (var ms = report.WriteToStream(asJson: false, compressed: true))
            {
                var userId = this.GetRowId("Users", _authContext.Principal.Identity.Name, connection);

                SqlCommand insert = new SqlCommand("insert into Messages([UserId], [InstitutionId], [Hash_SHA256], [Month], [Year], [Date], [Data]) values(@userId, @institutionId, @hash, @month, @year, @date, @data)", connection);
                insert.Parameters.AddWithValue("@userId", userId);
                insert.Parameters.AddWithValue("@institutionId", institutionId);
                insert.Parameters.AddWithValue("@hash", info.HashSHA256);
                insert.Parameters.AddWithValue("@month", info.Month);
                insert.Parameters.AddWithValue("@year", info.Year);
                insert.Parameters.AddWithValue("@date", DateTime.Now);
                insert.Parameters.AddWithValue("@data", ms.ToArray());
                try
                {
                    insert.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, ex.Message);
                    throw ex;
                }

                _logger.LogInformation("Report saved");
            }
        }
Example #4
0
        public static (Person person, PersonalData Data) AddDummyPerson(this HkpvReport report)
        {
            var p = DataGenerator.Instance.CreatePerson();

            report.AddPerson(p);
            return(p);
        }
        public MemoryStream WriteToStream(HkpvReport report, bool asJson, bool compressed = true)
        {
            report = report.AsSorted();
            var ms     = new MemoryStream();
            var result = ms;

            if (asJson)
            {
                var ss = new StreamWriter(ms);
                Google.Protobuf.JsonFormatter.Default.WriteValue(ss, report);
                ss.Flush();
                ms.Position = 0;
            }
            else
            {
                Google.Protobuf.MessageExtensions.WriteTo(report, ms);
                ms.Position = 0;
            }

            if (compressed)
            {
                var filename = GetFileName(report, asJson, false);
                result = ZipStream(ms, filename);
                ms.Dispose();
            }

            return(result);
        }
Example #6
0
        public HkpvReport CreateHkpvReport(int?year = null, int?month = null, int persons = 100, int staffs = 5, bool addActivities = true)
        {
            var report = new HkpvReport()
            {
                Institution = new Institution()
                {
                    Id = "kpv_test", Name = "Testverein"
                }
            };

            var from = year.HasValue || month.HasValue ? new DateTime(year ?? DateTime.Today.Year, month ?? DateTime.Today.Month, 1) : DateTime.Today.FirstDateInMonth().AddMonths(-1);


            report.FromD = from;
            report.ToD   = report.FromD.LastDateInMonth();

            report.AddDummyPersons(persons);
            report.AddDummyStaffs(staffs);

            if (addActivities)
            {
                report.AddDummyActivities();
            }

            return(report);
        }
Example #7
0
        private string GetNameOfPerson(HkpvReport report, int index)
        {
            if (report.Persons.Count > index && index >= 0)
            {
                var e = report.PersonalData[index];
                return($"Person: {e.FamilyName} {e.GivenName}");
            }

            return(string.Empty);
        }
Example #8
0
        private string GetNameOfStaff(HkpvReport report, int index)
        {
            if (report.Staffs.Count > index && index >= 0)
            {
                var e = report.Staffs[index];
                return($"Mitarbeiter: {e.FamilyName} {e.GivenName}");
            }

            return(string.Empty);
        }
Example #9
0
        private string GetNameOfActivity(HkpvReport report, int index)
        {
            if (report.Activities.Count > index && index >= 0)
            {
                var e = report.Activities[index];
                return($"Aktivität {e.DateD.ToString("dd.MM.yyyy")}{_template.Linefeed}  {e.Type}{_template.Linefeed}  {GetNameOfPersonById(report, e.PersonId)}{_template.Linefeed}  {GetNameOfStaffById(report, e.StaffId)}");
            }

            return(string.Empty);
        }
Example #10
0
        private string GetNameOfConsultation(HkpvReport report, int id)
        {
            if (report.Consultations.Count > id && id >= 0)
            {
                var e = report.Consultations[id];
                return($"Beratung {e.DateD.ToString("dd.MM.yyyy")}, {e.Type}: {GetNameOfStaffById(report, e.StaffId)}");
            }

            return(string.Empty);
        }
Example #11
0
        public async Task <SendResult> Send(HkpvReport report, string username, string password)
        {
            using (var client = new HttpClient())
                using (var data = report.WriteToStream())
                {
                    var url     = new Uri(_address, $"{report.FromD.Year}/{report.FromD.Month}");
                    var content = new ByteArrayContent(data.ToArray());

                    if (!string.IsNullOrEmpty(username))
                    {
                        var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
                        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
                    }

                    var response = await client.PutAsync(url, content);

                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return new SendResult()
                               {
                                   IsValid = false, ErrorMessage = "Unauthorized"
                               }
                    }
                    ;

                    SendResult result = null;

                    var responseMsg = await response.Content.ReadAsStringAsync();

                    if (!string.IsNullOrEmpty(responseMsg))
                    {
                        try
                        {
                            result = JsonConvert.DeserializeObject <SendResult>(responseMsg);
                        }
                        catch (Exception e)
                        {
                            result = new SendResult()
                            {
                                IsValid = false, ErrorMessage = e.Message
                            };
                        }
                    }
                    else
                    {
                        result = new SendResult()
                        {
                            IsValid = false, ErrorMessage = $"{response.StatusCode}: Empty"
                        };
                    }

                    return(result);
                }
        }
    }
Example #12
0
        private string GetNameOfStaffById(HkpvReport report, string id)
        {
            var e = report.Staffs.Where(x => x.Id == id).FirstOrDefault();

            if (e == null)
            {
                return(string.Empty);
            }

            return($"{e.FamilyName} {e.GivenName}");
        }
Example #13
0
 public void WriteToFile(HkpvReport report, string filename, bool asJson, bool compressed = true)
 {
     using (var ms = WriteToStream(report, asJson, compressed))
     {
         ms.Position = 0;
         using (var s = File.OpenWrite(filename))
         {
             ms.CopyTo(s);
         }
     }
 }
Example #14
0
 private void AddConsultation(HkpvReport report, string staffId)
 {
     report.Consultations.Add(new Consultation()
     {
         Date = report.From, Amount = 1, StaffId = staffId, Type = ConsultationType.Lv31
     });
     report.Consultations.Add(new Consultation()
     {
         Date = report.From, Amount = 1, StaffId = staffId, Type = ConsultationType.Lv32
     });
 }
Example #15
0
 public static HkpvReportInfo Create(HkpvReport report, int id, DateTime created)
 {
     return(new HkpvReportInfo
     {
         Id = id,
         Created = created,
         Month = report.FromD.Month,
         Year = report.FromD.Year,
         Institution = report.Institution.Id,
         HashSHA256 = report.GetSHA256Hash()
     });
 }
Example #16
0
            public (bool Success, string Info) GetInfo(HkpvReport report, string propertyName)
            {
                var m = this._pattern.Match(propertyName);

                if (m.Success)
                {
                    int.TryParse(m.Groups["id"].Value, out int id);

                    return(true, _resolveInfo(report, id));
                }
                return(false, string.Empty);
            }
Example #17
0
        private string GetInfo(HkpvReport report, string propertyName)
        {
            foreach (var strategy in _strategies)
            {
                var r = strategy.GetInfo(report, propertyName);

                if (r.Success)
                {
                    return(r.Info);
                }
            }

            return(propertyName);
        }
Example #18
0
 private void AddActivities(HkpvReport report, string personId, string staffId)
 {
     report.Activities.Add(new Activity()
     {
         Date = report.From, Amount = 1, PersonId = personId, StaffId = staffId, Type = ActivityType.Lv02
     });
     report.Activities.Add(new Activity()
     {
         Date = report.From, Amount = 1, PersonId = personId, StaffId = staffId, Type = ActivityType.Lv04
     });
     report.Activities.Add(new Activity()
     {
         Date = report.From, Amount = 1, PersonId = personId, StaffId = staffId, Type = ActivityType.Lv15
     });
 }
Example #19
0
        private void Save(HkpvReport report)
        {
            var(info, lastFilename) = GetLastFile(report.Institution.Id);

            if (info != null && string.Equals(GetFilename(report, info.Id), lastFilename, StringComparison.CurrentCultureIgnoreCase))
            {
                _logger.LogInformation("Report already exits. Skip saving.");
                return;
            }

            var filename = Path.Combine(_path, GetFilename(report, (info?.Id ?? 0) + 1));

            report.WriteToFile(filename, asJson: false, compressed: true);

            _logger.LogInformation("Report saved: {filename}", filename);
        }
Example #20
0
        public static string GetFileName(HkpvReport report, bool asJson, bool compressed = true)
        {
            var filename = $"{report.Institution.Id}_{report.FromD.Year}_{report.FromD.Month}_{report.GetSHA256Hash()}";

            if (compressed)
            {
                return($"{filename}.zip");
            }
            else if (asJson)
            {
                return($"{filename}.json");
            }
            else
            {
                return($"{filename}.hkpv");
            }
        }
Example #21
0
        public Activity[] CreateActivities(HkpvReport report)
        {
            var result = new List <Activity>();

            foreach (var staff in report.Staffs)
            {
                // die zu betreuenden Personen zufällig zuordnen
                var persons = report.Persons.Count == 1 || report.Staffs.Count == 1 ? report.Persons.ToArray() : report.Persons.Where(x => _rand.Next(report.Staffs.Count) == 0).ToArray();

                // ein Mitarbeiter soll pro Monat max. 6000 Minuten arbeiten.
                // wenn nur wenige Personen betreut werden: max 500 Minuten pro Person
                var minuten = _rand.Next(Math.Min(persons.Count() * 500, 6000));

                while (minuten > 0)
                {
                    var personId = persons[_rand.Next(persons.Length)].Id;

                    var date = report.FromD.AddDays(_rand.Next(report.ToD.Day - report.FromD.Day + 1));

                    // Pro Tag, Person und Mitarbeiter nur ein Eintrag erlaubt:
                    if (!result.Where(x => x.PersonId == personId && x.StaffId == staff.Id && x.DateD.Equals(date)).Any())
                    {
                        var a = CreateRandomActivity(personId, staff.Id, date).ToArray();

                        minuten -= a.Select(x => x.GetMinutes()).Sum();

                        result.AddRange(a);
                    }
                }
            }

            //sicherstellen, dass jede Person zumindest einen Eintrag hat
            foreach (var p in report.Persons.Where(x => !result.Where(a => a.PersonId == x.Id).Any()).ToArray())
            {
                var date = report.FromD.AddDays(_rand.Next(report.ToD.Day - report.FromD.Day + 1));

                result.AddRange(CreateRandomActivity(p.Id, report.Staffs[_rand.Next(report.Staffs.Count)].Id, date));
            }


            return(result.ToArray());
        }
Example #22
0
        public string Format(HkpvReport report, ValidationResult validationResult)
        {
            if (!validationResult.Errors.Any())
            {
                return(string.Empty);
            }

            var result = new StringBuilder();

            result.Append(_template.Header(report, validationResult));

            var severities = validationResult.Errors.OrderBy(x => x.Severity).GroupBy(x => x.Severity);

            foreach (var severity in severities)
            {
                result.Append(_template.HeaderSeverity(GetSeverityName(severity.Key)));

                var entries = severity.Select(x => new
                {
                    Info    = this.GetInfo(report, x.PropertyName),
                    Message = x.ErrorMessage,
                    Value   = x.AttemptedValue?.ToString()
                }).ToArray();

                foreach (var groupedInfos in entries.OrderBy(x => x.Info).GroupBy(x => x.Info))
                {
                    result.Append(_template.FirstLine((groupedInfos.Key, groupedInfos.First().Message, groupedInfos.First().Value)));

                    foreach (var info in groupedInfos.Skip(1))
                    {
                        result.Append(_template.Line((info.Message, info.Value)));
                    }
                }

                result.Append(_template.FooterSeverity(severity.ToString()));
            }
            return(result.ToString());
        }
Example #23
0
        public string Write(ReadResult data, bool asJson = false)
        {
            var date   = data.L.Select(x => x.Datum).First().FirstDateInMonth();
            var report = new HkpvReport()
            {
                FromD       = date,
                ToD         = date.LastDateInMonth(),
                Institution = new Institution()
                {
                    Id = data.V.Vereinsnummer.ToString(), Name = data.V.Bezeichnung
                }
            };

            foreach (var a in data.A)
            {
                var name = GetName(a.Name_1);
                report.AddPerson((new Person()
                {
                    Id = GetId(a.Adressnummer),
                    Insurance = a.Versicherung ?? string.Empty,
                    Nationality = a.Staatsbuergerschaft ?? string.Empty,
                    CareAllowance = (CareAllowance)a.Pflegestufe,
                    Religion = ReligionCodeProvider.Instance.Unknown,
                    Postcode = a.Postleitzahl ?? string.Empty,
                    City = a.Ort ?? string.Empty,
                    Gender = GetGender(a.Geschlecht)
                }, new PersonalData()
                {
                    Id = GetId(a.Adressnummer),
                    BirthdayD = a.Geburtsdatum,
                    FamilyName = name.Familyname,
                    GivenName = name.Givenname,
                    Ssn = a.Versicherungsnummer ?? string.Empty,
                    Street = a.Adresse ?? string.Empty,
                }));
            }


            foreach (var p in data.P)
            {
                var name = GetName(p.Pflegername);

                report.Staffs.Add(new Staff()
                {
                    Id = GetId(p.Pflegernummer), FamilyName = name.Familyname, GivenName = name.Givenname
                });
            }

            foreach (var l in data.L)
            {
                if (l.Leistung < 20)
                {
                    report.Activities.Add(new Activity()
                    {
                        Amount   = l.Anzahl,
                        DateD    = l.Datum,
                        PersonId = GetId(l.Adressnummer),
                        StaffId  = GetId(l.Pfleger),
                        Type     = (ActivityType)l.Leistung
                    });
                }
                else
                {
                    report.Consultations.Add(new Consultation()
                    {
                        Amount  = l.Anzahl,
                        DateD   = l.Datum,
                        StaffId = GetId(l.Pfleger),
                        Type    = (ConsultationType)l.Leistung
                    });
                }
            }

            var filename = report.WriteToPath("", asJson: asJson, compressed: true);

            return(filename);
        }
Example #24
0
 private string GetFilename(HkpvReport report, int id) => $"{id:00000000}__{HkpvReportSerializer.GetFileName(report, false, true)}";