本文主要是介绍瑞吉外卖项目学习笔记:P19-移动端-收货地址|菜品展示业|购物车|用户下单页务功能开发,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
P19-移动端-收货地址|菜品展示业|购物车|用户下单页务功能开发
- 1.用户地址簿相关功能
- 1.1需求分析
- 1.2页面分析
- 1.2数据模型
- 1.3前端页面代码
- 1.3.1收货地址管理页面
- 1.3.2收货地址编辑页面
- 1.3.3js代码-新增收货地址
- 1.3.4js代码-修改地址
- 1.3.5js代码-删除地址
- 1.4后端代码
- 1.4.1实体类AddressBook
- 1.4.2Mapper接口 AddressBookMapper
- 1.4.3业务层接口AddressBookService
- 1.4.4业务层实现类AddressBookServicelmpl
- 1.4.5控制层AddressBookController
- 2.菜品展示功能
- 2.1需求分析
- 2.1前后端交互流程分析
- 2.3前端代码
- 2.3.1front/index.html页面代码
- 2.4后端代码
- 2.4.1 改造DishController下代码
- 2.4.2SetmealController ,加入根据分类id 查询套餐信息 代码
- 3.购物车功能
- 3.1需求分析
- 3.2数据模型
- 3.3前后端交互流程分析
- 3.4前端代码
- 3.4.1页面代码为front/index.html
- 3.4.2js代码-获取购物车内商品的集合
- 3.4.3js代码-购物车中添加商品
- 3.4.4js代码-购物车中修改商品
- 3.4.5js代码-删除购物车的商品
- 3.5后端代码-准备
- 3.5.1实体类ShoppingCart
- 3.5.2Mapper接口 ShoppingCartMapper
- 3.5.3业务层接口ShoppingCartService
- 3.5.4业务层实现类ShoppingCartServicelmpl
- 3.5.5控制层 ShoppingCartController
- 3.6后端代码-正式开发
- 3.6.1 添加菜品或套餐到购物车代码实现
- 3.6.2获取购物车数据
- 3.6.3清空购物车
- 4.用户下单功能
- 4.1需求分析
- 4.2数据模型
- 4.3前后端交互流程
- 4.3前端代码
- 4.3.1支付页面代码
- 4.3. js代码-订单确认页面点击【去支付】按钮,发送ajax请求
- 4.4后端代码-准备
- 4.4.1实体类Orders、OrderDetail
- 4.4.2Mapper接 口OrderMapper、OrderDetailMapper
- 4.4.3业务层接口OrderService、OrderDetailService
- 4.4.4业务层实现类OrderServicelmpl、OrderDetailServicelmpl
- 4.4.5控制层OrderController、OrderDetailController
- 4.5后端代码-正式开发
1.用户地址簿相关功能
1.1需求分析
地址簿,指的是移动端消费者用户的地址信息,用户登录成功后可以维护自己的地址信息。同一个用户可以有多个地址信息,但是只能有一个默认地址。
1.2页面分析
1.2数据模型
用户信息存储在address_book表
1.3前端页面代码
1.3.1收货地址管理页面
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"><title>菩提阁</title><link rel="icon" href="./../images/favico.ico"><!--不同屏幕尺寸根字体设置--><script src="./../js/base.js"></script><!--element-ui的样式--><link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" /><!--引入vant样式--><link rel="stylesheet" href="../styles/vant.min.css"/><!-- 引入样式 --><link rel="stylesheet" href="../styles/index.css" /><!--本页面内容的样式--><link rel="stylesheet" href="./../styles/address.css" /></head><body><div id="address" class="app"><div class="divHead"><div class="divTitle"><i class="el-icon-arrow-left" @click="goBack"></i>地址管理</div></div><div class="divContent"><div class="divItem" v-for="(item,index) in addressList" :key="index" @click.capture="itemClick(item)"><div class="divAddress"><span :class="{spanCompany:item.label === '公司',spanHome:item.label === '家',spanSchool:item.label === '学校'}">{{item.label}}</span>{{item.detail}}</div><div class="divUserPhone"><span>{{item.consignee}}</span><span>{{item.sex === '0' ? '女士' : '先生'}}</span><span>{{item.phone}}</span></div><img src="./../images/edit.png" @click.stop.prevent="toAddressEditPage(item)"/><div class="divSplit"></div><div class="divDefault" ><img src="./../images/checked_true.png" v-if="item.isDefault === 1"><img src="./../images/checked_false.png" @click.stop.prevent="setDefaultAddress(item)" v-else>设为默认地址</div></div></div><div class="divBottom" @click="toAddressCreatePage">+ 添加收货地址</div></div><!-- 开发环境版本,包含了有帮助的命令行警告 --><script src="../../backend/plugins/vue/vue.js"></script><!-- 引入组件库 --><script src="../../backend/plugins/element-ui/index.js"></script><!-- 引入vant样式 --><script src="./../js/vant.min.js"></script> <script src="./../api/address.js"></script><!-- 引入axios --><script src="../../backend/plugins/axios/axios.min.js"></script><script src="./../js/request.js"></script><script>new Vue({el:"#address",data(){return {addressList:[// {// label:'公司',// detail:'金燕龙写字楼 4层电梯口fsdfdsfsdfsdfsssssssssssss(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:0,//是否是默认// },// {// label:'家',// detail:'金燕龙写字楼 4层电梯口(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:0,//是否是默认// },// {// label:'学校',// detail:'金燕龙写字楼 4层电梯口(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:0,//是否是默认// },// {// label:'公司',// detail:'金燕龙写字楼 4层电梯口(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:0,//是否是默认// },// {// label:'公司',// detail:'金燕龙写字楼 4层电梯口(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:0,//是否是默认// },// {// label:'公司',// detail:'金燕龙写字楼 4层电梯口(电梯可…)',// consignee:'周先生',//姓名// phone:18544445566,//手机号// isDefault:1,//是否是默认// }],}},computed:{},created(){this.initData()},mounted(){},methods:{goBack(){history.go(-1)},toAddressEditPage(item){window.requestAnimationFrame(()=>{window.location.href= `/front/page/address-edit.html?id=${item.id}`})},toAddressCreatePage(){window.requestAnimationFrame(()=>{window.location.href= '/front/page/address-edit.html'})},async initData(){const res = await addressListApi()if(res.code === 1){this.addressList = res.data}else{this.$message.error(res.msg)}},async setDefaultAddress(item){if(item.id){const res = await setDefaultAddressApi({id:item.id})if(res.code === 1){this.initData()}else{this.$message.error(res.msg)}}},itemClick(item){const url = document.referrer//表示是从订单页面跳转过来的if(url.includes('order')){this.setDefaultAddress(item)history.go(-1)}}}})</script></body>
</html>
1.3.2收货地址编辑页面
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"><title>菩提阁</title><link rel="icon" href="./../images/favico.ico"><!--不同屏幕尺寸根字体设置--><script src="./../js/base.js"></script><!--element-ui的样式--><link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" /><!--引入vant样式--><link rel="stylesheet" href="../styles/vant.min.css"/><!-- 引入样式 --><link rel="stylesheet" href="../styles/index.css" /><!--本页面内容的样式--><link rel="stylesheet" href="./../styles/address-edit.css" /></head><body><div id="address_edit" class="app"><div class="divHead"><div class="divTitle"><i class="el-icon-arrow-left" @click="goBack"></i>{{title}}</div></div><div class="divContent"><div class="divItem"><span>联系人:</span> <el-input placeholder=" 请填写收货人的姓名" v-model="form.consignee" maxlength='10' class="inputUser"/></el-input><span class="spanChecked" @click="form.sex = '1'"><i :class="{iActive:form.sex === '1'}"></i>先生</span><span class="spanChecked" @click="form.sex = '0'"><i :class="{iActive:form.sex === '0'}"></i>女士</span></div><div class="divItem"><span>手机号:</span> <el-input placeholder=" 请填写收货人手机号码" v-model="form.phone" maxlength='20' style="width: calc(100% - 80rem);"/></el-input></div><div class="divItem"><span>收货地址:</span> <el-input placeholder=" 请输入收货地址" v-model="form.detail" maxlength='140'/></el-input></div><div class="divItem "><span>标签:</span> <span v-for="(item,index) in labelList" :key="index" @click="form.label = item;activeIndex = index" :class="{spanItem:true,spanActiveSchool:activeIndex === index}">{{item}}</span></div><div class="divSave" @click="saveAddress">保存地址</div><div class="divDelete" @click="deleteAddress" v-if="id">删除地址</div></div></div><!-- 开发环境版本,包含了有帮助的命令行警告 --><script src="../../backend/plugins/vue/vue.js"></script><!-- 引入组件库 --><script src="../../backend/plugins/element-ui/index.js"></script><!-- 引入vant样式 --><script src="./../js/vant.min.js"></script> <script src="./../js/common.js"></script><script src="./../api/address.js"></script><!-- 引入axios --><script src="../../backend/plugins/axios/axios.min.js"></script><script src="./../js/request.js"></script><script>new Vue({el:"#address_edit",data(){return {title:'新增收货地址',form:{consignee:'',//联系人phone:undefined,//手机号sex:'1',//0表示女 1 表示男detail:'',//收货地址label:'公司',//标签},labelList:['无','公司','家','学校'],id:undefined,activeIndex :0}},computed:{},created(){this.initData()},mounted(){},methods:{goBack(){history.go(-1)},async initData(){const params = parseUrl(window.location.search)this.id = params.idif(params.id){this.title = '编辑收货地址'const res = await addressFindOneApi(params.id)if(res.code === 1){this.form = res.data}else{this.$notify({ type:'warning', message:res.msg});}}},async saveAddress(){const form = this.formif(!form.consignee){this.$notify({ type:'warning', message:'请输入联系人'});return }if(!form.phone){this.$notify({ type:'warning', message:'请输入手机号'});return }if(!form.detail){this.$notify({ type:'warning', message:'请输入收货地址'});return }const reg = /^1[3|4|5|7|8][0-9]{9}$/if(!reg.test(form.phone)){this.$notify({ type:'warning', message:'手机号码不合法'});return }let res= {}if(this.id){res = await updateAddressApi(this.form)}else{res = await addAddressApi(this.form)}if(res.code === 1){window.requestAnimationFrame(()=>{window.location.replace('/front/page/address.html')})}else{this.$notify({ type:'warning', message:res.msg});}},deleteAddress(){this.$dialog.confirm({title: '确认删除',message: '确认要删除当前地址吗?',}).then( async () => {const res = await deleteAddressApi({ids:this.id })if(res.code === 1){window.requestAnimationFrame(()=>{window.location.replace('/front/page/address.html')})}else{this.$notify({ type:'warning', message:res.msg});}}).catch(() => {});},}})</script></body>
</html>
1.3.3js代码-新增收货地址
//新增地址
function addAddressApi(data){return $axios({'url': '/addressBook','method': 'post',data})
}
1.3.4js代码-修改地址
//修改地址
function updateAddressApi(data){return $axios({'url': '/addressBook','method': 'put',data})
}
1.3.5js代码-删除地址
//删除地址
function deleteAddressApi(params) {return $axios({'url': '/addressBook','method': 'delete',params})
}
1.4后端代码
1.4.1实体类AddressBook
package com.jq.entity;import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import java.io.Serializable;
import java.time.LocalDateTime;/*** 地址簿*/
@Data
public class AddressBook implements Serializable {private static final long serialVersionUID = 1L;private Long id;//用户idprivate Long userId;//收货人private String consignee;//手机号private String phone;//性别 0 女 1 男private String sex;//省级区划编号private String provinceCode;//省级名称private String provinceName;//市级区划编号private String cityCode;//市级名称private String cityName;//区级区划编号private String districtCode;//区级名称private String districtName;//详细地址private String detail;//标签private String label;//是否默认 0 否 1是private Integer isDefault;//创建时间@TableField(fill = FieldFill.INSERT)private LocalDateTime createTime;//更新时间@TableField(fill = FieldFill.INSERT_UPDATE)private LocalDateTime updateTime;//创建人@TableField(fill = FieldFill.INSERT)private Long createUser;//修改人@TableField(fill = FieldFill.INSERT_UPDATE)private Long updateUser;//是否删除private Integer isDeleted;
}
1.4.2Mapper接口 AddressBookMapper
package com.jq.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jq.entity.AddressBook;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface AddressBookMapper extends BaseMapper<AddressBook>{
}
1.4.3业务层接口AddressBookService
package com.jq.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.jq.entity.AddressBook;public interface AddressBookService extends IService<AddressBook> {
}
1.4.4业务层实现类AddressBookServicelmpl
package com.jq.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jq.entity.AddressBook;
import com.jq.mapper.AddressBookMapper;
import com.jq.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;@Slf4j
@Service
public class AddressBookServicelmpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {
}
1.4.5控制层AddressBookController
package com.jq.controller;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.jq.commom.BaseContext;
import com.jq.commom.R;
import com.jq.entity.AddressBook;
import com.jq.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;import java.util.List;@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {@Autowiredprivate AddressBookService addressBookService;/*** 新增*/@PostMappingpublic R<AddressBook> save(@RequestBody AddressBook addressBook) {addressBook.setUserId(BaseContext.getCurrentId());log.info("addressBook:{}", addressBook);addressBookService.save(addressBook);return R.success(addressBook);}/*** 设置默认地址*/@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);}/*** 根据id查询地址*/@GetMapping("/{id}")public R get(@PathVariable Long id) {AddressBook addressBook = addressBookService.getById(id);if (addressBook != null) {return R.success(addressBook);} else {return R.error("没有找到该对象");}}/*** 查询默认地址*/@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 = 1AddressBook addressBook = addressBookService.getOne(queryWrapper);if (null == addressBook) {return R.error("没有找到该对象");} else {return R.success(addressBook);}}/*** 查询指定用户的全部地址*/@GetMapping("/list")public R<List<AddressBook>> list(AddressBook addressBook) {addressBook.setUserId(BaseContext.getCurrentId());log.info("addressBook:{}", addressBook);//条件构造器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 descreturn R.success(addressBookService.list(queryWrapper));}
}
2.菜品展示功能
2.1需求分析
用户登录成功后跳转到系统首页,在首页需要根据分类来展示菜品和套餐。如果菜品设置了口味信息,需要展示【选择规格】按钮,否则显示【+】按钮。
2.1前后端交互流程分析
-
页面(front/index.html)发送ajax请求,获取分类数据(菜品分类和套餐分类)
//获取所有的菜品分类 function categoryListApi() {return $axios({'url': '/category/list','method': 'get',})}
-
页面发送ajax请求,获取第一个分类下的菜品或者套餐
//获取菜品分类对应的菜品 function dishListApi(data) {return $axios({'url': '/dish/list','method': 'get',params:{...data}}) }
开发菜品展示功能,其实就是在服务端编写代码去处理前端页面发送的这2次请求即可。
注意:首页加载完成后,还发送了一次ajax请求用于加载购物车数据,此处可以将这次请求的地址暂时修改一下,从静态json文件获取数据,等后续开发购物车功能时再修改回来,如下:
//获取购物车内商品的集合
function cartListApi(data) {return $axios({'url': '/shoppingCart/list',//'url': '/front/cartData.json','method': 'get',params:{...data}})
}
2.3前端代码
2.3.1front/index.html页面代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"><title>菩提阁</title><link rel="icon" href="images/favico.ico"><!--不同屏幕尺寸根字体设置--><script src="./js/base.js"></script><!--element-ui的样式--><link rel="stylesheet" href="../backend/plugins/element-ui/index.css" /><!--引入vant样式--><link rel="stylesheet" href="styles/vant.min.css"/><!-- 引入样式 --><link rel="stylesheet" href="styles/index.css" /><!--本页面内容的样式--><link rel="stylesheet" href="styles/main.css" /></head><body><div id="main" class="app"><div class="divHead"><img src="./images/user.png" @click="toUserPage"/></div><div class="divTitle"><div class="divStatic"><img src="./images/logo.png" class="logo"/><div class="divDesc"><div class="divName">菩提阁餐厅</div><div class="divSend"><span><img src="./images/time.png"/> 距离1.5km</span><span><img src="./images/money.png"/> 配送费6元</span><span><img src="./images/location.png"/> 预计时长12min</span></div></div></div><div class="divDesc">简介: 菩提阁中餐厅是菩提阁点餐的独立的品牌,定位“大众 化的美食外送餐饮”,旨为顾客打造专业美食。</div></div><div class="divBody"><div class="divType"><ul><li v-for="(item,index) in categoryList" :key="index" @click="categoryClick(index,item.id,item.type)" :class="{active:activeType === index}">{{item.name}}</li></ul></div><div class="divMenu"><div><div class="divItem" v-for="(item,index) in dishList" :key="index" @click="dishDetails(item)"><el-image :src="imgPathConvert(item.image)" ><div slot="error" class="image-slot"><img src="./images/noImg.png"/></div></el-image><div><div class="divName">{{item.name}}</div><div class="divDesc">{{item.description}}</div><div class="divDesc">{{'月销' + (item.saleNum ? item.saleNum : 0) }}</div><div class="divBottom"><span>¥</span><span>{{item.price/100}}</span></div><div class="divNum"><div class="divSubtract" v-if="item.number > 0"><img src="./images/subtract.png" @click.prevent.stop="subtractCart(item)"/></div><div class="divDishNum">{{item.number}}</div><div class="divTypes" v-if="item.flavors && item.flavors.length > 0 && !item.number " @click.prevent.stop="chooseFlavorClick(item)">选择规格</div><div class="divAdd" v-else><img src="./images/add.png" @click.prevent.stop="addCart(item)"/></div></div></div></div></div></div></div><div class="divLayer"><div class="divLayerLeft"></div><div class="divLayerRight"></div></div><div class="divCart" v-if="categoryList.length > 0"><div :class="{imgCartActive: cartData && cartData.length > 0, imgCart:!cartData || cartData.length<1}" @click="openCart"></div><div :class="{divGoodsNum:1===1, moreGoods:cartData && cartData.length > 99}" v-if="cartData && cartData.length > 0">{{ goodsNum }}</div><div class="divNum"><span>¥</span><span>{{goodsPrice}}</span></div><div class="divPrice"></div><div :class="{btnSubmitActive: cartData && cartData.length > 0, btnSubmit:!cartData || cartData.length<1}" @click="toAddOrderPage">去结算</div></div><van-dialog v-model="dialogFlavor.show" :show-confirm-button="false" class="dialogFlavor" ref="flavorDialog"><div class="dialogTitle">{{dialogFlavor.name}}</div><div class="divContent"><div v-for="flavor in dialogFlavor.flavors" :key="flavor.id"><div class="divFlavorTitle">{{flavor.name}}</div><span v-for="item in JSON.parse(flavor.value)" :key="item" @click="flavorClick(flavor,item)":class="{spanActive:flavor.dishFlavor === item}">{{item}}</span></div></div><div class="divBottom"><div><span class="spanMoney">¥</span>{{dialogFlavor.price/100}}</div><div @click="dialogFlavorAddCart">加入购物车</div></div><div class="divFlavorClose" @click="dialogFlavor.show = false"><img src="./images/close.png"/></div></van-dialog><van-popup v-model="cartDialogShow" position="bottom" :style="{ height: '50%' }" class="dialogCart"><div class="divCartTitle"><div class="title">购物车</div><div class="clear" @click="clearCart"><i class="el-icon-delete"></i> 清空</div></div><div class="divCartContent"><div v-for="item in cartData" :key="item.id" class="divCartItem"><el-image :src="imgPathConvert(item.image)" ><div slot="error" class="image-slot"><img src="./images/noImg.png"/></div></el-image><div class="divDesc"><div class="name">{{item.name}}</div><div class="price"><span class="spanMoney">¥</span>{{item.amount}}</div></div><div class="divNum"><div class="divSubtract"><img src="./images/subtract.png" @click="cartNumberSubtract(item)"/></div><div class="divDishNum">{{item.number}}</div><div class="divAdd"><img src="./images/add.png" @click="cartNumAdd(item)"/></div></div><div class="divSplit"></div></div></div></van-popup><van-dialog v-model="detailsDialog.show" :show-confirm-button="false" class="detailsDialog" ref="detailsDialog"v-if="detailsDialog.show"><div class="divContainer"><el-image :src="imgPathConvert(detailsDialog.item.image)" ><div slot="error" class="image-slot"><img src="./images/noImg.png"/></div></el-image><div class="title">{{detailsDialog.item.name}}</div><div class="content">{{detailsDialog.item.description}}</div></div><div class="divNum"><div class="left"><span>¥</span><span>{{detailsDialog.item.price/100}}</span></div><div class="right"><div class="divSubtract" v-if="detailsDialog.item.number > 0"><img src="./images/subtract.png" @click="subtractCart(detailsDialog.item)"/></div><div class="divDishNum">{{detailsDialog.item.number}}</div><div class="divTypes" v-if="detailsDialog.item.flavors && detailsDialog.item.flavors.length > 0 && !detailsDialog.item.number " @click ="chooseFlavorClick(detailsDialog.item)">选择规格</div><div class="divAdd" v-else><img src="./images/add.png" @click="addCart(detailsDialog.item)"/></div></div></div><div class="detailsDialogClose" @click="detailsDialog.show = false"><img src="./images/close.png"/></div></van-dialog><van-dialog v-model="setMealDialog.show" :show-confirm-button="false" class="setMealDetailsDialog" ref="setMealDetailsDialogd"v-if="setMealDialog.show"><div class="divContainer"><div class="title">{{setMealDialog.item.name}}</div><div class="item" v-for="(item,index) in setMealDialog.item.list" :key="index"><el-image :src="imgPathConvert(item.image)"><div slot="error" class="image-slot"><img src="./images/noImg.png"/></div></el-image><div class="divSubTitle">{{item.name + '(' + item.copies + '份)' }}<div class="divPrice"><span>¥</span><span>{{item.price/100}}</span></div></div> <div class="content">{{item.description}}</div></div></div><div class="divNum"><div class="left"><span>¥</span><span>{{setMealDialog.item.price/100}}</span></div><div class="right"><div class="divSubtract" v-if="setMealDialog.item.number > 0"><img src="./images/subtract.png" @click="subtractCart(setMealDialog.item)"/></div><div class="divDishNum">{{setMealDialog.item.number}}</div><div class="divAdd" v-if="setMealDialog.item.number"><img src="./images/add.png" @click="addCart(setMealDialog.item)"/></div><div class="addCart" @click="addCart(setMealDialog.item)" v-if="!setMealDialog.item.number">加入购物车</div></div></div><div class="detailsDialogClose" @click="setMealDialog.show = false"><img src="./images/close.png"/></div></van-dialog></div><!-- 开发环境版本,包含了有帮助的命令行警告 --><script src="../backend/plugins/vue/vue.js"></script><!-- 引入组件库 --><script src="../backend/plugins/element-ui/index.js"></script><!-- 引入vant样式 --><script src="./js/vant.min.js"></script> <!-- 引入axios --><script src="../backend/plugins/axios/axios.min.js"></script><script src="./js/request.js"></script><script src="./js/common.js"></script><script src="./api/main.js"></script></body><script>new Vue({el:'#main',data(){return {//左边菜品类别indexactiveType:0,categoryList:[],categoryId:undefined,dishList:[],cartData:[],dialogFlavor:{name:'',flavors:[],dishId:undefined,price:undefined,show:false,image:''},cartDialogShow:false,detailsDialog:{show:false,item:{image:''}},setMealDialog:{show:false,item:{}},}},computed:{goodsNum(){let num = 0this.cartData.forEach(item=>{num += item.number })if(num <99){return num}else{return '99+'}},goodsPrice(){let price = 0this.cartData.forEach(item=>{price += (item.number * item.amount)})return price}},created(){},watch:{'dialogFlavor.show'(flag){if(flag){document.querySelector('.divCart').style.zIndex = 1}else{document.querySelector('.divCart').style.zIndex = 3000}},},mounted(){this.initData()},methods:{//初始化数据initData(){Promise.all([categoryListApi(),cartListApi({})]).then(res=>{//获取分类数据if(res[0].code === 1){this.categoryList = res[0].dataif(Array.isArray(res[0].data) && res[0].data.length > 0){this.categoryId = res[0].data[0].idif(res[0].data[0].type === 1){this.getDishList()}else{this.getSetmealData()}}}else{this.$notify({ type:'warning', message:res[0].msg});}//获取菜品数据if(res[1].code === 1){this.cartData = res[1].data}else{this.$notify({ type:'warning', message:res[1].msg});}})},//分类点击categoryClick(index,id,type){this.activeType = indexthis.categoryId = idif(type === 1){//菜品this.getDishList()}else{this.getSetmealData()}},//获取菜品数据async getDishList(){if(!this.categoryId){return}const res = await dishListApi({categoryId:this.categoryId,status:1})if(res.code === 1){let dishList = res.dataconst cartData = this.cartDataif(dishList.length > 0 && cartData.length > 0){dishList.forEach(dish=>{cartData.forEach(cart=>{if(dish.id === cart.dishId){dish.number = cart.number}})})}this.dishList = dishList}else{this.$notify({ type:'warning', message:res.msg});}},//获取套餐数据setmealIdasync getSetmealData(){if(!this.categoryId){return}const res = await setmealListApi({categoryId:this.categoryId,status:1})if(res.code === 1){let dishList = res.dataconst cartData = this.cartDataif(dishList.length > 0 && cartData.length > 0){dishList.forEach(dish=>{cartData.forEach(cart=>{if(dish.id === cart.setmealId){dish.number = cart.number}})})}this.dishList = dishList}else{this.$notify({ type:'warning', message:res.msg});}},//获取购物车数据async getCartData(){const res = await cartListApi({})if(res.code === 1){this.cartData = res.data}else{this.$notify({ type:'warning', message:res.msg});}},//菜单中往购物车中添加商品async addCart(item){let params = {amount:item.price/100,//金额dishFlavor:item.dishFlavor,//口味 如果没有传undefineddishId:undefined,//菜品idsetmealId:undefined,//套餐idname:item.name,image:item.image}if(Array.isArray(item.flavors)){//表示是菜品params.dishId = item.id}else{//表示套餐 套餐没有口味params.setmealId = item.id}const res = await addCartApi(params)if(res.code === 1){this.dishList.forEach(dish=>{if(dish.id === item.id){dish.number = res.data.number}})if(this.setMealDialog.show){item.number = res.data.number}this.getCartData()}else{this.$notify({ type:'warning', message:res.msg});}},//菜单中减少选中的商品async subtractCart(item){let params = {dishId:item.id,}if(!Array.isArray(item.flavors)){params = {setmealId:item.id,}}const res = await updateCartApi(params)if(res.code === 1){this.dishList.forEach(dish=>{if(dish.id === item.id){dish.number = (res.data.number === 0 ? undefined : res.data.number)}})if(this.setMealDialog.show){item.number = (res.data.number === 0 ? undefined : res.data.number)}this.getCartData()}else{this.$notify({ type:'warning', message:res.msg});}},//展开购物车openCart(){if(this.cartData.length > 0){this.cartDialogShow = true}},//购物车中增加商品数量async cartNumAdd(item){let params = {amount:item.amount,//金额dishFlavor:item.dishFlavor,//口味 如果没有传undefineddishId:item.dishId,//菜品idsetmealId:item.setmealId,//套餐idname:item.name,image:item.image}const res = await addCartApi(params)if(res.code === 1){this.dishList.forEach(dish=>{if(dish.id === (item.dishId || item.setmealId)){dish.number = res.data.number}})console.log(this.dishList)this.getCartData()}else{this.$notify({ type:'warning', message:res.msg});}},//购物车中减少商品数量async cartNumberSubtract(item){let params = {dishId:item.dishId,setmealId:item.setmealId,}const res = await updateCartApi(params)if(res.code === 1){this.dishList.forEach(dish=>{if(dish.id === (item.dishId || item.setmealId)){dish.number = (res.data.number === 0 ? undefined : res.data.number)}})this.getCartData()}else{this.$notify({ type:'warning', message:res.msg});}},//修改商品列表中的数据numberchangeDishList(item){for(let ele of this.dishList){if(ele.id === (item.setmealId || item.dishId)){ele.number = item.number}}},//清空购物车async clearCart(){const res = await clearCartApi()if(res.code === 1){for(let ele of this.dishList){ele.number = undefined}this.cartData = []this.cartDialogShow = false}else{this.$notify({ type:'warning', message:res.msg});}},//点击选择规格chooseFlavorClick(item){this.dialogFlavor = {name:'',flavors:[],dishId:undefined,price:undefined,show:false}this.dialogFlavor={name:item.name,flavors:item.flavors,dishId:item.id,price:item.price,show:true,image:item.image}},flavorClick(flavor,item){flavor.dishFlavor = item//强制刷新dialog的domthis.dialogFlavor.show = falsethis.dialogFlavor.show = true},//选择规格加入购物车dialogFlavorAddCart(){const dialogFlavor = this.dialogFlavorlet flag = truelet dishFlavor = []dialogFlavor.flavors.forEach(item=>{if(item.dishFlavor){dishFlavor.push(item.dishFlavor)}else{flag = falseNotify({ type: 'warning', message: '请选择'+ item.name });}})if(flag){this.addCart({price:dialogFlavor.price,dishFlavor:dishFlavor.join(","),id:dialogFlavor.dishId,flavors:[],image:dialogFlavor.image,name:dialogFlavor.name})this.dialogFlavor.show = false}},//网络图片路径转换imgPathConvert(path){return imgPath(path)},//跳转到去结算界面toAddOrderPage(){if(this.cartData.length > 0){window.requestAnimationFrame(()=>{window.location.href ='/front/page/add-order.html'})}},toUserPage(){window.requestAnimationFrame(()=>{window.location.href= '/front/page/user.html'})},async dishDetails(item){//先清除对象数据,如果不行的话dialog使用v-ifthis.detailsDialog.item = {}this.setMealDialog.item = {}if(Array.isArray(item.flavors)){this.detailsDialog.item = itemthis.detailsDialog.show = true}else{//显示套餐的数据const res = await setMealDishDetailsApi(item.id)if(res.code === 1){this.setMealDialog.item = {...item,list:res.data}this.setMealDialog.show = true}else{this.$notify({ type:'warning', message:res.msg});}}}}})</script></html>
2.4后端代码
2.4.1 改造DishController下代码
根据条件查询对应的菜品数据和菜品口味数据
@GetMapping("/list")public R<List<DishDto>> list(Dish dish){//构早查询条件LambdaQueryWrapper<Dish>dishLambdaQueryWrapper=new LambdaQueryWrapper<>();dishLambdaQueryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());//添加排序条件dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);//添加查询调价,状态为1 在售的菜品dishLambdaQueryWrapper.eq(Dish::getStatus,1);//执行查询List<Dish> list = dishService.list(dishLambdaQueryWrapper);List<DishDto>dishDtoList=list.stream().map((item)->{ //item 为dish 实体类对应的项DishDto dishDto = new DishDto();BeanUtils.copyProperties(item,dishDto);Long categoryId = item.getCategoryId(); //分类categoryId在 dish实体类里面//根据categoryId查询分类对象Category category = categoryService.getById(categoryId);if (category!=null){String categoryName = category.getName();//分类名称在 category实体类里面dishDto.setCategoryName(categoryName); //给实体类 dishDto的categoryName赋值}//当前菜品的idLong dishId = item.getId();LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper=new LambdaQueryWrapper<>();dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishId);//菜品的口味List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);dishDto.setFlavors(dishFlavorList);return dishDto;}).collect(Collectors.toList());return R.success(dishDtoList);}
2.4.2SetmealController ,加入根据分类id 查询套餐信息 代码
/*** 根据条件查询套餐数据* @param setmeal* @return*/@GetMapping("/list")public R<List<Setmeal>>list(Setmeal setmeal){LambdaQueryWrapper<Setmeal>queryWrapper=new LambdaQueryWrapper<>();queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());queryWrapper.eq(setmeal.getStatus()!=null,Setmeal::getStatus,setmeal.getStatus());queryWrapper.orderByDesc(Setmeal::getUpdateTime);List<Setmeal> list = setmealService.list();return R.success(list);}
3.购物车功能
3.1需求分析
移动端用户可以将菜品或者套餐添加到购物车。
- 对于菜品来说,如果设置了口味信息,则需要【选择规格】后才能加入购物车;
- 对于套餐来说,可以直接点击【+】将当前套餐加入购物车。在购物车中可以修改菜品和套餐的数量,
- 也可以清空购物车。
3.2数据模型
购物车对应的数据表为shopping_cart
3.3前后端交互流程分析
- 点击【加入购物车】 或者【+】按钮,页面发送ajax请求,请求服务端,将菜品或者套餐添加到购物车
- 点击购物车图标,页面发送ajax请求,请求服务端查询购物车中的菜品和套餐
- 点击清空购物车按钮,页面发送ajax请求,请求服务端来执行清空购物车操作
开发购物车功能,其实就是在服务端编写代码去处理前端页面发送的这3次请求即可。
3.4前端代码
3.4.1页面代码为front/index.html
3.4.2js代码-获取购物车内商品的集合
//获取购物车内商品的集合
function cartListApi(data) {return $axios({'url': '/shoppingCart/list',//'url': '/front/cartData.json','method': 'get',params:{...data}})
}
3.4.3js代码-购物车中添加商品
//购物车中添加商品
function addCartApi(data){return $axios({'url': '/shoppingCart/add','method': 'post',data})
}
3.4.4js代码-购物车中修改商品
//购物车中修改商品
function updateCartApi(data){return $axios({'url': '/shoppingCart/sub','method': 'post',data})
}
3.4.5js代码-删除购物车的商品
//删除购物车的商品
function clearCartApi() {return $axios({'url': '/shoppingCart/clean','method': 'delete',})
}
3.5后端代码-准备
3.5.1实体类ShoppingCart
package com.jq.entity;import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;/*** 购物车*/
@Data
public class ShoppingCart implements Serializable {private static final long serialVersionUID = 1L;private Long id;//名称private String name;//用户idprivate Long userId;//菜品idprivate Long dishId;//套餐idprivate Long setmealId;//口味private String dishFlavor;//数量private Integer number;//金额private BigDecimal amount;//图片private String image;private LocalDateTime createTime;
}
3.5.2Mapper接口 ShoppingCartMapper
package com.jq.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jq.entity.ShoppingCart;
import org.apache.ibatis.annotations.Mapper;@Mapper
public interface ShoppingCartMapper extends BaseMapper<ShoppingCart> {
}
3.5.3业务层接口ShoppingCartService
package com.jq.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.jq.entity.ShoppingCart;public interface ShoppingCartService extends IService<ShoppingCart> {
}
3.5.4业务层实现类ShoppingCartServicelmpl
package com.jq.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jq.entity.ShoppingCart;
import com.jq.mapper.ShoppingCartMapper;
import com.jq.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;@Slf4j
@Service
public class ShoppingCartServicelmpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {
}
3.5.5控制层 ShoppingCartController
package com.jq.controller;import com.jq.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {@Autowiredprivate ShoppingCartService shoppingCartService;
}
3.6后端代码-正式开发
3.6.1 添加菜品或套餐到购物车代码实现
/*** 添加购物车* @param shoppingCart* @return*/@PostMapping("/add")public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){log.info("购物车数据:{}",shoppingCart);//1.设置用户id,指定当前是哪个用户的购物车数据Long currentId = BaseContext.getCurrentId();shoppingCart.setUserId(currentId);//2.根据userID和DishId 查询当前添加的菜品或套餐有没有在购物车中Long dishId = shoppingCart.getDishId();//添加查询条件,userIDLambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();queryWrapper.eq(ShoppingCart::getUserId,currentId);//判断加入的是菜品还是套餐if(dishId!=null){//添加到购物车的是菜品,查询条件 查询加入的菜品是否在购物车queryWrapper.eq(ShoppingCart::getDishId,dishId);}else {//添加到购物车的是套餐,查询条件 加入的套餐是否在购物车queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCart.getSetmealId());}//执行查询,查询当前添加的菜品或套餐有没有在购物车中ShoppingCart cartServiceOne = shoppingCartService.getOne(queryWrapper);if (cartServiceOne != null){// 如果已经加入购物车,number+1Integer number = cartServiceOne.getNumber();cartServiceOne.setNumber(number + 1);shoppingCartService.updateById(cartServiceOne);}else {// 如果没有在购物车,则添加到购物车,数量默认是1shoppingCart.setNumber(1);shoppingCart.setCreateTime(LocalDateTime.now());shoppingCartService.save(shoppingCart);cartServiceOne=shoppingCart;}return R.success(cartServiceOne);}
3.6.2获取购物车数据
/*** 查看购物车数据* @return*/@GetMapping("/list")public R<List<ShoppingCart>>list(){log.info("查看购物车...");LambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();// 不同的用户拥有不同的购物车,根据用户id查询购物车数据queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());queryWrapper.orderByAsc(ShoppingCart::getCreateTime);List<ShoppingCart> list = shoppingCartService.list(queryWrapper);return R.success(list);}
3.6.3清空购物车
/*** 清空购物车* @return*/@DeleteMapping("/clean")public R<String> clean(){//SQL:delete from shopping_cart where user_id = ?LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.eq(ShoppingCart::getUserId,BaseContext.getCurrentId());shoppingCartService.remove(queryWrapper);return R.success("清空购物车成功");}
4.用户下单功能
4.1需求分析
移动端用户将菜品或者套餐加入购物车后,可以点击购物车中的【去结算】按钮,页面跳转到订单确认页面,点击【去结算】按钮则完成下单操作。
4.2数据模型
用户下单业务对应的数据表为
- orders: 订单表
- order_detail:订单明细表
4.3前后端交互流程
代码开发梳理交互过程
在开发代码之前,需要梳理-下用户下单操作时前端页面和服务端的交互过程:
-
在购物车中点击【去结算】按钮,页面跳转到订单确认页面
-
在订单确认页面,发送ajax请求,请求服务端获取当前登录用户的默认地址
-
在订单确认页面,发送ajax请求,请求服务端获取当前登录用户的购物车数据
-
在订单确认页面点击【去支付】按钮,发送ajax请求,请求服务端完成下单操作
开发用户下单功能,其实就是在服务端编写代码去处理前端页面发送的请求即可。
4.3前端代码
4.3.1支付页面代码
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui"><title>菩提阁</title><link rel="icon" href="./../images/favico.ico"><!--不同屏幕尺寸根字体设置--><script src="./../js/base.js"></script><!--element-ui的样式--><link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" /><!--引入vant样式--><link rel="stylesheet" href="../styles/vant.min.css"/><!-- 引入样式 --><link rel="stylesheet" href="../styles/index.css" /><!--本页面内容的样式--><link rel="stylesheet" href="./../styles/add-order.css" /></head><body><div id="add_order" class="app"><div class="divHead"><div class="divTitle"><i class="el-icon-arrow-left" @click="goBack"></i>菩提阁</div></div><div class="divContent"><div class="divAddress"><div @click="toAddressPage"> <div class="address">{{address.detail}}</div><div class="name"><span>{{address.consignee}}{{address.sex === '1' ? '先生':'女士'}}</span><span>{{address.phone}}</span></div><i class="el-icon-arrow-right"></i></div><div class="divSplit"></div><div class="divFinishTime">预计{{finishTime}}送达</div></div><div class="order"><div class="title">订单明细</div><div class="divSplit"></div><div class="itemList"><div class="item" v-for="(item,index) in cartData" :key="index"><el-image :src="imgPathConvert(item.image)"><div slot="error" class="image-slot"><img src="./../images/noImg.png"/></div></el-image><div class="desc"><div class="name">{{item.name}}</div><div class="numPrice"><span class="num">x{{item.number}}</span><div class="price"><span class="spanMoney">¥</span>{{item.amount}}</div></div></div></div></div></div><div class="note"><div class="title">备注</div><van-fieldv-model="note"rows="2"autosizetype="textarea"maxlength="50"placeholder="请输入您需要备注的信息"show-word-limit/></div></div><div class="divCart"><div :class="{imgCartActive: cartData && cartData.length > 0, imgCart:!cartData || cartData.length<1}"></div><div :class="{divGoodsNum:1===1, moreGoods:cartData && cartData.length > 99}" v-if="cartData && cartData.length > 0">{{ goodsNum }}</div><div class="divNum"><span>¥</span><span>{{goodsPrice}}</span></div><div class="divPrice"></div><div :class="{btnSubmitActive: cartData && cartData.length > 0, btnSubmit:!cartData || cartData.length<1}" @click="goToPaySuccess">去支付</div></div></div><!-- 开发环境版本,包含了有帮助的命令行警告 --><script src="../../backend/plugins/vue/vue.js"></script><!-- 引入组件库 --><script src="../../backend/plugins/element-ui/index.js"></script><!-- 引入vant样式 --><script src="./../js/vant.min.js"></script> <script src="./../api/address.js"></script><!-- 引入axios --><script src="../../backend/plugins/axios/axios.min.js"></script><script src="./../js/request.js"></script><script src="./../js/common.js"></script><script src="./../api/main.js"></script><script src="./../api/order.js"></script><script>new Vue({el:"#add_order",data(){return {address:{phone:'',//手机号consignee:'',//姓名detail:'',//详细地址sex:'1',id:undefined},finishTime:'',//送达时间cartData:[],note:''//备注信息}},computed:{goodsNum(){let num = 0this.cartData.forEach(item=>{num += item.number })if(num <99){return num}else{return '99+'}},goodsPrice(){let price = 0this.cartData.forEach(item=>{price += (item.number * item.amount)})return price}},created(){this.initData()},mounted(){},methods:{goBack(){history.go(-1)},initData(){//获取默认的地址this.defaultAddress()//获取购物车的商品this.getCartData()},//获取默认地址async defaultAddress(){const res = await getDefaultAddressApi()if(res.code === 1){this.address = res.datathis.getFinishTime()}else{window.requestAnimationFrame(()=>{window.location.href = '/front/page/address-edit.html'})}},//获取送达时间getFinishTime(){let now = new Date()let hour = now.getHours() +1let minute = now.getMinutes()if(hour.toString().length <2){hour = '0' + hour}if(minute.toString().length <2){minute = '0' + minute}this.finishTime = hour + ':' + minute},toAddressPage(){window.requestAnimationFrame(()=>{window.location.href = '/front/page/address.html'})},//获取购物车数据async getCartData(){const res = await cartListApi({})if(res.code === 1){this.cartData = res.data}else{this.$notify({ type:'warning', message:res.msg});}},async goToPaySuccess(){const params = {remark:this.note,payMethod:1,addressBookId:this.address.id}const res = await addOrderApi(params)if(res.code === 1){window.requestAnimationFrame(()=>{window.location.replace('/front/page/pay-success.html')})}else{this.$notify({ type:'warning', message:res.msg});}},//网络图片路径转换imgPathConvert(path){return imgPath(path)},}})</script></body></html>
4.3. js代码-订单确认页面点击【去支付】按钮,发送ajax请求
//提交订单
function addOrderApi(data){return $axios({'url': '/order/submit','method': 'post',data})
}
4.4后端代码-准备
4.4.1实体类Orders、OrderDetail
-
实体类Orders
package com.jq.entity;import lombok.Data;import java.io.Serializable;import java.math.BigDecimal;import java.time.LocalDateTime;/*** 订单*/@Datapublic class Orders implements Serializable {private static final long serialVersionUID = 1L;private Long id;//订单号private String number;//订单状态 1待付款,2待派送,3已派送,4已完成,5已取消private Integer status;//下单用户idprivate Long userId;//地址idprivate Long addressBookId;//下单时间private LocalDateTime orderTime;//结账时间private LocalDateTime checkoutTime;//支付方式 1微信,2支付宝private Integer payMethod;//实收金额private BigDecimal amount;//备注private String remark;//用户名private String userName;//手机号private String phone;//地址private String address;//收货人private String consignee;}```
-
实体类OrderDetail
package com.jq.entity;import com.baomidou.mybatisplus.annotation.IdType;import com.baomidou.mybatisplus.annotation.TableId;import lombok.Data;import java.io.Serializable;import java.math.BigDecimal;/*** 订单明细*/@Datapublic class OrderDetail implements Serializable {private static final long serialVersionUID = 1L;private Long id;//名称private String name;//订单idprivate Long orderId;//菜品idprivate Long dishId;//套餐idprivate Long setmealId;//口味private String dishFlavor;//数量private Integer number;//金额private BigDecimal amount;//图片private String image;}```
4.4.2Mapper接 口OrderMapper、OrderDetailMapper
-
Mapper接口OrderMapper
package com.jq.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.jq.entity.Orders; import org.apache.ibatis.annotations.Mapper;@Mapper public interface OrderMapper extends BaseMapper<Orders> { }
-
Mapper接口OrderDetailMapper
package com.jq.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.jq.entity.OrderDetail; import org.apache.ibatis.annotations.Mapper;@Mapper public interface OrderDetailMapper extends BaseMapper<OrderDetail> { }
4.4.3业务层接口OrderService、OrderDetailService
-
业务层接口OrderService
package com.jq.service;import com.baomidou.mybatisplus.extension.service.IService; import com.jq.entity.Orders;public interface OrderService extends IService<Orders> { }
-
业务层接口OrderDetailService
package com.jq.service;import com.baomidou.mybatisplus.extension.service.IService; import com.jq.entity.OrderDetail;public interface OrderDetailService extends IService<OrderDetail> { }
4.4.4业务层实现类OrderServicelmpl、OrderDetailServicelmpl
-
业务层实现类OrderServicelmpl
package com.jq.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.jq.entity.Orders; import com.jq.mapper.OrderMapper; import com.jq.service.OrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service;@Slf4j @Service public class OrderServicelmpl extends ServiceImpl<OrderMapper, Orders> implements OrderService { }
-
业务层实现类OrderDetailServicelmpl
package com.jq.service.impl;import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.jq.entity.OrderDetail; import com.jq.mapper.OrderDetailMapper; import com.jq.service.OrderDetailService; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service;@Slf4j @Service public class OrderDetailServicelmpl extends ServiceImpl<OrderDetailMapper, OrderDetail>implements OrderDetailService { }
4.4.5控制层OrderController、OrderDetailController
-
控制层OrderController
package com.jq.controller;import com.jq.service.OrderService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;/*** 订单*/ @Slf4j @RestController @RequestMapping("/order") public class OrderController {@Autowiredprivate OrderService orderService;}
-
控制层OrderDetailController
package com.jq.controller;import com.jq.service.OrderDetailService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;@Slf4j @RestController @RequestMapping("/orderDetail") public class OrderDetailController {@Autowiredprivate OrderDetailService orderDetailService; }
4.5后端代码-正式开发
package com.jq.service.impl;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jq.commom.BaseContext;
import com.jq.commom.CustomException;
import com.jq.entity.*;
import com.jq.mapper.OrderMapper;
import com.jq.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;@Slf4j
@Service
public class OrderServicelmpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {@Autowiredprivate ShoppingCartService shoppingCartService;@Autowiredprivate UserService userService;@Autowiredprivate AddressBookService addressBookService;@Autowiredprivate OrderDetailService orderDetailService;/*** 用户下单方法实现* @param orders*/@Transactional@Overridepublic void submit(Orders orders) {//1.获取当前用户的idLong currentUserId = BaseContext.getCurrentId();//2.查询当前用户的购物车LambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();queryWrapper.eq(ShoppingCart::getUserId,currentUserId);List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);//如果购物车为空,就没必要执行下单操作if (shoppingCartList==null || shoppingCartList.size()==0){throw new CustomException("购物车为空,不能下单,请先加入商品");}//3.查询用户数据User user = userService.getById(currentUserId);//4.查询地址数据Long addressBookId = orders.getAddressBookId();AddressBook addressBook = addressBookService.getById(addressBookId);//如果地址信息为空,无法执行下单操作if (shoppingCartList==null || shoppingCartList.size()==0){throw new CustomException("地址信息为空,无法执行下单操作,请先添加收货地址");}long orderId = IdWorker.getId();//订单号//遍历购物车数据,计算订单明细,计算总金额amountAtomicInteger amount= new AtomicInteger(0);List<OrderDetail> orderDetailList = shoppingCartList.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());//5.完成下单,向订单表中,插入一条数据orders.setId(orderId);orders.setOrderTime(LocalDateTime.now());orders.setCheckoutTime(LocalDateTime.now());orders.setStatus(2);orders.setAmount(new BigDecimal(amount.get()));//总金额orders.setUserId(currentUserId);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()));this.save(orders);//5.完成下单,向订单明细表中,插入一/多条数据orderDetailService.saveBatch(orderDetailList);//6.下单完成后,清空购物车中对应数据shoppingCartService.remove(queryWrapper);}
}
这篇关于瑞吉外卖项目学习笔记:P19-移动端-收货地址|菜品展示业|购物车|用户下单页务功能开发的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!