This commit is contained in:
Ino 2023-04-27 16:58:16 +04:00
parent ac0427a16e
commit 816d2d1284
9 changed files with 80 additions and 136 deletions

View File

@ -1,5 +1,6 @@
package com.example.demo.supply.Order; package com.example.demo.supply.Order;
import com.example.demo.supply.Product.ProductDto;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.List; import java.util.List;
@ -24,18 +25,23 @@ public class OrderController {
return orderService.findAllOrders().stream().map(OrderDto::new).toList(); return orderService.findAllOrders().stream().map(OrderDto::new).toList();
} }
@GetMapping("/getProducts/{id}")
public List<ProductDto> getOrderProducts(@PathVariable Long id) {
return orderService.findAllOrderProducts(id).stream().map(ProductDto::new).toList();
}
@PostMapping("/") @PostMapping("/")
public OrderDto createOrder(@RequestParam() Long supplierId) { public OrderDto createOrder(@RequestParam() Long supplierId) {
return new OrderDto(orderService.addOrder(supplierId)); return new OrderDto(orderService.addOrder(supplierId));
} }
@PatchMapping("/addProduct/{id}/") @PatchMapping("/addProduct/{id}")
public OrderDto addProduct(@PathVariable Long id, public OrderDto addProduct(@PathVariable Long id,
@RequestParam() Long productId){ @RequestParam() Long productId){
return new OrderDto(orderService.addProduct(id, productId)); return new OrderDto(orderService.addProduct(id, productId));
} }
@PatchMapping("/removeProduct/{id}/") @PatchMapping("/removeProduct/{id}")
public OrderDto removeProduct(@PathVariable Long id, public OrderDto removeProduct(@PathVariable Long id,
@RequestParam() Long productId){ @RequestParam() Long productId){
return new OrderDto(orderService.removeProduct(id, productId)); return new OrderDto(orderService.removeProduct(id, productId));

View File

@ -1,6 +1,10 @@
package com.example.demo.supply.Order; package com.example.demo.supply.Order;
import com.example.demo.supply.Product.Product;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
public interface OrderRepository extends JpaRepository<_Order, Long> { public interface OrderRepository extends JpaRepository<_Order, Long> {
} }

View File

@ -1,5 +1,6 @@
package com.example.demo.supply.Order; package com.example.demo.supply.Order;
import com.example.demo.supply.Product.Product;
import com.example.demo.supply.Product.ProductService; import com.example.demo.supply.Product.ProductService;
import com.example.demo.supply.Supplier.SupplierService; import com.example.demo.supply.Supplier.SupplierService;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -64,6 +65,12 @@ public class OrderService {
return orderRepository.findAll(); return orderRepository.findAll();
} }
@Transactional(readOnly = true)
public List<Product> findAllOrderProducts(Long orderId) {
final Optional<_Order> order = orderRepository.findById(orderId);
return order.orElseThrow(() -> new OrderNotFoundException(orderId)).getProducts();
}
@Transactional @Transactional
public _Order deleteOrder(Long id) { public _Order deleteOrder(Long id) {
final _Order currentOrder = findOrder(id); final _Order currentOrder = findOrder(id);

View File

@ -12,6 +12,7 @@ function getFullUrl(url, data) {
if (field === 'date') continue if (field === 'date') continue
if (field === 'countProducts') continue if (field === 'countProducts') continue
if (field === 'products') continue if (field === 'products') continue
if (field === 'supplierName') continue
currentUrl.searchParams.append(field, data[field]) currentUrl.searchParams.append(field, data[field])
} }
@ -39,7 +40,7 @@ export default class DataService {
} }
static async create(url, data) { static async create(url, data) {
console.log(data) //console.log(data)
await fetch(getFullUrl(this.mainUrl + url, data), { await fetch(getFullUrl(this.mainUrl + url, data), {
method: 'POST', method: 'POST',
}).catch(e => console.log(e)) }).catch(e => console.log(e))

View File

@ -1,4 +1,5 @@
import { React, useState, useEffect } from "react"; import { React, useState, useEffect } from "react";
import { Link } from 'react-router-dom';
import Supplier from "../models/Supplier"; import Supplier from "../models/Supplier";
import DataService from "../DataService"; import DataService from "../DataService";
import Order from "../models/Order"; import Order from "../models/Order";
@ -11,6 +12,8 @@ export default function CreateOrderPage(props){
const supplierUrl = 'supplier/' const supplierUrl = 'supplier/'
const productUrl = 'product/' const productUrl = 'product/'
let orderProductsArr = []
const headers = [ const headers = [
{ name: 'name', label: 'Продукт' }, { name: 'name', label: 'Продукт' },
{ name: 'cost', label: 'Цена' } { name: 'cost', label: 'Цена' }
@ -23,50 +26,65 @@ export default function CreateOrderPage(props){
const [suppliers, setSuppliers] = useState([]) const [suppliers, setSuppliers] = useState([])
const [products, setProducts] = useState([]) const [products, setProducts] = useState([])
const [productsOrder, setProductsOrder] = useState([]) const [order, setOrder] = useState(new Order())
const [addsProduct, setAddsProduct] = useState(new Product())
const [orderProducts, setOrderProducts] = useState([])
const [modalHeader, setModalHeader] = useState('') const [modalHeader, setModalHeader] = useState('')
const [modalConfirm, setModalConfirm] = useState('') const [modalConfirm, setModalConfirm] = useState('')
const [modalVisible, setModalVisible] = useState(false) const [modalVisible, setModalVisible] = useState(false)
const [isAddProd, setIsAddProd] = useState(false)
const [isAddSupplier, setIsAddSupplier] = useState(false)
useEffect(() => { useEffect(() => {
loadItems() loadItems()
//eslint-disable-next-line react-hooks/exhaustive-deps //eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
const loadItems = () => { const loadItems = () => {
// DataService.getOrders(url).then(data => {
// console.log(data)
// setOrders([])
// data.map(order => {
// setOrders(prevState => [...prevState, new Order(order)])
// })
// })
DataService.readAll(supplierUrl, transformerSupplier).then(data => setSuppliers(data)) DataService.readAll(supplierUrl, transformerSupplier).then(data => setSuppliers(data))
DataService.readAll(productUrl, transformerProduct).then(data => setProducts(data)) DataService.readAll(productUrl, transformerProduct).then(data => setProducts(data))
} }
const saveItems = () => { const createOrder = () => {
console.log("saveItems") // console.log(order)
DataService.create(url, order)
}
const addProductInOrder = () => {
DataService.read(`${productUrl}${addsProduct.id}`, transformerProduct)
.then(data => {
order.products.push(data)
setOrder({ ...order, products: order.products })
})
} }
const handleFormChange = (event) => { const handleFormChange = (event) => {
//console.log([event.target.id].event.target.value) setOrder({ ...order, [event.target.id]: event.target.value })
// console.log(currOrder) }
// setData({ ...data, [event.target.id]: event.target.value })
// console.log(data) const handleAddProduct = (event) => {
setAddsProduct({ ...addsProduct, [event.target.id]: event.target.value })
} }
const addProduct = () => { const addProduct = () => {
console.log(addsProduct)
setAddsProduct(new Product())
console.log(addsProduct)
setIsAddProd(true)
setModalHeader('Добавление продукта'); setModalHeader('Добавление продукта');
setModalConfirm('Добавить'); setModalConfirm('Добавить');
setModalVisible(true); setModalVisible(true);
} }
const hideModal = () => setModalVisible(false) const hideModal = () => setModalVisible(false)
const modalDone = () => saveItems() const modalDone = () => {
}
const ds = () => console.log("") const ds = () => console.log("")
return( return(
@ -77,15 +95,18 @@ export default function CreateOrderPage(props){
<div className="row gx-5"> <div className="row gx-5">
<div className="btn-group" role="group" aria-label="Basic mixed styles example"> <div className="btn-group" role="group" aria-label="Basic mixed styles example">
<button type="button" className="btn btn-success">Создать</button> <Link to="/orders">
<button type="button" className="btn btn-success" onClick={createOrder}>Создать</button>
<button type="button" className="btn btn-danger">Отмена</button> <button type="button" className="btn btn-danger">Отмена</button>
</Link>
</div> </div>
</div> </div>
<br></br> <br></br>
<div className="mb-3"> <div className="mb-3">
<p className="h4" htmlFor="supplierId">Поставщик</p> <p className="h4" htmlFor="supplierId">Поставщик</p>
<select id="supplierId" className="form-select " required <select id="supplierId" className="form-select " required
onChange={handleFormChange}> value={order.supplierId} onChange={handleFormChange}>
<option disabled value="">Укажите поставщика</option> <option disabled value="">Укажите поставщика</option>
{ {
suppliers.map(supplier => suppliers.map(supplier =>
@ -97,12 +118,12 @@ export default function CreateOrderPage(props){
<p className="h4">Продукты</p> <p className="h4">Продукты</p>
<div className="btn-group" role="group" aria-label="Basic mixed styles example"> <div className="btn-group" role="group" aria-label="Basic mixed styles example">
<button type="button" className="btn btn-success" onClick={addProduct}>Добавить продукт</button> <button type="button" className="btn btn-success" onClick={addProduct}>Добавить продукт</button>
<button type="button" className="btn btn-danger">Удалить продукт</button> <button type="button" className="btn btn-danger" >Удалить продукт</button>
</div> </div>
<Table <Table
headers={headers} headers={headers}
items={productsOrder} items={order.products}
selectable={true} selectable={true}
onClick={ds} onClick={ds}
onDblClick={ds}/> onDblClick={ds}/>
@ -112,11 +133,11 @@ export default function CreateOrderPage(props){
confirm={modalConfirm} confirm={modalConfirm}
visible={modalVisible} visible={modalVisible}
onHide={hideModal} onHide={hideModal}
onDone={modalDone}> onDone={addProductInOrder}>
<div className="mb-3"> <div className="mb-3">
<p className="h4" htmlFor="product">Продукт</p> <p className="h4" htmlFor="id">Продукт</p>
<select id="product" className="form-select " required <select id="id" className="form-select " required
onChange={handleFormChange}> value={addsProduct.id} onChange={handleAddProduct}>
<option disabled value="">Укажите продукт</option> <option disabled value="">Укажите продукт</option>
{ {
products.map(product => products.map(product =>

View File

@ -1,8 +1,6 @@
import { Link } from 'react-router-dom';
import { React, useState, useEffect } from "react"; import { React, useState, useEffect } from "react";
import Table from "../general/Table"; import Table from "../general/Table";
import ToolBar from "../general/ToolBar"; import ToolBar from "../general/ToolBar";
import Modal from "../general/Modal";
import DataService from "../DataService"; import DataService from "../DataService";
import Order from "../models/Order"; import Order from "../models/Order";
import Product from "../models/Product"; import Product from "../models/Product";
@ -10,8 +8,6 @@ import Supplier from "../models/Supplier";
export default function OrderPage(){ export default function OrderPage(){
const url = 'order/' const url = 'order/'
const supplierUrl = 'supplier/'
const productUrl = 'product/'
const transformer = (data) => new Order(data) const transformer = (data) => new Order(data)
const transformerSupplier = (data) => new Product(data) const transformerSupplier = (data) => new Product(data)
@ -20,18 +16,7 @@ export default function OrderPage(){
const [orders, setOrders] = useState([]) const [orders, setOrders] = useState([])
const [currOrder, setCurrOrder] = useState('') const [currOrder, setCurrOrder] = useState('')
const[suppliers, setSuppliers] = useState([])
const[supplier, setSupplier] = useState('')
const [products, setProducts] = useState([])
const [modalHeader, setModalHeader] = useState('')
const [modalConfirm, setModalConfirm] = useState('')
const [modalVisible, setModalVisible] = useState(false)
const [isAddProd, setIsAddProd] = useState(false)
const [isEdit, setEdit] = useState(false) const [isEdit, setEdit] = useState(false)
const [addProdVisible, setAddProdVisible] = useState(false)
const headers = [ const headers = [
{ name: 'date', label: 'Дата заказа' }, { name: 'date', label: 'Дата заказа' },
@ -48,15 +33,12 @@ export default function OrderPage(){
const loadItems = () => { const loadItems = () => {
DataService.getOrders(url).then(data => { DataService.getOrders(url).then(data => {
console.log(data) //console.log(data)
setOrders([]) setOrders([])
data.map(order => { data.map(order => {
setOrders(prevState => [...prevState, new Order(order)]) setOrders(prevState => [...prevState, new Order(order)])
}) })
}) })
DataService.readAll(supplierUrl, transformerSupplier).then(data => setSuppliers(data))
DataService.readAll(productUrl, transformerProduct).then(data => setProducts(data))
} }
const add = () =>{ const add = () =>{
@ -68,44 +50,24 @@ export default function OrderPage(){
} }
const remove = () =>{ const remove = () =>{
}
const addProduct = () =>{
if (selectedItems.length === 0) if (selectedItems.length === 0)
return return
DataService.read(url + selectedItems[0], transformer) if (window.confirm('Удалить выбранные элементы?')) {
.then(data => { const promises = [];
selectedItems.forEach(item => {
promises.push(DataService.delete(url + item));
});
setEdit(false) Promise.all(promises).then(results => {
setAddProdVisible(true) selectedItems.length = 0;
setModalHeader('Добавление продукта к заказу') loadItems();
setModalConfirm('Сохранить')
edit(data)
}); });
} }
const removeProduct = () =>{
}
const handleFormChange = (event) => {
// console.log(currOrder)
// setData({ ...data, [event.target.id]: event.target.value })
// console.log(data)
} }
const handleTableClick = (tableSelectedItems) => {selectedItems = tableSelectedItems;} const handleTableClick = (tableSelectedItems) => {selectedItems = tableSelectedItems;}
const handleTableDblClick = (tableSelectedItem) =>{} const handleTableDblClick = (tableSelectedItem) =>{}
const hideModal = () => {
setModalVisible(false)
setAddProdVisible(false)
}
const modalDone = () => {}
return( return(
<> <>
@ -113,8 +75,6 @@ export default function OrderPage(){
add={add} add={add}
edit={edit} edit={edit}
remove={remove} remove={remove}
addProduct={addProduct}
removeProduct={removeProduct}
addsVisible={true}/> addsVisible={true}/>
<Table <Table
@ -123,59 +83,6 @@ export default function OrderPage(){
selectable={true} selectable={true}
onClick={handleTableClick} onClick={handleTableClick}
onDblClick={handleTableDblClick}/> onDblClick={handleTableDblClick}/>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={modalVisible}
onHide={hideModal}
onDone={modalDone}>
{/* <div className="mb-3">
<label htmlFor="supplierId" className="form-label">Поставщик</label>
<select id="supplierId" className="form-select" required
value={currOrder.supplierId} onChange={handleFormChange}>
<option disabled value="">Укажите поставщика</option>
{
suppliers.map(supplier =>
<option key={supplier.id} value={supplier.id}>{supplier.name}</option>
)
}
</select>
</div> */}
{/* <div className="mb-3">
<label htmlFor="product" className="form-label">Поставщик</label>
<select id="product" className="form-select" required
onChange={handleFormChange}>
<option disabled value="">Укажите продукт</option>
{
products.map(product =>
<option key={product.id} value={product.id}>{product.name}</option>
)
}
</select>
</div> */}
</Modal>
<Modal
header={modalHeader}
confirm={modalConfirm}
visible={addProdVisible}
onHide={hideModal}
onDone={modalDone}>
{/* <div className="mb-3">
<label htmlFor="product" className="form-label">Поставщик</label>
<select id="product" className="form-select" required
value={products} onChange={handleFormChange}>
<option disabled value="">Укажите продукт</option>
{
products.map(product =>
<option key={product.id} value={product.id}>{product.name}</option>
)
}
</select>
</div> */}
</Modal>
</> </>
) )
} }

View File

@ -54,7 +54,7 @@ import styles from './Table.module.css';
</thead> </thead>
<tbody> <tbody>
{ {
props.items.map((item, index) => props.items && props.items.map((item, index) =>
<tr key={item.id} <tr key={item.id}
className={isSelected(item.id) ? styles.selected : ''} className={isSelected(item.id) ? styles.selected : ''}
onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}> onClick={(e) => click(item.id, e)} onDoubleClick={(e) => dblClick(item.id, e)}>

View File

@ -8,8 +8,6 @@ function ToolBar(props) {
const add = () => props.add() const add = () => props.add()
const edit = () => props.edit() const edit = () => props.edit()
const remove = () => props.remove() const remove = () => props.remove()
const addProduct = () => props.addProduct()
const removeProduct = () => props.removeProduct()
return ( return (
<div className="btn-group mt-2" role="group"> <div className="btn-group mt-2" role="group">

View File

@ -6,6 +6,6 @@ export default class Order {
this.date = data?.dateOfOrder || ''; this.date = data?.dateOfOrder || '';
this.supplierId = data?.supplier.id || ''; this.supplierId = data?.supplier.id || '';
this.supplierName = data?.supplier.name || ''; this.supplierName = data?.supplier.name || '';
this.products = data?.products || ''; this.products = data?.products || [];
} }
} }