public static List<PlanDdMonth> LoadPlanDd(Application excel, IBackgroundContext context) { context.ReportProgress("Загружаем данные плана ..."); var result = new List<PlanDdMonth>(); var planDdDocFileName = Utils.GetOptionsFileName("PlanDD.xls"); var planDdDoc = excel.Workbooks.Open(planDdDocFileName); var ws = ((Worksheet)planDdDoc.Worksheets[1]); for (int month = 1; month <= 12; month++) { var planDdMonth = new PlanDdMonth() { Month = month }; result.Add(planDdMonth); for (int colIndex = 4; colIndex <= 30; colIndex++) { var rowIndex = 2 + (month - 1) * 8; var newCol = ((Range)ws.Columns[colIndex]); var planDdData = new PlanDdData(); planDdMonth.DdDataList.Add(planDdData); planDdData.Age = Utils.FromExcel<int>(newCol, 1, 1); rowIndex++; planDdData.WorkMan = Utils.FromExcel<int>(newCol, rowIndex++, 1); planDdData.NotWorkMan = Utils.FromExcel<int>(newCol, rowIndex++, 1); planDdData.StudentMan = Utils.FromExcel<int>(newCol, rowIndex++, 1); rowIndex++; planDdData.WorkWoman = Utils.FromExcel<int>(newCol, rowIndex++, 1); planDdData.NotWorkWoman = Utils.FromExcel<int>(newCol, rowIndex++, 1); planDdData.StudentWoman = Utils.FromExcel<int>(newCol, rowIndex++, 1); } } planDdDoc.Close(SaveChanges:false); return result; }
public ProgressPanel(IBackgroundContext context) { InitializeComponent(); this.context = context; //this.context.Progress += ContextOnProgress; Instance = this; }
public static void ClearColorMakers(IBackgroundContext context, LpuExecParams executorParams) { context.ProgressSeparator(); context.ReportProgress(@"УДАЛЕНИЕ МАРКЕРОВ НЕДЕЙСТВИТЕЛЬНЫХ ПОЛИСОВ"); context.ProgressSeparator(); using (var dataContext = new VistaMedDataContext(context)) { var invMarkerType = getInvMarkerType(dataContext); if(invMarkerType != null) { context.ReportProgress(@""); try { dataContext.VistaMed.ExecuteCommand(@"DELETE FROM Client_StatusObservation WHERE statusObservationType_id IS NULL"); dataContext.VistaMed.ExecuteCommand(@"DELETE FROM Client_StatusObservation WHERE statusObservationType_id = {0}", invMarkerType.Id); dataContext.VistaMed.SubmitChanges(); context.ReportProgress(@"Удаление маркеров проведено"); } catch (Exception exception) { context.ReportError(@"{0}", exception.Message); } } else { //context.ReportError(@"Тип маркера недействительного полиса не найден в БД ВистаМед"); } } context.ProgressSeparator('-'); }
public static void BuildConvertReports(IBackgroundContext context, DirParams args) { var fileNames = new List<string>(); getTxtFiles(args.DirName, fileNames); foreach (var fileName in fileNames) { reformatBillTextToWord(fileName); } }
public static void BuildSvedDdReport(IBackgroundContext context, MonthParams args) { var dateBegin = args.DateBegin; var dateEnd = args.DateEnd; var miacCode = args.LpuCode; using (var dataConext = new VistaMedDataContext(context)) { var ddrDataContext = new DdrDataContext(); ddrDataContext.dataConext = dataConext; ddrDataContext.context = context; ddrDataContext.dateEnd = dateEnd; ddrDataContext.dateBegin = dateBegin; ddrDataContext.LpuCode = miacCode; var templateFileName = @"SvodDdr.xls"; var templateName = Utils.GetReportFileName(templateFileName); if (File.Exists(templateName)) { var excel = new Application(); excel.Visible = true; ddrDataContext.planDd = PlanDd.LoadPlanDd(excel, context); var newDoc = excel.Workbooks.Add(templateName); ddrDataContext.newDoc = newDoc; excel.ScreenUpdating = false; var lpu = dataConext.VistaMed.Organisations.FirstOrDefault(x => x.MiacCode == miacCode); if (lpu != null) { ddrDataContext.LpuId = lpu.Id; newDoc.Names.Item("ЛПУ").RefersToRange.Value2 = lpu.FullName; newDoc.Names.Item("Адрес").RefersToRange.Value2 = lpu.Address; } SvodDdr1000.Fill1000(ddrDataContext); SvodDdr2000.Fill2000(ddrDataContext); SvodDdr3000.Fill3000(ddrDataContext); SvodDdr4000.Fill4000(ddrDataContext); SvodDdr5000.Fill5000(ddrDataContext); SvodDdr6000.Fill6000(ddrDataContext); SvodDdr7000.Fill7000(ddrDataContext); excel.ScreenUpdating = true; } } context.ReportProgress(@"Формирование отчета закончено"); context.ProgressSeparator('-'); }
public static void SetBillNumbers(IBackgroundContext context, BillsEnumeratorParams args) { if (!(args.UseBillDate || args.UseCreateDate)) return; context.ProgressSeparator(); context.ReportProgress(@"ПРОСТАНОВКА НОМЕРОВ СЧЕТОВ"); context.ReportProgress(""); using (var dataContext = new VistaMedDataContext(context)) { if (context.CancellationPending) return; var sqlText = string.Format(@"SELECT a.id AS Id, a.number AS Number, a.amount AS Amount, a.sum AS Summa, a.settleDate AS BillDate, a.date AS CreateDate, o.miacCode AS SmoCode, o.shortName AS SmoName, IF(DATE_ADD(a.settleDate, INTERVAL 1 MONTH) < a.date, 1, 0) AS IsDop, MAX(et.code) AS MaxEtCode FROM Account a JOIN Contract c ON a.contract_id = c.id JOIN rbFinance f ON c.finance_id = f.id JOIN Organisation o ON c.payer_id = o.id JOIN Account_Item ai ON a.id = ai.master_id JOIN Event e ON ai.event_id = e.id JOIN EventType et ON e.eventType_id = et.id WHERE a.deleted = 0 AND ai.deleted = 0 AND e.deleted = 0 AND f.name LIKE 'омс' AND ('{0}' = '0' OR a.settleDate = '{1}') AND ('{2}' = '0' OR a.date = '{3}') AND a.number NOT LIKE '%перевыпол%' GROUP BY 1", args.UseBillDate ? 1 : 0, args.BillDate.SqlStr(), args.UseCreateDate ? 1 : 0, args.CreateDate.SqlStr()); var billData = dataContext.VistaMed.SelectSqlData<AccountData>(sqlText). OrderByDescending(x => x.IsDop).ThenBy(x => x.SmoIndex). ThenBy(x => x.TypeIndex).ThenBy(x => x.Id).ToList(); assignBillNumbers(context, dataContext, billData); } context.ProgressSeparator('-'); }
/// <summary> /// Заполнение формы контроля /// </summary> /// <param name="context"></param> /// <param name="args"></param> /// <param name="methodCaption"></param> /// <param name="fillAction"></param> private static void fillAccountCheckPlan(IBackgroundContext context, MonthParams args, string methodCaption, Action<PageType, Worksheet, MonthParams> fillAction) { context.ProgressSeparator(); context.ReportProgress(methodCaption); context.ProgressSeparator(); string templateName = Path.Combine(Path.GetFullPath(@".\"), string.Format(@"AccountCheckPlan{0}.xls", args.DateEnd.Year)); if (File.Exists(templateName)) { var excel = new Application(); excel.Visible = true; Workbook newDoc = excel.Workbooks.Add(templateName); newDoc.Names.Item(@"Период").RefersToRange.Value2 = Utils.GetPeriodName(args.DateBegin, args.DateEnd); newDoc.Names.Item(@"КоличествоМесяцев").RefersToRange.Value2 = args.DateEnd.Month; excel.ScreenUpdating = false; using (var dataContext = new VistaMedDataContext(context)) { dataContext.VistaMed.Connection.Open(); try { List<PageType> pageTypes = (new PageType[] { new Polyclinic(context, dataContext), new Stacionar(context, dataContext), new Ambulance(context, dataContext) }).ToList(); foreach (Worksheet ws in newDoc.Worksheets.Cast<Worksheet>()) { pageTypes.ForEach(x => fillAction(x, ws, args)); } } finally { dataContext.VistaMed.Connection.Close(); } } excel.ScreenUpdating = true; } else context.ReportError(@"Не найден файл {0}", templateName); context.ProgressSeparator('-'); }
private static void checkDateInOut(IBackgroundContext context, BillsValidatorDataContext dataContext, BillData bill) { if (context.CancellationPending) return; var invalidUsl = (from u in bill.Reestr.USL where u.Kol_Usl == 1 && u.Date_In != u.Date_Out && !(u.CODE_USL.StartsWith("0100") || u.CODE_USL.StartsWith("1000")) && !(u.IsFullStationar || u.IsDayStationar) select u).ToList(); if(invalidUsl.Any()) { context.ReportError(@"Даты начала и окончания услуги не равны при количестве = 1"); invalidUsl.ForEach(x => context.ReportProgress(@" -> {0}", x)); } }
public FileSystemWatcherSearchService(string directoryPath, IPinStateService pinStateService, IBackgroundContext backgroundContext, ILogFactory logFactory, IExceptionHandler backgroundExceptionHandler) { Ensure.Condition.DirectoryExists(directoryPath, "directoryPath"); Ensure.NotNull(pinStateService, "pinStateService"); Ensure.NotNull(backgroundContext, "backgroundContext"); Ensure.NotNull(logFactory, "logFactory"); Ensure.NotNull(backgroundExceptionHandler, "backgroundExceptionHandler"); this.directoryPath = directoryPath; this.pinStateService = pinStateService; this.backgroundContext = backgroundContext; this.log = logFactory.Scope("FileSystemWatcherSearch"); this.backgroundExceptionHandler = backgroundExceptionHandler; this.matcherFactory = new PatternMatcherFactory(log.Factory); this.watchers = new List <FileSystemWatcher>(); }
public BillData(IBackgroundContext context, string lFileName, string hFileName) { LFileName = Path.GetFileName(lFileName); HFileName = Path.GetFileName(hFileName); if (File.Exists(lFileName) && File.Exists(hFileName)) { Reestr = new ZL_LIST(); context.ReportProgress(@"Загрузка файла {0} ...", Path.GetFileName(hFileName)); Reestr.ReadXml(hFileName); Persons = new PERS_LIST(); context.ReportProgress(@"Загрузка файла {0} ...", Path.GetFileName(lFileName)); Persons.ReadXml(lFileName); } else throw new ApplicationException(string.Format(@"Файл счета не найден {0}/{1}", lFileName, hFileName)); }
private IFileSearchService CreateFileSearchService(IBackgroundContext backgroundContext) { if (fileSearchService == null || directoryPath != settings.SourceDirectoryPath) { ClearService(); if (directoryPath != null) { FileSystemWatcherSearchService.ClearCache(); } directoryPath = settings.SourceDirectoryPath; fileSearchService = new FileSystemWatcherSearchService(directoryPath, pinStateService, backgroundContext, logFactory, exceptionHandler); } return(fileSearchService); }
public static void AnalyzeErrors(IBackgroundContext context, LpuExecParams executorParams) { if (context.CancellationPending) return; context.ProgressSeparator(); context.ReportProgress(@"АНАЛИЗ ОШИБОК"); context.ReportProgress(""); using (var dataContext = new ErrorsAnalyzerDataContext()) { var dir = Settings.Default.DataDir; dataContext.Load(context, dir, dir, dir); if (context.CancellationPending) return; foreach (var errorDataSet in dataContext.Errors.TakeWhile(x => !context.CancellationPending)) { analyzeErrorsDataSet(context, dataContext, errorDataSet); } } context.ProgressSeparator('-'); }
public static void CheckPersonal(IBackgroundContext context, DateParams checkPersonalParams) { if (context.CancellationPending) return; var onDate = checkPersonalParams.DateEnd.Date; context.ProgressSeparator(); context.ReportProgress(@"ПРОВЕРКА СПРАВОЧНИКА СОТРУДНИКОВ ВистаМед на {0}", onDate.ToShortDateString()); context.ReportProgress(""); using (var dataContext = new PersonalCheckDataContext(context)) { var dir = Properties.Settings.Default.DataDir; dataContext.Load(context, dir); var vistaPersonal = (from p in dataContext.VistaMed.People where p.RetireDate == null && p.RbSpeciality != null && p.FederalCode != "000-000-000" select p).ToList(); var notFoundPers = (from p in vistaPersonal where !dataContext.DoctorList.Any(x => x.SNILS == p.FederalCode) select p); notFoundPers.ToList().ForEach(x => context.ReportError(@"сотрудник {0} не найден в списке ФРМР", x.ToLongString())); var nonCertPers = (from p in vistaPersonal from d in dataContext.DoctorList where d.SNILS == p.FederalCode && !d.SpecCodes.Contains(p.RbSpeciality.FederalCode) select new {p, d}); nonCertPers.ToList().ForEach(x => context.ReportError(@"сотрудник {0} не сертиф.по спец.""{1}"" (но имеет по ФРМР серт. {2})", x.p.ToLongString(), x.p.RbSpeciality.FederalCode + " " + x.p.RbSpeciality.Name, x.d.CertNames)); var expiredCert = (from p in vistaPersonal from d in dataContext.DoctorList from c in d.LastCertificates() where d.SNILS == p.FederalCode && p.RbSpeciality.FederalCode == c.SPEC_CODE && (onDate < c.CERT_DATE || onDate > c.CERT_DATE.AddYears(5)) select new { p, c }); expiredCert.ToList().ForEach(x => context.ReportError(@"сотрудник {0} имеет просроченный сертификат ""{1}""", x.p.ToLongString(), x.c.ToString())); } context.ProgressSeparator('-'); }
public static void ValidateBills(IBackgroundContext context, LpuExecParams executorParams) { if (context.CancellationPending) return; context.ProgressSeparator(); context.ReportProgress(@"ПРОВЕРКА СЧЕТОВ"); context.ReportProgress(""); using (var dataContext = new BillsValidatorDataContext()) { var dir = Properties.Settings.Default.DataDir; dataContext.Load(context, dir, dir, dir); if (context.CancellationPending) return; foreach (var bill in dataContext.Bills.TakeWhile(x => !context.CancellationPending)) { validateBill(context, dataContext, bill); } } context.ProgressSeparator('-'); }
private static void checkForDoubleUsl(IBackgroundContext context, BillsValidatorDataContext dataContext, BillData bill) { if (context.CancellationPending) return; var dupGroups = from u in bill.Reestr.USL where !(u.CODE_USL.StartsWith("0090") || u.CODE_USL.StartsWith("1090") || u.CODE_USL.StartsWith("00184")) group u by u.PacientRow.ID_PAC + " " + u.DATE_IN + " " + u.DATE_OUT + " " + u.CODE_USL into g where g.Count() > 1 select g; foreach (var dupGroup in dupGroups) { context.ReportError(@"Дублирование услуг"); foreach (var uslRow in dupGroup) { context.ReportProgress(@" > {0}", uslRow); } } }
private static void checkForCrossPeriods(IBackgroundContext context, BillsValidatorDataContext dataContext, BillData bill) { if (context.CancellationPending) return; var fullStationar = (from u in bill.Reestr.USL where u.IsFullStationar select u).ToList(); foreach (var usl in fullStationar.TakeWhile(x => !context.CancellationPending)) { var stacUsl = usl; var crossUsl = (from c in bill.Reestr.USL where c != stacUsl && c.PacientRow.PersRow == stacUsl.PacientRow.PersRow && (new DateRange(c.Date_In, c.Date_Out)).Intersects(new DateRange(stacUsl.Date_In, stacUsl.Date_Out)) select c).ToList(); crossUsl = crossUsl.Where(x => !x.IsFullStationar).ToList(); if (crossUsl.Count > 0) { context.ReportError(@" Оказание услуг во время нахождения в кругл.стационаре {0}", stacUsl.PacientRow.ToString()); context.ReportProgress(@" Стац. {0}", stacUsl.ToShortString()); crossUsl.ForEach(x => context.ReportProgress(@" -> {0}", x.ToShortString())); } } }
public static void ExportLog(IBackgroundContext context, ExportLogParams args) { var logLines = args.LogText; if (logLines.Length == 0) context.ReportError(@"Протокол пуст"); else { var word = new Application(); word.Visible = true; var templateName = Utils.GetReportFileName(@"Log.doc"); if (File.Exists(templateName)) { var newDoc = word.Documents.Add(templateName); var table = newDoc.Tables[1]; foreach (var logLine in logLines.Where(x => !string.IsNullOrEmpty(x) && x.Length > 8)) { var newRow = table.Rows.Add(); var recTime = logLine.Substring(0, 8); var recText = logLine.Substring(9); newRow.Cells[1].Range.Text = recTime; newRow.Cells[2].Range.Text = recText; if (recText.StartsWith("*")) newRow.Cells[2].Range.Font.Color = WdColor.wdColorBlue; else if (recText.StartsWith(">>")) newRow.Cells[2].Range.Font.Color = WdColor.wdColorRed; else if (recText.Trim().StartsWith("->") || recText.Trim().StartsWith("> ")) newRow.Cells[2].Range.Font.Color = WdColor.wdColorDarkRed; else if (recText.StartsWith("-----")) newRow.Cells[2].Range.Font.Color = WdColor.wdColorGreen; else newRow.Cells[2].Range.Font.Color = WdColor.wdColorAutomatic; } } else { context.ReportError(@"Файл шаблона отчета {0} не найден", templateName); } } }
public Polyclinic(IBackgroundContext context, VistaMedDataContext dataContext) : base(context, dataContext) { }
/// <summary> /// Заполняем сведения о выполнении заказ-задания /// </summary> /// <param name="context"></param> /// <param name="args"></param> public static void FillFomsReport(IBackgroundContext context, AccountCorrectParams args) { context.ProgressSeparator(); context.ReportProgress(@"ФОРМИРОВАНИЕ СВЕДЕНИЙ О ВЫПОЛНЕНИИ ЗАКАЗ-ЗАДАНИЯ"); context.ProgressSeparator(); // книга планов var excelFileName = args.AccountCheckPlanFileName; if (File.Exists(excelFileName)) { var excel = new Application(); excel.Visible = true; var reportData = getFomsReportData(context, args, excelFileName, excel); if (reportData.Count > 0) { excel.ScreenUpdating = false; using (var dataContext = new VistaMedDataContext(context)) { dataContext.VistaMed.Connection.Open(); var templateName = Path.Combine(Path.GetFullPath(@".\"), @"AccountFomsReport.xls"); Workbook newDoc = excel.Workbooks.Add(templateName); newDoc.Names.Item(@"Период").RefersToRange.Value2 = Utils.GetPeriodName(args.DateBegin, args.DateEnd); var lpu = dataContext.VistaMed.Organisations.FirstOrDefault(x => x.MiacCode == args.LpuCode); if (lpu != null) { newDoc.Names.Item("ЛПУ").RefersToRange.Value2 = lpu.FullName; newDoc.Names.Item("ФИОРуководителя").RefersToRange.Value2 = lpu.Chief; //newDoc.Names.Item("ФИОГлавбуха").RefersToRange.Value2 = lpu.Accountant; } try { var ws = (Worksheet)newDoc.Worksheets[1]; for (int rowIndex = 8; rowIndex < 19; rowIndex++) { var row = (Range)ws.Rows[rowIndex]; var rowName = row.GetCellValue<string>(1, 1); var smoCode = row.GetCellValue<string>(1, 8); if (!string.IsNullOrEmpty(smoCode)) { var rowDataType = (rowName.StartsWith("Плановое") ? FomsReportRowType.Plan : FomsReportRowType.Fact); var rowData = reportData.FirstOrDefault(x => x.SmoCode == smoCode && x.RowType == rowDataType); if (rowData != null) { var colIndex = 2; row.SetCellValue(1, colIndex++, rowData.StacFullCount + rowData.StacApuCount); row.SetCellValue(1, colIndex++, rowData.StacDayCount); row.SetCellValue(1, colIndex++, rowData.EmergencyCount); row.SetCellValue(1, colIndex++, rowData.TreatmentCount); row.SetCellValue(1, colIndex++, rowData.VisitCount + rowData.ProfilacticCount); row.SetCellValue(1, colIndex++, rowData.AmbulanceCount); } } } } finally { dataContext.VistaMed.Connection.Close(); } } excel.ScreenUpdating = true; } } else context.ReportError(@"Файл {0} не найден", excelFileName); context.ProgressSeparator('-'); }
private static List<FomsReportRowData> getFomsReportData(IBackgroundContext context, AccountCorrectParams args, string excelFileName, Application excel) { var result = new List<FomsReportRowData>(); Workbook newDoc; try { context.ReportProgress(@"Открываем файл {0} ...", excelFileName); newDoc = excel.Workbooks.Open(excelFileName); } catch (Exception exception) { newDoc = null; context.ReportError(@"Ошибка открытия файла {0} : {1}", excelFileName, exception.Message); } if (newDoc != null) { // ищем имя КоличествоМесяцев var kolMonthExists = false; for (int i = 1; i <= newDoc.Names.Count; i++) { if (newDoc.Names.Item(i).Name == @"КоличествоМесяцев") { kolMonthExists = true; break; } } if (kolMonthExists) { // сравниваем КоличествоМесяцев из книги с отчетным периодом int kolMonth = (int)newDoc.Names.Item(@"КоличествоМесяцев").RefersToRange.Value2; if (args.DateEnd.Month == kolMonth) { excel.ScreenUpdating = false; using (var dataContext = new VistaMedDataContext(context)) { dataContext.VistaMed.Connection.Open(); try { // массив с объектами - типами листов книги List<PageType> pageTypes = (new PageType[] { new Polyclinic(context, dataContext), new Stacionar(context, dataContext), new Ambulance(context, dataContext) }).ToList(); // сканируем все листы foreach (Worksheet ws in newDoc.Worksheets.Cast<Worksheet>()) { // попытка обработать текущий лист для всех типов листов // фактическая работа делается в этих объектах pageTypes.ForEach(x => x.SelectFomsReportData(ws, args, result)); } } finally { dataContext.VistaMed.Connection.Close(); } } excel.ScreenUpdating = true; } else context.ReportError(@"КоличествоМесяцев в файле не соответствует выбранному Вами периоду"); } else context.ReportError(@"Имя ячейки ""КоличествоМесяцев"" не найдено в файле {0}", excelFileName); newDoc.Close(false); } return result; }
private static void saveReport(IBackgroundContext context, ReestrDdParams args, string insurerName, Account smpBill, Workbook newDoc) { if (!string.IsNullOrEmpty(args.DirName) && Directory.Exists(args.DirName)) { if (!string.IsNullOrEmpty(insurerName)) { var dirName = Path.Combine(args.DirName, insurerName); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } var fileName = Path.Combine(dirName, "Реестр " + Enum.GetName(typeof (AccountType), smpBill.AccountType) + " к счету №" + smpBill.Number + " от " + smpBill.SettleDate.ToString("ddMMyy") + " " + insurerName); try { if (File.Exists(fileName)) File.Delete(fileName); newDoc.SaveAs(fileName); } catch (Exception e) { context.ReportError("Ошибка сохранения файла {0}: {1}", fileName, e.Message); } } } }
private static void generateTotals(Application excel, List<ReestrTotals> totals, List<ErrorZeroSum> errors, ReestrDdParams args, IBackgroundContext context) { var templateName = Utils.GetReportFileName(@"ReestrDdTotals.xls"); if (!File.Exists(templateName)) return; var newDoc = excel.Workbooks.Add(templateName); var ws = newDoc.Worksheets[1]; var allInsurers = (from c in totals select c.InsurerName).Distinct().ToList(); var accountTypes = (from c in totals select c.AccountType).Distinct().ToList(); var headerColIndex = 2; var firstRow = (Range)ws.Rows[1]; foreach (var accountType in accountTypes) { ((Range) firstRow.Cells[1, headerColIndex]).Value2 = Enum.GetName(typeof (AccountType), accountType); headerColIndex++; } var rowIndex = 2; foreach (var insurer in allInsurers) { var row = (Range) ws.Rows[rowIndex]; ((Range) row.Cells[1, 1]).Value2 = insurer; var colIndex = 2; foreach (var accountType in accountTypes) { ((Range)row.Cells[1, colIndex]).Value2 = totals .Where(x => x.AccountType == accountType && x.InsurerName == insurer).Sum(y => y.Kol); colIndex++; } rowIndex++; } var rowItog = (Range)ws.Rows[rowIndex]; ((Range)rowItog.Cells[1, 1]).Value2 = "ИТОГО"; var colIndexItog = 2; foreach (var accountType in accountTypes) { ((Range)rowItog.Cells[1, colIndexItog]).Value2 = totals .Where(x => x.AccountType == accountType).Sum(y => y.Kol); colIndexItog++; } rowIndex += 2; foreach (var error in errors) { var row = (Range)ws.Rows[rowIndex]; ((Range)row.Cells[1, 1]).Value2 = error.Insurer + " " + Enum.GetName(typeof(AccountType), error.AccountType) + " " + error.Fio; rowIndex++; } if (!string.IsNullOrEmpty(args.DirName) && Directory.Exists(args.DirName)) { var fileName = Path.Combine(args.DirName, "Итоги диспансеризации"); try { if (File.Exists(fileName)) File.Delete(fileName); newDoc.SaveAs(fileName); } catch (Exception e) { context.ReportError("Ошибка сохранения файла {0}: {1}", fileName, e.Message); } } }
private static void afterFill(IBackgroundContext context, ReestrDdParams args, VistaMedDataContext dataConext, Account smpBill, Workbook newDoc, List<ReestrTotals> totals, List<IGrouping<Event, AccountItem>> eventGroups, List<ErrorZeroSum> errors, List<string> zeroFioList) { var insurer = (from o in dataConext.VistaMed.Organisations where o.Id == smpBill.Contract.PayerId select o).FirstOrDefault(); if (insurer != null) { string insurerName = ""; if (insurer.MiacCode == "67002") insurerName = "СОГАЗ"; else if (insurer.MiacCode == "67003") insurerName = "МАКС"; else if (insurer.MiacCode == "67004") insurerName = "РГС"; else if (insurer.MiacCode == "67005") insurerName = "СПВ"; if (string.IsNullOrEmpty(insurerName)) { insurerName = new string(insurer.ShortName.ToArray() .Except(Path.GetInvalidFileNameChars()).ToArray()); } saveReport(context, args, insurerName, smpBill, newDoc); totals.Add(new ReestrTotals() { AccountType = smpBill.AccountType, InsurerName = insurerName, Kol = eventGroups.Count }); errors.AddRange(zeroFioList.Select(x => new ErrorZeroSum() {AccountType = smpBill.AccountType, Fio = x, Insurer = insurerName})); } }
public static void BuildReestrDd(IBackgroundContext context, ReestrDdParams args) { var dateBegin = args.DateBegin; var dateEnd = args.DateEnd; var miacCode = args.LpuCode; var billNum = args.AccountNumbers; using (var dataConext = new VistaMedDataContext(context)) { var smpBills = (from b in dataConext.VistaMed.Accounts where b.SettleDate >= dateBegin && b.SettleDate <= dateEnd && b.Date == args.CreateDate && b.Contract != null && b.Contract.RbFinance != null && b.Contract.RbFinance.Name.ToLower() == "омс" && (from a in b.AccountItems from s in dataConext.VistaMed.RbServices where a.ServiceId == s.Id && (s.Code.StartsWith("061") || s.Code.StartsWith("161") || s.Code.StartsWith("062") || s.Code.StartsWith("162")) select a).Any() select b).ToList(); if (!string.IsNullOrEmpty(billNum)) { var billNumList = billNum.Split(','); smpBills = smpBills.Where(x => billNumList.Contains(x.Number)).ToList(); } if (smpBills.Count == 0) context.ReportError(@"Счета ДД за период с {0} по {1} не найдены", dateBegin, dateEnd); else { var excel = new Application(); excel.Visible = true; var totals = new List<ReestrTotals>(); var errors = new List<ErrorZeroSum>(); foreach (var smpBill in smpBills) { var templateFileName = @"ReestrDd.xls"; if (smpBill.AccountType == AccountType.DDR2) templateFileName = @"ReestrDd2.xls"; var templateName = Utils.GetReportFileName(templateFileName); var zeroFioList = new List<string>(); if (!File.Exists(templateName)) continue; var newDoc = excel.Workbooks.Add(templateName); excel.ScreenUpdating = false; var ws = ((Worksheet)newDoc.Worksheets[1]); newDoc.Names.Item(@"ДатаНачала").RefersToRange.Value2 = dateBegin; newDoc.Names.Item(@"ДатаКонца").RefersToRange.Value2 = dateEnd; newDoc.Names.Item(@"ДатаОтчета").RefersToRange.Value2 = DateTime.Today; var lpu = dataConext.VistaMed.Organisations.FirstOrDefault(x => x.MiacCode == miacCode); if (lpu != null) { newDoc.Names.Item("ЛПУ").RefersToRange.Value2 = lpu.FullName + " ОГРН " + lpu.OGRN ?? ""; newDoc.Names.Item("ФИОРуководителя").RefersToRange.Value2 = lpu.Chief; newDoc.Names.Item("ФИОГлавбуха").RefersToRange.Value2 = lpu.Accountant; } var smo = (from payer in dataConext.VistaMed.Organisations where payer.Id == smpBill.PayerId select payer).FirstOrDefault(); if (smo != null) { newDoc.Names.Item("СМО").RefersToRange.Value2 = smo.FullName; } newDoc.Names.Item("НомерСчета").RefersToRange.Value2 = smpBill.Number; newDoc.Names.Item("ДатаСчета").RefersToRange.Value2 = smpBill.SettleDate; string ddName = null; string tarifHeader = null; string header13 = null; switch (smpBill.AccountType) { case AccountType.DdVet: ddName = "в рамках первого этапа диспансеризации ветеранов ВОВ и инвалидов"; tarifHeader = "Тариф на плату первого этапа диспансеризации, проведенной застрахованному лицу"; header13 = "Первый этап диспансеризации в объеме, утвержденном Минздравом России, " + "специальность медицинского работника, проводящего диспансеризацию (код)"; break; case AccountType.DDR1: ddName = "в рамках первого этапа диспансеризации определенных групп взрослого населения"; tarifHeader = "Тариф на плату первого этапа диспансеризации, проведенной застрахованному лицу"; header13 = "Первый этап диспансеризации в объеме, утвержденном Минздравом России, " + "специальность медицинского работника, проводящего диспансеризацию (код)"; break; case AccountType.DDR2: ddName = "в рамках второго этапа диспансеризации определенных групп взрослого населения"; tarifHeader = "Стоимость второго этапа диспансеризации, проведенной застрахованному лицу"; header13 = "Второй этап диспансеризации в объеме, утвержденном Минздравом России, " + "специальность медицинского работника, проводящего диспансеризацию (код), " + "тариф на оплату второго этапа диспансеризации, проведенной застрахованному лицу"; break; case AccountType.DDOrhan: ddName = "в рамках диспансеризации детей-сирот и детей, оставшихся без попечения родителей, " + "в том числе усыновленных (удочеренных), принятых под опеку (попечительство), " + "в приемную или патронатную семью"; header13 = "Диспансеризация в объеме утвержденном Минздравом России, " + "специальность медицинского работника, проводящего диспансеризацию (код)"; tarifHeader = "Тариф на оплату диспансеризации проведенной застрахованному лицу"; break; case AccountType.DDHardLive: ddName = "в рамках диспансеризации детей сирот, пребывающих в стационарных учреждениях и детей, " + "находящихся в трудной жизненной ситуации"; header13 = "Диспансеризация в объеме утвержденном Минздравом России, " + "специальность медицинского работника, проводящего диспансеризацию (код)"; tarifHeader = "Тариф на оплату диспансеризации проведенной застрахованному лицу"; break; case AccountType.DD14: break; case AccountType.Osm18: ddName = "в рамках медицинских осмотров несовершеннолетних"; header13 = "Медицинские осмотры несовершеннолетних в объеме, утвержденном Минздравом России, " + "специальность медицинского работника, проводящего медицинские осмотры (код)"; tarifHeader = "Тариф на оплату медицинского осмотра проведенного застрахованному лицу"; break; case AccountType.ProfOsm: ddName = "за проведенные профилактические медицинские осмотры взрослого населения"; header13 = "Медицинские осмотры в объеме, утвержденном Минздравом России, " + "специальность медицинского работника, проводящего профилактический " + "медицинский осмотр (код)"; tarifHeader = "Тариф на оплату профилактических медицинских осмотров, " + "проведенных застрахованному лицу"; break; default: break; } if (!string.IsNullOrEmpty(ddName)) newDoc.Names.Item("НазваниеДД").RefersToRange.Value2 = ddName; if (!string.IsNullOrEmpty(tarifHeader)) newDoc.Names.Item("ЗаголовокТарифа").RefersToRange.Value2 = tarifHeader; if (!string.IsNullOrEmpty(header13)) newDoc.Names.Item("Кол13").RefersToRange.Value2 = header13; var eventGroups = (from accItem in smpBill.AccountItems group accItem by accItem.Event into g orderby g.Key.Client.Fio select g).ToList(); foreach (var eventGroup in eventGroups) { ((Range)ws.Rows[14]).Insert(); ((Range)ws.Rows[15]).Copy(Destination: ((Range)ws.Rows[14])); } var rowIndex = 1; foreach (var eventGroup in eventGroups) { var client = eventGroup.Key.Client; if (client != null) { var newRow = ((Range)ws.Rows[rowIndex + 13]); ((Range)newRow.Cells[1, 1]).Value2 = rowIndex; ((Range)newRow.Cells[1, 2]).Value2 = client.Fio; ((Range)newRow.Cells[1, 3]).Value2 = client.Sex == 1 ? "М" : "Ж"; ((Range)newRow.Cells[1, 4]).Value2 = client.BirthDate; var clientDocId = dataConext.VistaMed.GetClientDocumentId(client.Id); var clientDoc = (from c in dataConext.VistaMed.ClientDocuments where c.Id == clientDocId select c).FirstOrDefault(); if (clientDoc != null) ((Range)newRow.Cells[1, 6]).Value2 = clientDoc.Serial + " " + clientDoc.Number; ((Range)newRow.Cells[1, 7]).Value2 = dataConext.VistaMed.GetClientLocAddress(client.Id); var clientPolicyId = dataConext.VistaMed.GetClientPolicyId(client.Id, 1); var clientPolicy = dataConext.VistaMed.ClientPolicies.FirstOrDefault(x => x.Id == clientPolicyId); ((Range)newRow.Cells[1, 9]).Value2 = client.GetSnilsFormatted(); if (clientPolicy != null) ((Range)newRow.Cells[1, 10]).Value2 = (clientPolicy.Serial + " " + clientPolicy.Number).Trim(); ((Range)newRow.Cells[1, 11]).Value2 = "1"; var diagnosisId = dataConext.VistaMed.GetEventDiagnosis(eventGroup.Key.Id); var mkb = (from d in dataConext.VistaMed.Diagnoses where d.Id == diagnosisId select d.MKB) .FirstOrDefault(); ((Range)newRow.Cells[1, 12]).Value2 = mkb ?? ""; var prnActions = (from item in eventGroup where item.Action != null && (item.Action.ActionType.Name.StartsWith(@"Комплексная услуга") || item.Action.ActionType.Name.StartsWith(@"Комп. услуга") || item.Action.ActionType.Name.StartsWith(@"Осмотр врача")) select item).ToList(); ((Range)newRow.Cells[1, 13]).Value2 = string.Join(" ", prnActions.Select(x => x.Action.ActionType.Code)); ((Range)newRow.Cells[1, 14]).Value2 = string.Join(" ", prnActions.Select(x => x.Action.BegDate.Value.ToShortDateString())); ((Range)newRow.Cells[1, 15]).Value2 = string.Join(" ", prnActions.Select(x => x.Action.EndDate.Value.ToShortDateString())); ((Range)newRow.Cells[1, 16]).Value2 = string.Join(" ", prnActions.Select( x => x.Action.Person_PersonId == null ? "" : x.Action.Person_PersonId.RbSpeciality.FederalCode.PadRight(15))); var colIndex = 17; if (smpBill.AccountType == AccountType.DDR2) { ((Range)newRow.Cells[1, colIndex++]).Value2 = string.Join(" ", prnActions.Select(x => x.Sum.ToString(@"F2"))); } var summa = eventGroup.Sum(x => x.Sum); ((Range) newRow.Cells[1, colIndex++]).Value2 = summa; ((Range)newRow.Cells[1, colIndex++]).Value2 = eventGroup.Key.RbResult.FederalCode; if (Math.Abs(summa) < 0.01) { zeroFioList.Add(eventGroup.Key.Client.Fio + " " + eventGroup.Key.Client.BirthDate.ToShortDateString()); } rowIndex++; } } var totalRow = ((Range)ws.Rows[rowIndex + 13]); ((Range)totalRow.Cells[1, 2]).Value2 = @"ИТОГО"; ((Range)totalRow.Cells[1, 17 + (smpBill.AccountType == AccountType.DDR2 ? 1 : 0)]).Value2 = smpBill.Sum; excel.ScreenUpdating = true; ws.Activate(); afterFill(context, args, dataConext, smpBill, newDoc, totals, eventGroups, errors, zeroFioList); } generateTotals(excel, totals, errors, args, context); } } }
private static void analyzeErrorsDataSet(IBackgroundContext context, ErrorsAnalyzerDataContext dataContext, SmoErrorDataSet errorDataSet) { context.ProgressSeparator(); context.ReportProgress("РЕВЬЮ {0}", errorDataSet.FileName); var bill = dataContext.Bills.FirstOrDefault( x => x.LFileName == errorDataSet.SourceFileName || x.HFileName == errorDataSet.SourceFileName); if (bill == null) { context.ReportProgress(@"Не найден файл счета {0}", errorDataSet.SourceFileName); return; } if (errorDataSet.PR.Rows.Count == 0) { context.ReportProgress(@"Ошибки не обнаружены", errorDataSet.FileName); return; } if (errorDataSet.SourceFileName.StartsWith("L")) { /* ошибки по списку персон */ foreach (var prRow in errorDataSet.PR) { context.ReportError(@"{0}", prRow); if(prRow.N_ZAP != "") { var pers = bill.Persons.PERS.FirstOrDefault(x => x.ID_PAC == prRow.N_ZAP); if(pers != null) context.ReportProgress(@" -> {0}", pers); } } } else { /* ошибки по услугам */ foreach (var prRow in errorDataSet.PR) { context.ReportError(@"{0}", prRow); if(prRow.OSHIB == "904") { var doc = dataContext.DoctorList.FirstOrDefault( x => x.SNILS == prRow.COMMENT.Substring(prRow.COMMENT.Length - 11)); if(doc != null) context.ReportProgress(@" Доктор {0}", doc.ToString()); } if (prRow.N_ZAP != "") { var zap = bill.Reestr.ZAP.FirstOrDefault(x => x.N_ZAP == prRow.N_ZAP); if (zap != null) { foreach (var sluchRow in zap.GetSLUCHRows()) { context.ReportProgress(@" -> {0}", sluchRow.ToString()); } } } } } }
public void LoadErrors(IBackgroundContext context, string errorsDir) { if (context.CancellationPending) return; context.ProgressSeparator(); context.ReportProgress(@"Загрузка файлов с ошибками СМО ..."); if (string.IsNullOrEmpty(errorsDir)) errorsDir = @".\"; errorsDir = Path.GetFullPath(errorsDir); if (Directory.Exists(errorsDir)) { foreach (var xmlFileName in Directory.GetFiles(errorsDir, "FLK_*.xml").TakeWhile(x => !context.CancellationPending)) { if (File.Exists(xmlFileName) && File.Exists(xmlFileName)) { var errorDataSet = new SmoErrorDataSet(); errorDataSet.ReadXml(xmlFileName); Errors.Add(errorDataSet); } } } context.ReportProgress(@"Загрузка файлов с ошибками СМО закончена"); }
public Ambulance(IBackgroundContext context, VistaMedDataContext dataContext) : base(context, dataContext) { }
public Stacionar(IBackgroundContext context, VistaMedDataContext dataContext) : base(context, dataContext) { }
public Section(int minRowIndex, int maxRowIndex, VistaMedDataContext dataContext, StacionarType stacionarType, IBackgroundContext context) { this.minRowIndex = minRowIndex; this.maxRowIndex = maxRowIndex; this.dataContext = dataContext; this.stacionarType = stacionarType; this.context = context; }
public void Load(IBackgroundContext context, string frmrDir, string billsDir, string errorsDir) { LoadFrmr(context, frmrDir); LoadBills(context, billsDir); LoadErrors(context, errorsDir); }
protected PageType(IBackgroundContext context, VistaMedDataContext dataContext) { this.context = context; this.dataContext = dataContext; }
public static void BuildSvedProf(IBackgroundContext context, MonthAccountParams args) { var dateBegin = args.DateBegin; var dateEnd = args.DateEnd; var miacCode = args.LpuCode; using (var dataConext = new VistaMedDataContext(context)) { var smpBills = (from b in dataConext.VistaMed.Accounts where b.Date >= args.DateBegin.AddDays(15) && b.Date < args.NextMonthBegin.AddDays(15) && b.Contract != null && b.Contract.RbFinance != null && b.Contract.RbFinance.Name.ToLower() == "омс" && (from a in b.AccountItems from s in dataConext.VistaMed.RbServices where a.ServiceId == s.Id && s.Code.StartsWith("062") select a).Any() select b).ToList(); smpBills = smpBills.Where(x => args.IsValidAccountNumber(x.Number) && !x.Number.StartsWith(PlanExecution.ReserveAccountName)).ToList(); if (smpBills.Count == 0) context.ReportError(@"Счета ДД за период с {0} по {1} не найдены", dateBegin, dateEnd); else { var excel = new Application(); excel.Visible = true; var plans = loadPlans(excel); var templateName = Utils.GetReportFileName(@"SvedProf.xls"); if (File.Exists(templateName)) { var newDoc = excel.Workbooks.Add(templateName); excel.ScreenUpdating = false; var ws = ((Worksheet) newDoc.Worksheets[1]); newDoc.Names.Item(@"ДатаНачала").RefersToRange.Value2 = dateBegin; newDoc.Names.Item(@"ДатаКонца").RefersToRange.Value2 = dateEnd; newDoc.Names.Item(@"ДатаОтчета").RefersToRange.Value2 = DateTime.Today; newDoc.Names.Item(@"ОтчетныйПериод").RefersToRange.Value2 = Utils.GetPeriodName(dateBegin, dateEnd); var lpu = dataConext.VistaMed.Organisations.FirstOrDefault(x => x.MiacCode == miacCode); if (lpu != null) { newDoc.Names.Item("ЛПУ").RefersToRange.Value2 = lpu.FullName; newDoc.Names.Item("ФИОРуководителя").RefersToRange.Value2 = lpu.Chief; newDoc.Names.Item("ФИОГлавбуха").RefersToRange.Value2 = lpu.Accountant; } var reportColumn = new ReportColumn(); reportColumn.Man = plans.Sum(x => x.Man); reportColumn.Woman = plans.Sum(x => x.Woman); fillReportColumn(ws, reportColumn, 3); reportColumn = new ReportColumn(); reportColumn.Man = plans.Where(y => y.Month == dateEnd.Month).Sum(x => x.Man); reportColumn.Woman = plans.Where(y => y.Month == dateEnd.Month).Sum(x => x.Woman); fillReportColumn(ws, reportColumn, 7); var allevents = (from b in smpBills from a in b.AccountItems where !a.Deleted && a.Event != null && a.Event.Client != null group a by a.Event into e select new {Event = e.Key, Client = e.Key.Client, Summa = e.Sum(x => x.Sum)}).ToList(); var man = (from e in allevents where e.Client.Sex == 1 select e).ToList(); var woman = (from e in allevents where e.Client.Sex == 2 select e).ToList(); reportColumn = new ReportColumn(); reportColumn.Man = man.Sum(x => x.Summa); reportColumn.Woman = woman.Sum(x => x.Summa); fillReportColumn(ws, reportColumn, 8); reportColumn = new ReportColumn(); reportColumn.Man = man.Count(); reportColumn.Woman = woman.Count(); fillReportColumn(ws, reportColumn, 9); excel.ScreenUpdating = true; ws.Activate(); } } } }