items updating sys

This commit is contained in:
Sergey Yarkov 2019-12-26 20:45:23 +03:00
parent dea2740b3c
commit c082fee5c8
12 changed files with 120 additions and 26 deletions

View File

@ -7,6 +7,7 @@ function checkAuthenticated(req, res, next) {
}
module.exports = function(server, db) {
// роуты
server.get('/control-panel', checkAuthenticated, (req, res) => {
try {
res.render('admin/control-panel', {
@ -91,6 +92,8 @@ module.exports = function(server, db) {
}
});
// редактирование категорий
server.post('/control-panel/categories/create', checkAuthenticated, (req, res) => {
try {
const data = {
@ -147,4 +150,22 @@ module.exports = function(server, db) {
res.render('main/404');
}
});
// товары
server.post('/control-panel/items/update', checkAuthenticated, (req, res) => {
try {
const data = {
id: req.body.id,
title: req.body.title,
price: parseFloat(req.body.price),
description: req.body.description,
category: JSON.parse(req.body.category)
}
db.collection('items').updateOne({"_id": ObjectID(data.id)}, {$set: {title: data.title, price: data.price, description: data.description, category: data.category.title}});
res.redirect('/control-panel/items');
} catch (error) {
console.log(error);
res.render('main/404');
}
});
}

View File

@ -53,5 +53,7 @@ MongoClient.connect(db_config.url, {useNewUrlParser: true, useUnifiedTopology: t
});
})
.finally(() => {
server.listen(3000, () => console.log('Listen port 3000...'));
server.listen(3000, () => {
console.log('Listen port 3000...');
});
});

View File

@ -1,5 +1,5 @@
// Edit Category
#editCategory.c_modal-wrap.hide
#editCategoryModal.c_modal-wrap.hide
.container
.row
.c_modal
@ -32,5 +32,5 @@
input(type="text" name="format" required)
label Формат аккаунтов
.edit_success
button(type="submit" class="btn green waves-effect" style="width: 100%;height:50px") Редактировать
button(type="submit" class="btn orange waves-effect" style="width: 100%;height:50px") Редактировать
// Edit Category END

View File

@ -0,0 +1,31 @@
// Edit Item
#editItemModal.c_modal-wrap.hide
.container
.row
.c_modal
.c_modal-content.editItem
.modal-content
.modal-content__header(style="margin-bottom: 1rem;")
h4.small-title Редактирование товара
span#editItemClose.modal-close
i.material-icons close
.modal-content__form
form(action="/control-panel/items/update" method="POST")
.input-field
input.id(style="color: gray;" type="text" name="id" required readonly)
label ID товара
.input-field
input.title(id="title" type="text" name="title" required)
label(for="title") Новое название товара
.input-field
input.price(id="price" type="text" name="price" required)
label(for="price") Цена
.input-field
textarea.description(id="description" class="materialize-textarea" type="text" name="description")
label(for="description") Описание товара
.input-field
select.category(name="category")
label Категория
.edit_success
button(type="submit" class="btn orange waves-effect" style="width: 100%;height:50px") Редактировать
// Edit Category END

View File

@ -23,8 +23,8 @@ body.has-fixed-sidenav
.input-field.col.l6.s12
input(name="title" type="text" required)
label(for="title") Название категории
#icons.input-field.col.l6.s12
select(name="img" required)
.input-field.col.l6.s12
select#icons_select(name="img" required)
option(value="" disabled selected)
| Выберите иконку
label(for="img") Иконка
@ -51,16 +51,16 @@ body.has-fixed-sidenav
button(type="submit" class="btn right" style="margin-right: 10px;") Добавить
.category-edit
.row
#edit.input-field.col.s12
select
.input-field.col.s12
select#editCategory_select
option(value="" disabled selected)
| Выберите категорию для редактирования
label Редактирование категории
.icon-dell
.row
form(id="dellIcon" action="/control-panel/categories/dellicon" method="POST")
#dellIcon.input-field.col.s12
select(name="img")
.input-field.col.s12
select#dellIcon_select(name="img")
option(value="" disabled selected)
| Выберите иконку для удаления
label Удаление иконки
@ -69,8 +69,8 @@ body.has-fixed-sidenav
.category-delete
.row
form(id="dellCategory" action="/control-panel/categories/delete" method="POST")
#delete.input-field.col.s12
select(name="category")
.input-field.col.s12
select#delete_select(name="category")
option(value="" disabled selected)
| Выберите категорию для удаления
label Удаление категории

View File

@ -30,11 +30,11 @@ body.has-fixed-sidenav
th Редактирование
.divider
tbody
tbody#editItem
#loader.progress
.indeterminate
ul#pagination.pagination.center(data-page="1")
include ./assets/templates/modals/edit_item.pug
include ./assets/templates/footer.pug
include ./assets/scripts.pug

View File

@ -9,13 +9,13 @@ export class CategoriesComponent extends Component {
}
setElems() {
// обозначим все селекты для рендера в них наши категории и иконки в дальнейшем
this.$editSelect = this.$el.querySelector('#edit select');
this.$dellSelect = this.$el.querySelector('#delete select');
this.$iconsSelect = this.$el.querySelector('#icons select');
this.$dellIconsSelect = this.$el.querySelector('#dellIcon select');
// селекты в которых рендерится контент
this.$editSelect = this.$el.querySelector('#editCategory_select'); // редактирование категории
this.$dellSelect = this.$el.querySelector('#delete_select'); // удаление категории
this.$iconsSelect = this.$el.querySelector('#icons_select'); // выбор иконки
this.$dellIconsSelect = this.$el.querySelector('#dellIcon_select'); // удаление иконки
// формы
// обработка форм
this.$dellIconFrom = this.$el.querySelector('#dellIcon'); // удаление иконки
this.$addForm = this.$el.querySelector('#addCategory'); // добавление категории
this.$dellForm = this.$el.querySelector('#dellCategory'); // удаление категории

View File

@ -8,18 +8,26 @@ export class Modal {
init() {
if (this.open) {
this.setElems();
this.open.addEventListener('click', this.show.bind(this));
this.close.addEventListener('click', this.hide.bind(this));
}
}
show() {
this.$el.classList.remove('hide');
document.body.style.overflowY = 'hidden';
show(e) {
if (e.target.id === this.open.id) {
this.$el.classList.remove('hide');
document.body.style.overflowY = 'hidden';
this.openHandler(e);
}
}
hide() {
this.$el.classList.add('hide');
document.body.style.overflowY = '';
}
openHandler() {}
setElems() {}
}

View File

@ -4,11 +4,13 @@ import { editCategoryModal } from "./modals/editCategory.modal.js";
import { ItemsComponent } from "./components/items.component.js";
import { LoaderComponent } from "./components/loader.component.js";
import { PaginationComponent } from "./components/pagination.component.js";
import { editItemModal } from "./modals/editItem.modal.js";
const loader = new LoaderComponent('loader');
const pagination = new PaginationComponent('pagination', {loader});
const categories = new CategoriesComponent('categories');
const items = new ItemsComponent('items', {pagination});
const editCategory = new editCategoryModal('editCategory', 'edit', 'editCategoryClose');
const editCategory = new editCategoryModal('editCategoryModal', 'editCategory_select', 'editCategoryClose');
const editItem = new editItemModal('editItemModal', 'editItem', 'editItemClose')
const materialize = new MaterializeConfig();
console.log('Control-Panel v1.0.0');

View File

@ -10,14 +10,13 @@ export class editCategoryModal extends Modal {
// перепишем метод для перевода ивента open в событие onchange
init() {
if (this.open) {
this.open.addEventListener('change', this.openHandler.bind(this));
this.open.addEventListener('change', this.show.bind(this));
this.close.addEventListener('click', this.hide.bind(this));
this.$el.querySelector('form').addEventListener('submit', this.updateCategory.bind(this));
}
}
async openHandler(e) {
this.show();
const data = JSON.parse(e.target.value);
this.$el.querySelector('form .id input').value = data.id;
this.$el.querySelector('form .originalTitle input').value = data.title[0].toUpperCase() + data.title.slice(1);

View File

@ -0,0 +1,31 @@
import { Modal } from "../core/modal";
import { apiService } from "../services/api.service";
import { renderCategories } from "../templates/categories.template";
export class editItemModal extends Modal {
constructor(id, open, close) {
super(id, open, close);
}
setElems() {
this.$id = this.$el.querySelector('.id');
this.$title = this.$el.querySelector('.title');
this.$price = this.$el.querySelector('.price');
this.$description = this.$el.querySelector('.description');
this.$category = this.$el.querySelector('.category');
}
async openHandler(e) {
const data = JSON.parse(e.target.parentNode.parentNode.dataset.info),
categories = await apiService.getCategories();
this.$category.innerHTML = `<option value='{"title": "${data.category}"}' selected>Оставить прежнюю</option>`;
this.$id.value = data.id;
this.$title.value = data.title;
this.$price.value = data.price;
this.$description.value = data.description;
this.$category.insertAdjacentHTML('beforeend', renderCategories(categories));
M.FormSelect.init(this.$category);
M.updateTextFields();
}
}

View File

@ -3,7 +3,7 @@ export function renderItems(items, categories) {
categories.forEach(category => {
items.forEach(item => {
if (item.category.toLowerCase() === category.title.toLowerCase()) html += `<tr><td><img src="../img/service-icons/${category.img}" alt="alt"></td><td>${item.title}</td><td>${item.category}</td><td>${new Date(item.date).toLocaleDateString()}</td><td>${item.count}</td><td>${item.price} ₽</td><td><button class="btn red">Удалить</button><button class="btn orange">Изменить</button></td></tr>`
if (item.category.toLowerCase() === category.title.toLowerCase()) html += `<tr data-info='{"id": "${item._id}", "title": "${item.title}", "category": "${item.category}", "price": "${item.price}", "description": "${item.description}"}'><td><img src="../img/service-icons/${category.img}" alt="alt"></td><td>${item.title}</td><td>${item.category}</td><td>${new Date(item.date).toLocaleDateString()}</td><td>${item.count}</td><td>${item.price} ₽</td><td><button class="btn red">Удалить</button><button id="editItem" class="btn orange">Изменить</button></td></tr>`
});
});
return html;