Files
Inf_Tec_Auto/document_collections.py
2024-12-19 09:03:07 -08:00

374 lines
13 KiB
Python

from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
QListWidget, QListWidgetItem, QInputDialog,
QMessageBox, QMenu, QDialog, QLabel, QLineEdit,
QTextEdit, QComboBox)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QAction, QColor, QIcon
from database import get_session
from models import Collection, Document
import json
class CollectionDialog(QDialog):
def __init__(self, collection=None, parent=None):
super().__init__(parent)
self.collection = collection
self.setup_ui()
def setup_ui(self):
self.setWindowTitle("Coleção")
layout = QVBoxLayout(self)
# Name
name_layout = QHBoxLayout()
name_layout.addWidget(QLabel("Nome:"))
self.name_edit = QLineEdit()
if self.collection:
self.name_edit.setText(self.collection.name)
name_layout.addWidget(self.name_edit)
layout.addLayout(name_layout)
# Description
layout.addWidget(QLabel("Descrição:"))
self.desc_edit = QTextEdit()
if self.collection:
self.desc_edit.setText(self.collection.description)
layout.addWidget(self.desc_edit)
# Color
color_layout = QHBoxLayout()
color_layout.addWidget(QLabel("Cor:"))
self.color_combo = QComboBox()
colors = ["#FF0000", "#00FF00", "#0000FF", "#FFFF00", "#FF00FF", "#00FFFF"]
for color in colors:
self.color_combo.addItem("")
self.color_combo.setItemData(
self.color_combo.count() - 1,
QColor(color),
Qt.BackgroundRole
)
if self.collection:
index = colors.index(self.collection.color)
self.color_combo.setCurrentIndex(index)
color_layout.addWidget(self.color_combo)
layout.addLayout(color_layout)
# Buttons
button_layout = QHBoxLayout()
cancel_btn = QPushButton("Cancelar")
cancel_btn.clicked.connect(self.reject)
button_layout.addWidget(cancel_btn)
save_btn = QPushButton("Salvar")
save_btn.clicked.connect(self.accept)
button_layout.addWidget(save_btn)
layout.addLayout(button_layout)
def get_data(self):
return {
'name': self.name_edit.text(),
'description': self.desc_edit.toPlainText(),
'color': self.color_combo.itemData(
self.color_combo.currentIndex(),
Qt.BackgroundRole
).name()
}
class CollectionsWidget(QWidget):
collection_selected = Signal(int) # collection_id
def __init__(self, parent=None):
super().__init__(parent)
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout(self)
# Toolbar
toolbar = QHBoxLayout()
new_btn = QPushButton("Nova Coleção")
new_btn.clicked.connect(self.add_collection)
toolbar.addWidget(new_btn)
toolbar.addStretch()
layout.addLayout(toolbar)
# Collections list
self.collections_list = QListWidget()
self.collections_list.itemClicked.connect(self.on_collection_clicked)
self.collections_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.collections_list.customContextMenuRequested.connect(
self.show_context_menu)
layout.addWidget(self.collections_list)
self.refresh_collections()
def refresh_collections(self):
self.collections_list.clear()
try:
session = get_session()
collections = session.query(Collection).all()
for collection in collections:
item = QListWidgetItem(collection.name)
item.setData(Qt.UserRole, collection.id)
item.setBackground(QColor(collection.color))
# Add document count
doc_count = len(collection.documents)
item.setToolTip(
f"{collection.description}\n\n"
f"Documentos: {doc_count}"
)
self.collections_list.addItem(item)
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao carregar coleções: {str(e)}")
def add_collection(self):
dialog = CollectionDialog(parent=self)
if dialog.exec_():
try:
session = get_session()
data = dialog.get_data()
collection = Collection(
name=data['name'],
description=data['description'],
color=data['color']
)
session.add(collection)
session.commit()
self.refresh_collections()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao criar coleção: {str(e)}")
finally:
session.close()
def edit_collection(self, collection_id):
try:
session = get_session()
collection = session.query(Collection).get(collection_id)
if collection:
dialog = CollectionDialog(collection, self)
if dialog.exec_():
data = dialog.get_data()
collection.name = data['name']
collection.description = data['description']
collection.color = data['color']
session.commit()
self.refresh_collections()
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao editar coleção: {str(e)}")
def delete_collection(self, collection_id):
reply = QMessageBox.question(
self,
"Confirmar Exclusão",
"Tem certeza que deseja excluir esta coleção?",
QMessageBox.Yes | QMessageBox.No
)
if reply == QMessageBox.Yes:
try:
session = get_session()
collection = session.query(Collection).get(collection_id)
if collection:
session.delete(collection)
session.commit()
self.refresh_collections()
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao excluir coleção: {str(e)}")
def on_collection_clicked(self, item):
collection_id = item.data(Qt.UserRole)
self.collection_selected.emit(collection_id)
def show_context_menu(self, position):
item = self.collections_list.itemAt(position)
if not item:
return
collection_id = item.data(Qt.UserRole)
menu = QMenu()
edit_action = menu.addAction("Editar")
edit_action.triggered.connect(
lambda: self.edit_collection(collection_id))
delete_action = menu.addAction("Excluir")
delete_action.triggered.connect(
lambda: self.delete_collection(collection_id))
menu.exec_(self.collections_list.mapToGlobal(position))
class CollectionDocuments(QWidget):
document_selected = Signal(int) # document_id
def __init__(self, parent=None):
super().__init__(parent)
self.current_collection = None
self.setup_ui()
def setup_ui(self):
layout = QVBoxLayout(self)
# Header
header_layout = QHBoxLayout()
self.collection_label = QLabel()
header_layout.addWidget(self.collection_label)
self.add_doc_btn = QPushButton("Adicionar Documento")
self.add_doc_btn.clicked.connect(self.add_document)
header_layout.addWidget(self.add_doc_btn)
layout.addLayout(header_layout)
# Documents list
self.documents_list = QListWidget()
self.documents_list.itemClicked.connect(self.on_document_clicked)
self.documents_list.setContextMenuPolicy(Qt.CustomContextMenu)
self.documents_list.customContextMenuRequested.connect(
self.show_context_menu)
layout.addWidget(self.documents_list)
def load_collection(self, collection_id):
self.current_collection = collection_id
self.refresh_documents()
def refresh_documents(self):
self.documents_list.clear()
if not self.current_collection:
return
try:
session = get_session()
collection = session.query(Collection).get(self.current_collection)
if collection:
self.collection_label.setText(
f"Coleção: {collection.name}"
)
for doc in collection.documents:
item = QListWidgetItem(doc.file_name)
item.setData(Qt.UserRole, doc.id)
item.setToolTip(
f"Marca: {doc.marca}\n"
f"Modelo: {doc.modelo}\n"
f"Ano: {doc.ano}"
)
self.documents_list.addItem(item)
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao carregar documentos: {str(e)}")
def add_document(self):
if not self.current_collection:
return
try:
session = get_session()
# Get documents not in collection
collection = session.query(Collection).get(self.current_collection)
all_docs = session.query(Document).all()
collection_doc_ids = [doc.id for doc in collection.documents]
available_docs = [doc for doc in all_docs
if doc.id not in collection_doc_ids]
if not available_docs:
QMessageBox.information(
self,
"Aviso",
"Não há documentos disponíveis para adicionar."
)
return
# Show document selection dialog
doc_names = [f"{doc.file_name} ({doc.marca} {doc.modelo})"
for doc in available_docs]
name, ok = QInputDialog.getItem(
self,
"Adicionar Documento",
"Selecione um documento:",
doc_names,
0,
False
)
if ok and name:
index = doc_names.index(name)
doc = available_docs[index]
collection.documents.append(doc)
session.commit()
self.refresh_documents()
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao adicionar documento: {str(e)}")
def remove_document(self, doc_id):
if not self.current_collection:
return
try:
session = get_session()
collection = session.query(Collection).get(self.current_collection)
document = session.query(Document).get(doc_id)
if collection and document:
collection.documents.remove(document)
session.commit()
self.refresh_documents()
session.close()
except Exception as e:
QMessageBox.critical(self, "Erro",
f"Erro ao remover documento: {str(e)}")
def on_document_clicked(self, item):
doc_id = item.data(Qt.UserRole)
self.document_selected.emit(doc_id)
def show_context_menu(self, position):
item = self.documents_list.itemAt(position)
if not item:
return
doc_id = item.data(Qt.UserRole)
menu = QMenu()
remove_action = menu.addAction("Remover da Coleção")
remove_action.triggered.connect(
lambda: self.remove_document(doc_id))
menu.exec_(self.documents_list.mapToGlobal(position))