Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
PZ.doc
Скачиваний:
0
Добавлен:
01.07.2025
Размер:
971.78 Кб
Скачать

2 Проектний розділ

2.1 Розробка структури додатку

Структура програми буде складатися з трьох базових підсистем:

  • моделі даних;

  • системи обробки даних, та допоміжних класів;

  • системи візуалізації, яка буде реалізована за технологією windows forms.

Модель даних програми представлена на рисунку 2.1 та буде складатися з наступних класів.

  • Depatment – призначено для збереження інформації про відділенні поліклініки, що відкрити у лікувальному закладі.

  • Employee – призначено для збереження інформації про співробітників. Кожен співробітник категорії лікар буде відноситися до одного з відділень.

  • ClassInfo – містить довідникову інформацію, наприклад перелік посад та кваліфікацій співробітників.

  • Patients – містить особисту інформацію про кожного пацієнта.

  • InfoPatient – містить інформацію про звернення пацієнта до лікувального закладу, встановлені діагнози та історію призначень. Цей клас є реалізацією електронної медичної картки пацієнта.

  • Raspisanie – клас що містить розклад роботи лікарів.

  • Diagnoze – клас, що забезпечить збереження та обробку переліку встановлених діагнозів.

  • ClassTax – клас, що буде містити назви та тарифи нарахувань та відрахувань. Клас є реалізацією довідника.

  • Zapis – клас, що містить інформацію про записи пацієнтів на прийом до лікаря. Буде складатися з коду лікаря, дати та часу. Запис можлива як первинна, тобто без оформленої медичної картки, та і вторинна, для вже зареєстрованих пацієнтів.

Рисунок 2.1 – Модель даних програми

Програма буде мати декілька допоміжних класів, на основі яких буде реалізовано з’єднання програми з базою даних та обробка отриманої інформації, як з бази даних, так і з користувальницького інтерфейсу. Планується, що програма буде містити наступні класи:

  • ClassDataBase – призначено для реалізації логіки роботи з базою даних. У класі необхідно передбачити реалізацію методів доступу до інформації у вигляді записів та первинної обробки інформації. Інформація повинна повертатися у вигляді сформованих переліків, або результату виконання запиту. Клас необхідно буде реалізувати за технологією шаблонів, щоб забезпечити універсальний підхід до роботи з переліками різних типів даних.

  • ClassSetupProgram – клас, що буде містити налаштування програмного продукту, наприклад рядок з’єднання з базою даних.

  • ClassSerialiaze – клас, що забезпечить формування вхідних даних для побудови звітів та іншої документації відповідно до технології Fast Report.

Рисунок 2.2 – Структурна схема допоміжних класів програми

Підсистема візуалізації програми буде складатися з форм, кожна з яких буде містити елементи керування, які забезпечать зв’язок користувача з функціоналом роботи програми. Структура підсистеми візуалізації представлена на рисунку 2.3. Підсистема буде складатися з наступного переліку форм:

Business – форма для відображення нарахувань та відрахувань при обчисленні заробітної прати співробітникам.

Employees – форма для відображення переліку співробітників лікувального закладу, реєстрації нового співробітника, створення розкладу його роботи, призначення та зняття з посад.

Department – форма для перегляду переліку відділень лікувального закладу, створення та вилучення відділення, призначення керівника відділення.

FormReport – форма для відображення звітних та медичних документів (довідок, медичної картки, форм обліку, встановлених міністерством охорони здоров’я України)

FormReportStatistic – форма для забезпечення встановлення параметрів і перегляду статистичної інформації по лікувальному закладу.

Patient – форма для реєстрації нового пацієнта, занесення його особистих даних. Перегляду переліку зареєстрованих пацієнтів та здійсненні вибірок за різними критеріями.

RecordToDoctor – форма запису пацієнта на прийом до лікаря, пошук потрібного фахівця.

RegistratureMain – головна форма програми, яка дозволяє перемикатися між функціоналом програми.

StatusPeople – форма для встановлення та зміни статусу пацієнта (на лікарняному, госпіталізовано, виписано та інше).

TablesForEmployee – форма для перегляду та редагування розкладу роботи працівників закладу.

Рисунок 2.3 – Структурна схема підсистеми візуалізації програмного продукту.

2.2 Розробка бази даних

Проектування – це процес створення такої структури бази даних (БД), яка б відповідала вимогам користувачів.

Життєвий цикл БД, а також програмних систем в цілому можна розділити на 2 фази:

  • фаза проектування:

  • фаза реалізації.

Після аналізу функціонування предметної області «Реєстратура приватної поліклініки» можна виділити такі сутності та їх атрибути:

  1. Лікарі:

  • ПІБ лікаря;

  • спеціалізація;

  • відділення у якому працює лікар;

  • кваліфікація;

  • посада.

  1. Хворі:

  • ПІБ хворого;

  • дата народження;

  • телефон;

  • адреса проживання;

  • особиста інформація та попередній анамнез (наявність алергічних реакцій, інфекційних захворювань, перенесених хірургічних утручань ).

  1. Запис на прийом до лікаря:

  • ПІБ хворого;

  • лікар;

  • дата та час відвідування.

Запис на прийом до лікаря ґрунтується на зверненні хворого до реєстратури та повідомлення ним особистих даних та розкладу прийому лікарів. ЕR діаграма бази даних представлена на рисунку 2.4

Рисунок 2.4 – ER діаграма бази даних приватної поліклініки

На рисунках 2.5 – 2.10 представлено процес проектування кожної з ER діаграми таблиць із значеннями

Рисунок 2.5 – Department «Відділення приватної поліклініки»

Рисунок 2.5 – Diagnoze «Діагнози»

Рисунок 2.6 – Employee «Співробітники»

Таблиця 2.7 – InfoPacient «Інформація про пацієнтів»

Рисунок 2.8 – Pacient «Пацієнти»

Рисунок 2.9 – Raspisanie «Розклад»

Рисунок 2.10 – Zapis «Запис на прийом до лікаря»

Рисунок 2.11 – Схема бази даних реєстратури приватної поліклініки

2.3 Алгоритм функціонування

Робота програми буде розпочинатися з завантаження форми RegistratureMain, при виконанні обробника на подію Load() буде виконано завантаження переліків з інформацією, що найбільш часто використовується при виконанні дій програми. Будуть сформовані переліки відділень, співробітників, та пацієнтів. З даної форми буде здійснюватися перехід до інших форм, які забезпечать виконання базового функціоналу програми. Передача завантаженої інформації буде здійснюватися статичним відкритим методом, або через її копіювання у конструкторах другорядних підлеглих форм.

На формі будуть розташовані компоненти Button.

При роботі з відділеннями буде завантажуватися форма frmMain. У конструкторі даною форми буде виконуватися передача завантажених раніш з бази даних інформації. Обробника на подію Load() викликатиме метод showDataToDGV(), який забезпечить відображення переліку відділень на компоненті DataGreadView. Дана форма буде містить методи:

  • updateData(List<Employee> _listEmpl), який дозволить зберегти змінені дані по співробітникам,

  • detectFild() – метод перевірки коректності заповнених даних;

  • writeDataToDb() – метод додавання даних до бази даних. Робота даного метода ґрунтується на реалізації класу ClassDataBase;

  • Сохранить_Click() – обробник викликає описані вище методи, та забезпечує реєстрацію нового відділення у лікувальному закладі;

  • createFileReportDepartment() – метод створюватиме документ, що буде містити інформацію про відділення. Алгоритм роботи даного метода відповідає технології FastReport. На початку виконується серіалізація необхідних даних у файл формату xml, даний файл підключається до шаблону у форматі frx, завантажуються дані, виконується їх підставлення у шаблон та відображаються на компоненті для перегляду створених звітів. Усі звіти, що будуть реалізовані у даному програмному продукті будуть побудовані за даним алгоритмом.

  • DetectRepeat(string NameDepartment) – метод блокування можливості створення відділення, що вже зареєстровано у поліклініці.

При роботі зі співробітниками буде завантажуватися форма Employees. Обробник Employees_Load() буде завантажувати перелік співробітників, у разі відсутності цих даних на момент виклику форми а також викликати методи showDataToDGV(ref listEmpl) та Load_comboBoxDep(), які забезпечать ініціалізацію компонентів форми та відображення завантажених даних. Будуть реалізовані наступні методи:

  • DecectCorrect() – перевірка коректності заповнення обов’язкових полів;

  • writeDataToDb() – запис даних до бази даних;

  • pdateList() – оновлення даних, після внесення змін;

  • createBlancRaspisanieSotrudnika() – створення бланку для роботи з розкладом співробітника;

  • UpdateInfoToEmployee() – оновлення інформації про режим роботи співробітника.

Базовий функціонал роботи з пацієнтами буде починатися з завантаження форми Patient. У обробнику Patient_Load() –формуватиметься перелік пацієнтів, що є зареєстрованими на поточний час та відображення даного переліку на компоненті DataGreadView.

Форма буде складатися з наступного функціоналу:

  • DecectCorrect() – перевірка коректності введених даних;

  • showDataToDGV(ref List<Patients> currentListPacient) – відображення переліку зареєстрованих даних;

  • updateData(List<Patients> _listPatients) – оновлення переліку зареєстрованих даних;

  • удалитьToolStripMenuItem_Click() – обробник, що забезпечить видалення інформації про пацієнта у разі необхідності. Функція реалізована із збереженням реляційності, тобто, спочатку буде видалена уся інформація, що була пов’язана з пацієнтом(діагнози, записи до лікарів, призначення, довідки та інше), потім буде видалена узагальнена інформація та медичка картка.

  • Form086() – метод формування довідки за формою У086;

  • bTmedCard() – метод формування медичної картки пацієнта;

  • OtherInfo() – метод занесення додаткової інформації про пацієнта;

  • searchNumberCard(),searchPacientFIO(),outputResultSearch() – методи, що забезпечать функцію пошуку пацієнта у базі даних за різними критеріями, та відображення результатів пошуку.

Алгоритм запису пацієнта на прийом до лікаря буде реалізовано у формі RecordToDoctor. У формі будуть реалізовані наступні методи:

  • SearchDepCb() – реалізація пошуку відділення;

  • getIdDay(DateTime timeWeek) – відначення порядкового номеру дня, як що відома дата;

  • SearchEmplCb(string depName) – пошук співробітника (лікаря);

  • EmplDateWork(string fio, DateTime timeWeek) – функція визначення переліку лікарів, що будуть працювати у вибрану дату.

  • ShowZapisDGV(ref List<Zapis> CurrentZapis) – відображення переліку вже записаних пацієнтів до даного лікаря на обрану дату;

  • CreateBlank() – створення бланку запису. Бланк створюється один раз, при первинному записі будь якого пацієнта до обраного лікаря на вказану дату;

  • WriteZapisToDB() – запис пацієнта на прийом до лікаря;

  • btnSearch() – пошук інформації про пацієнта у разу повторних записів до лікаря.

В основі описаних вище алгоритмів роботи програми є клас ClassDataBase. Клас буде створено за технологією створення шаблонів и буде складатися з наступних методів:

  • int ExecuteNonQuery(ref ClassSetupProgram setupProgram, string sSql, int where) – метод для виконання запитів до бази даних категорії додавання, редагування та вилучення даних. На початку буде встановлено зв’язок з базою даних та виконано відкриття з’єднання, відправлення команди на виконання та очікування відповіді від бази даних. Результатом повинно прийти ціле значення, яке містить кількість оновлених, видалених, або доданих рядків з даними до бази даних. У разі виникнення виняткової ситуації – метод поверне у програму значення 0;

  • int ExecuteItog(ref ClassSetupProgram setupProgram, string sSql) – метод призначений для виконання запитів з підсумковими функціями. Алгоритм роботи аналогічний вище описаному. Повертається ціле значення;

  • T GetObject<T>(params object[] args) – метод, що створює об’єкт класу на базі конструктора, що містить у якості вхідного параметру тільки один вхідний рядок з описом та значеннями для створення та ініціалізації об’єкту;

  • Execute<T>(ref ClassSetupProgram setupProgram, string sSql, ref List<T> listResult) – метод, що забезпечує завантаження будь яких даних з бази даних. Керування даним методом здійснюється за допомогою вхідних параметрів, де: ref ClassSetupProgram setupProgram – посилання на об’єкт, що містить рядок з’єднання з базою даних, string sSql – sql радок з командою, ref List<T> listResult – вихідний список, для збереження результату завантажених даних.

Створення даних для побудови звітів буде виконуватися у класі ClassSerialiaze, який буде реалізовано на базі технології створення темплейтів та матиме наступний алгоритм роботи.

SerialiazeToXml<T>(ref T inObject, string inFileName) – метод буде призначено для збереження об’єктів ref T inObject у файл string inFileName за допомогою стандартних методів framework.

DeserializationFromXml<T>(ref T inObject, string inFileName) – метод буде призначено для витягу об’єктів ref T inObject з файлу string inFileName за допомогою стандартних методів framework.

Завершення програми буде здійснюватися за ініціативою користувача при закритті форми RegistratureMain. Підлеглі форми будуть вивантажені та закриті автоматично.

ВИСНОВКИ

У ході розробки курсового проекту була створена база даних в СКБД SQLite і додаток для роботи адміністратора приватної поліклініки. Всі запити до БД та операції над даними виконуються додатком. Вхідні дані перевіряються на коректність, у разі неправильного введення, система повідомляє про помилку і пропонує користувачеві перевірити введені дані на наявність останніх.

Створюючи дану базу і додаток для роботи адміністратора реєстратури приватної поліклініки, було виконано аналіз існуючих аналогів, розглянуть сучасні технології розробки програмних продуктів, розроблені алгоритми функціонування програми. Під час роботи були закріплені навички роботи в СКБД SQLite, розширені знання в області написання програм мовою C # і створення дружнього інтерфейсу.

Обрана СКБД проста в розумінні і використанні, що робить її досить корисним інструментом при розробці баз даних. Обрані технології дозволяють у повному обсязі реалізувати функціонал роботи програми.

ПЕРЕЛІК ПОСИЛАНЬ

ДОДАТОК А

Програмний код системи автоматизацій роботи реєстратури приватної поліклініки.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace Registratura

{

public partial class RegistratureMain : Form

{

public RegistratureMain()

{

InitializeComponent();

}

public List<Depatment> listDepartament = new List<Depatment>();

public List<Employee> listEmployee = new List<Employee>();

public List<Patients> listPatients = new List<Patients>();

ClassDataBase db = new ClassDataBase();

public ClassSetupProgram setupProgr = new ClassSetupProgram();

private void button1_Click(object sender, EventArgs e)

{

frmMain frm = new frmMain(this);

frm.Show();

}

private void Register1_Load(object sender, EventArgs e)

{

string commandText = "select id, departmentName, departmentEtag, departmentPhone, departmentDescription from Department order by id";

db.Execute<Depatment>(ref setupProgr, commandText, ref listDepartament);

string commandText1 = "select Id, employeeSuName, employeeName, employeeSecondName, employeeSpecial, employeeDepartment, employeeKategor, employeeDolgnost, employeeDateReg from Employee order by employeeSuName, employeeName, employeeSecondName";

db.Execute<Employee>(ref setupProgr, commandText1, ref listEmployee);

string commandText2 = "select id, pacientSuName, pacientName, pacientSecondName, pacientBDate, pacientDateReg, pacientAddress, pacientWork, pacientPhone from Pacient order by id";

db.Execute<Patients>(ref setupProgr, commandText2, ref listPatients);

}

private void button2_Click(object sender, EventArgs e)

{

Employees frm = new Employees(this);

frm.Show();

}

private void button3_Click(object sender, EventArgs e)

{

Patient frm = new Patient(this);

frm.Show();

}

private void button6_Click(object sender, EventArgs e)

{

TablesForEmployee frm = new TablesForEmployee(this);

frm.Show();

}

private void button7_Click(object sender, EventArgs e)

{

RecordToDoctor frm = new RecordToDoctor(this);

frm.Show();

}

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)

{

FormReportStatistic frm = new FormReportStatistic();

frm.Show();

}

}

}

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml.Serialization;

namespace Registratura

{

public partial class TablesForEmployee : Form

{

public TablesForEmployee(RegistratureMain _frm)

{

InitializeComponent();

frm = _frm;

}

RegistratureMain frm;

ClassSetupProgram setupProgram = new ClassSetupProgram();

private void TablesForEmpl_Load(object sender, EventArgs e)

{

listDepartament = frm.listDepartament;

listEmployee = frm.listEmployee;

setupCbDep();

loadFullNamberRooms(); // Загрузка существующих кабинетов

dgvRasp.Rows.Add(" ", " ", " ", " ", " ", " "); dgvRasp.Rows.Add(" ", " ", " ", " ", " ", " ");

}

public List<Depatment> listDepartament = new List<Depatment>(); //Загрузка листов для выборки

public List<Employee> listEmployee = new List<Employee>();

public List<Raspisanie> listRasp = new List<Raspisanie>();

public List<int> numberRooms = new List<int>(); // список кабинетов, которые есть в поликлинике.

void loadFullNamberRooms() // Загрузка существующих кабинетов

{

ClassSerialiaze.DeserializationFromXml<List<int>>(ref numberRooms, "NumberRooms.xml");

}

// Проверка на наличие данного номера кабинета в поликлинике

public bool detectExistRooms(int inNumberRoom)

{

for (int i = 0; i < numberRooms.Count; i++)

{

if (numberRooms.ElementAt(i) == inNumberRoom) { return true; }

}

return false;

}

ClassDataBase db = new ClassDataBase();

public ClassSetupProgram setupProgr = new ClassSetupProgram();

private void setupCbDep() //

{

if (listDepartament.Count > 0)

{

for (int i = 0; i < listDepartament.Count; i++)

cbDep.Items.Add(listDepartament.ElementAt(i).departmentName);

cbDep.Text = listDepartament.ElementAt(0).departmentName;

}

}

private void setupCbEmpl(string depName) //

{

cbEmployee.Items.Clear();

cbEmployee.Text = "";

if (listEmployee.Count > 0)

for (int i = 0; i < listEmployee.Count; i++)

if (listEmployee.ElementAt(i).employeeDepartment == depName)

cbEmployee.Items.Add(listEmployee.ElementAt(i).employeeSuName + " " + listEmployee.ElementAt(i).employeeName + " " + listEmployee.ElementAt(i).employeeSecondName);

}

int getIdByFIO(string inFIO) //

{

string[] val = inFIO.Split(' ');

for (int i = 0; i < listEmployee.Count; i++)

{

if (listEmployee.ElementAt(i).employeeSuName == val[0]) return listEmployee.ElementAt(i).Id;

}

return 0;

}

int idCurrentEmpl = -1;

private void setupRaspisanie() //

{

dgvRasp.Rows.Clear();

dgvRasp.Rows.Add(" ", " ", " ", " ", " ", " "); dgvRasp.Rows.Add(" ", " ", " ", " ", " ", " ");

listRasp.Clear();

idCurrentEmpl = getIdByFIO(cbEmployee.Text);

string text = "select * from Raspisanie where idEmployee = " + idCurrentEmpl;

db.Execute<Raspisanie>(ref setupProgr, text, ref listRasp);

for (int i = 0; i < 12; i++)

{

try

{

string room = Convert.ToString(listRasp.ElementAt(i).numberRoom);

if (Convert.ToString(listRasp.ElementAt(i).numberRoom) == "0") room = "";

dgvRasp[Convert.ToInt32(listRasp.ElementAt(i).numberWeekDay) - 1, Convert.ToInt32(listRasp.ElementAt(i).numberSmenu) - 1].Value = room;

}

catch { }

}

}

private void cbDep_TextChanged(object sender, EventArgs e) //

{

setupCbEmpl(cbDep.Text);

}

private void cbEmployee_TextChanged(object sender, EventArgs e) //

{

setupRaspisanie();

}

#region Поиск повторного задания кабинетов в расписании

// true - можно использовать данный кабинет false - кабинет занят

private bool DetectRoom(int numberWeekDay, int numberSmenu, int numberRoom, int idEmployee)

{

bool Rezult = true;

string text = "select count(id) from Raspisanie where numberWeekDay = " + Convert.ToString(numberWeekDay) +

" and numberSmenu = " + Convert.ToString(numberSmenu) + " and numberRoom = " + Convert.ToString(numberRoom)

+ " and idEmployee != " + Convert.ToString(idEmployee);

int x = db.ExecuteItog(ref setupProgram, text);

if (x > 0)

return false;

return Rezult;

}

# endregion

private void NewListRaspisanie()

{

string textqvery = "";

for (int i = 0; i < dgvRasp.Columns.Count; i++)

{

for (int j = 0; j < dgvRasp.Rows.Count; j++)

{

if ((Convert.ToString(dgvRasp[i, j].Value)) != "" && ((Convert.ToString(dgvRasp[i, j].Value)) != " "))

{

// вызов метода,который проверяет не занят ли кабинет в этот день

bool existNumberRoom = detectExistRooms(Convert.ToInt32(dgvRasp[i, j].Value));

if (existNumberRoom)

{

bool d = DetectRoom(i + 1, j + 1, Convert.ToInt32(dgvRasp[i, j].Value), idCurrentEmpl);

if (d)

{

string room = "";

if (Convert.ToString(dgvRasp[i, j].Value) == "0") room = "";

else room = Convert.ToString(dgvRasp[i, j].Value);

textqvery = "update Raspisanie set NumberRoom = " + room +

" where idEmployee = " + idCurrentEmpl + " and numberWeekDay = " + Convert.ToString(i + 1) +

" and numberSmenu = " + Convert.ToString(j + 1);

db.ExecuteNonQuery(ref setupProgr, textqvery, 0);

statLine.Text = "Данные редактированы успешно";

timerStatusLine.Start();

}

else if (Convert.ToInt32(dgvRasp[i, j].Value) != 0) { MessageBox.Show("Кабинет " + Convert.ToString(dgvRasp[i, j].Value) + " занят. ", "Внимание!!!"); }

}

else { MessageBox.Show("Кабинет " + Convert.ToString(dgvRasp[i, j].Value) + " не существует ", "Ошибка ввода данных"); }

}

else statLine.Text = "Данные редактированы успешно"; // логически не верно расписание

}

}

}

private void button1_Click(object sender, EventArgs e)

{

NewListRaspisanie();

}

private void timerStatusLine_Tick(object sender, EventArgs e)

{

statLine.Text = "";

timerStatusLine.Stop();

}

#region Создание документов по расписанию

// Создание документа - расписание работы врача или вречей по отделению

private void setupCreateDocument()

{

cBox2.Items.Clear();

cBox2.Text = "";

if (rbEmployee.Checked)

{

if (listEmployee.Count > 0)

for (int i = 0; i < listEmployee.Count; i++)

cBox2.Items.Add(listEmployee.ElementAt(i).employeeSuName + " " + listEmployee.ElementAt(i).employeeName + " " + listEmployee.ElementAt(i).employeeSecondName);

if (cBox2.Items.Count > 0) cBox2.Text = cBox2.Items[0].ToString();

}

else

{

if (listDepartament.Count > 0)

for (int i = 0; i < listDepartament.Count; i++)

cBox2.Items.Add(listDepartament.ElementAt(i).departmentName);

if (cBox2.Items.Count > 0) cBox2.Text = cBox2.Items[0].ToString();

}

}

private void butt2_Click(object sender, EventArgs e)

{

try

{

setupRasrisanieReport("reportRaspisanie1.xml", 0);

if (rbEmployee.Checked)

{

FormReport frm = new FormReport();

frm.fileName = "ReportRaspisanieFIO.frx";

frm.formTitle = "Расписание";

frm.Show();

}

else

{

FormReport frm = new FormReport();

frm.fileName = "ReportRaspisanieDep.frx";

frm.formTitle = "Расписание";

frm.Show();

}

}

catch { }

}

private void rbEmployee_CheckedChanged(object sender, EventArgs e)

{

setupCreateDocument();

}

private void rButt2_CheckedChanged(object sender, EventArgs e)

{

setupCreateDocument();

}

public void GetDataByReport(ref List<Raspisanie> tempRaspisanie, int regim) // 0 - это по радио баттону 1- это по кнопке

{

string text = "";

tempRaspisanie.Clear();

if (regim == 0)

{

if (rbEmployee.Checked)

{

// тут собираем запрос если выбран переключатель сотрудник

text = "select * from Raspisanie where idEmployee = " + getIdByFIO(cBox2.Text);

db.Execute<Raspisanie>(ref setupProgr, text, ref tempRaspisanie);

}

if (rButt2.Checked)

{

//тут собираем запрос если выбран переключатель отделения

for (int i = 0; i < listEmployee.Count; i++)

{

if (listEmployee.ElementAt(i).employeeDepartment == cBox2.Text)

{

text = "select * from Raspisanie where idEmployee = " + listEmployee.ElementAt(i).Id;

db.Execute<Raspisanie>(ref setupProgr, text, ref tempRaspisanie);

}

}

}

}

if (regim == 1)

{

for (int i = 0; i < listEmployee.Count; i++)

{

text = "select * from Raspisanie where idEmployee = " + listEmployee.ElementAt(i).Id;

db.Execute<Raspisanie>(ref setupProgr, text, ref tempRaspisanie);

}

}

}

private string GetNameCode(int codeId)

{

for (int i = 0; i < listEmployee.Count; i++)

if (listEmployee.ElementAt(i).Id == codeId) return listEmployee.ElementAt(i).employeeSuName + " " + listEmployee.ElementAt(i).employeeName + " " + listEmployee.ElementAt(i).employeeSecondName;

return "";

}

private void setupRasrisanieReport(string fileNameReport, int z)

{

List<Raspisanie> tempRaspisanie = new List<Raspisanie>();

tempRaspisanie.Clear();

GetDataByReport(ref tempRaspisanie, z);

string depName = "";

if (rButt2.Checked) depName = cBox2.Text; //если выбрано кнопка отделения,то ключевое слово депнейм равно комбо2

else

{

for (int i = 0; i < listEmployee.Count; i++) //иначе мы проходим по циклу Листа Сотрудников,заодно определяя их количество

if (listEmployee.ElementAt(i).Id == getIdByFIO(cBox2.Text)) { depName = listEmployee.ElementAt(i).employeeDepartment; break; } //и если находим нам нужный елемент,то преравыем цикл

}

Dictionary<int, ClassRaspisanieReport> dictionaryRaspisanie = new Dictionary<int, ClassRaspisanieReport>(); // Создаем словарь для списка,который создаст упорядоченную таблицу расписания

List<ClassRaspisanieReport> listRaspisanieReport = new List<ClassRaspisanieReport>(); // создадим новый список для временного использования

listRaspisanieReport.Clear(); //Очистим лист чтобы не было накладки при следующем запросе

for (int i = 0; i < tempRaspisanie.Count; i++) //Теперь проходим по временному списку

{

ClassRaspisanieReport reportResult = new ClassRaspisanieReport(); // Здесь проходит процес создания отчет для вывода на печать

try { dictionaryRaspisanie.Add(tempRaspisanie.ElementAt(i).idEmployee, reportResult); }

catch { }

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].dapartamentName = depName; // расписания,которое находится уже упорядоченное,и из него можно получиться название департамента

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].employeeFIO = GetNameCode(tempRaspisanie.ElementAt(i).idEmployee);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 1) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].monday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 1) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].monday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 2) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].tuesday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 2) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].tuesday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 3) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].wendesday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 3) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].wednesday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 4) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].thousday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 4) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].thousday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 5) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].friday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 5) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].friday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 6) && (tempRaspisanie.ElementAt(i).numberSmenu == 1))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].saturday1 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

if ((tempRaspisanie.ElementAt(i).numberWeekDay == 6) && (tempRaspisanie.ElementAt(i).numberSmenu == 2))

dictionaryRaspisanie[tempRaspisanie.ElementAt(i).idEmployee].saturday2 = Convert.ToString(tempRaspisanie.ElementAt(i).numberRoom);

}

foreach (int x in dictionaryRaspisanie.Keys)

listRaspisanieReport.Add(dictionaryRaspisanie[x]);

ClassSerialiaze.SerialiazeToXml<List<ClassRaspisanieReport>>(ref listRaspisanieReport, fileNameReport);

}

# endregion

private void but_Click(object sender, EventArgs e)

{

setupRasrisanieReport("reportRaspisanie1.xml", 1);

FormReport frm = new FormReport();

frm.fileName = "ReportRaspisanieDep.frx";

frm.formTitle = "Расписание";

frm.Show();

}

private void button4_Click(object sender, EventArgs e)

{

int numberDay = 0;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Monday) numberDay = 1;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Tuesday) numberDay = 2;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Wednesday) numberDay = 3;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Thursday) numberDay = 4;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Friday) numberDay = 5;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Saturday) numberDay = 6;

if (dateTimePicker1.Value.DayOfWeek == DayOfWeek.Sunday) numberDay = 7;

List<Raspisanie> Raspis = new List<Raspisanie>();

string textqueery = "select * from Raspisanie where numberWeekDay = " + Convert.ToString(numberDay);

db.Execute<Raspisanie>(ref setupProgr, textqueery, ref Raspis); // в списке Raspis находиться расписание всех сотрудников на весь день

Dictionary<int, ClassRaspisanieReport> dictionaryRaspisanie = new Dictionary<int, ClassRaspisanieReport>();

List<ClassRaspisanieReport> listRaspisanieReport = new List<ClassRaspisanieReport>(); // создадим новый список для временного использования

listRaspisanieReport.Clear(); //Очистим лист чтобы не было накладки при следующем запросе

for (int i = 0; i < Raspis.Count; i++) //Теперь проходим по временному списку

{

ClassRaspisanieReport reportResult = new ClassRaspisanieReport(); // Здесь проходит процес создания отчет для вывода на печать

try { dictionaryRaspisanie.Add(Raspis.ElementAt(i).idEmployee, reportResult); }

catch { }

//dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].dapartamentName = depName; // расписания,которое находится уже упорядоченное,и из него можно получиться название департамента

dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].employeeFIO = GetNameCode(Raspis.ElementAt(i).idEmployee);

for (int j = 0; j < listEmployee.Count; j++) //проходим по циклу Листа Сотрудников,определенного количества значений

if (listEmployee.ElementAt(j).Id == getIdByFIO(dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].employeeFIO)) { dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].dapartamentName = listEmployee.ElementAt(j).employeeDepartment; break; }

dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].currentDate = dateTimePicker1.Value.ToShortDateString();

if (Raspis.ElementAt(i).numberSmenu == 1) dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].monday1 = Convert.ToString(Raspis.ElementAt(i).numberRoom);

if (Raspis.ElementAt(i).numberSmenu == 2) dictionaryRaspisanie[Raspis.ElementAt(i).idEmployee].monday2 = Convert.ToString(Raspis.ElementAt(i).numberRoom);

}

DeleteDateEmpl(ref dictionaryRaspisanie);

foreach (int x in dictionaryRaspisanie.Keys)

{

listRaspisanieReport.Add(dictionaryRaspisanie[x]);

}

ClassSerialiaze.SerialiazeToXml<List<ClassRaspisanieReport>>(ref listRaspisanieReport, "DateOneDay.xml");

FormReport frm = new FormReport();

frm.fileName = "RaspisOneDay.frx";

frm.formTitle = "Расписание";

frm.Show();

}

// функция удаления сотрудников которые не работают в этот день

private void DeleteDateEmpl(ref Dictionary<int, ClassRaspisanieReport> templ)

{

List<int> key = new List<int>();

key.Clear();

foreach (int x in templ.Keys)

if (((templ[x].monday1 == "") || (templ[x].monday1 == "0")) && ((templ[x].monday2 == "") || (templ[x].monday2 == "0"))) key.Add(x);

for (int i = 0; i < key.Count; i++)

templ.Remove(key.ElementAt(i));

}

private void cbDep_SelectedIndexChanged(object sender, EventArgs e)

{

}

}

public class ClassRaspisanieReport

{

[XmlAttribute]

public string dapartamentName = "";

[XmlAttribute]

public string employeeFIO = "";

[XmlAttribute]

public string monday1 = "";

[XmlAttribute]

public string monday2 = "";

[XmlAttribute]

public string tuesday1 = "";

[XmlAttribute]

public string tuesday2 = "";

[XmlAttribute]

public string wendesday1 = "";

[XmlAttribute]

public string wednesday2 = "";

[XmlAttribute]

public string thousday1 = "";

[XmlAttribute]

public string thousday2 = "";

[XmlAttribute]

public string friday1 = "";

[XmlAttribute]

public string friday2 = "";

[XmlAttribute]

public string saturday1 = "";

[XmlAttribute]

public string saturday2 = "";

[XmlAttribute]

public string currentDate = "";

}

}

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.Xml.Serialization;

//

// не решён вопрос с отображение телефона и места работы, скорее всего нет данного поля при первичной загрузке и нет разбора в конструкторе

// реализовать отчёты

// реализовать документы по выбору для печати

// не реализовано редактирование и удаление

//

namespace Registratura

{

public partial class Patient : Form

{

public Patient(RegistratureMain _frm)

{

InitializeComponent();

frm = _frm;

}

RegistratureMain frm;

public ClassSetupProgram setupProgram = new ClassSetupProgram();

public ClassDataBase db = new ClassDataBase();

public List<Patients> listPatients = new List<Patients>(); //хранение списка всех пациентов

private bool DecectCorrect()

{

lbStatLine.Text = "";

if (Fam1.Text == "")

{

lbStatLine.Text = "Поле Фамилия обязательно к заполнению";

return false;

}

if (Nam2.Text == "")

{

lbStatLine.Text = "Поле Имя обязательно к заполнению";

return false;

}

if (Otch2.Text == "")

{

lbStatLine.Text = "Поле Отчество обязательно к заполнению";

return false;

}

if (dTPicr1.Text == "")

{

lbStatLine.Text = "Укажите Дату рождения";

return false;

}

if (KonTel2.Text == "")

{

lbStatLine.Text = "Укажите Кон. Телефон";

return false;

}

if (AdrPro2.Text == "")

{

lbStatLine.Text = "Укажите Адрес";

return false;

}

if (cbFLGResult.Text == "")

{

lbStatLine.Text = "Укажите результат последней флюорографии";

return false;

}

if ((chbAllergo.Checked) && (tbAlergo.Text == ""))

{

lbStatLine.Text = "Укажите препараты на которые была ранее выявлена аллергия";

return false;

}

if ((chbOperation.Checked) && (tbOperation.Text == ""))

{

lbStatLine.Text = "Укажите перенесённые ранее операции";

return false;

}

if ((chbInfection.Checked) && (tbInfection.Text == ""))

{

lbStatLine.Text = "Укажите перенесённые ранее инфекционные заболевания";

return false;

}

return true;

}

#region отображение данных

private void showDataToDGV(ref List<Patients> currentListPacient)

{

dGVpat.Rows.Clear();

if (currentListPacient.Count > 0)

{

for (int i = 0; i < currentListPacient.Count; i++)

dGVpat.Rows.Add(Convert.ToString(currentListPacient.ElementAt(i).Id),

currentListPacient.ElementAt(i).pacientSuName,

currentListPacient.ElementAt(i).pacientName,

currentListPacient.ElementAt(i).pacientSecondName,

Convert.ToString(currentListPacient.ElementAt(i).pacientBDate),

currentListPacient.ElementAt(i).pacientWork);

}

}

public void updateData(List<Patients> _listPatients)

{

List<Patients> templ = new List<Patients>();

for (int i = 0; i < _listPatients.Count; i++) templ.Add(_listPatients.ElementAt(i));

listPatients.Clear();

listPatients = templ;

showDataToDGV( ref listPatients);

}

#endregion

private void Patient_Load(object sender, EventArgs e)

{

listPatients = frm.listPatients;

showDataToDGV(ref listPatients);

}

#region Запись данных при регистрации нового пациента

//1. записать данные в таблицу Pacient

private void insertDataPacientToDB()

{

string sqlText = "insert into Pacient (pacientSuName, pacientName, pacientSecondName, pacientBDate, pacientDateReg, pacientAddress, pacientWork, pacientPhone) values (\"" +

Fam1.Text + "\", \"" + Nam2.Text + "\", \"" + Otch2.Text + "\", \"" +

dTPicr1.Value.Date.ToShortDateString() + "\", \"" + DateTime.Now.Date.ToShortDateString() +

"\", \"" + AdrPro2.Text + "\", \"" + tbWork.Text + "\", \"" +

KonTel2.Text + "\")";

int n = db.ExecuteNonQuery(ref setupProgram, sqlText, 0);

}

private void updateDataToPacient()

{

string quvery1 = "update Pacient set pacientAddress = \"" + AdrPro2.Text + "\", pacientPhone = \""

+ KonTel2.Text + "\", pacientWork = \"" + tbWork.Text + "\" where id = " + tbNumberCard.Text;

string quvery2 = "update InfoPacient set infoAlergoya = \""+ tbAlergo.Text + "\", infoDateFLG = \"" +

dtpLastFLG.Value.ToShortDateString() + "\", infoResultFLG = \"" + cbFLGResult.Text +

"\", infoInfection = \"" + tbInfection.Text + "\", infoOperacion = \"" + tbOperation.Text + "\" where idPacient = " + tbNumberCard.Text;

db.ExecuteNonQuery(ref setupProgram, quvery1, 0);

int n = 0;

try

{

n = db.ExecuteNonQuery(ref setupProgram, quvery2, 0);

}

catch { }

if(n==0)

{

InsertDataAboutPacientInfo(Convert.ToInt32(tbNumberCard.Text));

}

}

private void button1_Click(object sender, EventArgs e)

{

if (DecectCorrect())

{

if (tbNumberCard.Text == "")

{

insertDataPacientToDB();

int id = GetLastIdPacient();

if (InsertDataAboutPacientInfo(id) > 0)

{

addPacientToList(id);

showDataToDGV(ref listPatients);

}

clearInterface();

}

else

{

updateDataToPacient();

listPatients.Clear();

string commandText2 = "select id, pacientSuName, pacientName, pacientSecondName, pacientBDate, pacientDateReg, pacientAddress, pacientWork, pacientPhone from Pacient order by id";

db.Execute<Patients>(ref setupProgram, commandText2, ref listPatients);

ClearForm();

showDataToDGV(ref listPatients);

}

}

}

//2. получить id записанного пациента из таблицы Pacient

private int GetLastIdPacient()

{

int result = 0;

string sqlText = "Select max(Id) from Pacient";

result = db.ExecuteItog(ref setupProgram, sqlText);

return result;

}

//3. если предыдущая запись выполнена корректно(id получен), то записать данные в таблицу InfoPacient

private int InsertDataAboutPacientInfo( int idPacient)

{

string gepatite = "-";

if(chbGeppatite.Checked) gepatite = "+";

string sqlText = "insert into InfoPacient (idPacient, infoAlergoya, infoOperacion, infoInfection, infoGepatite, infoAmbulance, infoDateFLG, infoResultFLG) values(" +

Convert.ToString(idPacient) + ", \"" + tbAlergo.Text + "\", \"" + tbOperation.Text + "\", \"" + tbInfection.Text +

"\", \"" + gepatite + "\", \"\", \"" + dtpLastFLG.Value.ToShortDateString() + "\", \"" + cbFLGResult.Text + "\")";

return db.ExecuteNonQuery(ref setupProgram, sqlText, 0);

}

//4. записать данные в список пациентов и обновить датагрид

private void addPacientToList(int idPacient)

{

Patients temp = new Patients();

temp.Id = idPacient;

temp.pacientSuName = Fam1.Text;

temp.pacientName = Nam2.Text;

temp.pacientSecondName = Otch2.Text;

temp.pacientAddress = AdrPro2.Text;

temp.pacientWork = tbWork.Text;

temp.pacientBDate = dTPicr1.Value.Date;

temp.pacientDateReg = DateTime.Now.Date;

listPatients.Add(temp);

}

private void clearInterface()

{

tbNumberCard.Text = "";

Fam1.Text = "";

Nam2.Text = "";

Otch2.Text = "";

dTPicr1.Value = DateTime.Now;

KonTel2.Text = "";

AdrPro2.Text = "";

tbWork.Text = "";

dtpLastFLG.Value = DateTime.Now;

cbFLGResult.Text = Convert.ToString(cbFLGResult.Items[0]);

chbAllergo.Checked = false;

tbAlergo.Text = "";

chbGeppatite.Checked = false;

chbOperation.Checked = false;

tbOperation.Text = "";

chbInfection.Checked = false;

tbInfection.Text = "";

}

#endregion

#region Поиск данных по пациентам

public List<Patients> tempListPatients = new List<Patients>(); //информация о списках пациентов,которые храняться временно

public List<InfoPatient> tempListInfoPatient = new List<InfoPatient>();

private void ClearForm()

{

tbNumberCard.Text = "";

tbAlergo.Text = "";

tbInfection.Text = "";

tbOperation.Text = "";

tbWork.Text = "";

Fam1.Text = "";

Nam2.Text = "";

Otch2.Text = "";

KonTel2.Text = "";

AdrPro2.Text = "";

cbFLGResult.Text = "";

dTPicr1.Value = DateTime.Now;

dtpLastFLG.Value = DateTime.Now;

chbAllergo.Checked = false;

chbGeppatite.Checked = false;

chbInfection.Checked = false;

chbOperation.Checked = false;

}

private void button3_Click(object sender, EventArgs e)

{

lbStatLine.Text = "";

string temp = tbNumberCard.Text;

ClearForm();

tbNumberCard.Text = temp;

if (tbNumberCard.Text != "") { searchNumberCard(); }

else if ((Fam1.Text != "") && (Nam2.Text != "") && (Otch2.Text != "")) { searchPacientFIO(); }

else { lbStatLine.Text = "Не верно заданы критерии поиска."; }

showDataToDGV(ref tempListPatients);

outputResultSearch();

}

// Поиск по номеру карты

private void searchNumberCard()

{

tempListPatients.Clear();

tempListInfoPatient.Clear();

string sqlText = "select id, pacientSuName, pacientName, pacientSecondName, pacientBDate, pacientDateReg, pacientAddress, pacientWork, pacientPhone from Pacient where id = " + Convert.ToString(tbNumberCard.Text);

db.Execute<Patients>(ref setupProgram, sqlText, ref tempListPatients);

sqlText = "select Id, idPacient, infoAlergoya, infoOperacion, infoInfection, infoGepatite, infoAmbulance, infoDateFLG, infoResultFLG from InfoPacient where idPacient= " + Convert.ToString(tbNumberCard.Text);

db.Execute<InfoPatient>(ref setupProgram, sqlText, ref tempListInfoPatient);

}

private void searchPacientFIO()

{

tempListPatients.Clear();

tempListInfoPatient.Clear();

string sqlText = "select id, pacientSuName, pacientName, pacientSecondName, pacientBDate, pacientDateReg, pacientAddress, pacientWork, pacientPhone from Pacient where pacientSuName = \"" +

Fam1.Text + "\" and pacientName =\"" + Nam2.Text + "\" and pacientSecondName =\"" + Otch2.Text + "\"";

db.Execute<Patients>(ref setupProgram, sqlText, ref tempListPatients);

if (tempListPatients.Count > 0)

{

sqlText = "select Id, idPacient, infoAlergoya, infoOperacion, infoInfection, infoGepatite, infoAmbulance, infoDateFLG, infoResultFLG from InfoPacient where idPacient= " + Convert.ToString(tempListPatients.ElementAt(0).Id);

db.Execute<InfoPatient>(ref setupProgram, sqlText, ref tempListInfoPatient);

}

}

private void outputResultSearch()

{

if(tempListPatients.Count > 0)

{

tbNumberCard.Text = Convert.ToString(tempListPatients.ElementAt(0).Id);

Fam1.Text = tempListPatients.ElementAt(0).pacientSuName;

Nam2.Text = tempListPatients.ElementAt(0).pacientName;

Otch2.Text = tempListPatients.ElementAt(0).pacientSecondName;

dTPicr1.Value = tempListPatients.ElementAt(0).pacientBDate;

KonTel2.Text = tempListPatients.ElementAt(0).pacientPhone;

AdrPro2.Text = tempListPatients.ElementAt(0).pacientAddress;

tbWork.Text = tempListPatients.ElementAt(0).pacientWork;

}

if (tempListInfoPatient.Count > 0)

{

if (tempListInfoPatient.ElementAt(0).infoAlergoya != "") { chbAllergo.Checked = true; tbAlergo.Text = tempListInfoPatient.ElementAt(0).infoAlergoya; }

if (tempListInfoPatient.ElementAt(0).infoDateFLG != "") { dtpLastFLG.Value = Convert.ToDateTime(tempListInfoPatient.ElementAt(0).infoDateFLG); }

if (tempListInfoPatient.ElementAt(0).infoGepatite == "+") { chbGeppatite.Checked = true; }

if (tempListInfoPatient.ElementAt(0).infoInfection != "") { chbInfection.Checked = true; tbInfection.Text = tempListInfoPatient.ElementAt(0).infoInfection; }

if (tempListInfoPatient.ElementAt(0).infoOperacion != "") { chbOperation.Checked = true; tbOperation.Text = tempListInfoPatient.ElementAt(0).infoOperacion; }

if (tempListInfoPatient.ElementAt(0).infoResultFLG != "") { cbFLGResult.Text = tempListInfoPatient.ElementAt(0).infoResultFLG; }

}

}

#endregion

private void btnAllList_Click(object sender, EventArgs e)

{

ClearForm();

showDataToDGV(ref listPatients);

}

private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)

{

// удаление пациента из базы и информации о нём.

lbStatLine.Text = "";

if (dGVpat.SelectedRows.Count == 1)

{

string val = dGVpat.SelectedRows[0].Cells[0].Value.ToString();

string TextQeryu = "delete from Pacient where Id = " + val;

int n = db.ExecuteNonQuery(ref setupProgram, TextQeryu, 0);

if (n == 1)

{

lbStatLine.Text = "Данные удалены успешно";

int index = -1;

for (int i = 0; i < listPatients.Count; i++)

{

if (listPatients.ElementAt(i).Id == Convert.ToInt32( val))

{

index = i; break;

}

}

if (index >=0 ) listPatients.RemoveAt(index) ;

}

showDataToDGV(ref listPatients);

}

else

{

lbStatLine.Text = "Для удаления записи необходимо выделить строку";

}

}

private void Form086()

{

FormReport frm = new FormReport();

frm.fileName = "Form086.frx";

frm.formTitle = "Форма № 086/у";

frm.Show();

}

private void bTformY_Click(object sender, EventArgs e)

{

ClassForm086Report resultPacient = new ClassForm086Report();

if (Fam1.Text.Trim() != "")

{

resultPacient.pacientSuName = Fam1.Text;

resultPacient.pacientName = Nam2.Text;

resultPacient.pacientSecondName = Otch2.Text;

resultPacient.pacientWork = tbWork.Text;

resultPacient.pacientAddress = AdrPro2.Text;

resultPacient.infoAlergoya = tbAlergo.Text;

resultPacient.infoOperacion = tbOperation.Text;

resultPacient.infoInfection = tbInfection.Text;

resultPacient.infoGepatite = chbGeppatite.Text;

resultPacient.infoDateFLG = dtpLastFLG.Text;

resultPacient.infoResultFLG = cbFLGResult.Text;

ClassSerialiaze.SerialiazeToXml<ClassForm086Report>(ref resultPacient, "PacientInfo.xml");

Form086();

}

else { MessageBox.Show("Ошибка заполнения данных, выполните поиск пациента!!!"); }

}

public class ClassForm086Report

{

[XmlAttribute]

public string pacientSuName = "";

[XmlAttribute]

public string pacientName = "";

[XmlAttribute]

public string pacientSecondName = "";

[XmlAttribute]

public DateTime pacientBDate = DateTime.Now;

[XmlAttribute]

public DateTime pacientDateReg = DateTime.Now;

[XmlAttribute]

public string pacientAddress = "";

[XmlAttribute]

public string pacientWork = "";

[XmlAttribute]

public string pacientPhone = "";

[XmlAttribute]

public string infoAlergoya = "";

[XmlAttribute]

public string infoOperacion = "";

[XmlAttribute]

public string infoInfection = "";

[XmlAttribute]

public string infoGepatite = "";

[XmlAttribute]

public string infoAmbulance = "";

[XmlAttribute]

public string infoDateFLG = "";

[XmlAttribute]

public string infoResultFLG = "";

[XmlAttribute]

public string employeeSuName = "";

[XmlAttribute]

public string employeeName = "";

[XmlAttribute]

public string employeeSecondName = "";

[XmlAttribute]

public string employeeSpecial = "";

[XmlAttribute]

public string employeeDepartment = "";

[XmlAttribute]

public string employeeKategor = "";

[XmlAttribute]

public string employeeDolgnost = "";

}

private void bTmedCard_Click(object sender, EventArgs e)

{

// мед карта

ClassForm086Report resultPacient = new ClassForm086Report();

if (Fam1.Text.Trim() != "")

{

resultPacient.pacientSuName = Fam1.Text;

resultPacient.pacientName = Nam2.Text;

resultPacient.pacientSecondName = Otch2.Text;

resultPacient.pacientWork = tbWork.Text;

resultPacient.pacientAddress = AdrPro2.Text;

resultPacient.pacientBDate = dTPicr1.Value.Date;

resultPacient.infoAlergoya = tbAlergo.Text;

resultPacient.infoOperacion = tbOperation.Text;

resultPacient.infoInfection = tbInfection.Text;

resultPacient.infoGepatite = chbGeppatite.Text;

resultPacient.infoDateFLG = dtpLastFLG.Value.ToShortDateString();

resultPacient.infoResultFLG = cbFLGResult.Text;

ClassSerialiaze.SerialiazeToXml<ClassForm086Report>(ref resultPacient, "PacientInfo.xml");

FormReport frm = new FormReport();

frm.fileName = "medCard.frx";

frm.formTitle = "Медицинская карта амбулаторного больного";

frm.Show();

}

else { MessageBox.Show("Ошибка заполнения данных, выполните поиск пациента!!!"); }

}

}

}

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

namespace Registratura

{

public partial class Employees : Form

{

public Employees(RegistratureMain _frmReg)

{

InitializeComponent();

frmReg = _frmReg;

}

RegistratureMain frmReg;

public List<Employee> listEmpl = new List<Employee>();

public List<Depatment> listDep = new List<Depatment>();

ClassDataBase db = new ClassDataBase();

ClassSetupProgram setupProgr = new ClassSetupProgram();

private void Load_comboBoxDep()

{

if (listDep.Count > 0)

{

for (int i = 0; i < listDep.Count; i++)

{

cbZavDep.Items.Add(listDep.ElementAt(i).departmentName);

}

}

}

private bool DecectCorrect()

{

lbStatusLine.Text = "";

if (tbFhazerName.Text == "")

{

lbStatusLine.Text = "Поле Отчество обязательно к заполнению";

return false;

}

if (tbFam.Text == "")

{

lbStatusLine.Text = "Поле Фамилия обязательно к заполнению";

return false;

}

if (tbName.Text == "")

{

lbStatusLine.Text = "Поле Имя обязательно к заполнению";

return false;

}

if (cbZavDep.Text == "")

{

lbStatusLine.Text = "Укажите отделение";

return false;

}

if (cbSpecial.Text == "")

{

lbStatusLine.Text = "Укажите Специальность";

return false;

}

if (cbKat.Text == "")

{

lbStatusLine.Text = "Укажите Категорию";

return false;

}

return true;

}

private void showDataToDGV(ref List<Employee> temp)

{

dGV.Rows.Clear();

if (temp.Count > 0)

{

for (int i = 0; i < temp.Count; i++)

dGV.Rows.Add(temp.ElementAt(i).employeeSuName + " " + temp.ElementAt(i).employeeName + " " + temp.ElementAt(i).employeeSecondName, temp.ElementAt(i).employeeSpecial,

temp.ElementAt(i).employeeDepartment, temp.ElementAt(i).employeeKategor, temp.ElementAt(i).employeeDolgnost, Convert.ToString(temp.ElementAt(i).Id));

}

}

private void Employees_Load(object sender, EventArgs e)

{

if (frmReg.listEmployee.Count == 0)

{

string text = "select * from Employee";

listEmpl.Clear();

frmReg.listEmployee.Clear();

db.Execute<Employee>(ref setupProgr, text, ref frmReg.listEmployee);

db.Execute<Employee>(ref setupProgr, text, ref listEmpl);

}

else listEmpl = frmReg.listEmployee;

listDep = frmReg.listDepartament;

showDataToDGV(ref listEmpl);

Load_comboBoxDep();

}

private void writeDataToDb()

{

string zav = "";

if (chbZav.Checked) zav = "зав отделения";

string strQuvery = "insert into Employee (employeeSuName, employeeName, employeeSecondName, employeeSpecial, employeeDepartment, employeeKategor, employeeDolgnost, employeeDateReg) values (\"" +

tbFam.Text + "\", \"" + tbName.Text + "\", \"" + tbFhazerName.Text + "\", \"" + cbSpecial.Text + "\", \"" +

cbZavDep.Text + "\", \"" + cbKat.Text + "\", \"" + zav + "\", \"" + DateTime.Now.Date.ToString()+ "\")";

int n = db.ExecuteNonQuery(ref setupProgr, strQuvery, 0);

if (n > 0)

{

lbStatusLine.Text = "Данные сохранены успешно";

}

else lbStatusLine.Text = "Ошибка записи данных в базу";

}

Employee temp;

private void updateList()

{

temp = new Employee();

temp.Id = db.ExecuteItog(ref setupProgr, "select max(id) from Employee");

temp.employeeSuName = tbFam.Text;

temp.employeeName = tbName.Text;

temp.employeeSecondName = tbFhazerName.Text;

temp.employeeSpecial = cbSpecial.Text;

temp.employeeDepartment = cbZavDep.Text;

temp.employeeKategor = cbKat.Text;

if (chbZav.Checked) temp.employeeDolgnost = "зав отделения";

else temp.employeeDolgnost = "";

listEmpl.Add(temp);

}

private void clearFormInput()

{

tbFam.Text = "";

tbName.Text = "";

tbFhazerName.Text = "";

chbZav.Checked = false;

}

private void btnSave_Click(object sender, EventArgs e)

{

if (DecectCorrect())

{

// 1. Сохранить данные в базу

writeDataToDb();

// 2. Обновить списки

updateList();

// 3. Обновить таблицу

showDataToDGV(ref listEmpl);

//4. Очистить форму ввода

clearFormInput();

//5. Создать пустой бланк для расписания работы сотрудника

createBlancRaspisanieSotrudnika();

}

}

#region Создание бланка расписания для сотрудника

private void createBlancRaspisanieSotrudnika()

{

if(temp!=null)

{

for (int i = 1; i <= 6; i++)

{

string text = "insert into Raspisanie (idEmployee, numberWeekDay, numberSmenu) values (" + Convert.ToString(temp.Id) + ", " + Convert.ToString(i) + ", 1)";

db.ExecuteNonQuery(ref setupProgr, text, 0);

text = "insert into Raspisanie (idEmployee, numberWeekDay, numberSmenu) values (" + Convert.ToString(temp.Id) + ", " + Convert.ToString(i) + ", 2)";

db.ExecuteNonQuery(ref setupProgr, text, 0);

}

}

}

#endregion

private void удалитьЗаписьToolStripMenuItem_Click(object sender, EventArgs e)

{

lbStatusLine.Text = "";

if (dGV.SelectedRows.Count == 1)

{

string[] val = dGV.SelectedRows[0].Cells[0].Value.ToString().Split(' ');

string TextQeryu = "delete from Employee where employeeSuName = \"" + val[0] + "\" and employeeName = \"" + val[1] + "\" and employeeSecondName = \"" + val[2] + "\"";

int n = db.ExecuteNonQuery(ref setupProgr, TextQeryu, 0);

if (n == 1)

{

lbStatusLine.Text = "Данные удалены успешно";

int index = -1;

for (int i = 0; i < listEmpl.Count; i++)

{

if ((listEmpl.ElementAt(i).employeeSuName == val[0]) && (listEmpl.ElementAt(i).employeeName == val[1]) && (listEmpl.ElementAt(i).employeeSecondName == val[2]))

{

index = i; break;

}

}

if (index >=0 ) listEmpl.RemoveAt(index) ;

}

showDataToDGV(ref listEmpl);

}

else

{

lbStatusLine.Text = "Для удаления записи желательно выделить строку";

}

}

private void редактироватьДанныеToolStripMenuItem_Click(object sender, EventArgs e)

{

lbStatusLine.Text = "";

if (dGV.SelectedRows.Count == 1)

{

string[] val = dGV.SelectedRows[0].Cells[0].Value.ToString().Split(' ');

string TextQeryu = "update Employee set employeeSuName= \"" + tbFam.Text + "\" , employeeName= \"" + tbName.Text + "\", employeeSecondName= \"" + tbFhazerName.Text + "\", employeeSpecial= \"" + cbSpecial.Text + "\", employeeDepartment= \"" +

cbZavDep.Text + "\", employeeKategor= \"" + cbKat.Text + "\", employeeDateReg=\"" + DateTime.Now.Date.ToString();

int n = db.ExecuteNonQuery(ref setupProgr, TextQeryu, 0);

if (n == 1)

{

lbStatusLine.Text = "Данные редактированы успешно";

int index = -1;

for (int i = 0; i < listEmpl.Count; i++)

{

if ((listEmpl.ElementAt(i).employeeSuName == val[0]) && (listEmpl.ElementAt(i).employeeName == val[1]) && (listEmpl.ElementAt(i).employeeSecondName == val[2]))

{

index = i; break;

}

}

if (index >=0 ) listEmpl.RemoveAt(index) ;

}

showDataToDGV(ref listEmpl);

}

else

{

lbStatusLine.Text = "Для редактирования записи желательно выделить строку";

}

}

private void btnSearch_Click(object sender, EventArgs e)

{

string textQuvery = "select * from Employee ";

if (rbDep.Checked) textQuvery += " where employeeDepartment =\"" + tbSearch.Text + "\"";

if (rbSpecial.Checked) textQuvery += " where employeeSpecial =\"" + tbSearch.Text + "\"";

if (rbCategor.Checked) textQuvery += " where employeeKategor =\"" + tbSearch.Text + "\"";

if (rbFIO.Checked) textQuvery += " where employeeSuName =\"" + tbSearch.Text + "\"";

List<Employee> resultSearch = new List<Employee>();

db.Execute<Employee>(ref setupProgr, textQuvery, ref resultSearch);

showDataToDGV(ref resultSearch);

tbSearch.Text = "";

rbDep.Checked = false;

rbSpecial.Checked = false;

rbCategor.Checked = false;

rbFIO.Checked = false;

}

private void btnFullList_Click(object sender, EventArgs e)

{

showDataToDGV(ref listEmpl);

}

private void UpdateInfoToEmployee()

{

for (int i = 0; i < dGV.Rows.Count; i++)

{

string[] val = dGV[0, i].Value.ToString().Split(' ');

string textQuvery = "update Employee set employeeSuName = \"" + val[0] +

"\", employeeName = \"" + val[1] +

"\", employeeSecondName = \"" + val[2] +

"\", employeeSpecial = \"" + dGV[1, i].Value.ToString() +

"\", employeeDepartment = \"" + dGV[2, i].Value.ToString() +

"\", employeeKategor = \"" + dGV[3, i].Value.ToString() +

"\", employeeDolgnost = \"" + dGV[4, i].Value.ToString() +

"\" where Id = " + dGV[5, i].Value.ToString();

db.ExecuteNonQuery(ref setupProgr, textQuvery, 0);

}

listEmpl.Clear();

db.Execute<Employee>(ref setupProgr, "select * from Employee", ref listEmpl);

showDataToDGV(ref listEmpl);

}

private void button2_Click(object sender, EventArgs e)

{

//Сохранение редактирований информации по сотрудникам.

UpdateInfoToEmployee();

}

private void tbName_TextChanged(object sender, EventArgs e)

{

}

private void dGV_CellContentClick(object sender, DataGridViewCellEventArgs e)

{

}

private void button1_Click(object sender, EventArgs e)

{

}

Харківський патентно-комп’ютерний коледж

Відділення „Розробка програмного забезпечення”

Предметно-циклова комісія „Програмування”

___________«Інформаційна система «Відділ кадрів»»_______

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]