db.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import psycopg2
  2. from psycopg2.extras import DictCursor
  3. import os
  4. from dotenv import load_dotenv
  5. # Список организаций, сотрудников и корреспонденций
  6. organizations = []
  7. employees = []
  8. correspondencies = []
  9. # Подключение к базе данных
  10. conn = None
  11. # Инициализация подключения к базе данных
  12. def init_connection(username, password):
  13. global conn
  14. # Загрузка переменных окружения из .env файла
  15. load_dotenv()
  16. # Подключение к базе данных
  17. conn = psycopg2.connect(
  18. dbname=os.getenv("DB_NAME"),
  19. user=username,
  20. password=password,
  21. host=os.getenv("DB_HOST"),
  22. port=os.getenv("DB_PORT")
  23. )
  24. # Изменяем текущую схему
  25. with conn.cursor() as cur:
  26. cur.execute(f"SET search_path TO {os.getenv('DB_SCHEMA')};")
  27. # Получение всех организаций
  28. def get_all_organizations():
  29. global organizations
  30. with conn.cursor(cursor_factory=DictCursor) as cur:
  31. cur.execute("SELECT id, name, legal_form FROM organization;")
  32. organizations = cur.fetchall()
  33. # Получение всех сотрудников
  34. def get_all_employees():
  35. global employees
  36. with conn.cursor(cursor_factory=DictCursor) as cur:
  37. cur.execute("SELECT id, name, lastname, patronymic, organization_id FROM employee;")
  38. employees = cur.fetchall()
  39. # Получение всех корреспонденций
  40. def get_all_correspondencies():
  41. global correspondencies
  42. with conn.cursor(cursor_factory=DictCursor) as cur:
  43. cur.execute("SELECT id, document_type, document_number, receipt_date, execution_date, employee_id FROM correspondence;")
  44. correspondencies = cur.fetchall()
  45. # Добавление новой корреспонденции
  46. def add_correspondence(document_type, document_number, receipt_date, execution_date, employee_id):
  47. with conn.cursor() as cur:
  48. cur.execute(
  49. "INSERT INTO correspondence (document_type, document_number, receipt_date, execution_date, employee_id) VALUES (%s, %s, %s, %s, %s) RETURNING id;",
  50. (document_type, document_number, receipt_date, execution_date, employee_id)
  51. )
  52. new_id = cur.fetchone()[0]
  53. conn.commit()
  54. return new_id
  55. # Редактирование существующей корреспонденции
  56. def edit_correspondence(correspondence_id, document_type, document_number, receipt_date, execution_date, employee_id):
  57. with conn.cursor() as cur:
  58. cur.execute(
  59. "UPDATE correspondence SET document_type = %s, document_number = %s, receipt_date = %s, execution_date = %s, employee_id = %s WHERE id = %s;",
  60. (document_type, document_number, receipt_date, execution_date, employee_id, correspondence_id)
  61. )
  62. conn.commit()
  63. # Удаление корреспонденции
  64. def delete_correspondence(correspondence_id):
  65. with conn.cursor() as cur:
  66. cur.execute("DELETE FROM correspondence WHERE id = %s;", (correspondence_id,))
  67. conn.commit()
  68. # Подсчитать количество корреспонденций для выбранной
  69. def count_correspondencies_by_organization(organization_id):
  70. with conn.cursor() as cur:
  71. cur.execute(
  72. "SELECT COUNT(*) FROM correspondence c JOIN employee e ON c.employee_id = e.id WHERE e.organization_id = %s;",
  73. (organization_id,)
  74. )
  75. count = cur.fetchone()[0]
  76. return count