Готовая 3 лаба

This commit is contained in:
spacyboy 2023-12-06 20:23:44 +04:00
parent 94c04e0b85
commit d0af1c80a3
9 changed files with 113 additions and 106 deletions

File diff suppressed because one or more lines are too long

View File

@ -145,13 +145,16 @@
<label class="form-label" for="image">Изображение</label> <label class="form-label" for="image">Изображение</label>
<input id="image" type="file" name="image" class="form-control" accept="image/*" required> <input id="image" type="file" name="image" class="form-control" accept="image/*" required>
</div> </div>
<div class="mb-2 width_add_object">
<label for="item" class="form-label">Скидка</label>
<select id="discounts" class="form-select" name="selected" required>
</select>
</div>
</div> </div>
<div class="modal-footer"> <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
<button type="submit" class="btn btn-primary">Сохранить</button> <button type="submit" class="btn btn-primary">Сохранить</button>
</div> </div>
</div> </div>
</form> </form>
</div> </div>
@ -162,7 +165,6 @@
import validation from "./js/validation"; import validation from "./js/validation";
import {linesFormOnIndex} from "./js/lines"; import {linesFormOnIndex} from "./js/lines";
import {linesForm} from "./js/lines"; import {linesForm} from "./js/lines";
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
validation(); validation();
linesFormOnIndex(); linesFormOnIndex();
@ -170,16 +172,5 @@
}); });
</script> </script>
</body> </body>
</html> </html>

View File

@ -20,6 +20,7 @@ function resetValues() {
cntrls.itemsType.value = ""; cntrls.itemsType.value = "";
cntrls.price.value = parseFloat(0).toFixed(2); cntrls.price.value = parseFloat(0).toFixed(2);
cntrls.count.value = 0; cntrls.count.value = 0;
cntrls.discountsType.value = "";
cntrls.image.value = ""; cntrls.image.value = "";
cntrls.imagePreview.src = imagePlaceholder; cntrls.imagePreview.src = imagePlaceholder;
} }
@ -36,6 +37,8 @@ export function showUpdateModal(item) {
cntrls.itemsType.value = item.itemsId; cntrls.itemsType.value = item.itemsId;
cntrls.price.value = item.price; cntrls.price.value = item.price;
cntrls.count.value = item.count; cntrls.count.value = item.count;
cntrls.discountsType.value = item.discountsId;
// заполнение превью // заполнение превью
// Если пользователь выбрал изображение, то оно загружается // Если пользователь выбрал изображение, то оно загружается
// в тэг image с id image - preview // в тэг image с id image - preview

View File

@ -4,11 +4,12 @@
const serverUrl = "http://localhost:8081"; const serverUrl = "http://localhost:8081";
// функция возвращает объект нужной структуры для отправки на сервер // функция возвращает объект нужной структуры для отправки на сервер
function createLineObject(item, price, count, image) { function createLineObject(item, price, count, discounts, image) {
return { return {
itemsId: item, itemsId: item,
price: parseFloat(price).toFixed(2), price: parseFloat(price).toFixed(2),
count, count,
discountsId: discounts,
image, image,
}; };
} }
@ -21,10 +22,17 @@ export async function getAllItemTypes() {
} }
return response.json(); return response.json();
} }
export async function getAllDisountsTypes() {
const response = await fetch(`${serverUrl}/discounts`);
if (!response.ok) {
throw response.statusText;
}
return response.json();
}
// обращение к серверу для получения всех записей (get) // обращение к серверу для получения всех записей (get)
export async function getAllLines() { export async function getAllLines() {
const response = await fetch(`${serverUrl}/lines?_expand=items`); const response = await fetch(`${serverUrl}/lines?_expand=items&_expand=discounts`);
if (!response.ok) { if (!response.ok) {
throw response.statusText; throw response.statusText;
} }
@ -34,7 +42,7 @@ export async function getAllLines() {
// обращение к серверу для получения записи по первичному ключу (id) (get) // обращение к серверу для получения записи по первичному ключу (id) (get)
// id передается в качестве части пути URL get-запроса // id передается в качестве части пути URL get-запроса
export async function getLine(id) { export async function getLine(id) {
const response = await fetch(`${serverUrl}/lines/${id}?_expand=items`); const response = await fetch(`${serverUrl}/lines/${id}?_expand=items&_expand=discounts`);
if (!response.ok) { if (!response.ok) {
throw response.statusText; throw response.statusText;
} }
@ -43,8 +51,8 @@ export async function getLine(id) {
// обращение к серверу для создания записи (post) // обращение к серверу для создания записи (post)
// объект отправляется в теле запроса (body) // объект отправляется в теле запроса (body)
export async function createLine(item, price, count, image) { export async function createLine(item, price, count, discounts, image) {
const itemObject = createLineObject(item, price, count, image); const itemObject = createLineObject(item, price, count, discounts,image);
const options = { const options = {
method: "POST", method: "POST",
@ -54,22 +62,19 @@ export async function createLine(item, price, count, image) {
"Content-Type": "application/json", "Content-Type": "application/json",
}, },
}; };
const response = await fetch(`${serverUrl}/lines`, options); const response = await fetch(`${serverUrl}/lines`, options);
if (!response.ok) { if (!response.ok) {
throw response.statusText; throw response.statusText;
} }
return response.json(); return response.json();
} }
// обращение к серверу для обновления записи по id (put) // обращение к серверу для обновления записи по id (put)
// объект отправляется в теле запроса (body) // объект отправляется в теле запроса (body)
// id передается в качестве части пути URL get-запроса // id передается в качестве части пути URL get-запроса
export async function updateLine(id, item, price, count, image) { export async function updateLine(id, item, price, count,discounts, image) {
const itemObject = createLineObject(item, price, count, image); const itemObject = createLineObject(item, price, count,discounts, image);
const options = { const options = {
method: "PUT", method: "PUT",
@ -101,5 +106,4 @@ export async function deleteLine(id) {
} }
await response.json(); await response.json();
location.reload(); location.reload();
} }

View File

@ -14,6 +14,7 @@ export const cntrls = {
name: document.getElementById("name"), name: document.getElementById("name"),
price: document.getElementById("price"), price: document.getElementById("price"),
count: document.getElementById("count"), count: document.getElementById("count"),
discountsType: document.getElementById("discounts"),
image: document.getElementById("image"), image: document.getElementById("image"),
imagePreview: document.getElementById("image-preview"), imagePreview: document.getElementById("image-preview"),
}; };
@ -62,8 +63,6 @@ function createTableColumn(value) {
td.textContent = value; td.textContent = value;
return td; return td;
} }
export function createTableRow(item, index, editCallback, editPageCallback, deleteCallback) { export function createTableRow(item, index, editCallback, editPageCallback, deleteCallback) {
const rowNumber = document.createElement("th"); const rowNumber = document.createElement("th");
rowNumber.scope = "row"; rowNumber.scope = "row";
@ -76,16 +75,15 @@ export function createTableRow(item, index, editCallback, editPageCallback, dele
row.appendChild(createTableColumn(item.items.name)); row.appendChild(createTableColumn(item.items.name));
row.appendChild(createTableColumn(parseFloat(item.price).toFixed(2))); row.appendChild(createTableColumn(parseFloat(item.price).toFixed(2)));
row.appendChild(createTableColumn(item.count)); row.appendChild(createTableColumn(item.count));
row.appendChild(createTableColumn(item.discounts.name));
// редактировать в модальном окне // редактировать в модальном окне
row.appendChild(createTableAnchor("fa-pencil", editCallback)); row.appendChild(createTableAnchor("fa-pencil", editCallback));
// удаление // удаление
row.appendChild(createTableAnchor("fa-trash", deleteCallback)); row.appendChild(createTableAnchor("fa-trash", deleteCallback));
return row; return row;
} }
export function createTableRowOnIndex(item, index, editCallback, editPageCallback, deleteCallback) { export function createTableRowOnIndex(item, index, editCallback, editPageCallback, deleteCallback) {
console.log(item) console.log(item);
const img = document.createElement("img"); const img = document.createElement("img");
img.classList.add("objects"); img.classList.add("objects");
@ -97,9 +95,9 @@ export function createTableRowOnIndex(item, index, editCallback, editPageCallbac
const name = document.createElement("div"); const name = document.createElement("div");
name.classList.add("caption"); name.classList.add("caption");
name.innerText = item.items.name name.innerText = item.items.name;
name.style.padding = "0px"; name.style.padding = "0px";
name.style.marginBottom = "-10px" name.style.marginBottom = "-10px";
const count = document.createElement("div"); const count = document.createElement("div");
count.classList.add("caption_count"); count.classList.add("caption_count");
@ -112,17 +110,19 @@ export function createTableRowOnIndex(item, index, editCallback, editPageCallbac
price.innerText = parseInt(item.price) + "₽"; price.innerText = parseInt(item.price) + "₽";
price.style.padding = "0"; price.style.padding = "0";
const a = document.createElement("a"); const a = document.createElement("a");
a.href = "page4.html" a.href = "page4.html";
a.style.textDecoration = "none" a.style.textDecoration = "none";
const discounts = document.createElement("div");
discounts.classList.add("caption");
discounts.innerText = item.discounts.name;
a.appendChild(img); a.appendChild(img);
a.appendChild(name); a.appendChild(name);
a.appendChild(count); a.appendChild(count);
a.appendChild(price); a.appendChild(price);
a.appendChild(discounts);
const buttonsContainer = document.createElement("div"); const buttonsContainer = document.createElement("div");
buttonsContainer.style.display = "flex"; buttonsContainer.style.display = "flex";
@ -130,15 +130,13 @@ export function createTableRowOnIndex(item, index, editCallback, editPageCallbac
const editButton = createTableAnchor("fa-pencil", editCallback); const editButton = createTableAnchor("fa-pencil", editCallback);
const deleteButton = createTableAnchor("fa-trash", deleteCallback); const deleteButton = createTableAnchor("fa-trash", deleteCallback);
deleteButton.style.marginLeft = "1.2vw" deleteButton.style.marginLeft = "1.2vw";
buttonsContainer.appendChild(editButton); buttonsContainer.appendChild(editButton);
buttonsContainer.appendChild(deleteButton); buttonsContainer.appendChild(deleteButton);
buttonsContainer.style.marginTop = "-6px" buttonsContainer.style.marginTop = "-6px";
buttonsContainer.style.marginBottom = "10px" buttonsContainer.style.marginBottom = "10px";
a.appendChild(buttonsContainer); a.appendChild(buttonsContainer);
const div = document.createElement("div"); const div = document.createElement("div");
div.classList.add("col"); div.classList.add("col");
div.classList.add("clear-float"); div.classList.add("clear-float");
@ -152,12 +150,3 @@ export function createTableRowOnIndex(item, index, editCallback, editPageCallbac
div.style.boxSizing = "border-box"; div.style.boxSizing = "border-box";
return div; return div;
} }

View File

@ -1,26 +1,38 @@
// модуль с логикой // модуль с логикой
import {hideUpdateModal, showUpdateModal} from "./lines-modal"; import {hideUpdateModal, showUpdateModal} from "./lines-modal";
import {createLine, deleteLine, getAllItemTypes, getAllLines, getLine, updateLine,} from "./lines-rest-api"; import {
createLine,
deleteLine,
getAllDisountsTypes,
getAllItemTypes,
getAllLines,
getLine,
updateLine,
} from "./lines-rest-api";
import {cntrls, createItemsOption, createTableRow, createTableRowOnIndex, imagePlaceholder,} from "./lines-ui"; import {cntrls, createItemsOption, createTableRow, createTableRowOnIndex, imagePlaceholder,} from "./lines-ui";
async function drawItemsSelect() { async function drawItemsSelect() {
// вызов метода REST API для получения списка типов товаров // вызов метода REST API для получения списка типов товаров
const data = await getAllItemTypes(); const data = await getAllItemTypes();
const data2 = await getAllDisountsTypes();
// очистка содержимого select // очистка содержимого select
// удаляется все, что находится между тегами <select></select> // удаляется все, что находится между тегами <select></select>
// но не атрибуты // но не атрибуты
cntrls.itemsType.innerHTML = ""; cntrls.itemsType.innerHTML = "";
cntrls.discountsType.innerHTML = "";
// пустое значение // пустое значение
cntrls.itemsType.appendChild(createItemsOption("Выберите значение", "", true));
// цикл по результату ответа от сервера // цикл по результату ответа от сервера
// используется лямбда-выражение // используется лямбда-выражение
// (item) => {} аналогично function(item) {} // (item) => {} аналогично function(item) {}
data.forEach((item) => { data.forEach((item) => {
cntrls.itemsType.appendChild(createItemsOption(item.name, item.id)); cntrls.itemsType.appendChild(createItemsOption(item.name, item.id));
}); });
data2.forEach((item) => {
cntrls.discountsType.appendChild(createItemsOption(item.name, item.id));
});
} }
async function drawLinesTable() { async function drawLinesTable() {
console.info("Try to load data"); console.info("Try to load data");
if (!cntrls.table) { if (!cntrls.table) {
@ -50,7 +62,6 @@ async function drawLinesTable() {
); );
}); });
} }
async function drawLinesTableOnIndex() { async function drawLinesTableOnIndex() {
console.info("Try to load data On Index"); console.info("Try to load data On Index");
if (!cntrls.container) { if (!cntrls.container) {
@ -81,20 +92,20 @@ async function drawLinesTableOnIndex() {
}); });
} }
async function addLine(item, price, count, image) { async function addLine(item, price, count,discounts, image) {
console.info("Try to add item"); console.info("Try to add item");
// вызов метода REST API для добавления записи // вызов метода REST API для добавления записи
const data = await createLine(item, price, count, image); const data = await createLine(item, price, count,discounts, image);
console.info("Added"); console.info("Added");
console.info(data); console.info(data);
// загрузка и заполнение table // загрузка и заполнение table
drawLinesTable(); drawLinesTable();
} }
async function editLine(id, item, price, count, image) { async function editLine(id, item, price, count, discounts,image) {
console.info("Try to update item"); console.info("Try to update item");
// вызов метода REST API для обновления записи // вызов метода REST API для обновления записи
const data = await updateLine(id, item, price, count, image); const data = await updateLine(id, item, price, count, discounts,image);
console.info("Updated"); console.info("Updated");
console.info(data); console.info(data);
// загрузка и заполнение table // загрузка и заполнение table
@ -114,7 +125,6 @@ async function removeLine(id) {
drawLinesTable(); drawLinesTable();
} }
// функция для получения содержимого файла в виде base64 строки // функция для получения содержимого файла в виде base64 строки
// https://ru.wikipedia.org/wiki/Base64 // https://ru.wikipedia.org/wiki/Base64
async function readFile(file) { async function readFile(file) {
@ -217,6 +227,7 @@ export function linesForm() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} else { } else {
@ -225,6 +236,7 @@ export function linesForm() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} }
@ -282,6 +294,7 @@ export async function linesFormOnIndex() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} else { } else {
@ -290,6 +303,7 @@ export async function linesFormOnIndex() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} }
@ -297,10 +311,7 @@ export async function linesFormOnIndex() {
// после выполнения добавления/обновления модальное окно скрывается // после выполнения добавления/обновления модальное окно скрывается
hideUpdateModal(); hideUpdateModal();
}); });
} }
// Функция для обработки создания и редактирования элементов таблицы через страницу page-admin.html // Функция для обработки создания и редактирования элементов таблицы через страницу page-admin.html
// Если хотите делать через модальное окно, то удалите эту функцию // Если хотите делать через модальное окно, то удалите эту функцию
export async function linesPageForm() { export async function linesPageForm() {
@ -331,6 +342,7 @@ export async function linesPageForm() {
// заполнение формы для редактирования // заполнение формы для редактирования
cntrls.price.value = line.price; cntrls.price.value = line.price;
cntrls.count.value = line.count; cntrls.count.value = line.count;
cntrls.discountsType.value = line.discounts2Type;
// заполнение превью // заполнение превью
// Если пользователь выбрал изображение, то оно загружается // Если пользователь выбрал изображение, то оно загружается
// в тэг image с id image - preview // в тэг image с id image - preview
@ -381,6 +393,7 @@ export async function linesPageForm() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} else { } else {
@ -389,6 +402,7 @@ export async function linesPageForm() {
cntrls.itemsType.value, cntrls.itemsType.value,
cntrls.price.value, cntrls.price.value,
cntrls.count.value, cntrls.count.value,
cntrls.discountsType.value,
imageBase64, imageBase64,
); );
} }

View File

@ -46,6 +46,11 @@
<!-- <label class="form-label" for="image">Изображение</label>--> <!-- <label class="form-label" for="image">Изображение</label>-->
<input id="image" type="file" name="image" class="form-control" accept="image/*" required> <input id="image" type="file" name="image" class="form-control" accept="image/*" required>
</div> </div>
<div class="mb-2 width_add_object">
<label for="item" class="form-label">Скидка</label>
<select id="discounts" class="form-select" name="selected" required>
</select>
</div>
<div class="text-center"> <div class="text-center">
<button class="btn btn-primary add_object-button" type="submit">Добавить</button> <button class="btn btn-primary add_object-button" type="submit">Добавить</button>
@ -63,6 +68,5 @@
linesPageForm(); linesPageForm();
}); });
</script> </script>
</body> </body>
</html> </html>

View File

@ -30,6 +30,7 @@
<th scope="col" class="w-25">Товар</th> <th scope="col" class="w-25">Товар</th>
<th scope="col" class="w-25">Цена</th> <th scope="col" class="w-25">Цена</th>
<th scope="col" class="w-25">Количество</th> <th scope="col" class="w-25">Количество</th>
<th scope="col" class="w-25">Скидка</th>
</thead> </thead>
<tbody></tbody> <tbody></tbody>
</table> </table>
@ -67,6 +68,11 @@
<input id="count" name="count" class="form-control" type="number" value="0" min="1" step="1" <input id="count" name="count" class="form-control" type="number" value="0" min="1" step="1"
required> required>
</div> </div>
<div class="mb-2 width_add_object">
<label for="item" class="form-label">Скидка</label>
<select id="discounts" class="form-select" name="selected" required>
</select>
</div>
<div class="mb-2"> <div class="mb-2">
<label class="form-label" for="image">Изображение</label> <label class="form-label" for="image">Изображение</label>
<input id="image" type="file" name="image" class="form-control" accept="image/*"> <input id="image" type="file" name="image" class="form-control" accept="image/*">
@ -91,5 +97,4 @@
}); });
</script> </script>
</body> </body>
</html> </html>