редактирование ящика
This commit is contained in:
Binary file not shown.
+13
-1
@@ -16,7 +16,19 @@ async def add_toolbox(reqDict=Depends(requestDict)):
|
||||
result = await ToolboxHandler.add(toolboxData, userId)
|
||||
if result:
|
||||
response["status"] = "ok"
|
||||
logger.info(response)
|
||||
return response
|
||||
|
||||
|
||||
@router.put("/", summary="Обновление ящика")
|
||||
async def update_toolbox(reqDict=Depends(requestDict)):
|
||||
toolboxId = reqDict.get("body").get("toolboxId")
|
||||
logger.info(f"Обновление ящика #{toolboxId}")
|
||||
response = {"status": "error"}
|
||||
userId = reqDict.get("body").get("userId")
|
||||
toolboxData = reqDict.get("body").get("editToolboxData")
|
||||
result = await ToolboxHandler.edit(toolboxId, **toolboxData, user_id=userId)
|
||||
if result:
|
||||
response["status"] = "ok"
|
||||
return response
|
||||
|
||||
|
||||
|
||||
+72
-10
@@ -463,7 +463,7 @@ function setupFilters(tabId, tools, categoriesMap) {
|
||||
}
|
||||
}
|
||||
|
||||
function addToolbox() {
|
||||
function addToolbox(editData = null) {
|
||||
// Проверяем, существует ли уже модальное окно
|
||||
let modal = document.getElementById('addToolboxModal');
|
||||
|
||||
@@ -482,7 +482,7 @@ function addToolbox() {
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title">Добавить новый склад</h5>
|
||||
<h5 class="modal-title" id="addToolboxModalLabel">Добавить новый склад</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
<form id="addToolboxForm" novalidate>
|
||||
@@ -505,7 +505,7 @@ function addToolbox() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<div class="mb-3" id="toolboxMonitoringContainer">
|
||||
<div class="form-check form-switch d-flex flex-column flex-md-row align-items-md-center justify-content-left"">
|
||||
<input class="form-check-input me-2" type="checkbox"
|
||||
role="switch" id="toolboxMonitoring">
|
||||
@@ -525,7 +525,7 @@ function addToolbox() {
|
||||
<button type="submit" class="btn btn-primary" id="submitToolboxBtn">
|
||||
<span class="spinner-border spinner-border-sm me-1"
|
||||
id="submitToolboxSpinner" style="display: none;"></span>
|
||||
Добавить склад
|
||||
<span id="submitToolboxText">Добавить склад</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@@ -533,8 +533,22 @@ function addToolbox() {
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Если редактирование
|
||||
if (editData) {
|
||||
modal.querySelector('#toolboxTitle').value = editData.title;
|
||||
modal.querySelector('#toolboxDescription').value = editData.description;
|
||||
modal.querySelector('#toolboxMonitoring').checked = editData.monitoring;
|
||||
modal.querySelector('#addToolboxModalLabel').textContent = 'Редактировать склад';
|
||||
modal.querySelector('#submitToolboxText').textContent = 'Сохранить';
|
||||
if (editData.owner_id) {
|
||||
modal.querySelector('#toolboxMonitoringContainer').classList.add('d-none');
|
||||
}
|
||||
}
|
||||
|
||||
// Добавляем модальное окно в DOM
|
||||
document.body.appendChild(modal);
|
||||
|
||||
|
||||
// Инициализация модального окна
|
||||
const bsModal = new bootstrap.Modal(modal);
|
||||
|
||||
@@ -623,39 +637,76 @@ function addToolbox() {
|
||||
|
||||
const userId = userData.id;
|
||||
|
||||
let editToolboxData = {}
|
||||
|
||||
if (editData) {
|
||||
Object.keys(toolboxData).forEach(key => {
|
||||
if (toolboxData[key] !== editData[key]) {
|
||||
editToolboxData[key] = toolboxData[key];
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Object.keys(editToolboxData).length === 0 && editData) {
|
||||
showInfo('Новые данные склада совпадают с текущими', 'warning');
|
||||
// Возвращаем кнопку в исходное состояние
|
||||
submitBtn.disabled = false;
|
||||
spinner.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Отправка данных (замените на ваш реальный endpoint)
|
||||
const response = await apiRequest("/toolbox/", { toolboxData, userId });
|
||||
// Отправка данных
|
||||
|
||||
let method = 'POST'
|
||||
let sendData = { toolboxData, userId }
|
||||
|
||||
if (editData) {
|
||||
method = 'PUT';
|
||||
const toolboxId = editData.id;
|
||||
sendData = { toolboxId, userId, editToolboxData };
|
||||
}
|
||||
|
||||
const response = await apiRequest("/toolbox/", sendData, method);
|
||||
|
||||
if (response.status !== 'ok') {
|
||||
if (!editData) {
|
||||
throw new Error('Ошибка при добавлении склада');
|
||||
} else {
|
||||
throw new Error('Ошибка при обновлении склада');
|
||||
}
|
||||
}
|
||||
|
||||
// Успешная отправка
|
||||
bsModal.hide();
|
||||
|
||||
// Показываем уведомление об успехе
|
||||
showInfo('Склад успешно добавлен', 'success');
|
||||
const successMessageText = editData ? 'Склад успешно обновлен' : 'Склад успешно добавлен';
|
||||
showInfo(successMessageText, 'success');
|
||||
|
||||
// Здесь можно добавить обновление списка складов
|
||||
await uploadTab('toolbox');
|
||||
|
||||
} catch (error) {
|
||||
console.error('Ошибка при добавлении склада:', error);
|
||||
console.error('Ошибка при добавлении (обновлении) склада:', error);
|
||||
|
||||
// Возвращаем кнопку в исходное состояние
|
||||
submitBtn.disabled = false;
|
||||
spinner.style.display = 'none';
|
||||
|
||||
// Показываем сообщение об ошибке
|
||||
showInfo('Ошибка при добавлении склада. Попробуйте еще раз.', 'error');
|
||||
const errorMessageText = editData ? 'Ошибка при обновлении склада' : 'Ошибка при добавлении склада';
|
||||
showInfo(errorMessageText, 'error');
|
||||
|
||||
// Можно добавить более детальное сообщение об ошибке
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'alert alert-danger mt-3';
|
||||
errorDiv.innerHTML = `
|
||||
errorDiv.innerHTML = !editData ? `
|
||||
<strong>Ошибка!</strong> Не удалось добавить склад.
|
||||
Проверьте соединение и попробуйте еще раз.
|
||||
` : `
|
||||
<strong>Ошибка!</strong> Не удалось обновить склад.
|
||||
Проверьте соединение и попробуйте еще раз.
|
||||
`;
|
||||
|
||||
const modalBody = modal.querySelector('.modal-body');
|
||||
@@ -855,6 +906,9 @@ async function loadToolboxContent(toolboxId) {
|
||||
<h5 class="mb-1">${toolboxInfo?.title || 'Склад'}</h5>
|
||||
<p class="text-muted mb-0 small">${toolboxInfo?.description || 'Описание отсутствует'}</p>
|
||||
</div>
|
||||
<button class="btn btn-sm btn-outline-danger" id="editToolbox">
|
||||
<i class="bi bi-pencil-square"></i> Редактировать
|
||||
</button>
|
||||
<span class="badge bg-secondary">${toolboxOwn}</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -910,6 +964,14 @@ async function loadToolboxContent(toolboxId) {
|
||||
</div>
|
||||
`;
|
||||
|
||||
if (accessData.manage_toolboxes) {
|
||||
contentContainer.querySelector('#editToolbox').addEventListener('click', () => {
|
||||
addToolbox(toolboxInfo);
|
||||
});
|
||||
} else {
|
||||
contentContainer.querySelector('#editToolbox').remove();
|
||||
}
|
||||
|
||||
|
||||
// Инициализация таблицы с данными
|
||||
await initializeToolboxTable(processedData, toolboxOwn, quantityMonitoring);
|
||||
|
||||
+23
-9
@@ -1,4 +1,4 @@
|
||||
from sqlalchemy import delete, update
|
||||
from sqlalchemy import delete
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
|
||||
from sqlalchemy.exc import InvalidRequestError
|
||||
@@ -17,6 +17,7 @@ Base = declarative_base()
|
||||
|
||||
class CRUD:
|
||||
|
||||
@staticmethod
|
||||
async def create(db_data, refresh: bool = False):
|
||||
try:
|
||||
is_lst = isinstance(db_data, list)
|
||||
@@ -43,9 +44,10 @@ class CRUD:
|
||||
logger.debug("Запись создана")
|
||||
return db_data if refresh else None
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка создания: {str(e)}", exc_debug=True)
|
||||
logger.error(f"Ошибка создания: {str(e)}", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def read(query, all: bool = False):
|
||||
try:
|
||||
async with SessionLocal() as db:
|
||||
@@ -58,9 +60,10 @@ class CRUD:
|
||||
else results.unique().scalars().first()
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка чтения: {str(e)}", exc_debug=True)
|
||||
logger.error(f"Ошибка чтения: {str(e)}", exc_info=True)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
async def delete(db_data) -> bool:
|
||||
def itemdebug(instance):
|
||||
from sqlalchemy import inspect
|
||||
@@ -98,18 +101,29 @@ class CRUD:
|
||||
return True
|
||||
except Exception as e:
|
||||
await db.rollback()
|
||||
logger.error(f"Ошибка удаления: {str(e)}", exc_debug=True)
|
||||
logger.error(f"Ошибка удаления: {str(e)}", exc_info=True)
|
||||
return False
|
||||
|
||||
async def update(db_data, id, **kwargs):
|
||||
@staticmethod
|
||||
async def update(model, id: int, **kwargs):
|
||||
from sqlalchemy import update as sa_update
|
||||
|
||||
async with SessionLocal() as db:
|
||||
try:
|
||||
query = update(db_data).where(db_data.id == id).values(**kwargs)
|
||||
item = await db.execute(query)
|
||||
query = (
|
||||
sa_update(model)
|
||||
.where(model.id == id)
|
||||
.values(**kwargs)
|
||||
.execution_options(synchronize_session="fetch")
|
||||
)
|
||||
await db.execute(query)
|
||||
await db.commit()
|
||||
|
||||
logger.debug("Запись обновлена")
|
||||
return await db.get(db_data, id)
|
||||
|
||||
return await db.get(model, id)
|
||||
|
||||
except Exception as e:
|
||||
await db.rollback()
|
||||
logger.error(f"Ошибка обновления: {str(e)}", exc_debug=True)
|
||||
logger.error(f"Ошибка обновления: {str(e)}", exc_info=True)
|
||||
return None
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -42,7 +42,7 @@ class ToolboxHandler:
|
||||
return {}
|
||||
try:
|
||||
user_id = kwargs.pop("user_id", None)
|
||||
editedToolbox = await toolbox.edit(**kwargs)
|
||||
editedToolbox = await toolbox.edit(toolboxId, **kwargs)
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка обновления тулбокса: {str(e)}")
|
||||
return {}
|
||||
|
||||
Binary file not shown.
@@ -27,5 +27,6 @@ class Toolbox(Base):
|
||||
async def save(self):
|
||||
return await CRUD.create(self, refresh=True)
|
||||
|
||||
@staticmethod
|
||||
async def edit(id: int, **kwargs):
|
||||
return await CRUD.update(Toolbox, id, **kwargs)
|
||||
|
||||
Reference in New Issue
Block a user