当前位置:网站首页>[PROJECT] small hat takeout (VII)
[PROJECT] small hat takeout (VII)
2022-04-22 02:17:00 【Lemon hat】
Small hat takeout
Chapter vii. Food display 、 The shopping cart 、 Place an order
One 、 Effect display

Two 、 Import function codes related to user address book
1. Demand analysis
- Address book , It refers to the address information of mobile consumer users , After logging in successfully, users can maintain their own address information . The same user can have multiple address information , But there can only be one Default address .

2. Data model
- The user's address information will be stored in address_book surface , That is, in the address book table . The specific table structure is as follows :

3. Import function code
- Function code list :
- Entity class AddressBook
- Mapper Interface AddressBookMapper
- Business layer interface AddressBookService
- Business layer implementation classes AddressBookServiceImpl
- Control layer AddressBookController
@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
@Autowired
private AddressBookService addressBookService;
/** * newly added */
@PostMapping
public R<AddressBook> save(@RequestBody AddressBook addressBook) {
addressBook.setUserId(BaseContext.getCurrentId());
log.info("addressBook:{}", addressBook);
addressBookService.save(addressBook);
return R.success(addressBook);
}
/** * Set the default address */
@PutMapping("default")
public R<AddressBook> setDefault(@RequestBody AddressBook addressBook) {
log.info("addressBook:{}", addressBook);
LambdaUpdateWrapper<AddressBook> wrapper = new LambdaUpdateWrapper<>();
wrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
wrapper.set(AddressBook::getIsDefault, 0);
//SQL:update address_book set is_default = 0 where user_id = ?
addressBookService.update(wrapper);
addressBook.setIsDefault(1);
//SQL:update address_book set is_default = 1 where id = ?
addressBookService.updateById(addressBook);
return R.success(addressBook);
}
/** * according to id Search address */
@GetMapping("/{id}")
public R get(@PathVariable Long id) {
AddressBook addressBook = addressBookService.getById(id);
if (addressBook != null) {
return R.success(addressBook);
} else {
return R.error(" The object was not found ");
}
}
/** * Query default address */
@GetMapping("default")
public R<AddressBook> getDefault() {
LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(AddressBook::getUserId, BaseContext.getCurrentId());
queryWrapper.eq(AddressBook::getIsDefault, 1);
//SQL:select * from address_book where user_id = ? and is_default = 1
AddressBook addressBook = addressBookService.getOne(queryWrapper);
if (null == addressBook) {
return R.error(" The object was not found ");
} else {
return R.success(addressBook);
}
}
/** * Query all addresses of the specified user */
@GetMapping("/list")
public R<List<AddressBook>> list(AddressBook addressBook) {
addressBook.setUserId(BaseContext.getCurrentId());
log.info("addressBook:{}", addressBook);
// Conditional constructor
LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(null != addressBook.getUserId(), AddressBook::getUserId, addressBook.getUserId());
queryWrapper.orderByDesc(AddressBook::getUpdateTime);
//SQL:select * from address_book where user_id = ? order by update_time desc
return R.success(addressBookService.list(queryWrapper));
}
}
3、 ... and 、 Food display
1. Demand analysis
- After logging in successfully, the user jumps to the system home page , On the home page, you need to display dishes and set meals according to classification . If the dish is set with taste information , Need to show the select specification button , Otherwise, it will show + Button .

2. Code development
- Sort out the interaction process
- Before developing code , You need to sort out the interaction process between the front-end page and the server :
- page (front/index.html) send out ajax request , Get classified data ( Classification of dishes and packages )
- Page sending ajax request , Get the dishes or packages under the first category
- Develop dish display function , In fact, it is to write code on the server side to process the information sent by the front-end page 2 One request is enough .
- Be careful : After the home page is loaded , Also sent once ajax Request to load shopping cart data , Here you can temporarily change the address of this request , From static json File access data , It will be modified when the shopping cart function is developed later , as follows :

- Before developing code , You need to sort out the interaction process between the front-end page and the server :
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
@Autowired
private DishService dishService;
@Autowired
private DishFlavorService dishFlavorService;
@Autowired
private CategoryService categoryService;
/** * Query the corresponding dish data according to the conditions * @param dish * @return */
@GetMapping("/list")
public R<List<DishDto>> list(Dish dish) {
// Construct query conditions
LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
// Adding conditions , The query status is 1( Starting status ) The dishes
queryWrapper.eq(Dish::getStatus,1);
// Add sorting criteria
queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
List<Dish> list = dishService.list(queryWrapper);
List<DishDto> dishDtoList = list.stream().map((item) -> {
DishDto dishDto = new DishDto();
BeanUtils.copyProperties(item, dishDto);
Long categoryId = item.getCategoryId(); // classification id
// according to id Query classification objects
Category category = categoryService.getById(categoryId);
if(category != null) {
String categoryName = category.getName();
dishDto.setCategoryName(categoryName);
}
// Of the current dish id
Long dishId = item.getId();
LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
queryWrapper1.eq(DishFlavor::getDishId, dishId);
List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper1);
dishDto.setFlavors(dishFlavorList);
return dishDto;
}).collect(Collectors.toList());
return R.success(dishDtoList);
}
}
Four 、 The shopping cart
1. Demand analysis
- Mobile end users can add dishes or packages to the shopping cart . For dishes , If taste information is set , You need to select the specification before you can add it to the shopping cart ; For the package , You can click + Add the current package to the shopping cart . You can modify the number of dishes and packages in the shopping cart , You can also empty the shopping cart .

2. Data model
- The data table corresponding to the shopping cart is shopping_cart surface , The specific table structure is as follows :

3. Code development
3.1 Sort out the interaction process
- Before developing code , You need to sort out the interaction process between the front-end page and the server during shopping cart operation :
- Click Add to cart or + Button , Page sending ajax request , Request server , Add dishes or packages to the shopping cart
- Click on the shopping cart icon , Page sending ajax request , Request the server to query the dishes and packages in the shopping cart
- Click the empty cart button , Page sending ajax request , Request the server to empty the shopping cart
- Develop shopping cart function , In fact, it is to write code on the server side to process the information sent by the front-end page 3 One request is enough .
3.2 preparation
- Before developing business functions , First, create the basic structure of classes and interfaces that need to be used :
- Entity class ShoppingCart
- Mapper Interface ShoppingCartMapper
- Business layer interface ShoppingCartService
- Business layer implementation classes ShoppingCartServiceImpl
- Control layer ShoppingCartController
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
@Autowired
private ShoppingCartService shoppingCartService;
/** * Add cart * @param shoppingCart * @return */
@PostMapping("/add")
public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart) {
log.info(" Shopping cart data :{}", shoppingCart);
// Set user id, Specify which user's shopping cart data is currently
Long currentId = BaseContext.getCurrentId();
shoppingCart.setUserId(currentId);
Long dishId = shoppingCart.getDishId();
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShoppingCart::getUserId, currentId);
if(dishId != null) {
// Added to the shopping cart are dishes
queryWrapper.eq(ShoppingCart::getDishId, dishId);
} else {
// The package added to the shopping cart
queryWrapper.eq(ShoppingCart::getSetmealId, shoppingCart.getSetmealId());
}
// Check whether the current dish or package is in the shopping cart
ShoppingCart cartServiceOne = shoppingCartService.getOne(queryWrapper);
if(cartServiceOne != null) {
// If it already exists , Add... To the original quantity 1
Integer number = cartServiceOne.getNumber();
cartServiceOne.setNumber(number + 1);
shoppingCartService.updateById(cartServiceOne);
} else {
// If it doesn't exist , Add to shopping cart , The default quantity is 1
shoppingCart.setNumber(1);
shoppingCart.setCreateTime(LocalDateTime.now());
shoppingCartService.save(shoppingCart);
cartServiceOne = shoppingCart;
}
return R.success(cartServiceOne);
}
/** * Check out the shopping cart * @return */
@GetMapping("/list")
public R<List<ShoppingCart>> list() {
log.info(" Check out the shopping cart ...");
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
queryWrapper.orderByAsc(ShoppingCart::getCreateTime);
List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
return R.success(list);
}
/** * empty cart * @return */
@DeleteMapping("/clean")
public R<String> clean() {
LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
shoppingCartService.remove(queryWrapper);
return R.success(" Empty shopping cart successfully ");
}
}
5、 ... and 、 Users to place the order
1. Demand analysis
- After the mobile end user adds dishes or packages to the shopping cart , You can click the go to settlement button in the shopping cart , The page jumps to the order confirmation page , Click the pay button to complete the order placing operation .

2. Data model
- The data table corresponding to the user's order business is orders Table and order_detail surface :
- orders: The order sheet
- order_detail: Order details


3. Code development
3.1 Sort out the interaction process
- Before developing code , You need to sort out the interaction process between the front-end page and the server when the user orders :
- Click the go to settlement button in the shopping cart , The page jumps to the order confirmation page
- On the order confirmation page , send out ajax request , Get the default login address of the server
- On the order confirmation page , send out ajax request , Request the server to obtain the shopping cart data of the currently logged in user
- Click the pay button on the order confirmation page , send out ajax request , Request the server to complete the order placing operation
- Develop user ordering function , In fact, it is just to write code on the server to process the request sent by the front-end page .
3.2 preparation
- Before developing business functions , First, create the basic structure of classes and interfaces that need to be used :
- Entity class Orders、OrderDetail
- Mapper Interface OrderMapper、OrderDetailMapper
- Business layer interface OrderService、OrderDetailService
- Business layer implementation classes OrderServiceImpl、OrderDetailServiceImpl
- Control layer OrderController、OrderDetailController
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
/** * Users to place the order * @param orders * @return */
@PostMapping("/submit")
public R<String> submit(@RequestBody Orders orders) {
log.info(" Order data :{}", orders);
orderService.submit(orders);
return R.success(" checkout success ");
}
}
public interface OrderService extends IService<Orders> {
/** * Users to place the order * @param orders */
public void submit(Orders orders);
}
@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {
@Autowired
private ShoppingCartService shoppingCartService;
@Autowired
private UserService userService;
@Autowired
private AddressBookService addressBookService;
@Autowired
private OrderDetailService orderDetailService;
/** * Users to place the order * @param orders */
@Transactional
public void submit(Orders orders) {
// Get current user id
Long userId = BaseContext.getCurrentId();
// Query the shopping cart data of the current user
LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShoppingCart::getUserId,userId);
List<ShoppingCart> shoppingCarts = shoppingCartService.list(wrapper);
if(shoppingCarts == null || shoppingCarts.size() == 0){
throw new CustomException(" The shopping cart is empty , Can't place an order ");
}
// Query user data
User user = userService.getById(userId);
// Query address data
Long addressBookId = orders.getAddressBookId();
AddressBook addressBook = addressBookService.getById(addressBookId);
if(addressBook == null){
throw new CustomException(" Incorrect user address information , Can't place an order ");
}
long orderId = IdWorker.getId();// The order number
AtomicInteger amount = new AtomicInteger(0);
List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
OrderDetail orderDetail = new OrderDetail();
orderDetail.setOrderId(orderId);
orderDetail.setNumber(item.getNumber());
orderDetail.setDishFlavor(item.getDishFlavor());
orderDetail.setDishId(item.getDishId());
orderDetail.setSetmealId(item.getSetmealId());
orderDetail.setName(item.getName());
orderDetail.setImage(item.getImage());
orderDetail.setAmount(item.getAmount());
amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
return orderDetail;
}).collect(Collectors.toList());
orders.setId(orderId);
orders.setOrderTime(LocalDateTime.now());
orders.setCheckoutTime(LocalDateTime.now());
orders.setStatus(2);
orders.setAmount(new BigDecimal(amount.get()));// Total sum
orders.setUserId(userId);
orders.setNumber(String.valueOf(orderId));
orders.setUserName(user.getName());
orders.setConsignee(addressBook.getConsignee());
orders.setPhone(addressBook.getPhone());
orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
+ (addressBook.getCityName() == null ? "" : addressBook.getCityName())
+ (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
+ (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
// Insert data into the order table , A piece of data
this.save(orders);
// Insert data into the order parts list , Multiple data
orderDetailService.saveBatch(orderDetails);
// Empty cart data
shoppingCartService.remove(wrapper);
}
}
版权声明
本文为[Lemon hat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220213286266.html
边栏推荐
- Time and current time judgment in MySQL database
- (counting line segment tree) lintcode medium 248 · count the number of numbers smaller than a given integer
- DEJA_VU3D - Cesium功能集 之 012-军事标绘系列六:自定义多边形
- Solve the problem that the search box of select2 in modal is invalid
- Shell basic syntax
- Opencv 4.0 learning notes
- DEJA_ Vu3d - cesium feature set 012 - military plotting Series 6: Custom polygons
- 信息安全概述
- MySQL cannot find my INI file
- 高级面试题 解析,阿里巴巴发布“限量版”Android零基础宝典
猜你喜欢

Jetcode prize essay solicitation activity | interesting stories of low code industry waiting for you to share

How to select the appropriate neo4j Version (2022)

Advanced formula 44 of C language: the secret of function parameters (Part 1)

互联网行业为什么能吸引越来越多的年轻人?尤其是程序员……

Page 107 planning and design of enterprise digital transformation

Window7激活 电话激活小记;

单层神经⽹络的详细实现

Information Security Overview

error:there‘s no Qt version assigned to project please assign a Qt installation in qt project settin

postgresql中在查询结果中将字符串转换为整形或浮点型
随机推荐
【pytorch图像分类】AlexNet网络结构
Raspberry pie 4B 8g installation log (3) - Programming Environment
Review of SV knowledge points
Interview question: use the program to realize the alternating printing of odd and even numbers from 0 to 100 by two threads
102 page master plan for new generation digital transformation and informatization
[programming question] deletion
Hexadecimal conversion
Shell basic syntax
[check which package provides the installed packages and commands]
The advanced UI doesn't understand why they can get a high salary. It's hot
8种MySQL常见SQL错误用法详解
SSLHandshakeException
Unity3D RPG角色扮演游戏源码(上下)-----源代码分析----01-----主角人物动画
Why can the Internet industry attract more and more young people? Especially programmers
DEJA_ Vu3d - cesium feature set 012 - military plotting Series 6: Custom polygons
Deadlock of select statements in golang
49 pages enterprise digital transformation cases and common tools enterprise digital transformation ideas
Page 78 digital twin + smart building solutions
Detailed explanation of transaction isolation level
SV知识点回顾