Merge remote-tracking branch 'origin/master'

# Conflicts:
#	order/order-service-impl/src/main/java/cn/iocoder/mall/order/biz/service/OrderReturnServiceImpl.java
This commit is contained in:
sin 2019-05-08 21:34:03 +08:00
commit de9f191c30
81 changed files with 2444 additions and 526 deletions

View File

@ -25,4 +25,16 @@ export default {
changeOrigin: true,
pathRewrite: {},
},
'/user-api/': {
// target: 'http://180.167.213.26:18085/',
target: 'http://127.0.0.1:18082/',
changeOrigin: true,
pathRewrite: {},
},
'/pay-api/': {
// target: 'http://180.167.213.26:18085/',
target: 'http://127.0.0.1:18084/',
changeOrigin: true,
pathRewrite: {},
},
};

View File

@ -6,11 +6,21 @@ export default {
changeOrigin: true,
pathRewrite: {},
},
'/product-api/': {
target: 'http://api.shop.iocoder.cn:18099/product-api',
changeOrigin: true,
pathRewrite: {},
},
'/order-api/': {
target: 'http://api.shop.iocoder.cn:18099/order-api',
changeOrigin: true,
pathRewrite: {},
},
'/promotion-api/': {
target: 'http://api.shop.iocoder.cn:18099/promotion-api',
changeOrigin: true,
pathRewrite: {},
},
'/pay-api/': {
target: 'http://api.shop.iocoder.cn:18099/pay-api',
changeOrigin: true,

View File

@ -58,6 +58,19 @@ export default [
},
],
},
// user
{
path: '/member', // TODO 芋艿,后面调整
name: 'user',
icon: 'user',
routes: [
{
path: '/member/user-list',
name: 'user-list',
component: './User/UserList',
},
],
},
// order
{
path: 'order',
@ -142,6 +155,24 @@ export default [
}
],
},
// pay
{
path: '/pay',
name: 'pay',
icon: 'user',
routes: [
{
path: '/pay/transaction-list',
name: 'pay-transaction-list',
component: './Pay/PayTransactionList',
},
{
path: '/pay/refund-list',
name: 'pay-refund-list',
component: './Pay/PayRefundList',
},
],
},
{
path: '/dashboard',
name: 'dashboard',

View File

@ -60,4 +60,9 @@ export default {
'menu.promotion.coupon-card-template-list': '优惠劵管理',
'menu.promotion.time-limit-discount-list': '限时折扣',
'menu.promotion.full-privilege-list': '满减送',
// 会员相关
'menu.user.user-list': '会员资料',
// 支付相关
'menu.pay.pay-transaction-list': '支付单',
'menu.pay.pay-refund-list': '退款单',
};

View File

@ -0,0 +1,97 @@
import { message } from 'antd';
import { productSpuPage, productSpuUpdateSort } from '../../services/product';
import {routerRedux} from "dva/router";
import PaginationHelper from '../../../helpers/PaginationHelper';
import {getPromotionActivityPage} from "../../services/promotion";
import {queryPayRefundPage, queryPayTransactionPage} from "../../services/pay";
const SEARCH_PARAMS_DEFAULT = {
createBeginTime: undefined,
createEndTime: undefined,
finishBeginTime: undefined,
finishEndTime: undefined,
status: undefined,
payChannel: undefined,
};
export default {
namespace: 'payRefundList',
state: {
// 分页列表相关
list: [],
listLoading: false,
pagination: PaginationHelper.defaultPaginationConfig,
searchParams: SEARCH_PARAMS_DEFAULT,
// 添加 or 修改表单相关
},
effects: {
*page({ payload }, { call, put }) {
// const { queryParams } = payload;
// const response = yield call(productSpuPage, payload);
// message.info('查询成功!');
// yield put({
// type: 'treeSuccess',
// payload: {
// list: response.data,
// },
// });
// 显示加载中
yield put({
type: 'changeListLoading',
payload: true,
});
// 请求
const response = yield call(queryPayRefundPage, payload);
// 响应
yield put({
type: 'setAll',
payload: {
list: response.data.list,
pagination: PaginationHelper.formatPagination(response.data, payload),
searchParams: {
createBeginTime: payload.createBeginTime,
createEndTime: payload.createEndTime,
finishBeginTime: payload.finishBeginTime,
finishEndTime: payload.finishEndTime,
status: payload.status,
payChannel: payload.payChannel,
}
},
});
// 隐藏加载中
yield put({
type: 'changeListLoading',
payload: false,
});
},
},
reducers: {
treeSuccess(state, { payload }) {
return {
...state,
...payload,
};
},
// 修改加载中的状态
changeListLoading(state, { payload }) {
return {
...state,
listLoading: payload,
};
},
// 设置所有属性
setAll(state, { payload }) {
return {
...state,
...payload,
};
}
},
};

View File

@ -0,0 +1,101 @@
import { message } from 'antd';
import { productSpuPage, productSpuUpdateSort } from '../../services/product';
import {routerRedux} from "dva/router";
import PaginationHelper from '../../../helpers/PaginationHelper';
import {getPromotionActivityPage} from "../../services/promotion";
import {queryPayTransactionPage} from "../../services/pay";
const SEARCH_PARAMS_DEFAULT = {
createBeginTime: undefined,
createEndTime: undefined,
paymentBeginTime: undefined,
paymentEndTime: undefined,
status: undefined,
hasRefund: undefined,
payChannel: undefined,
orderSubject: '',
};
export default {
namespace: 'payTransactionList',
state: {
// 分页列表相关
list: [],
listLoading: false,
pagination: PaginationHelper.defaultPaginationConfig,
searchParams: SEARCH_PARAMS_DEFAULT,
// 添加 or 修改表单相关
},
effects: {
*page({ payload }, { call, put }) {
// const { queryParams } = payload;
// const response = yield call(productSpuPage, payload);
// message.info('查询成功!');
// yield put({
// type: 'treeSuccess',
// payload: {
// list: response.data,
// },
// });
// 显示加载中
yield put({
type: 'changeListLoading',
payload: true,
});
// 请求
const response = yield call(queryPayTransactionPage, payload);
// 响应
yield put({
type: 'setAll',
payload: {
list: response.data.list,
pagination: PaginationHelper.formatPagination(response.data, payload),
searchParams: {
createBeginTime: payload.createBeginTime,
createEndTime: payload.createEndTime,
paymentBeginTime: payload.paymentBeginTime,
paymentEndTime: payload.paymentEndTime,
status: payload.status,
hasRefund: payload.hasRefund,
payChannel: payload.payChannel,
orderSubject: payload.orderSubject,
}
},
});
// 隐藏加载中
yield put({
type: 'changeListLoading',
payload: false,
});
},
},
reducers: {
treeSuccess(state, { payload }) {
return {
...state,
...payload,
};
},
// 修改加载中的状态
changeListLoading(state, { payload }) {
return {
...state,
listLoading: payload,
};
},
// 设置所有属性
setAll(state, { payload }) {
return {
...state,
...payload,
};
}
},
};

View File

@ -5,9 +5,14 @@ import PaginationHelper from '../../../helpers/PaginationHelper';
import {getPromotionActivityPage} from "../../services/promotion";
const SEARCH_PARAMS_DEFAULT = {
title: '',
activityType: 2,
status: 'ALL',
createBeginTime: undefined,
createEndTime: undefined,
paymentBeginTime: undefined,
paymentEndTime: undefined,
status: undefined,
hasRefund: undefined,
payChannel: undefined,
orderSubject: '',
};
export default {
@ -63,36 +68,6 @@ export default {
payload: false,
});
},
*updateSort({ payload }, { call, put }) {
// 显示加载中
yield put({
type: 'changeSortModalLoading',
payload: true,
});
// 请求
const { callback, body } = payload;
// 响应
const response = yield call(productSpuUpdateSort, body);
if(response.code === 0) {
if (callback) {
callback(response);
}
yield put({
type: 'page',
payload: {
...this.state.pagination,
...this.state.searchParams,
},
});
}
// 隐藏加载中
yield put({
type: 'changeSortModalLoading',
payload: false,
});
},
},
reducers: {
@ -103,12 +78,6 @@ export default {
};
},
// 修改加载中的状态
changeSortModalLoading(state, { payload }) {
return {
...state,
sortModalLoading: payload,
};
},
changeListLoading(state, { payload }) {
return {
...state,

View File

@ -63,36 +63,6 @@ export default {
payload: false,
});
},
*updateSort({ payload }, { call, put }) {
// 显示加载中
yield put({
type: 'changeSortModalLoading',
payload: true,
});
// 请求
const { callback, body } = payload;
// 响应
const response = yield call(productSpuUpdateSort, body);
if(response.code === 0) {
if (callback) {
callback(response);
}
yield put({
type: 'page',
payload: {
...this.state.pagination,
...this.state.searchParams,
},
});
}
// 隐藏加载中
yield put({
type: 'changeSortModalLoading',
payload: false,
});
},
},
reducers: {
@ -103,12 +73,6 @@ export default {
};
},
// 修改加载中的状态
changeSortModalLoading(state, { payload }) {
return {
...state,
sortModalLoading: payload,
};
},
changeListLoading(state, { payload }) {
return {
...state,

View File

@ -0,0 +1,89 @@
import { message } from 'antd';
import { productSpuPage, productSpuUpdateSort } from '../../services/product';
import {routerRedux} from "dva/router";
import PaginationHelper from '../../../helpers/PaginationHelper';
import {getPromotionActivityPage} from "../../services/promotion";
import {queryUserPage} from "../../services/user";
const SEARCH_PARAMS_DEFAULT = {
nickname: '',
status: 1,
};
export default {
namespace: 'userList',
state: {
// 分页列表相关
list: [],
listLoading: false,
pagination: PaginationHelper.defaultPaginationConfig,
searchParams: SEARCH_PARAMS_DEFAULT,
// 添加 or 修改表单相关
},
effects: {
*page({ payload }, { call, put }) {
// const { queryParams } = payload;
// const response = yield call(productSpuPage, payload);
// message.info('查询成功!');
// yield put({
// type: 'treeSuccess',
// payload: {
// list: response.data,
// },
// });
// 显示加载中
yield put({
type: 'changeListLoading',
payload: true,
});
// 请求
const response = yield call(queryUserPage, payload);
// 响应
yield put({
type: 'setAll',
payload: {
list: response.data.list,
pagination: PaginationHelper.formatPagination(response.data, payload),
searchParams: {
nickname: payload.nickname,
status: payload.status,
}
},
});
// 隐藏加载中
yield put({
type: 'changeListLoading',
payload: false,
});
},
},
reducers: {
treeSuccess(state, { payload }) {
return {
...state,
...payload,
};
},
// 修改加载中的状态
changeListLoading(state, { payload }) {
return {
...state,
listLoading: payload,
};
},
// 设置所有属性
setAll(state, { payload }) {
return {
...state,
...payload,
};
}
},
};

View File

@ -0,0 +1,319 @@
/* eslint-disable */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
Card,
Form,
Input,
Row,
Col,
Button,
Modal,
message,
Table,
Divider,
Tree,
Tabs,
TreeSelect,
Spin,
InputNumber, DatePicker, Select
} from 'antd';
const TabPane = Tabs.TabPane;
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
const { RangePicker } = DatePicker;
import styles from './PayRefundList.less';
import PaginationHelper from "../../../helpers/PaginationHelper";
const FormItem = Form.Item;
const statuses = {
1: '处理中',
2: '成功',
3: '失败',
};
const payChannels = {
100: '微信 App 支付',
101: '微信 JS API 支付',
200: '支付宝 App 支付',
9999: 'ping++',
};
// 列表
function List({ dataSource, loading, pagination, searchParams, dispatch,}) {
function onPageChange(page) { // 翻页
dispatch({
type: 'payRefundList/page',
payload: {
pageNo: page.current,
pageSize: page.pageSize,
...searchParams
}
})
}
const columns = [
// {
// title: 'id',
// dataIndex: 'id',
// render: text => <strong>{text}</strong>,
// },
{
title: '创建时间',
dataIndex: 'createTime',
render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
width: 120,
},
{
title: '完成时间',
dataIndex: 'finishTime',
render: val => val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : '',
width: 120,
},
{
title: '渠道流水号',
dataIndex: 'tradeNo',
},
{
title: '退款金额',
dataIndex: 'price',
render: val => val / 100.0,
},
{
title: '退款状态',
dataIndex: 'status',
render: val => statuses[val + ''],
},
{
title: '支付时间',
dataIndex: 'transaction.finishTime',
render: val => val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : '',
width: 120,
},
{
title: '商户订单号',
dataIndex: 'orderId',
},
{
title: '商品名称',
dataIndex: 'transaction.orderSubject',
},
{
title: '支付金额',
dataIndex: 'transaction.price',
},
{
title: '支付渠道',
dataIndex: 'transaction.payChannel',
render: val => payChannels[val + ''],
},
{
title: '操作',
width: 120,
render: (text, record) => (
<Fragment>
{/*<a onClick={() => this.handleModalVisible(true, 'update', record)}>更新</a>*/}
<a onClick={() => alert('正在开发中')}>详情</a>
</Fragment>
),
},
];
// console.log(pagination);
return (
<div>
<Table
columns={columns}
dataSource={dataSource}
rowKey="id"
pagination={pagination}
onChange={onPageChange}
loading={loading} />
</div>
)
}
// 搜索表单
const SearchForm = Form.create()(props => {
const {
form,
form: { getFieldDecorator },
dispatch,
searchParams,
} = props;
function search() {
const getBeginAndEndTime = (key, beginKey, endKey) => {
let val = form.getFieldsValue()[key];
if (val && val.length === 2) {
let res = {};
res[beginKey] = val[0].format('YYYY-MM-DD HH:mm:ss');
res[endKey] = val[1].format('YYYY-MM-DD HH:mm:ss');
return res;
}
return {};
};
dispatch({
type: 'payRefundList/page',
payload: {
...PaginationHelper.defaultPayload,
...searchParams,
...form.getFieldsValue(),
createTime: undefined,
finishTime: undefined,
...getBeginAndEndTime('createTime', 'createBeginTime', 'createEndTime'),
...getBeginAndEndTime('finishTime', 'finishBeginTime', 'finishEndTime'),
}
})
}
// 提交搜索
function handleSubmit(e) {
// 阻止默认事件
e.preventDefault();
// 提交搜索
search();
}
// 重置搜索
function handleReset() {
// 重置表单
form.resetFields();
// 执行搜索
search();
}
return (
<Form onSubmit={handleSubmit} layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="创建时间">{getFieldDecorator('createTime')(<RangePicker style={{ width: '250px' }} />)}</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="完成时间">{getFieldDecorator('finishTime')(<RangePicker style={{ width: '250px' }} />)}</FormItem>
</Col>
</Row>
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="支付渠道">
{getFieldDecorator('payChannel')(
<Select placeholder="请选择" style={{ width: '250px' }}>
{Object.keys(payChannels).map((key, index) => <Option key={key} value={key + ''}>{payChannels[key]}</Option>)}
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="退款状态">
{getFieldDecorator('status')(
<Select placeholder="请选择" style={{ width: '250px' }}>
{Object.keys(statuses).map((key, index) => <Option key={key} value={key + ''}>{statuses[key]}</Option>)}
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
查询
</Button>
<Button style={{ marginLeft: 8 }} onClick={handleReset}>
重置
</Button>
</span>
</Col>
</Row>
</Form>
);
});
// payRefundList
@connect(({ payRefundList }) => ({
...payRefundList,
// list: payRefundList.list.spus,
// loading: loading.models.payRefundList,
}))
@Form.create()
class PayTransactionList extends PureComponent {
state = {
modalVisible: false,
modalType: 'add', //add update
initValues: {},
};
componentDidMount() {
const { dispatch, searchParams } = this.props;
// 查询初始数据
dispatch({
type: 'payRefundList/page',
payload: {
...searchParams,
...PaginationHelper.defaultPayload,
},
});
}
handleSortModalVisible = (sortModalVisible, record) => {
const { dispatch } = this.props;
dispatch({
type: 'payRefundList/setAll',
payload: {
sortModalVisible,
formVals: record || {}
},
});
};
render() {
const { dispatch,
list, listLoading, searchParams, pagination,
categoryTree, formVals, } = this.props;
// 列表属性
const listProps = {
dataSource: list,
pagination,
searchParams,
dispatch,
categoryTree,
loading: listLoading,
handleSortModalVisible: this.handleSortModalVisible, // Func
};
// 搜索表单属性
const searchFormProps = {
dispatch,
categoryTree,
searchParams,
};
return (
<PageHeaderWrapper title="">
<Card bordered={false}>
<div className={styles.tableList}>
<div className={styles.tableListOperator}>
{/*<Button*/}
{/* icon="plus"*/}
{/* type="primary"*/}
{/* onClick={() => alert('正在开发中')}*/}
{/*>*/}
{/* 新建限时折扣*/}
{/*</Button>*/}
</div>
</div>
<SearchForm {...searchFormProps} />
<List {...listProps} />
</Card>
</PageHeaderWrapper>
);
}
}
export default PayTransactionList;

View File

@ -0,0 +1,15 @@
@import '~antd/lib/style/themes/default.less';
@import '~@/utils/utils.less';
.tableList {
.tableListOperator {
margin-bottom: 16px;
button {
margin-right: 8px;
}
}
}
.tableDelete {
color: red;
}

View File

@ -0,0 +1,328 @@
/* eslint-disable */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
Card,
Form,
Input,
Row,
Col,
Button,
Modal,
message,
Table,
Divider,
Tree,
Tabs,
TreeSelect,
Spin,
InputNumber, DatePicker, Select
} from 'antd';
const TabPane = Tabs.TabPane;
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
const { RangePicker } = DatePicker;
import styles from './PayTransactionList.less';
import PaginationHelper from "../../../helpers/PaginationHelper";
const FormItem = Form.Item;
const statuses = {
1: '等待支付',
2: '支付成功',
3: '取消支付',
};
const payChannels = {
100: '微信 App 支付',
101: '微信 JS API 支付',
200: '支付宝 App 支付',
9999: 'ping++',
};
// 列表
function List({ dataSource, loading, pagination, searchParams, dispatch,}) {
function onPageChange(page) { // 翻页
dispatch({
type: 'payTransactionList/page',
payload: {
pageNo: page.current,
pageSize: page.pageSize,
...searchParams
}
})
}
const columns = [
// {
// title: 'id',
// dataIndex: 'id',
// render: text => <strong>{text}</strong>,
// },
{
title: '创建时间',
dataIndex: 'createTime',
render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
width: 120,
},
{
title: '支付时间',
dataIndex: 'paymentTime',
render: val => val ? <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span> : '',
width: 120,
},
{
title: '商户订单号',
dataIndex: 'orderId',
},
{
title: '商品名称',
dataIndex: 'orderSubject',
},
{
title: '支付金额',
dataIndex: 'price',
render: val => val / 100.0,
},
{
title: '支付状态',
dataIndex: 'status',
render: val => statuses[val + ''],
},
{
title: '支付渠道',
dataIndex: 'payChannel',
render: val => payChannels[val + ''],
},
{
title: '退款情况',
dataIndex: 'refundTotal',
render: val => val && val > 0 ? '有退款' : '无退款' ,
},
{
title: '退款金额',
dataIndex: 'refundTotal',
render: val => val && val > 0 ? val / 100.0 : undefined ,
},
{
title: '操作',
width: 120,
render: (text, record) => (
<Fragment>
{/*<a onClick={() => this.handleModalVisible(true, 'update', record)}>更新</a>*/}
<a onClick={() => alert('正在开发中')}>退款</a>
</Fragment>
),
},
];
// console.log(pagination);
return (
<div>
<Table
columns={columns}
dataSource={dataSource}
rowKey="id"
pagination={pagination}
onChange={onPageChange}
loading={loading} />
</div>
)
}
// 搜索表单
const SearchForm = Form.create()(props => {
const {
form,
form: { getFieldDecorator },
dispatch,
searchParams,
} = props;
function search() {
const getBeginAndEndTime = (key, beginKey, endKey) => {
let val = form.getFieldsValue()[key];
if (val && val.length === 2) {
let res = {};
res[beginKey] = val[0].format('YYYY-MM-DD HH:mm:ss');
res[endKey] = val[1].format('YYYY-MM-DD HH:mm:ss');
return res;
}
return {};
};
dispatch({
type: 'payTransactionList/page',
payload: {
...PaginationHelper.defaultPayload,
...searchParams,
...form.getFieldsValue(),
createTime: undefined,
paymentTime: undefined,
...getBeginAndEndTime('createTime', 'createBeginTime', 'createEndTime'),
...getBeginAndEndTime('paymentTime', 'paymentBeginTime', 'paymentEndTime'),
}
})
}
// 提交搜索
function handleSubmit(e) {
// 阻止默认事件
e.preventDefault();
// 提交搜索
search();
}
// 重置搜索
function handleReset() {
// 重置表单
form.resetFields();
// 执行搜索
search();
}
return (
<Form onSubmit={handleSubmit} layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="创建时间">{getFieldDecorator('createTime')(<RangePicker style={{ width: '250px' }} />)}</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="支付时间">{getFieldDecorator('paymentTime')(<RangePicker style={{ width: '250px' }} />)}</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="商品名称">{getFieldDecorator('orderSubject')(<Input placeholder="请输入" style={{ width: '250px' }} />)}</FormItem>
</Col>
</Row>
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="支付渠道">
{getFieldDecorator('payChannel')(
<Select placeholder="请选择" style={{ width: '250px' }}>
{Object.keys(payChannels).map((key, index) => <Option key={key} value={key + ''}>{payChannels[key]}</Option>)}
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="支付状态">
{getFieldDecorator('status')(
<Select placeholder="请选择" style={{ width: '250px' }}>
{Object.keys(statuses).map((key, index) => <Option key={key} value={key + ''}>{statuses[key]}</Option>)}
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="退款状态">
{getFieldDecorator('hasRefund')(
<Select placeholder="请选择" style={{ width: '250px' }}>
<Option value={true}>有退款</Option>
<Option value={false}>无退款</Option>
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
查询
</Button>
<Button style={{ marginLeft: 8 }} onClick={handleReset}>
重置
</Button>
</span>
</Col>
</Row>
</Form>
);
});
// payTransactionList
@connect(({ payTransactionList }) => ({
...payTransactionList,
// list: payTransactionList.list.spus,
// loading: loading.models.payTransactionList,
}))
@Form.create()
class PayTransactionList extends PureComponent {
state = {
modalVisible: false,
modalType: 'add', //add update
initValues: {},
};
componentDidMount() {
const { dispatch, searchParams } = this.props;
// 查询初始数据
dispatch({
type: 'payTransactionList/page',
payload: {
...searchParams,
...PaginationHelper.defaultPayload,
},
});
}
handleSortModalVisible = (sortModalVisible, record) => {
const { dispatch } = this.props;
dispatch({
type: 'payTransactionList/setAll',
payload: {
sortModalVisible,
formVals: record || {}
},
});
};
render() {
const { dispatch,
list, listLoading, searchParams, pagination,
categoryTree, formVals, } = this.props;
// 列表属性
const listProps = {
dataSource: list,
pagination,
searchParams,
dispatch,
categoryTree,
loading: listLoading,
handleSortModalVisible: this.handleSortModalVisible, // Func
};
// 搜索表单属性
const searchFormProps = {
dispatch,
categoryTree,
searchParams,
};
return (
<PageHeaderWrapper title="">
<Card bordered={false}>
<div className={styles.tableList}>
<div className={styles.tableListOperator}>
{/*<Button*/}
{/* icon="plus"*/}
{/* type="primary"*/}
{/* onClick={() => alert('正在开发中')}*/}
{/*>*/}
{/* 新建限时折扣*/}
{/*</Button>*/}
</div>
</div>
<SearchForm {...searchFormProps} />
<List {...listProps} />
</Card>
</PageHeaderWrapper>
);
}
}
export default PayTransactionList;

View File

@ -0,0 +1,15 @@
@import '~antd/lib/style/themes/default.less';
@import '~@/utils/utils.less';
.tableList {
.tableListOperator {
margin-bottom: 16px;
button {
margin-right: 8px;
}
}
}
.tableDelete {
color: red;
}

View File

@ -0,0 +1,266 @@
/* eslint-disable */
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
Card,
Form,
Input,
Row,
Col,
Button,
Modal,
message,
Table,
Divider,
Tree,
Tabs,
TreeSelect,
Spin,
InputNumber, Select
} from 'antd';
const TabPane = Tabs.TabPane;
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './UserList.less';
import PaginationHelper from "../../../helpers/PaginationHelper";
const FormItem = Form.Item;
const statuses = {
1: '开启',
2: '关闭',
};
// 列表
function List({ dataSource, loading, pagination, searchParams, dispatch,}) {
function onPageChange(page) { // 翻页
dispatch({
type: 'userList/page',
payload: {
pageNo: page.current,
pageSize: page.pageSize,
...searchParams
}
})
}
const columns = [
// {
// title: 'id',
// dataIndex: 'id',
// render: text => <strong>{text}</strong>,
// },
{
title: '昵称',
dataIndex: 'nickname',
},
{
title: '手机号码',
dataIndex: 'mobile',
},
{
title: '会员卡', // TODO 芋艿,未来增加
},
{
title: '累积交易次数', // TODO 芋艿,未来增加
},
{
title: '累计交易额', // TODO 芋艿,未来增加
},
{
title: '积分', // TODO 芋艿,未来增加
},
{
title: '会员标签', // TODO 芋艿,未来增加
},
{
title: '备注', // TODO 芋艿,未来增加
},
{
title: '状态',
dataIndex: 'status',
render: val => statuses[val + ''],
},
{
title: '操作',
width: 300,
render: (text, record) => (
<Fragment>
{/*<a onClick={() => this.handleModalVisible(true, 'update', record)}>更新</a>*/}
<a onClick={() => alert('正在开发中')}>编辑</a>
</Fragment>
),
},
];
// console.log(pagination);
return (
<div>
<Table
columns={columns}
dataSource={dataSource}
rowKey="id"
pagination={pagination}
onChange={onPageChange}
loading={loading} />
</div>
)
}
// 搜索表单
const SearchForm = Form.create()(props => {
const {
form,
form: { getFieldDecorator },
dispatch,
searchParams,
} = props;
function search() {
dispatch({
type: 'userList/page',
payload: {
...PaginationHelper.defaultPayload,
...searchParams,
...form.getFieldsValue(),
}
})
}
// 提交搜索
function handleSubmit(e) {
// 阻止默认事件
e.preventDefault();
// 提交搜索
search();
}
// 重置搜索
function handleReset() {
// 重置表单
form.resetFields();
// 执行搜索
search();
}
return (
<Form onSubmit={handleSubmit} layout="inline">
<Row gutter={{ md: 8, lg: 24, xl: 48 }}>
<Col md={8} sm={24}>
<FormItem label="会员昵称">
{getFieldDecorator('nickname')(<Input placeholder="请输入" />)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<FormItem label="会员状态">
{getFieldDecorator('status')(
<Select placeholder="请选择" style={{ width: '200px' }}>
<Option value="1">开启</Option>
<Option value="2">关闭</Option>
</Select>
)}
</FormItem>
</Col>
<Col md={8} sm={24}>
<span className={styles.submitButtons}>
<Button type="primary" htmlType="submit">
查询
</Button>
<Button style={{ marginLeft: 8 }} onClick={handleReset}>
重置
</Button>
</span>
</Col>
</Row>
</Form>
);
});
// userList
@connect(({ userList }) => ({
...userList,
// list: userList.list.spus,
// loading: loading.models.userList,
}))
@Form.create()
class UserList extends PureComponent {
state = {
modalVisible: false,
modalType: 'add', //add update
initValues: {},
};
componentDidMount() {
const { dispatch, searchParams } = this.props;
// 查询初始数据
dispatch({
type: 'userList/page',
payload: {
...searchParams,
...PaginationHelper.defaultPayload,
},
});
}
handleSortModalVisible = (sortModalVisible, record) => {
const { dispatch } = this.props;
dispatch({
type: 'userList/setAll',
payload: {
sortModalVisible,
formVals: record || {}
},
});
};
render() {
const { dispatch,
list, listLoading, searchParams, pagination,
categoryTree, formVals, } = this.props;
// 列表属性
const listProps = {
dataSource: list,
pagination,
searchParams,
dispatch,
categoryTree,
loading: listLoading,
handleSortModalVisible: this.handleSortModalVisible, // Func
};
// 搜索表单属性
const searchFormProps = {
dispatch,
categoryTree,
searchParams,
};
return (
<PageHeaderWrapper title="">
<Card bordered={false}>
<div className={styles.tableList}>
<div className={styles.tableListOperator}>
{/*<Button*/}
{/* icon="plus"*/}
{/* type="primary"*/}
{/* onClick={() => alert('正在开发中')}*/}
{/*>*/}
{/* 新建会员*/}
{/*</Button>*/}
</div>
</div>
<SearchForm {...searchFormProps} />
<List {...listProps} />
</Card>
</PageHeaderWrapper>
);
}
}
export default UserList;

View File

@ -0,0 +1,15 @@
@import '~antd/lib/style/themes/default.less';
@import '~@/utils/utils.less';
.tableList {
.tableListOperator {
margin-bottom: 16px;
button {
margin-right: 8px;
}
}
}
.tableDelete {
color: red;
}

View File

@ -0,0 +1,18 @@
import { stringify } from '@/utils/request.qs';
import request from '@/utils/request';
// Transaction
export async function queryPayTransactionPage(params) {
return request(`/pay-api/admins/transaction/page?${stringify(params)}`, {
method: 'GET',
});
}
// Refund
export async function queryPayRefundPage(params) {
return request(`/pay-api/admins/refund/page?${stringify(params)}`, {
method: 'GET',
});
}

View File

@ -1,3 +1,4 @@
import { stringify } from '@/utils/request.qs';
import request from '@/utils/request';
export async function query() {
@ -7,3 +8,11 @@ export async function query() {
export async function queryCurrent() {
return request('/api/currentUser');
}
// User
export async function queryUserPage(params) {
return request(`/user-api/admins/user/page?${stringify(params)}`, {
method: 'GET',
});
}

View File

@ -71,6 +71,11 @@ public class ServiceExceptionUtil {
return new ServiceException(code, message);
}
public static ServiceException exception(Integer code, String messagePattern, Object... params) {
String message = doFormat(code, messagePattern, params);
return new ServiceException(code, message);
}
/**
* 将错误编号对应的消息使用 params 进行格式化
*
@ -107,4 +112,4 @@ public class ServiceExceptionUtil {
return sbuf.toString();
}
}
}

View File

@ -7,26 +7,28 @@
- [ ] 数据分析【待认领】
- [ ] TODO 未开始
- [ ] 店铺资产【待认领】
- [ ] TODO 未开始
- [ ] 支付单 20% 【待认领】
- [ ] 退款单 20% 【待认领】
- TODO 需要补充
- [ ] 商品管理
- [x] 发布商品
- [x] 商品列表
- [x] 展示类目
- [ ] 品牌管理【待认领】
- [ ] 订单管理
- [ ] 销售单
- [ ] 售后单
- [ ] 销售单 开发中
- [ ] 售后单 开发中
- [ ] 订单评价【待认领】
- [ ] 会员管理
- [ ] 会员资料【待认领】
- [ ] 会员资料 20%【待认领】
- TODO 需要补充
- [ ] 营销管理
- [x] 首页广告
- [x] 商品推荐
- [x] 优惠劵
- [ ] 优惠码【待认领】
- [ ] 满减送
- [ ] 限制折扣
- [ ] 满减送 20% 【待认领】
- [ ] 限制折扣 20% 【待认领】
- [ ] 多人拼团【待认领】
- [ ] 系统管理
- [ ] 员工管理

View File

@ -13,17 +13,14 @@ import cn.iocoder.mall.order.api.constant.OrderErrorCodeEnum;
import cn.iocoder.mall.order.api.dto.CalcOrderPriceDTO;
import cn.iocoder.mall.order.api.dto.OrderCreateDTO;
import cn.iocoder.mall.order.api.dto.OrderQueryDTO;
import cn.iocoder.mall.order.api.dto.OrderReturnApplyDTO;
import cn.iocoder.mall.order.application.convert.CartConvert;
import cn.iocoder.mall.order.application.convert.OrderConvertAPP;
import cn.iocoder.mall.order.application.convert.OrderReturnConvert;
import cn.iocoder.mall.order.application.po.user.OrderCreatePO;
import cn.iocoder.mall.order.application.po.user.OrderReturnApplyPO;
import cn.iocoder.mall.order.application.vo.UsersOrderConfirmCreateVO;
import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import org.apache.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -76,7 +73,7 @@ public class OrderController {
HttpServletRequest request) {
Integer userId = UserSecurityContextHolder.getContext().getUserId();
// 获得购物车中选中的商品
List<CartItemBO> cartItems = cartService.list(userId, true).getData();
List<CartItemBO> cartItems = cartService.list(userId, true);
if (cartItems.isEmpty()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_CREATE_CART_IS_EMPTY.getCode());
}
@ -105,12 +102,9 @@ public class OrderController {
.setUserId(UserSecurityContextHolder.getContext().getUserId())
.setItems(Collections.singletonList(new CalcOrderPriceDTO.Item(skuId, quantity, true)))
.setCouponCardId(couponCardId);
CommonResult<CalcOrderPriceBO> calcOrderPriceResult = cartService.calcOrderPrice(calcOrderPriceDTO);
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
CalcOrderPriceBO calcOrderPrice = cartService.calcOrderPrice(calcOrderPriceDTO);
// 执行数据拼装
return CommonResult.success(CartConvert.INSTANCE.convert(calcOrderPriceResult.getData()));
return CommonResult.success(CartConvert.INSTANCE.convert(calcOrderPrice));
}
@PostMapping("confirm_receiving")

View File

@ -23,6 +23,8 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("users/cart")
public class UsersCartController {
@ -38,26 +40,17 @@ public class UsersCartController {
public CommonResult<Integer> add(@RequestParam("skuId") Integer skuId,
@RequestParam("quantity") Integer quantity) {
// 添加到购物车
CommonResult<Boolean> addResult = cartService.add(UserSecurityContextHolder.getContext().getUserId(),
skuId, quantity);
// 添加失败则直接返回错误
if (addResult.isError()) {
return CommonResult.error(addResult);
}
cartService.add(UserSecurityContextHolder.getContext().getUserId(), skuId, quantity);
// 获得目前购物车商品总数量
return cartService.count(UserSecurityContextHolder.getContext().getUserId());
return success(cartService.count(UserSecurityContextHolder.getContext().getUserId()));
}
@PostMapping("update_quantity")
public CommonResult<UsersCartDetailVO> updateQuantity(@RequestParam("skuId") Integer skuId, // TODO 芋艿先暂用这个 VO 等促销活动出来后做调整
@RequestParam("quantity") Integer quantity) {
// 添加到购物车
CommonResult<Boolean> updateQuantityResult = cartService.updateQuantity(UserSecurityContextHolder.getContext().getUserId(),
cartService.updateQuantity(UserSecurityContextHolder.getContext().getUserId(),
skuId, quantity);
// 添加失败则直接返回错误
if (updateQuantityResult.isError()) {
return CommonResult.error(updateQuantityResult);
}
// 获得目前购物车明细
return getCartDetail();
}
@ -66,19 +59,14 @@ public class UsersCartController {
public CommonResult<UsersCartDetailVO> updateSelected(@RequestParam("skuIds") Set<Integer> skuIds, // TODO 芋艿先暂用这个 VO 等促销活动出来后做调整
@RequestParam("selected") Boolean selected) {
// 添加到购物车
CommonResult<Boolean> updateSelectedResult = cartService.updateSelected(UserSecurityContextHolder.getContext().getUserId(),
skuIds, selected);
// 添加失败则直接返回错误
if (updateSelectedResult.isError()) {
return CommonResult.error(updateSelectedResult);
}
cartService.updateSelected(UserSecurityContextHolder.getContext().getUserId(), skuIds, selected);
// 获得目前购物车明细
return getCartDetail();
}
@GetMapping("count")
public CommonResult<Integer> count() {
return cartService.count(UserSecurityContextHolder.getContext().getUserId());
return success(cartService.count(UserSecurityContextHolder.getContext().getUserId()));
}
@GetMapping("/list")
@ -88,50 +76,42 @@ public class UsersCartController {
private CommonResult<UsersCartDetailVO> getCartDetail() {
// 获得购物车中选中的
List<CartItemBO> cartItems = cartService.list(UserSecurityContextHolder.getContext().getUserId(), null).getData();
List<CartItemBO> cartItems = cartService.list(UserSecurityContextHolder.getContext().getUserId(), null);
// 购物车为空时构造空的 UsersOrderConfirmCreateVO 返回
if (cartItems.isEmpty()) {
UsersCartDetailVO result = new UsersCartDetailVO();
result.setItemGroups(Collections.emptyList());
result.setFee(new UsersCartDetailVO.Fee(0, 0, 0, 0));
return CommonResult.success(result);
return success(result);
}
// 计算商品价格
CommonResult<CalcOrderPriceBO> calcOrderPriceResult = list0(cartItems, null);
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
CalcOrderPriceBO calcOrder = list0(cartItems, null);
// 执行数据拼装
return CommonResult.success(CartConvert.INSTANCE.convert2(calcOrderPriceResult.getData()));
return success(CartConvert.INSTANCE.convert2(calcOrder));
}
@GetMapping("/confirm_create_order")
public CommonResult<UsersOrderConfirmCreateVO> getConfirmCreateOrder(@RequestParam(value = "couponCardId", required = false) Integer couponCardId) {
Integer userId = UserSecurityContextHolder.getContext().getUserId();
// 获得购物车中选中的
List<CartItemBO> cartItems = cartService.list(userId, true).getData();
List<CartItemBO> cartItems = cartService.list(userId, true);
// 购物车为空时构造空的 UsersOrderConfirmCreateVO 返回
if (cartItems.isEmpty()) {
UsersOrderConfirmCreateVO result = new UsersOrderConfirmCreateVO();
result.setItemGroups(Collections.emptyList());
result.setFee(new UsersOrderConfirmCreateVO.Fee(0, 0, 0, 0));
return CommonResult.success(result);
return success(result);
}
// 计算商品价格
CommonResult<CalcOrderPriceBO> calcOrderPriceResult = list0(cartItems, couponCardId);
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
CalcOrderPriceBO calcOrderPrice = list0(cartItems, couponCardId);
// 获得优惠劵
CalcOrderPriceBO calcOrderPrice = calcOrderPriceResult.getData();
List<CouponCardAvailableBO> couponCards = couponService.getCouponCardList(userId,
CartConvert.INSTANCE.convertList(calcOrderPrice.getItemGroups())).getData();
CartConvert.INSTANCE.convertList(calcOrderPrice.getItemGroups()));
// 执行数据拼装
return CommonResult.success(CartConvert.INSTANCE.convert(calcOrderPrice)
.setCouponCards(couponCards));
return success(CartConvert.INSTANCE.convert(calcOrderPrice).setCouponCards(couponCards));
}
private CommonResult<CalcOrderPriceBO> list0(List<CartItemBO> cartItems, Integer couponCardId) {
private CalcOrderPriceBO list0(List<CartItemBO> cartItems, Integer couponCardId) {
// 创建计算的 DTO
CalcOrderPriceDTO calcOrderPriceDTO = new CalcOrderPriceDTO()
.setUserId(UserSecurityContextHolder.getContext().getUserId())
@ -148,12 +128,8 @@ public class UsersCartController {
@PermitAll
public CommonResult<UsersCalcSkuPriceVO> calcSkuPrice(@RequestParam("skuId") Integer skuId) {
// 计算 sku 的价格
CommonResult<CalcSkuPriceBO> calcSkuPriceResult = cartService.calcSkuPrice(skuId);
// 返回结果
if (calcSkuPriceResult.isError()) {
return CommonResult.error(calcSkuPriceResult);
}
return CommonResult.success(CartConvert.INSTANCE.convert2(calcSkuPriceResult.getData()));
CalcSkuPriceBO calcSkuPrice = cartService.calcSkuPrice(skuId);
return success(CartConvert.INSTANCE.convert2(calcSkuPrice));
}
public CommonResult<Object> confirmOrder() {

View File

@ -1,7 +1,8 @@
package cn.iocoder.mall.order.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.order.api.bo.*;
import cn.iocoder.mall.order.api.bo.CalcOrderPriceBO;
import cn.iocoder.mall.order.api.bo.CalcSkuPriceBO;
import cn.iocoder.mall.order.api.bo.CartItemBO;
import cn.iocoder.mall.order.api.dto.CalcOrderPriceDTO;
import org.springframework.lang.Nullable;
@ -20,7 +21,7 @@ public interface CartService {
* @param quantity 数量
* @return 是否成功
*/
CommonResult<Boolean> add(Integer userId, Integer skuId, Integer quantity);
Boolean add(Integer userId, Integer skuId, Integer quantity);
/**
* 购物车更新商品数量
@ -30,7 +31,7 @@ public interface CartService {
* @param quantity 数量
* @return 是否成功
*/
CommonResult<Boolean> updateQuantity(Integer userId, Integer skuId, Integer quantity);
Boolean updateQuantity(Integer userId, Integer skuId, Integer quantity);
/**
* 购物车更新商品是否选中
@ -40,7 +41,7 @@ public interface CartService {
* @param selected 是否选中
* @return 是否成功
*/
CommonResult<Boolean> updateSelected(Integer userId, Collection<Integer> skuIds, Boolean selected);
Boolean updateSelected(Integer userId, Collection<Integer> skuIds, Boolean selected);
/**
* 购物车删除商品
@ -50,7 +51,7 @@ public interface CartService {
*
* @return 是否成功
*/
CommonResult<Boolean> deleteList(Integer userId, List<Integer> skuIds);
Boolean deleteList(Integer userId, List<Integer> skuIds);
/**
* 清空购物车
@ -58,7 +59,7 @@ public interface CartService {
* @param userId 用户编号
* @return 是否成功
*/
CommonResult<Boolean> deleteAll(Integer userId);
Boolean deleteAll(Integer userId);
/**
* 查询用户在购物车中的商品数量
@ -66,7 +67,7 @@ public interface CartService {
* @param userId 用户编号
* @return 商品数量
*/
CommonResult<Integer> count(Integer userId);
Integer count(Integer userId);
/**
* 显示买家购物车中的商品列表并根据 selected 进行过滤
@ -75,7 +76,7 @@ public interface CartService {
* @param selected 是否选中若为空则不进行筛选
* @return 购物车中商品列表信息
*/
CommonResult<List<CartItemBO>> list(Integer userId, @Nullable Boolean selected);
List<CartItemBO> list(Integer userId, @Nullable Boolean selected);
// ========== 购物车与订单相关的逻辑 ==========
@ -85,7 +86,7 @@ public interface CartService {
* @param calcOrderPriceDTO 计算订单金额 DTO
* @return 计算订单金额结果
*/
CommonResult<CalcOrderPriceBO> calcOrderPrice(CalcOrderPriceDTO calcOrderPriceDTO);
CalcOrderPriceBO calcOrderPrice(CalcOrderPriceDTO calcOrderPriceDTO);
/**
* 计算指定商品 SKU 的金额并返回计算结果
@ -95,6 +96,6 @@ public interface CartService {
* @param skuId 商品 SKU 编号
* @return 计算订单金额结果
*/
CommonResult<CalcSkuPriceBO> calcSkuPrice(Integer skuId);
CalcSkuPriceBO calcSkuPrice(Integer skuId);
}

View File

@ -2,7 +2,6 @@ package cn.iocoder.mall.order.biz.service;
import cn.iocoder.common.framework.constant.CommonStatusEnum;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.order.api.CartService;
import cn.iocoder.mall.order.api.bo.CalcOrderPriceBO;
import cn.iocoder.mall.order.api.bo.CalcSkuPriceBO;
@ -48,12 +47,12 @@ public class CartServiceImpl implements CartService {
@Override
@SuppressWarnings("Duplicates")
public CommonResult<Boolean> add(Integer userId, Integer skuId, Integer quantity) {
public Boolean add(Integer userId, Integer skuId, Integer quantity) {
// 查询 SKU 是否合法
ProductSkuBO sku = productSpuService.getProductSku(skuId);
if (sku == null
|| CommonStatusEnum.DISABLE.getValue().equals(sku.getStatus())) { // sku 被禁用
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
}
// TODO 芋艿后续基于商品是否上下架进一步完善
// 查询 CartItemDO
@ -66,10 +65,10 @@ public class CartServiceImpl implements CartService {
return add0(userId, sku, quantity);
}
private CommonResult<Boolean> add0(Integer userId, ProductSkuBO sku, Integer quantity) {
private Boolean add0(Integer userId, ProductSkuBO sku, Integer quantity) {
// 校验库存
if (quantity > sku.getQuantity()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
}
// 创建 CartItemDO 对象并进行保存
CartItemDO item = new CartItemDO()
@ -82,79 +81,79 @@ public class CartServiceImpl implements CartService {
item.setCreateTime(new Date());
cartMapper.insert(item);
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
@SuppressWarnings("Duplicates")
public CommonResult<Boolean> updateQuantity(Integer userId, Integer skuId, Integer quantity) {
public Boolean updateQuantity(Integer userId, Integer skuId, Integer quantity) {
// 查询 SKU 是否合法
ProductSkuBO sku = productSpuService.getProductSku(skuId);
if (sku == null
|| CommonStatusEnum.DISABLE.getValue().equals(sku.getStatus())) { // sku 被禁用
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
}
// 查询 CartItemDO
CartItemDO item = cartMapper.selectByUserIdAndSkuIdAndStatus(userId, skuId, CartItemStatusEnum.ENABLE.getValue());
if (item == null) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_NOT_FOUND.getCode());
}
// TODO 芋艿后续基于商品是否上下架进一步完善
return updateQuantity0(item, sku, quantity);
}
private CommonResult<Boolean> updateQuantity0(CartItemDO item, ProductSkuBO sku, Integer quantity) {
private Boolean updateQuantity0(CartItemDO item, ProductSkuBO sku, Integer quantity) {
// 校验库存
if (item.getQuantity() + quantity > sku.getQuantity()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
}
// 更新 CartItemDO
cartMapper.updateQuantity(item.getId(), quantity);
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> updateSelected(Integer userId, Collection<Integer> skuIds, Boolean selected) {
public Boolean updateSelected(Integer userId, Collection<Integer> skuIds, Boolean selected) {
// 更新 CartItemDO
cartMapper.updateListByUserIdAndSkuId(userId, skuIds, selected, null);
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> deleteList(Integer userId, List<Integer> skuIds) {
public Boolean deleteList(Integer userId, List<Integer> skuIds) {
// 更新 CartItemDO
cartMapper.updateListByUserIdAndSkuId(userId, skuIds, null, CartItemStatusEnum.DELETE_BY_MANUAL.getValue());
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> deleteAll(Integer userId) {
public Boolean deleteAll(Integer userId) {
return null;
}
@Override
public CommonResult<Integer> count(Integer userId) {
return CommonResult.success(cartMapper.selectQuantitySumByUserIdAndStatus(userId, CartItemStatusEnum.ENABLE.getValue()));
public Integer count(Integer userId) {
return cartMapper.selectQuantitySumByUserIdAndStatus(userId, CartItemStatusEnum.ENABLE.getValue());
}
@Override
public CommonResult<List<CartItemBO>> list(Integer userId, Boolean selected) {
public List<CartItemBO> list(Integer userId, Boolean selected) {
List<CartItemDO> items = cartMapper.selectByUserIdAndStatusAndSelected(userId, CartItemStatusEnum.ENABLE.getValue(), selected);
return CommonResult.success(CartConvert.INSTANCE.convert(items));
return CartConvert.INSTANCE.convert(items);
}
@Override
public CommonResult<CalcOrderPriceBO> calcOrderPrice(CalcOrderPriceDTO calcOrderPriceDTO) {
public CalcOrderPriceBO calcOrderPrice(CalcOrderPriceDTO calcOrderPriceDTO) {
// TODO 芋艿补充一些表单校验例如说需要传入用户编号
// 校验商品都存在
Map<Integer, CalcOrderPriceDTO.Item> calcOrderItemMap = calcOrderPriceDTO.getItems().stream()
.collect(Collectors.toMap(CalcOrderPriceDTO.Item::getSkuId, item -> item)); // KEYskuId
List<ProductSkuDetailBO> skus = productSpuService.getProductSkuDetailList(calcOrderItemMap.keySet());
if (skus.size() != calcOrderPriceDTO.getItems().size()) {
return ServiceExceptionUtil.error(OrderErrorCodeEnum.ORDER_ITEM_SOME_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.ORDER_ITEM_SOME_NOT_EXISTS.getCode());
}
// TODO 库存相关
// 查询促销活动
@ -172,11 +171,8 @@ public class CartServiceImpl implements CartService {
calcOrderPriceBO.setItemGroups(itemGroups);
// 4. 计算优惠劵
if (calcOrderPriceDTO.getCouponCardId() != null) {
CommonResult<Integer> result = modifyPriceByCouponCard(calcOrderPriceDTO.getUserId(), calcOrderPriceDTO.getCouponCardId(), itemGroups);
if (result.isError()) {
return CommonResult.error(result);
}
calcOrderPriceBO.setCouponCardDiscountTotal(result.getData());
Integer result = modifyPriceByCouponCard(calcOrderPriceDTO.getUserId(), calcOrderPriceDTO.getCouponCardId(), itemGroups);
calcOrderPriceBO.setCouponCardDiscountTotal(result);
}
// 5. 计算最终的价格
int buyTotal = 0;
@ -191,31 +187,31 @@ public class CartServiceImpl implements CartService {
String.format("价格合计( %d - %d == %d )不正确", buyTotal, discountTotal, presentTotal));
calcOrderPriceBO.setFee(new CalcOrderPriceBO.Fee(buyTotal, discountTotal, 0, presentTotal));
// 返回
return CommonResult.success(calcOrderPriceBO);
return calcOrderPriceBO;
}
@Override
@SuppressWarnings("Duplicates")
public CommonResult<CalcSkuPriceBO> calcSkuPrice(Integer skuId) {
public CalcSkuPriceBO calcSkuPrice(Integer skuId) {
// 查询 SKU 是否合法
ProductSkuBO sku = productSpuService.getProductSku(skuId);
if (sku == null
|| CommonStatusEnum.DISABLE.getValue().equals(sku.getStatus())) { // sku 被禁用
return ServiceExceptionUtil.error(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(OrderErrorCodeEnum.CARD_ITEM_SKU_NOT_FOUND.getCode());
}
// 查询促销活动
List<PromotionActivityBO> activityList = promotionActivityService.getPromotionActivityListBySpuId(sku.getSpuId(),
Arrays.asList(PromotionActivityStatusEnum.WAIT.getValue(), PromotionActivityStatusEnum.RUN.getValue()));
if (activityList.isEmpty()) { // 如果无促销活动则直接返回默认结果即可
return CommonResult.success(new CalcSkuPriceBO().setOriginalPrice(sku.getPrice()).setBuyPrice(sku.getPrice()));
return new CalcSkuPriceBO().setOriginalPrice(sku.getPrice()).setBuyPrice(sku.getPrice());
}
// 如果有促销活动则开始做计算 TODO 芋艿因为现在暂时只有限时折扣 + 满减送所以写的比较简单先
PromotionActivityBO fullPrivilege = findPromotionActivityByType(activityList, PromotionActivityTypeEnum.FULL_PRIVILEGE);
PromotionActivityBO timeLimitedDiscount = findPromotionActivityByType(activityList, PromotionActivityTypeEnum.TIME_LIMITED_DISCOUNT);
Integer presentPrice = calcSkuPriceByTimeLimitDiscount(sku, timeLimitedDiscount);
// 返回结果
return CommonResult.success(new CalcSkuPriceBO().setFullPrivilege(fullPrivilege).setTimeLimitedDiscount(timeLimitedDiscount)
.setOriginalPrice(sku.getPrice()).setBuyPrice(presentPrice));
return new CalcSkuPriceBO().setFullPrivilege(fullPrivilege).setTimeLimitedDiscount(timeLimitedDiscount)
.setOriginalPrice(sku.getPrice()).setBuyPrice(presentPrice);
}
private List<CalcOrderPriceBO.Item> initCalcOrderPriceItems(List<ProductSkuDetailBO> skus,
@ -306,14 +302,10 @@ public class CartServiceImpl implements CartService {
return itemGroups;
}
private CommonResult<Integer> modifyPriceByCouponCard(Integer userId, Integer couponCardId, List<CalcOrderPriceBO.ItemGroup> itemGroups) {
private Integer modifyPriceByCouponCard(Integer userId, Integer couponCardId, List<CalcOrderPriceBO.ItemGroup> itemGroups) {
Assert.isTrue(couponCardId != null, "优惠劵编号不能为空");
// 查询优惠劵
CommonResult<CouponCardDetailBO> couponCardResult = couponService.getCouponCardDetail(userId, couponCardId);
if (couponCardResult.isError()) {
return CommonResult.error(couponCardResult);
}
CouponCardDetailBO couponCard = couponCardResult.getData();
CouponCardDetailBO couponCard = couponService.getCouponCardDetail(userId, couponCardId);
// 获得匹配的商品
List<CalcOrderPriceBO.Item> items = new ArrayList<>();
if (RangeTypeEnum.ALL.getValue().equals(couponCard.getRangeType())) {
@ -347,7 +339,7 @@ public class CartServiceImpl implements CartService {
// 判断是否符合条件
int originalTotal = items.stream().mapToInt(CalcOrderPriceBO.Item::getPresentTotal).sum(); // 此处指的是以优惠劵视角的原价
if (originalTotal == 0 || originalTotal < couponCard.getPriceAvailable()) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_NOT_MATCH.getCode()); // TODO 芋艿这种情况会出现错误码的提示无法格式化出来另外这块的最佳实践找人讨论下
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_NOT_MATCH.getCode()); // TODO 芋艿这种情况会出现错误码的提示无法格式化出来另外这块的最佳实践找人讨论下
}
// 计算价格
// 获得到优惠信息进行价格计算
@ -370,7 +362,7 @@ public class CartServiceImpl implements CartService {
// 按比例拆分 presentTotal
splitDiscountPriceToItems(items, discountTotal, presentTotal);
// 返回优惠金额
return CommonResult.success(originalTotal - presentTotal);
return originalTotal - presentTotal;
}
/**

View File

@ -224,11 +224,7 @@ public class OrderServiceImpl implements OrderService {
}
// 价格计算
CommonResult<CalcOrderPriceBO> calcOrderPriceResult = calcOrderPrice(productList, orderCreateDTO);
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
CalcOrderPriceBO calcOrderPrice = calcOrderPriceResult.getData();
CalcOrderPriceBO calcOrderPrice = calcOrderPrice(productList, orderCreateDTO);
// 设置 orderItem
Map<Integer, ProductSkuDetailBO> productSpuBOMap = productList
@ -261,10 +257,7 @@ public class OrderServiceImpl implements OrderService {
// 标记优惠劵已使用
if (orderCreateDTO.getCouponCardId() != null) {
CommonResult<Boolean> useCouponCardResult = couponService.useCouponCard(userId, orderCreateDTO.getCouponCardId());
if (useCouponCardResult.isError()) {
return CommonResult.error(useCouponCardResult);
}
couponService.useCouponCard(userId, orderCreateDTO.getCouponCardId());
}
// TODO 芋艿扣除库存
@ -329,10 +322,7 @@ public class OrderServiceImpl implements OrderService {
orderItemMapper.insert(orderItemDOList);
// 创建预订单
CommonResult<PayTransactionBO> createPayTransactionResult = createPayTransaction(orderDO, orderItemDOList, orderCreateDTO.getIp());
if (calcOrderPriceResult.isError()) {
return CommonResult.error(calcOrderPriceResult);
}
createPayTransaction(orderDO, orderItemDOList, orderCreateDTO.getIp());
// if (commonResult.isError()) {
// //手动开启事务回滚
@ -349,7 +339,7 @@ public class OrderServiceImpl implements OrderService {
);
}
private CommonResult<CalcOrderPriceBO> calcOrderPrice(List<ProductSkuDetailBO> skus, OrderCreateDTO orderCreateDTO) {
private CalcOrderPriceBO calcOrderPrice(List<ProductSkuDetailBO> skus, OrderCreateDTO orderCreateDTO) {
// 创建计算的 DTO
CalcOrderPriceDTO calcOrderPriceDTO = new CalcOrderPriceDTO()
.setUserId(orderCreateDTO.getUserId())

View File

@ -0,0 +1,68 @@
package cn.iocoder.mall.pay.application.controller.admins;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.PayRefundService;
import cn.iocoder.mall.pay.api.PayTransactionService;
import cn.iocoder.mall.pay.api.bo.PayRefundBO;
import cn.iocoder.mall.pay.api.bo.PayRefundPageBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionBO;
import cn.iocoder.mall.pay.api.dto.PayRefundPageDTO;
import cn.iocoder.mall.pay.application.convert.PayRefundConvert;
import cn.iocoder.mall.pay.application.vo.admins.AdminsPayRefundPageVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("admins/refund")
public class AdminsPayRefundController {
@Reference(validation = "true", version = "${dubbo.provider.PayRefundService.version}")
private PayRefundService payRefundService;
@Reference(validation = "true", version = "${dubbo.provider.PayTransactionService.version}")
private PayTransactionService payTransactionService;
@GetMapping("/page")
public CommonResult<AdminsPayRefundPageVO> page(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "createBeginTime", required = false) Date createBeginTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "createEndTime", required = false) Date createEndTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "finishBeginTime", required = false) Date finishBeginTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "finishEndTime", required = false) Date finishEndTime,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "payChannel", required = false) Integer payChannel,
@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
PayRefundPageDTO payRefundPageDTO = new PayRefundPageDTO()
.setCreateBeginTime(createBeginTime).setCreateEndTime(createEndTime)
.setFinishBeginTime(finishBeginTime).setFinishEndTime(finishEndTime)
.setStatus(status).setPayChannel(payChannel)
.setPageNo(pageNo).setPageSize(pageSize);
// 执行查询
PayRefundPageBO refundBOPage = payRefundService.getRefundPage(payRefundPageDTO);
AdminsPayRefundPageVO result = new AdminsPayRefundPageVO()
.setList(PayRefundConvert.INSTANCE.convertList(refundBOPage.getList()))
.setTotal(refundBOPage.getTotal());
if (result.getList().isEmpty()) {
return success(result);
}
// 拼接结果
Map<Integer, PayTransactionBO> transactionMap = payTransactionService.getTransactionList(
result.getList().stream().map(PayRefundBO::getTransactionId).collect(Collectors.toSet()))
.stream().collect(Collectors.toMap(PayTransactionBO::getId, transaction -> transaction));
result.getList().forEach(refund -> refund.setTransaction(transactionMap.get(refund.getTransactionId())));
return success(result);
}
}

View File

@ -0,0 +1,50 @@
package cn.iocoder.mall.pay.application.controller.admins;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.PayTransactionService;
import cn.iocoder.mall.pay.api.bo.PayTransactionPageBO;
import cn.iocoder.mall.pay.api.dto.PayTransactionPageDTO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("admins/transaction")
public class AdminsPayTransactionController {
@Reference(validation = "true", version = "${dubbo.provider.PayTransactionService.version}")
private PayTransactionService payTransactionService;
@GetMapping("/page")
public CommonResult<PayTransactionPageBO> page(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "createBeginTime", required = false) Date createBeginTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "createEndTime", required = false) Date createEndTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "paymentBeginTime", required = false) Date paymentBeginTime,
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@RequestParam(value = "paymentEndTime", required = false) Date paymentEndTime,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "hasRefund", required = false) Boolean hasRefund,
@RequestParam(value = "payChannel", required = false) Integer payChannel,
@RequestParam(value = "orderSubject", required = false) String orderSubject,
@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
PayTransactionPageDTO payTransactionPageDTO = new PayTransactionPageDTO()
.setCreateBeginTime(createBeginTime).setCreateEndTime(createEndTime)
.setPaymentBeginTime(paymentBeginTime).setPaymentEndTime(paymentEndTime)
.setStatus(status).setHasRefund(hasRefund)
.setPayChannel(payChannel).setOrderSubject(orderSubject)
.setPageNo(pageNo).setPageSize(pageSize);
// 执行查询
return success(payTransactionService.getTransactionPage(payTransactionPageDTO));
}
}

View File

@ -3,9 +3,9 @@ package cn.iocoder.mall.pay.application.controller.users;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.PayRefundService;
import cn.iocoder.mall.pay.api.constant.PayChannelEnum;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@ -17,11 +17,11 @@ import java.io.IOException;
@RestController
@RequestMapping("users/refund") // TODO 芋艿理论来说是用户无关的这里先酱紫先~
public class PayRefundController {
public class UsersPayRefundController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
@Reference(validation = "true", version = "${dubbo.provider.PayRefundService.version}")
private PayRefundService payRefundService;
@PostMapping(value = "pingxx_refund_success", consumes = MediaType.APPLICATION_JSON_VALUE)

View File

@ -20,14 +20,15 @@ import java.io.IOException;
@RestController
@RequestMapping("users/transaction") // TODO 芋艿理论来说是用户无关的这里先酱紫先~
public class PayTransactionController {
public class UsersPayTransactionController {
private Logger logger = LoggerFactory.getLogger(getClass());
@Reference(validation = "true")
@Reference(validation = "true", version = "${dubbo.provider.PayTransactionService.version}")
private PayTransactionService payTransactionService;
@GetMapping("/get")
// TODO result 后面改下
public CommonResult<PayTransactionBO> get(@RequestParam("appId") String appId,
@RequestParam("orderId") String orderId) {
return payTransactionService.getTransaction(UserSecurityContextHolder.getContext().getUserId(), appId, orderId);

View File

@ -0,0 +1,19 @@
package cn.iocoder.mall.pay.application.convert;
import cn.iocoder.mall.pay.api.bo.PayRefundBO;
import cn.iocoder.mall.pay.application.vo.admins.AdminsPayRefundDetailVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public interface PayRefundConvert {
PayRefundConvert INSTANCE = Mappers.getMapper(PayRefundConvert.class);
@Mappings({})
List<AdminsPayRefundDetailVO> convertList(List<PayRefundBO> refunds);
}

View File

@ -0,0 +1,21 @@
package cn.iocoder.mall.pay.application.vo.admins;
import cn.iocoder.mall.pay.api.bo.PayRefundBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionBO;
import lombok.Data;
import lombok.experimental.Accessors;
/**
* 支付退款详细 VO
*/
@Data
@Accessors(chain = true)
public class AdminsPayRefundDetailVO extends PayRefundBO { // TODO 芋艿暂时偷懒下
/**
* 支付交易
*/
private PayTransactionBO transaction;
}

View File

@ -0,0 +1,25 @@
package cn.iocoder.mall.pay.application.vo.admins;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
/**
* 支付退款 Page VO
*/
@Data
@Accessors(chain = true)
public class AdminsPayRefundPageVO implements Serializable {
/**
* 支付退款数组
*/
private List<AdminsPayRefundDetailVO> list;
/**
* 总量
*/
private Integer total;
}

View File

@ -1,7 +1,9 @@
package cn.iocoder.mall.pay.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.bo.PayRefundPageBO;
import cn.iocoder.mall.pay.api.bo.PayRefundSubmitBO;
import cn.iocoder.mall.pay.api.dto.PayRefundPageDTO;
import cn.iocoder.mall.pay.api.dto.PayRefundSubmitDTO;
public interface PayRefundService {
@ -20,4 +22,6 @@ public interface PayRefundService {
*/
CommonResult<Boolean> updateRefundSuccess(Integer payChannel, String params);
PayRefundPageBO getRefundPage(PayRefundPageDTO payRefundPageDTO);
}

View File

@ -2,10 +2,15 @@ package cn.iocoder.mall.pay.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.bo.PayTransactionBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionPageBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionSubmitBO;
import cn.iocoder.mall.pay.api.dto.PayTransactionCreateDTO;
import cn.iocoder.mall.pay.api.dto.PayTransactionPageDTO;
import cn.iocoder.mall.pay.api.dto.PayTransactionSubmitDTO;
import java.util.Collection;
import java.util.List;
public interface PayTransactionService {
CommonResult<PayTransactionBO> getTransaction(Integer userId, String appId, String orderId);
@ -26,6 +31,10 @@ public interface PayTransactionService {
*/
CommonResult<Boolean> updateTransactionPaySuccess(Integer payChannel, String params);
List<PayTransactionBO> getTransactionList(Collection<Integer> ids);
PayTransactionPageBO getTransactionPage(PayTransactionPageDTO payTransactionPageDTO);
CommonResult cancelTransaction(); // TODO 1. params 2. result
}

View File

@ -0,0 +1,102 @@
package cn.iocoder.mall.pay.api.bo;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Date;
/**
* 支付退款 BO
*/
@Data
@Accessors(chain = true)
public class PayRefundBO {
/**
* 编号自增
*/
private Integer id;
/**
* 支付交易编号
*/
private Integer transactionId;
/**
* 生成传输给第三方的退款号
*
* 唯一索引
*/
private String refundCode;
/**
* 应用编号
*
* 不同业务线分配不同的 appId
* 举个例子
* 1. 电商系统的订单appId = 1024
* 2. 活动系统的订单appId = 2048
*/
private String appId;
/**
* 业务线的订单编号
*
* 1. 使用 String 的原因是业务线可能使用 String 做为编号
* 2. 每个 appId orderId 唯一
*/
private String orderId;
/**
* 发起交易的 IP
*/
private String createIp;
/**
* 业务退款描述
*/
private String orderDescription;
/**
* 退款金额单位
*
* TODO 暂时不考虑货币类型
*/
private Integer price;
/**
* 退款状态
*
* @see cn.iocoder.mall.pay.api.constant.PayRefundStatus
*/
private Integer status;
/**
* 回调业务线完成时间
*/
private Date finishTime;
/**
* 异步通知地址
*/
private String notifyUrl;
/**
* 扩展内容
*
* 异步通知的时候填充回调的数据
*/
private String extensionData;
/**
* 退款渠道
*/
private Integer refundChannel;
/**
* 第三方退款成功的时间
*/
private Date refundTime;
/**
* 收到第三方系统通知的时间
*
* 一般情况下即第三方系统的异步通知
*/
private Date notifyTime;
/**
* 第三方的流水号
*/
private String tradeNo;
/**
* 创建时间
*/
private Date createTime;
}

View File

@ -0,0 +1,25 @@
package cn.iocoder.mall.pay.api.bo;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
/**
* 支付退款 Page BO
*/
@Data
@Accessors(chain = true)
public class PayRefundPageBO implements Serializable {
/**
* 支付退款数组
*/
private List<PayRefundBO> list;
/**
* 总量
*/
private Integer total;
}

View File

@ -92,4 +92,11 @@ public class PayTransactionBO implements Serializable {
*/
private Date createTime;
// ========== 退款相关 ==========
/**
* 退款总金额
*/
private Integer refundTotal;
}

View File

@ -0,0 +1,25 @@
package cn.iocoder.mall.pay.api.bo;
import lombok.Data;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.List;
/**
* 支付交易 Page BO
*/
@Data
@Accessors(chain = true)
public class PayTransactionPageBO implements Serializable {
/**
* 支付交易数组
*/
private List<PayTransactionBO> list;
/**
* 总量
*/
private Integer total;
}

View File

@ -6,9 +6,9 @@ package cn.iocoder.mall.pay.api.constant;
public enum PayChannelEnum {
WEIXIN_APP(100, "wx", "微信 App 支付"),
WEIXIN_PUB(100, "wx", "微信 JS API 支付"),
WEIXIN_PUB(101, "wxjs", "微信 JS API 支付"),
ALIPAY(200, "alipay", "微信支付"),
ALIPAY(200, "alipay", "支付宝 App 支付"),
PINGXX(9999, "ping++", "ping++ 支付"),
;
@ -44,4 +44,4 @@ public enum PayChannelEnum {
return name;
}
}
}

View File

@ -0,0 +1,46 @@
package cn.iocoder.mall.pay.api.dto;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
* 支付退款分页 DTO
*/
@Data
@Accessors(chain = true)
public class PayRefundPageDTO {
/**
* 创建时间开始
*/
private Date createBeginTime;
/**
* 创建时间结束
*/
private Date createEndTime;
/**
* 完成时间开始
*/
private Date finishBeginTime;
/**
* 完成时间结束
*/
private Date finishEndTime;
/**
* 退款状态
*/
private Integer status;
/**
* 支付渠道
*/
private Integer payChannel;
@NotNull(message = "页码不能为空")
private Integer pageNo;
@NotNull(message = "每页条数不能为空")
private Integer pageSize;
}

View File

@ -0,0 +1,56 @@
package cn.iocoder.mall.pay.api.dto;
import lombok.Data;
import lombok.experimental.Accessors;
import javax.validation.constraints.NotNull;
import java.util.Date;
/**
* 支付交易分页 DTO
*/
@Data
@Accessors(chain = true)
public class PayTransactionPageDTO {
/**
* 创建时间开始
*/
private Date createBeginTime;
/**
* 创建时间结束
*/
private Date createEndTime;
/**
* 支付时间开始
*/
private Date paymentBeginTime;
/**
* 支付时间结束
*/
private Date paymentEndTime;
/**
* 支付状态
*/
private Integer status;
/**
* 是否有退款
*/
private Boolean hasRefund;
/**
* 支付渠道
*/
private Integer payChannel;
/**
* 商品标题
*
* 模糊匹配
*/
private String orderSubject;
@NotNull(message = "页码不能为空")
private Integer pageNo;
@NotNull(message = "每页条数不能为空")
private Integer pageSize;
}

View File

@ -1,11 +1,14 @@
package cn.iocoder.mall.pay.biz.convert;
import cn.iocoder.mall.pay.api.bo.PayRefundBO;
import cn.iocoder.mall.pay.api.dto.PayRefundSubmitDTO;
import cn.iocoder.mall.pay.biz.dataobject.PayRefundDO;
import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public interface PayRefundConvert {
@ -14,4 +17,10 @@ public interface PayRefundConvert {
@Mappings({})
PayRefundDO convert(PayRefundSubmitDTO payRefundSubmitDTO);
@Mappings({})
PayRefundBO convert(PayRefundDO refund);
@Mappings({})
List<PayRefundBO> convertList(List<PayRefundDO> refunds);
}

View File

@ -9,6 +9,8 @@ import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
import java.util.List;
@Mapper
public interface PayTransactionConvert {
@ -20,6 +22,9 @@ public interface PayTransactionConvert {
@Mappings({})
PayTransactionBO convert(PayTransactionDO payTransactionDO);
@Mappings({})
List<PayTransactionBO> convertList(List<PayTransactionDO> list);
@Mappings({})
PayTransactionExtensionDO convert(PayTransactionSubmitDTO payTransactionSubmitDTO);

View File

@ -4,6 +4,9 @@ import cn.iocoder.mall.pay.biz.dataobject.PayRefundDO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.Date;
import java.util.List;
@Repository
public interface PayRefundMapper {
@ -16,4 +19,20 @@ public interface PayRefundMapper {
PayRefundDO selectByRefundCode(@Param("refundCode") String refundCode);
List<PayRefundDO> selectListByPage(@Param("createBeginTime") Date createBeginTime,
@Param("createEndTime") Date createEndTime,
@Param("finishBeginTime") Date finishBeginTime,
@Param("finishEndTime") Date finishEndTime,
@Param("status") Integer status,
@Param("payChannel") Integer payChannel,
@Param("offset") Integer offset,
@Param("limit") Integer limit);
Integer selectCountByPage(@Param("createBeginTime") Date createBeginTime,
@Param("createEndTime") Date createEndTime,
@Param("finishBeginTime") Date finishBeginTime,
@Param("finishEndTime") Date finishEndTime,
@Param("status") Integer status,
@Param("payChannel") Integer payChannel);
}

View File

@ -4,6 +4,10 @@ import cn.iocoder.mall.pay.biz.dataobject.PayTransactionDO;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@Repository
public interface PayTransactionMapper {
@ -20,4 +24,26 @@ public interface PayTransactionMapper {
PayTransactionDO selectById(@Param("id") Integer id);
List<PayTransactionDO> selectListByIds(@Param("ids") Collection<Integer> ids);
List<PayTransactionDO> selectListByPage(@Param("createBeginTime") Date createBeginTime,
@Param("createEndTime") Date createEndTime,
@Param("paymentBeginTime") Date paymentBeginTime,
@Param("paymentEndTime") Date paymentEndTime,
@Param("status") Integer status,
@Param("hasRefund") Boolean hasRefund,
@Param("payChannel") Integer payChannel,
@Param("orderSubject") String orderSubject,
@Param("offset") Integer offset,
@Param("limit") Integer limit);
Integer selectCountByPage(@Param("createBeginTime") Date createBeginTime,
@Param("createEndTime") Date createEndTime,
@Param("paymentBeginTime") Date paymentBeginTime,
@Param("paymentEndTime") Date paymentEndTime,
@Param("status") Integer status,
@Param("hasRefund") Boolean hasRefund,
@Param("payChannel") Integer payChannel,
@Param("orderSubject") String orderSubject);
}

View File

@ -5,10 +5,12 @@ import cn.iocoder.common.framework.util.MathUtil;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.PayRefundService;
import cn.iocoder.mall.pay.api.bo.PayRefundPageBO;
import cn.iocoder.mall.pay.api.bo.PayRefundSubmitBO;
import cn.iocoder.mall.pay.api.constant.PayErrorCodeEnum;
import cn.iocoder.mall.pay.api.constant.PayRefundStatus;
import cn.iocoder.mall.pay.api.constant.PayTransactionStatusEnum;
import cn.iocoder.mall.pay.api.dto.PayRefundPageDTO;
import cn.iocoder.mall.pay.api.dto.PayRefundSubmitDTO;
import cn.iocoder.mall.pay.biz.client.AbstractPaySDK;
import cn.iocoder.mall.pay.biz.client.PaySDKFactory;
@ -30,7 +32,7 @@ import javax.annotation.Resource;
import java.util.Date;
@Service
@org.apache.dubbo.config.annotation.Service(validation = "true")
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.PayRefundService.version}")
public class PayRefundServiceImpl implements PayRefundService {
private Logger logger = LoggerFactory.getLogger(getClass());
@ -120,6 +122,7 @@ public class PayRefundServiceImpl implements PayRefundService {
PayRefundDO updatePayRefundDO = new PayRefundDO()
.setId(payRefund.getId())
.setStatus(status)
.setTradeNo(paySuccessResult.getData().getTradeNo())
.setExtensionData(params);
int updateCounts = payRefundMapper.update(updatePayRefundDO, PayRefundStatus.WAITING.getValue());
if (updateCounts == 0) { // 校验状态必须是待支付
@ -147,6 +150,24 @@ public class PayRefundServiceImpl implements PayRefundService {
return CommonResult.success(true);
}
@Override
public PayRefundPageBO getRefundPage(PayRefundPageDTO payRefundPageDTO) {
PayRefundPageBO payRefundPageBO = new PayRefundPageBO();
// 查询分页数据
int offset = (payRefundPageDTO.getPageNo() - 1) * payRefundPageDTO.getPageSize();
payRefundPageBO.setList(PayRefundConvert.INSTANCE.convertList(payRefundMapper.selectListByPage(
payRefundPageDTO.getCreateBeginTime(), payRefundPageDTO.getCreateEndTime(),
payRefundPageDTO.getFinishBeginTime(), payRefundPageDTO.getFinishEndTime(),
payRefundPageDTO.getStatus(), payRefundPageDTO.getPayChannel(),
offset, payRefundPageDTO.getPageSize())));
// 查询分页总数
payRefundPageBO.setTotal(payRefundMapper.selectCountByPage(
payRefundPageDTO.getCreateBeginTime(), payRefundPageDTO.getCreateEndTime(),
payRefundPageDTO.getFinishBeginTime(), payRefundPageDTO.getFinishEndTime(),
payRefundPageDTO.getStatus(), payRefundPageDTO.getPayChannel()));
return payRefundPageBO;
}
private String generateTransactionCode() {
// wx
// 2014

View File

@ -6,18 +6,20 @@ import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.pay.api.PayTransactionService;
import cn.iocoder.mall.pay.api.bo.PayTransactionBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionPageBO;
import cn.iocoder.mall.pay.api.bo.PayTransactionSubmitBO;
import cn.iocoder.mall.pay.api.constant.PayErrorCodeEnum;
import cn.iocoder.mall.pay.api.constant.PayTransactionStatusEnum;
import cn.iocoder.mall.pay.api.dto.PayTransactionCreateDTO;
import cn.iocoder.mall.pay.api.dto.PayTransactionPageDTO;
import cn.iocoder.mall.pay.api.dto.PayTransactionSubmitDTO;
import cn.iocoder.mall.pay.biz.client.AbstractPaySDK;
import cn.iocoder.mall.pay.biz.client.PaySDKFactory;
import cn.iocoder.mall.pay.biz.client.TransactionSuccessBO;
import cn.iocoder.mall.pay.biz.convert.PayTransactionConvert;
import cn.iocoder.mall.pay.biz.dao.PayNotifyTaskMapper;
import cn.iocoder.mall.pay.biz.dao.PayTransactionExtensionMapper;
import cn.iocoder.mall.pay.biz.dao.PayTransactionMapper;
import cn.iocoder.mall.pay.biz.dao.PayNotifyTaskMapper;
import cn.iocoder.mall.pay.biz.dataobject.PayAppDO;
import cn.iocoder.mall.pay.biz.dataobject.PayTransactionDO;
import cn.iocoder.mall.pay.biz.dataobject.PayTransactionExtensionDO;
@ -27,10 +29,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collection;
import java.util.Date;
import java.util.List;
@Service
@org.apache.dubbo.config.annotation.Service(validation = "true")
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.PayTransactionService.version}")
public class PayTransactionServiceImpl implements PayTransactionService {
private Logger logger = LoggerFactory.getLogger(getClass());
@ -193,6 +197,31 @@ public class PayTransactionServiceImpl implements PayTransactionService {
return CommonResult.success(true);
}
@Override
public List<PayTransactionBO> getTransactionList(Collection<Integer> ids) {
return PayTransactionConvert.INSTANCE.convertList(payTransactionMapper.selectListByIds(ids));
}
@Override
public PayTransactionPageBO getTransactionPage(PayTransactionPageDTO payTransactionPageDTO) {
PayTransactionPageBO payTransactionPage = new PayTransactionPageBO();
// 查询分页数据
int offset = (payTransactionPageDTO.getPageNo() - 1) * payTransactionPageDTO.getPageSize();
payTransactionPage.setList(PayTransactionConvert.INSTANCE.convertList(payTransactionMapper.selectListByPage(
payTransactionPageDTO.getCreateBeginTime(), payTransactionPageDTO.getCreateEndTime(),
payTransactionPageDTO.getPaymentBeginTime(), payTransactionPageDTO.getPaymentEndTime(),
payTransactionPageDTO.getStatus(), payTransactionPageDTO.getHasRefund(),
payTransactionPageDTO.getPayChannel(), payTransactionPageDTO.getOrderSubject(),
offset, payTransactionPageDTO.getPageSize())));
// 查询分页总数
payTransactionPage.setTotal(payTransactionMapper.selectCountByPage(
payTransactionPageDTO.getCreateBeginTime(), payTransactionPageDTO.getCreateEndTime(),
payTransactionPageDTO.getPaymentBeginTime(), payTransactionPageDTO.getPaymentEndTime(),
payTransactionPageDTO.getStatus(), payTransactionPageDTO.getHasRefund(),
payTransactionPageDTO.getPayChannel(), payTransactionPageDTO.getOrderSubject()));
return payTransactionPage;
}
@Override // TODO 芋艿后面去实现
public CommonResult cancelTransaction() {
return null;

View File

@ -23,6 +23,11 @@ dubbo:
name: dubbo
scan:
base-packages: cn.iocoder.mall.pay.biz.service
provider:
PayTransactionService:
version: 1.0.0
PayRefundService:
version: 1.0.0
# rocketmq
rocketmq:

View File

@ -66,4 +66,57 @@
WHERE id = #{id}
</select>
<select id="selectListByPage" resultType="PayRefundDO">
SELECT
<include refid="FIELDS"/>
FROM refund
<where>
<if test="createBeginTime != null">
AND create_time >= #{createBeginTime}
</if>
<if test="createEndTime != null">
AND #{createEndTime} >= create_time
</if>
<if test="finishBeginTime != null">
AND finish_time >= #{finishBeginTime}
</if>
<if test="finishEndTime != null">
AND #{finishEndTime} >= finish_time
</if>
<if test="status != null">
AND status = #{status}
</if>
<if test="payChannel != null">
AND pay_channel = #{payChannel}
</if>
</where>
LIMIT #{offset}, #{limit}
</select>
<select id="selectCountByPage" resultType="Integer">
SELECT
COUNT(1)
FROM refund
<where>
<if test="createBeginTime != null">
AND create_time >= #{createBeginTime}
</if>
<if test="createEndTime != null">
AND #{createEndTime} >= create_time
</if>
<if test="finishBeginTime != null">
AND finish_time >= #{finishBeginTime}
</if>
<if test="finishEndTime != null">
AND #{finishEndTime} >= finish_time
</if>
<if test="status != null">
AND status = #{status}
</if>
<if test="payChannel != null">
AND pay_channel = #{payChannel}
</if>
</where>
</select>
</mapper>

View File

@ -75,4 +75,85 @@
WHERE id = #{id}
</select>
<select id="selectListByIds" resultType="PayTransactionDO">
SELECT
<include refid="FIELDS" />
FROM transaction
WHERE id IN
<foreach item="id" collection="ids" separator="," open="(" close=")" index="">
#{id}
</foreach>
</select>
<select id="selectListByPage" resultType="PayTransactionDO">
SELECT
<include refid="FIELDS"/>
FROM transaction
<where>
<if test="createBeginTime != null">
AND create_time >= #{createBeginTime}
</if>
<if test="createEndTime != null">
AND #{createEndTime} >= create_time
</if>
<if test="paymentBeginTime != null">
AND payment_time >= #{paymentBeginTime}
</if>
<if test="paymentEndTime != null">
AND #{paymentEndTime} >= payment_time
</if>
<if test="status != null">
AND status = #{status}
</if>
<if test="hasRefund == true">
AND refund_total > 0
</if>
<if test="hasRefund == false">
AND refund_total = 0
</if>
<if test="payChannel != null">
AND pay_channel = #{payChannel}
</if>
<if test="orderSubject != null">
order_subject LIKE "%"#{orderSubject}"%"
</if>
</where>
LIMIT #{offset}, #{limit}
</select>
<select id="selectCountByPage" resultType="Integer">
SELECT
COUNT(1)
FROM transaction
<where>
<if test="createBeginTime != null">
AND create_time >= #{createBeginTime}
</if>
<if test="createEndTime != null">
AND #{createEndTime} >= create_time
</if>
<if test="paymentBeginTime != null">
AND payment_time >= #{paymentBeginTime}
</if>
<if test="paymentEndTime != null">
AND #{paymentEndTime} >= payment_time
</if>
<if test="status != null">
AND status = #{status}
</if>
<if test="hasRefund == true">
AND refund_total > 0
</if>
<if test="hasRefund == false">
AND refund_total = 0
</if>
<if test="payChannel != null">
AND pay_channel = #{payChannel}
</if>
<if test="orderSubject != null">
order_subject LIKE "%"#{orderSubject}"%"
</if>
</where>
</select>
</mapper>

View File

@ -22,6 +22,8 @@ import org.springframework.web.bind.annotation.*;
import java.util.Date;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("admins/coupon")
@Api("优惠劵(码)模块")
@ -48,10 +50,10 @@ public class AdminsCouponController {
@RequestParam(value = "preferentialType", required = false) Integer preferentialType,
@RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
CommonResult<CouponTemplatePageBO> result = couponService.getCouponTemplatePage(new CouponTemplatePageDTO()
CouponTemplatePageBO result = couponService.getCouponTemplatePage(new CouponTemplatePageDTO()
.setType(type).setTitle(title).setStatus(status).setPreferentialType(preferentialType)
.setPageNo(pageNo).setPageSize(pageSize));
return CouponTemplateConvert.INSTANCE.convert(result);
return success(CouponTemplateConvert.ADMINS.convertPage(result));
}
@PostMapping("/template/add_card")
@ -103,9 +105,9 @@ public class AdminsCouponController {
.setFixedBeginTerm(fixedBeginTerm).setFixedEndTerm(fixedEndTerm)
.setPreferentialType(preferentialType).setPriceOff(priceOff).setPercentOff(percentOff).setDiscountPriceLimit(discountPriceLimit);
// 提交请求
CommonResult<CouponTemplateBO> result = couponService.addCouponCardTemplate(couponCardTemplateAddDTO);
CouponTemplateBO result = couponService.addCouponCardTemplate(couponCardTemplateAddDTO);
// 返回结果
return CouponTemplateConvert.INSTANCE.convert2(result);
return success(CouponTemplateConvert.ADMINS.convert(result));
}
@PostMapping("/template/update_card")
@ -132,7 +134,7 @@ public class AdminsCouponController {
.setTitle(title).setDescription(description)
.setQuota(quota).setTotal(total)
.setRangeType(rangeType).setRangeValues(rangeValues);
return couponService.updateCouponCardTemplate(couponCardTemplateUpdateDTO);
return success(couponService.updateCouponCardTemplate(couponCardTemplateUpdateDTO));
}
@PostMapping("/template/update_status")
@ -143,7 +145,7 @@ public class AdminsCouponController {
})
public CommonResult<Boolean> templateUpdateStatus(@RequestParam("id") Integer id,
@RequestParam("status") Integer status) {
return couponService.updateCouponTemplateStatus(AdminSecurityContextHolder.getContext().getAdminId(), id, status);
return success(couponService.updateCouponTemplateStatus(AdminSecurityContextHolder.getContext().getAdminId(), id, status));
}
// ========== 优惠劵 ==========

View File

@ -20,6 +20,8 @@ import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("users/coupon")
@Api("优惠劵(码)模块")
@ -35,8 +37,8 @@ public class UsersCouponController {
@ApiImplicitParam(name = "id", value = "优惠劵(码)模板编号", required = true, example = "10")
@PermitAll
public CommonResult<UsersCouponTemplateVO> templateGet(@RequestParam("id") Integer id) {
CouponTemplateBO template = couponService.getCouponTemplate(id).getData();
return CommonResult.success(CouponTemplateConvert.INSTANCE.convert2(template));
CouponTemplateBO template = couponService.getCouponTemplate(id);
return success(CouponTemplateConvert.USERS.convert2(template));
}
// ========== 优惠劵 ==========
@ -51,18 +53,18 @@ public class UsersCouponController {
public CommonResult<UsersCouponCardPageVO> cardPage(@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
CommonResult<CouponCardPageBO> result = couponService.getCouponCardPage(new CouponCardPageDTO()
CouponCardPageBO result = couponService.getCouponCardPage(new CouponCardPageDTO()
.setStatus(status).setUserId(UserSecurityContextHolder.getContext().getUserId())
.setPageNo(pageNo).setPageSize(pageSize));
return CouponCardConvert.INSTANCE.convert2(result);
return success(CouponCardConvert.INSTANCE.convert2(result));
}
@PostMapping("/card/add")
@ApiOperation(value = "领取优惠劵")
@ApiImplicitParam(name = "templateId", value = "优惠劵(码)模板编号", required = true, example = "10")
public CommonResult<UsersCouponCardVO> cardAdd(@RequestParam("templateId") Integer templateId) {
CommonResult<CouponCardBO> result = couponService.addCouponCard(UserSecurityContextHolder.getContext().getUserId(), templateId);
return CouponCardConvert.INSTANCE.convert(result);
CouponCardBO result = couponService.addCouponCard(UserSecurityContextHolder.getContext().getUserId(), templateId);
return success(CouponCardConvert.INSTANCE.convert(result));
}
// ========== 优惠码 ==========

View File

@ -1,6 +1,5 @@
package cn.iocoder.mall.promotion.application.convert;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.promotion.api.bo.CouponCardBO;
import cn.iocoder.mall.promotion.api.bo.CouponCardPageBO;
import cn.iocoder.mall.promotion.application.vo.users.UsersCouponCardPageVO;
@ -15,13 +14,15 @@ public interface CouponCardConvert {
CouponCardConvert INSTANCE = Mappers.getMapper(CouponCardConvert.class);
@Mappings({})
CommonResult<UsersCouponCardVO> convert(CommonResult<CouponCardBO> result);
UsersCouponCardVO convert(CouponCardBO result);
@Mappings({})
CommonResult<UsersCouponCardPageVO> convert2(CommonResult<CouponCardPageBO> result);
UsersCouponCardPageVO convert2(CouponCardPageBO result);
//
// @Mappings({})
// List<UsersCouponTemplateVO> convertList2(List<CouponTemplateBO> banners);
}

View File

@ -1,6 +1,5 @@
package cn.iocoder.mall.promotion.application.convert;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.promotion.api.bo.CouponTemplateBO;
import cn.iocoder.mall.promotion.api.bo.CouponTemplatePageBO;
import cn.iocoder.mall.promotion.application.vo.admins.AdminsCouponTemplatePageVO;
@ -15,25 +14,30 @@ import java.util.List;
@Mapper
public interface CouponTemplateConvert {
CouponTemplateConvert INSTANCE = Mappers.getMapper(CouponTemplateConvert.class);
Users USERS = Mappers.getMapper(Users.class);
@Mappings({})
AdminsCouponTemplateVO convert(CouponTemplateBO template);
Admins ADMINS = Mappers.getMapper(Admins.class);
@Mappings({})
CommonResult<AdminsCouponTemplateVO> convert2(CommonResult<CouponTemplateBO> result);
@Mapper
interface Admins {
@Mappings({})
CommonResult<AdminsCouponTemplatePageVO> convert(CommonResult<CouponTemplatePageBO> result);
@Mappings({})
AdminsCouponTemplateVO convert(CouponTemplateBO template);
@Mappings({})
List<AdminsCouponTemplateVO> convertList(List<CouponTemplateBO> templates);
@Mappings({})
AdminsCouponTemplatePageVO convertPage(CouponTemplatePageBO result);
@Mappings({})
UsersCouponTemplateVO convert2(CouponTemplateBO template);
@Mappings({})
List<AdminsCouponTemplateVO> convertList(List<CouponTemplateBO> templates);
//
// @Mappings({})
// List<UsersCouponTemplateVO> convertList2(List<CouponTemplateBO> banners);
}
@Mapper
interface Users {
@Mappings({})
UsersCouponTemplateVO convert2(CouponTemplateBO template);
}
}

View File

@ -1,7 +1,6 @@
package cn.iocoder.mall.promotion.api;
import cn.iocoder.common.framework.validator.InEnum;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.promotion.api.bo.*;
import cn.iocoder.mall.promotion.api.constant.CouponTemplateStatusEnum;
import cn.iocoder.mall.promotion.api.dto.*;
@ -13,9 +12,9 @@ public interface CouponService {
// ========== 优惠劵模板 ==========
CommonResult<CouponTemplateBO> getCouponTemplate(Integer couponTemplateId);
CouponTemplateBO getCouponTemplate(Integer couponTemplateId);
CommonResult<CouponTemplatePageBO> getCouponTemplatePage(CouponTemplatePageDTO couponTemplatePageDTO);
CouponTemplatePageBO getCouponTemplatePage(CouponTemplatePageDTO couponTemplatePageDTO);
/**
* 创建优惠码模板
@ -23,7 +22,7 @@ public interface CouponService {
* @param couponCodeTemplateAddDTO 优惠码模板添加 DTO
* @return 优惠码模板
*/
CommonResult<CouponTemplateBO> addCouponCodeTemplate(CouponCodeTemplateAddDTO couponCodeTemplateAddDTO);
CouponTemplateBO addCouponCodeTemplate(CouponCodeTemplateAddDTO couponCodeTemplateAddDTO);
/**
* 创建优惠劵模板
@ -31,7 +30,7 @@ public interface CouponService {
* @param couponCardTemplateAddDTO 优惠码模板添加 DTO
* @return 优惠劵模板
*/
CommonResult<CouponTemplateBO> addCouponCardTemplate(CouponCardTemplateAddDTO couponCardTemplateAddDTO);
CouponTemplateBO addCouponCardTemplate(CouponCardTemplateAddDTO couponCardTemplateAddDTO);
/**
* 更新优惠码模板
@ -39,7 +38,7 @@ public interface CouponService {
* @param couponCodeTemplateUpdateDTO 优惠码模板修改 DTO
* @return 是否成功
*/
CommonResult<Boolean> updateCouponCodeTemplate(CouponCodeTemplateUpdateDTO couponCodeTemplateUpdateDTO);
Boolean updateCouponCodeTemplate(CouponCodeTemplateUpdateDTO couponCodeTemplateUpdateDTO);
/**
* 更新优惠劵模板
@ -47,71 +46,70 @@ public interface CouponService {
* @param couponCardTemplateUpdateDTO 优惠劵模板修改 DTO
* @return 是否成功
*/
CommonResult<Boolean> updateCouponCardTemplate(CouponCardTemplateUpdateDTO couponCardTemplateUpdateDTO);
Boolean updateCouponCardTemplate(CouponCardTemplateUpdateDTO couponCardTemplateUpdateDTO);
/**
* 更新优惠劵模板的状态
*
* @param adminId 操作管理员编号
* @param adminId 操作管理员编号
* @param couponTemplateId 模板编号
* @param status 状态
* @param status 状态
* @return 是否成功
*/
CommonResult<Boolean> updateCouponTemplateStatus(Integer adminId, Integer couponTemplateId,
@InEnum(value = CouponTemplateStatusEnum.class, message = "修改状态必须是 {value}") Integer status);
Boolean updateCouponTemplateStatus(Integer adminId, Integer couponTemplateId,
@InEnum(value = CouponTemplateStatusEnum.class, message = "修改状态必须是 {value}") Integer status);
// ========== 优惠劵 ==========
CommonResult<CouponCardPageBO> getCouponCardPage(CouponCardPageDTO couponCardPageDTO);
CouponCardPageBO getCouponCardPage(CouponCardPageDTO couponCardPageDTO);
/**
* 基于优惠劵模板领取优惠劵
*
* @param userId 用户编号
* @param userId 用户编号
* @param couponTemplateId 优惠劵模板
* @return 优惠劵
*/
CommonResult<CouponCardBO> addCouponCard(Integer userId, Integer couponTemplateId);
CouponCardBO addCouponCard(Integer userId, Integer couponTemplateId);
/**
* 使用优惠劵下单
*
* @param userId 用户编号
* @param userId 用户编号
* @param couponCardId 优惠劵编号
* @return 是否成功
*/
CommonResult<Boolean> useCouponCard(Integer userId,
Boolean useCouponCard(Integer userId,
@NotNull(message = "优惠劵编号不能为空") Integer couponCardId);
/**
* 取消优惠劵的使用
*
* @param userId 用户编号
* @param userId 用户编号
* @param couponCardId 优惠劵编号
* @return 是否成功
*/
CommonResult<Boolean> cancelUseCouponCard(Integer userId, Integer couponCardId);
Boolean cancelUseCouponCard(Integer userId, Integer couponCardId);
/**
* 获得指定优惠劵
*
* @param userId 用户编号
* @param userId 用户编号
* @param couponCardId 优惠劵编号
* @return 优惠劵
*/
CommonResult<CouponCardDetailBO> getCouponCardDetail(Integer userId, Integer couponCardId);
CouponCardDetailBO getCouponCardDetail(Integer userId, Integer couponCardId);
/**
* 获得用户所有优惠劵并标明是否可用
*
* <p>
* 注意spus 是作为条件判断优惠劵是否可用
*
* @param userId 用户编号
* @param spus 匹配的商品/分类
* @param spus 匹配的商品/分类
* @return 优惠劵列表
*/
CommonResult<List<CouponCardAvailableBO>> getCouponCardList(Integer userId, List<CouponCardSpuDTO> spus);
List<CouponCardAvailableBO> getCouponCardList(Integer userId, List<CouponCardSpuDTO> spus);
// ========== 优惠码 ==========
@ -119,9 +117,9 @@ public interface CouponService {
* 使用优惠码兑换优惠劵
*
* @param userId 用户编号
* @param code 优惠码
* @param code 优惠码
* @return 优惠劵
*/
CommonResult<CouponCardBO> useCouponCode(Integer userId, String code);
CouponCardBO useCouponCode(Integer userId, String code);
}

View File

@ -4,7 +4,6 @@ import cn.iocoder.common.framework.constant.SysErrorCodeEnum;
import cn.iocoder.common.framework.util.DateUtil;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.util.StringUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.promotion.api.CouponService;
import cn.iocoder.mall.promotion.api.bo.*;
import cn.iocoder.mall.promotion.api.constant.*;
@ -35,13 +34,13 @@ public class CouponServiceImpl implements CouponService {
// ========== 优惠劵模板 ==========
@Override
public CommonResult<CouponTemplateBO> getCouponTemplate(Integer couponTemplateId) {
public CouponTemplateBO getCouponTemplate(Integer couponTemplateId) {
CouponTemplateDO template = couponTemplateMapper.selectById(couponTemplateId);
return CommonResult.success(CouponTemplateConvertImpl.INSTANCE.convert(template));
return CouponTemplateConvertImpl.INSTANCE.convert(template);
}
@Override
public CommonResult<CouponTemplatePageBO> getCouponTemplatePage(CouponTemplatePageDTO couponTemplatePageDTO) {
public CouponTemplatePageBO getCouponTemplatePage(CouponTemplatePageDTO couponTemplatePageDTO) {
CouponTemplatePageBO couponTemplatePageBO = new CouponTemplatePageBO();
// 查询分页数据
int offset = (couponTemplatePageDTO.getPageNo() - 1) * couponTemplatePageDTO.getPageSize();
@ -53,31 +52,24 @@ public class CouponServiceImpl implements CouponService {
couponTemplatePageBO.setTotal(couponTemplateMapper.selectCountByPage(
couponTemplatePageDTO.getType(), couponTemplatePageDTO.getTitle(),
couponTemplatePageDTO.getStatus(), couponTemplatePageDTO.getPreferentialType()));
return CommonResult.success(couponTemplatePageBO);
return couponTemplatePageBO;
}
@Override
public CommonResult<CouponTemplateBO> addCouponCodeTemplate(CouponCodeTemplateAddDTO couponCodeTemplateAddDTO) {
public CouponTemplateBO addCouponCodeTemplate(CouponCodeTemplateAddDTO couponCodeTemplateAddDTO) {
return null;
}
@Override
public CommonResult<CouponTemplateBO> addCouponCardTemplate(CouponCardTemplateAddDTO couponCardTemplateAddDTO) {
public CouponTemplateBO addCouponCardTemplate(CouponCardTemplateAddDTO couponCardTemplateAddDTO) {
// 校验生效日期相关
CommonResult<Boolean> checkCouponCodeTemplateDateTypeResult = this.checkCouponTemplateDateType(
couponCardTemplateAddDTO.getDateType(),
checkCouponTemplateDateType(couponCardTemplateAddDTO.getDateType(),
couponCardTemplateAddDTO.getValidStartTime(), couponCardTemplateAddDTO.getValidEndTime(),
couponCardTemplateAddDTO.getFixedBeginTerm(), couponCardTemplateAddDTO.getFixedEndTerm());
if (checkCouponCodeTemplateDateTypeResult.isError()) {
return CommonResult.error(checkCouponCodeTemplateDateTypeResult);
}
// 校验优惠类型
CommonResult<Boolean> checkCouponTemplateDateTypeResult = this.checkCouponTemplatePreferentialType(
Boolean checkCouponTemplateDateTypeResult = checkCouponTemplatePreferentialType(
couponCardTemplateAddDTO.getPreferentialType(), couponCardTemplateAddDTO.getPercentOff(),
couponCardTemplateAddDTO.getPriceOff(), couponCardTemplateAddDTO.getPriceAvailable());
if (checkCouponTemplateDateTypeResult.isError()) {
return CommonResult.error(checkCouponTemplateDateTypeResult);
}
// 保存优惠劵模板到数据库
CouponTemplateDO template = CouponTemplateConvert.INSTANCE.convert(couponCardTemplateAddDTO)
.setType(CouponTemplateTypeEnum.CARD.getValue())
@ -86,97 +78,97 @@ public class CouponServiceImpl implements CouponService {
template.setCreateTime(new Date());
couponTemplateMapper.insert(template);
// 返回成功
return CommonResult.success(CouponTemplateConvert.INSTANCE.convert(template));
return CouponTemplateConvert.INSTANCE.convert(template);
}
@Override
public CommonResult<Boolean> updateCouponCodeTemplate(CouponCodeTemplateUpdateDTO couponCodeTemplateUpdateDTO) {
public Boolean updateCouponCodeTemplate(CouponCodeTemplateUpdateDTO couponCodeTemplateUpdateDTO) {
return null;
}
@Override
public CommonResult<Boolean> updateCouponCardTemplate(CouponCardTemplateUpdateDTO couponCardTemplateUpdateDTO) {
public Boolean updateCouponCardTemplate(CouponCardTemplateUpdateDTO couponCardTemplateUpdateDTO) {
// 校验 CouponCardTemplate 存在
CouponTemplateDO template = couponTemplateMapper.selectById(couponCardTemplateUpdateDTO.getId());
if (template == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
}
// 校验 CouponCardTemplate CARD
if (!CouponTemplateTypeEnum.CARD.getValue().equals(template.getType())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_CARD.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_CARD.getCode());
}
// 校验发放数量不能减少
if (couponCardTemplateUpdateDTO.getTotal() < template.getTotal()) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_TOTAL_CAN_NOT_REDUCE.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_TOTAL_CAN_NOT_REDUCE.getCode());
}
// 更新优惠劵模板到数据库
CouponTemplateDO updateTemplateDO = CouponTemplateConvert.INSTANCE.convert(couponCardTemplateUpdateDTO);
couponTemplateMapper.update(updateTemplateDO);
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> updateCouponTemplateStatus(Integer adminId, Integer couponTemplateId, Integer status) {
public Boolean updateCouponTemplateStatus(Integer adminId, Integer couponTemplateId, Integer status) {
// 校验 CouponCardTemplate 存在
CouponTemplateDO template = couponTemplateMapper.selectById(couponTemplateId);
if (template == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
}
// 更新到数据库
CouponTemplateDO updateTemplateDO = new CouponTemplateDO().setId(couponTemplateId).setStatus(status);
couponTemplateMapper.update(updateTemplateDO);
// 返回成功
return CommonResult.success(true);
return true;
}
private CommonResult<Boolean> checkCouponTemplateDateType(Integer dateType, Date validStartTime, Date validEndTime, Integer fixedBeginTerm, Integer fixedEndTerm) {
private Boolean checkCouponTemplateDateType(Integer dateType, Date validStartTime, Date validEndTime, Integer fixedBeginTerm, Integer fixedEndTerm) {
if (CouponTemplateDateTypeEnum.FIXED_DATE.getValue().equals(dateType)) { // 固定日期
if (validStartTime == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效开始时间不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效开始时间不能为空");
}
if (validEndTime == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效结束时间不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效结束时间不能为空");
}
if (validStartTime.after(validEndTime)) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效开始时间不能大于生效结束时间");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "生效开始时间不能大于生效结束时间");
}
} else if (CouponTemplateDateTypeEnum.FIXED_TERM.getValue().equals(dateType)) { // 领取日期
if (fixedBeginTerm == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "领取日期开始时间不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "领取日期开始时间不能为空");
}
if (fixedEndTerm == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "领取日期结束时间不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "领取日期结束时间不能为空");
}
} else {
throw new IllegalArgumentException("未知的生效日期类型:" + dateType);
}
return CommonResult.success(true);
return true;
}
private CommonResult<Boolean> checkCouponTemplatePreferentialType(Integer preferentialType, Integer percentOff,
private Boolean checkCouponTemplatePreferentialType(Integer preferentialType, Integer percentOff,
Integer priceOff, Integer priceAvailable) {
if (PreferentialTypeEnum.PRICE.getValue().equals(preferentialType)) {
if (priceOff == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "优惠金额不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "优惠金额不能为空");
}
if (priceOff >= priceAvailable) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "优惠金额不能d大于等于使用金额门槛");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "优惠金额不能d大于等于使用金额门槛");
}
} else if (PreferentialTypeEnum.DISCOUNT.getValue().equals(preferentialType)) {
if (percentOff == null) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "折扣百分比不能为空");
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "折扣百分比不能为空");
}
} else {
throw new IllegalArgumentException("未知的优惠类型:" + preferentialType);
}
return CommonResult.success(true);
return true;
}
// ========== 优惠劵 ==========
@Override
public CommonResult<CouponCardPageBO> getCouponCardPage(CouponCardPageDTO couponCardPageDTO) {
public CouponCardPageBO getCouponCardPage(CouponCardPageDTO couponCardPageDTO) {
CouponCardPageBO pageBO = new CouponCardPageBO();
// 查询分页数据
int offset = (couponCardPageDTO.getPageNo() - 1) * couponCardPageDTO.getPageSize();
@ -186,37 +178,37 @@ public class CouponServiceImpl implements CouponService {
// 查询分页总数
pageBO.setTotal(couponCardMapper.selectCountByPage(
couponCardPageDTO.getUserId(), couponCardPageDTO.getStatus()));
return CommonResult.success(pageBO);
return pageBO;
}
@Override
@Transactional
public CommonResult<CouponCardBO> addCouponCard(Integer userId, Integer couponTemplateId) {
public CouponCardBO addCouponCard(Integer userId, Integer couponTemplateId) {
// 校验 CouponCardTemplate 存在
CouponTemplateDO template = couponTemplateMapper.selectById(couponTemplateId);
if (template == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
}
// 校验 CouponCardTemplate CARD
if (!CouponTemplateTypeEnum.CARD.getValue().equals(template.getType())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_CARD.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_CARD.getCode());
}
// 校验 CouponCardTemplate 状态是否开启
if (!CouponTemplateStatusEnum.ENABLE.getValue().equals(template.getStatus())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_STATUS_NOT_ENABLE.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_STATUS_NOT_ENABLE.getCode());
}
// 校验 CouponCardTemplate 是否到达可领取的上限
if (template.getStatFetchNum() > template.getTotal()) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_TOTAL_NOT_ENOUGH.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_TOTAL_NOT_ENOUGH.getCode());
}
// 校验单人可领取优惠劵是否到达上限
if (couponCardMapper.selectCountByUserIdAndTemplateId(userId, couponTemplateId) > template.getQuota()) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_CARD_ADD_EXCEED_QUOTA.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_CARD_ADD_EXCEED_QUOTA.getCode());
}
// 增加优惠劵已领取量
int updateTemplateCount = couponTemplateMapper.updateStatFetchNumIncr(couponTemplateId);
if (updateTemplateCount == 0) { // 超过 CouponCardTemplate 发放量
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_CARD_ADD_EXCEED_QUOTA.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_CARD_ADD_EXCEED_QUOTA.getCode());
}
// 创建优惠劵
// 1. 基本信息 + 领取情况
@ -237,85 +229,85 @@ public class CouponServiceImpl implements CouponService {
card.setCreateTime(new Date());
couponCardMapper.insert(card);
// 返回成功
return CommonResult.success(CouponCardConvert.INSTANCE.convert(card));
return CouponCardConvert.INSTANCE.convert(card);
}
@Override
public CommonResult<Boolean> useCouponCard(Integer userId, Integer couponCardId) {
public Boolean useCouponCard(Integer userId, Integer couponCardId) {
// 查询优惠劵
CouponCardDO card = couponCardMapper.selectById(couponCardId);
if (card == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
}
if (!userId.equals(card.getUserId())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
}
if (CouponCardStatusEnum.UNUSED.getValue().equals(card.getStatus())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
}
if (DateUtil.isBetween(card.getValidStartTime(), card.getValidEndTime())) { // 为避免定时器没跑实际优惠劵已经过期
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
}
// 更新优惠劵已使用
int updateCount = couponCardMapper.updateByIdAndStatus(card.getId(), CouponCardStatusEnum.USED.getValue(),
new CouponCardDO().setStatus(CouponCardStatusEnum.USED.getValue()).setUsedTime(new Date()));
if (updateCount == 0) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_UNUSED.getCode());
}
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> cancelUseCouponCard(Integer userId, Integer couponCardId) {
public Boolean cancelUseCouponCard(Integer userId, Integer couponCardId) {
// 查询优惠劵
CouponCardDO card = couponCardMapper.selectById(couponCardId);
if (card == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
}
if (!userId.equals(card.getUserId())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
}
if (CouponCardStatusEnum.USED.getValue().equals(card.getStatus())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_USED.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_USED.getCode());
}
// 更新优惠劵已使用
int updateCount = couponCardMapper.updateByIdAndStatus(card.getId(), CouponCardStatusEnum.UNUSED.getValue(),
new CouponCardDO().setStatus(CouponCardStatusEnum.USED.getValue())); // TODO 芋艿usedTime 未设置空后面处理
if (updateCount == 0) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_USED.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_STATUS_NOT_USED.getCode());
}
// 有一点要注意更新会未使用时优惠劵可能已经过期了直接让定时器跑过期这里不做处理
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<CouponCardDetailBO> getCouponCardDetail(Integer userId, Integer couponCardId) {
public CouponCardDetailBO getCouponCardDetail(Integer userId, Integer couponCardId) {
// 查询优惠劵
CouponCardDO card = couponCardMapper.selectById(couponCardId);
if (card == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_NOT_EXISTS.getCode());
}
if (!userId.equals(card.getUserId())) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_CARD_ERROR_USER.getCode());
}
// 查询优惠劵模板
CouponTemplateDO template = couponTemplateMapper.selectById(card.getTemplateId());
if (template == null) {
return ServiceExceptionUtil.error(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(PromotionErrorCodeEnum.COUPON_TEMPLATE_NOT_EXISTS.getCode());
}
// 拼接结果
CouponCardDetailBO detail = CouponCardConvert.INSTANCE.convert2(card);
detail.setRangeType(template.getRangeType());
detail.setRangeValues(StringUtil.splitToInt(template.getRangeValues(), ","));
return CommonResult.success(detail);
return detail;
}
@Override
public CommonResult<List<CouponCardAvailableBO>> getCouponCardList(Integer userId, List<CouponCardSpuDTO> spus) {
public List<CouponCardAvailableBO> getCouponCardList(Integer userId, List<CouponCardSpuDTO> spus) {
// 查询用户未使用的优惠劵列表
List<CouponCardDO> cards = couponCardMapper.selectListByUserIdAndStatus(userId, CouponCardStatusEnum.UNUSED.getValue());
if (cards.isEmpty()) {
return CommonResult.success(Collections.emptyList());
return Collections.emptyList();
}
// 查询优惠劵模板集合
Map<Integer, CouponTemplateDO> templates = couponTemplateMapper.selectListByIds(cards.stream().map(CouponCardDO::getTemplateId).collect(Collectors.toSet()))
@ -328,7 +320,7 @@ public class CouponServiceImpl implements CouponService {
return availableCard;
}).collect(Collectors.toList());
// 返回结果
return CommonResult.success(availableCards);
return availableCards;
}
private void setCouponCardValidTime(CouponCardDO card, CouponTemplateDO template) {
@ -374,7 +366,7 @@ public class CouponServiceImpl implements CouponService {
// ========== 优惠码 ==========
@Override
public CommonResult<CouponCardBO> useCouponCode(Integer userId, String code) {
public CouponCardBO useCouponCode(Integer userId, String code) {
return null;
}

View File

@ -52,7 +52,7 @@
<select id="selectById" parameterType="Integer" resultType="AdminDO">
SELECT
<include refid="FIELDS" />
<include refid="FIELDS" />
FROM admin
WHERE id = #{id}
AND deleted = 0
@ -80,4 +80,4 @@
WHERE id = #{id}
</update>
</mapper>
</mapper>

View File

@ -16,6 +16,12 @@
</properties>
<dependencies>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>common-framework</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>cn.iocoder.mall</groupId>
<artifactId>user-service-api</artifactId>

View File

@ -15,7 +15,8 @@ import org.springframework.web.servlet.config.annotation.*;
@EnableWebMvc
@Configuration
@Import(value = {GlobalExceptionHandler.class, // 统一全局返回
UserSecurityInterceptor.class, AdminSecurityInterceptor.class}) // 安全拦截器实现认证和授权功能
UserSecurityInterceptor.class, UserAccessLogInterceptor.class,
AdminSecurityInterceptor.class}) // 安全拦截器实现认证和授权功能
public class MVCConfiguration implements WebMvcConfigurer {
@Autowired

View File

@ -12,16 +12,16 @@ import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("/admins/user")
@Api("用户模块")
public class AdminsUserController {
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.UserService.version}")
private UserService userService;
// 分页
@ -33,13 +33,15 @@ public class AdminsUserController {
@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, example = "10"),
})
public CommonResult<AdminsUserPageVO> page(@RequestParam(value = "nickname", required = false) String nickname,
@RequestParam(value = "pageNo", defaultValue = "0") Integer pageNo,
@RequestParam(value = "status", required = false) Integer status,
@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
UserPageDTO userPageDTO = new UserPageDTO().setNickname(nickname).setPageNo(pageNo).setPageSize(pageSize);
UserPageDTO userPageDTO = new UserPageDTO().setNickname(nickname).setStatus(status)
.setPageNo(pageNo).setPageSize(pageSize);
// 查询分页
CommonResult<UserPageBO> result = userService.getUserPage(userPageDTO);
UserPageBO result = userService.getUserPage(userPageDTO);
// 转换结果
return UserConvert.INSTANCE.convert(result);
return success(UserConvert.INSTANCE.convert(result));
}
@PostMapping("/update")
@ -54,7 +56,7 @@ public class AdminsUserController {
@RequestParam("avatar") String avatar) {
UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(id).setNickname(nickname).setNickname(nickname).setAvatar(avatar);
// 更新
return userService.updateUser(userUpdateDTO);
return success(userService.updateUser(userUpdateDTO));
}
@PostMapping("/update_status")
@ -65,7 +67,7 @@ public class AdminsUserController {
})
public CommonResult<Boolean> updateStatus(@RequestParam("id") Integer id,
@RequestParam("status") Integer status) {
return userService.updateUserStatus(id, status);
return success(userService.updateUserStatus(id, status));
}
}

View File

@ -1,38 +1,36 @@
package cn.iocoder.mall.user.application.controller.users;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.application.convert.PassportConvert;
import cn.iocoder.mall.user.application.vo.users.UsersAccessTokenVO;
import cn.iocoder.mall.user.sdk.annotation.PermitAll;
import cn.iocoder.mall.user.api.MobileCodeService;
import cn.iocoder.mall.user.api.OAuth2Service;
import cn.iocoder.mall.user.api.UserService;
import cn.iocoder.mall.user.api.bo.OAuth2AccessTokenBO;
import cn.iocoder.mall.user.application.convert.PassportConvert;
import cn.iocoder.mall.user.application.vo.users.UsersAccessTokenVO;
import cn.iocoder.mall.user.application.vo.users.UsersMobileRegisterVO;
import org.apache.dubbo.config.annotation.Reference;
import cn.iocoder.mall.user.sdk.annotation.PermitAll;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("users/passport")
@Api("Passport 模块")
public class PassportController {
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.OAuth2Service.version}")
private OAuth2Service oauth2Service;
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.UserService.version}")
private UserService userService;
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.MobileCodeService.version}")
private MobileCodeService mobileCodeService;
// TODO 功能手机密码登陆
@ -51,16 +49,17 @@ public class PassportController {
})
public CommonResult<UsersMobileRegisterVO> mobileRegister(@RequestParam("mobile") String mobile,
@RequestParam("code") String code) {
CommonResult<OAuth2AccessTokenBO> result = oauth2Service.getAccessToken(mobile, code);
return PassportConvert.INSTANCE.convert(result);
OAuth2AccessTokenBO result = oauth2Service.getAccessToken(mobile, code);
return success(PassportConvert.INSTANCE.convert(result));
}
@PermitAll
@PostMapping("mobile/send_register_code")
@ApiOperation(value = "发送手机验证码")
@ApiImplicitParam(name = "mobile", value = "手机号", required = true, example = "15601691300")
public CommonResult<Void> mobileSend(@RequestParam("mobile") String mobile) {
return mobileCodeService.send(mobile);
public CommonResult<Boolean> mobileSend(@RequestParam("mobile") String mobile) {
mobileCodeService.send(mobile);
return success(true);
}
// TODO 芋艿改绑手机号
@ -82,8 +81,8 @@ public class PassportController {
@PermitAll
@PostMapping("/refresh_token") // TODO 功能刷新 token
public CommonResult<UsersAccessTokenVO> refreshToken(@RequestParam("refreshToken") String refreshToken) {
CommonResult<OAuth2AccessTokenBO> result = oauth2Service.refreshToken(refreshToken);
return PassportConvert.INSTANCE.convert2(result);
OAuth2AccessTokenBO result = oauth2Service.refreshToken(refreshToken);
return success(PassportConvert.INSTANCE.convert2(result));
}
// TODO 功能退出销毁 token

View File

@ -12,7 +12,6 @@ import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@ -29,8 +28,7 @@ import java.util.List;
@Api(value = "用户地址API")
public class UserAddressController {
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.UserAddressService.version}")
private UserAddressService userAddressService;
@PostMapping("add")

View File

@ -1,32 +1,32 @@
package cn.iocoder.mall.user.application.controller.users;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.application.convert.UserConvert;
import cn.iocoder.mall.user.api.UserService;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.dto.UserUpdateDTO;
import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import cn.iocoder.mall.user.application.convert.UserConvert;
import cn.iocoder.mall.user.application.vo.users.UsersUserVO;
import cn.iocoder.mall.user.api.UserService;
import org.apache.dubbo.config.annotation.Reference;
import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;
import static cn.iocoder.common.framework.vo.CommonResult.success;
@RestController
@RequestMapping("/users/user")
@Api("用户模块")
public class UserController {
@Reference(validation = "true")
@Autowired // TODO dubbo 2.7.2 删除用于解决 bug
@Reference(validation = "true", version = "${dubbo.provider.UserService.version}")
private UserService userService;
@GetMapping("/info")
@ApiOperation(value = "用户信息")
public CommonResult<UsersUserVO> info() {
CommonResult<UserBO> userResult = userService.getUser(UserSecurityContextHolder.getContext().getUserId());
return UserConvert.INSTANCE.convert2(userResult);
UserBO userResult = userService.getUser(UserSecurityContextHolder.getContext().getUserId());
return success(UserConvert.INSTANCE.convert2(userResult));
}
@PostMapping("/update_avatar")
@ -36,7 +36,7 @@ public class UserController {
UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
.setAvatar(avatar);
// 更新头像
return userService.updateUser(userUpdateDTO);
return success(userService.updateUser(userUpdateDTO));
}
@PostMapping("/update_nickname")
@ -46,7 +46,7 @@ public class UserController {
UserUpdateDTO userUpdateDTO = new UserUpdateDTO().setId(UserSecurityContextHolder.getContext().getUserId())
.setNickname(nickname);
// 更新头像
return userService.updateUser(userUpdateDTO);
return success(userService.updateUser(userUpdateDTO));
}
}

View File

@ -1,6 +1,5 @@
package cn.iocoder.mall.user.application.convert;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.bo.OAuth2AccessTokenBO;
import cn.iocoder.mall.user.application.vo.users.UsersAccessTokenVO;
import cn.iocoder.mall.user.application.vo.users.UsersMobileRegisterVO;
@ -17,9 +16,6 @@ public interface PassportConvert {
UsersMobileRegisterVO convert(OAuth2AccessTokenBO oauth2AccessTokenBO);
@Mappings({})
CommonResult<UsersMobileRegisterVO> convert(CommonResult<OAuth2AccessTokenBO> oauth2AccessTokenBO);
@Mappings({})
CommonResult<UsersAccessTokenVO> convert2(CommonResult<OAuth2AccessTokenBO> result);
UsersAccessTokenVO convert2(OAuth2AccessTokenBO result);
}

View File

@ -1,10 +1,9 @@
package cn.iocoder.mall.user.application.convert;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.application.vo.admins.AdminsUserPageVO;
import cn.iocoder.mall.user.application.vo.users.UsersUserVO;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.bo.UserPageBO;
import cn.iocoder.mall.user.application.vo.admins.AdminsUserPageVO;
import cn.iocoder.mall.user.application.vo.users.UsersUserVO;
import org.mapstruct.Mapper;
import org.mapstruct.Mappings;
import org.mapstruct.factory.Mappers;
@ -15,9 +14,9 @@ public interface UserConvert {
UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);
@Mappings({})
CommonResult<AdminsUserPageVO> convert(CommonResult<UserPageBO> result);
AdminsUserPageVO convert(UserPageBO result);
@Mappings({})
CommonResult<UsersUserVO> convert2(CommonResult<UserBO> result);
UsersUserVO convert2(UserBO result);
}
}

View File

@ -13,8 +13,8 @@ import java.util.List;
public class AdminsUserPageVO {
@ApiModelProperty(value = "用户数组")
private List<AdminsUserVO> users;
private List<AdminsUserVO> list;
@ApiModelProperty(value = "用户总数")
private Integer count;
private Integer total;
}

View File

@ -8,7 +8,6 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@ -34,8 +33,7 @@ public class UserAccessLogInterceptor extends HandlerInterceptorAdapter {
*/
private static final ThreadLocal<Integer> USER_ID = new ThreadLocal<>();
@Reference
@Autowired(required = false)
@Reference(validation = "true", version = "${dubbo.provider.UserAccessLogService.version:1.0.0}")
private UserAccessLogService userAccessLogService;
@Override

View File

@ -2,14 +2,12 @@ package cn.iocoder.mall.user.sdk.interceptor;
import cn.iocoder.common.framework.exception.ServiceException;
import cn.iocoder.common.framework.util.HttpUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.OAuth2Service;
import cn.iocoder.mall.user.api.bo.OAuth2AuthenticationBO;
import cn.iocoder.mall.user.sdk.annotation.PermitAll;
import cn.iocoder.mall.user.sdk.context.UserSecurityContext;
import cn.iocoder.mall.user.sdk.context.UserSecurityContextHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@ -23,8 +21,7 @@ import javax.servlet.http.HttpServletResponse;
@Component
public class UserSecurityInterceptor extends HandlerInterceptorAdapter {
@Reference
@Autowired(required = false)
@Reference(validation = "true", version = "${dubbo.provider.OAuth2Service.version:1.0.0}")
private OAuth2Service oauth2Service;
@Override
@ -33,11 +30,7 @@ public class UserSecurityInterceptor extends HandlerInterceptorAdapter {
String accessToken = HttpUtil.obtainAccess(request);
OAuth2AuthenticationBO authentication = null;
if (accessToken != null) {
CommonResult<OAuth2AuthenticationBO> result = oauth2Service.checkToken(accessToken);
if (result.isError()) { // TODO 芋艿如果访问的地址无需登录这里也不用抛异常
throw new ServiceException(result.getCode(), result.getMessage());
}
authentication = result.getData();
authentication = oauth2Service.checkToken(accessToken); // TODO 芋艿如果访问的地址无需登录这里也不用抛异常
// 添加到 SecurityContext
UserSecurityContext context = new UserSecurityContext(authentication.getUserId());
UserSecurityContextHolder.setContext(context);

View File

@ -1,7 +1,6 @@
package cn.iocoder.mall.user.api;
import cn.iocoder.common.framework.exception.ServiceException;
import cn.iocoder.common.framework.vo.CommonResult;
public interface MobileCodeService {
@ -10,6 +9,6 @@ public interface MobileCodeService {
*
* @param mobile 手机号
*/
CommonResult<Void> send(String mobile) throws ServiceException;
void send(String mobile) throws ServiceException;
}

View File

@ -1,13 +1,12 @@
package cn.iocoder.mall.user.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.bo.OAuth2AccessTokenBO;
import cn.iocoder.mall.user.api.bo.OAuth2AuthenticationBO;
public interface OAuth2Service {
CommonResult<OAuth2AccessTokenBO> getAccessToken(String mobile, String code);
OAuth2AccessTokenBO getAccessToken(String mobile, String code);
/**
* 校验访问令牌获取身份信息( 不包括 accessToken 等等 )
@ -15,9 +14,9 @@ public interface OAuth2Service {
* @param accessToken 访问令牌
* @return 授权信息
*/
CommonResult<OAuth2AuthenticationBO> checkToken(String accessToken);
OAuth2AuthenticationBO checkToken(String accessToken);
CommonResult<OAuth2AccessTokenBO> refreshToken(String refreshToken);
OAuth2AccessTokenBO refreshToken(String refreshToken);
// TODO @see 移除 token

View File

@ -1,10 +1,9 @@
package cn.iocoder.mall.user.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.dto.UserAccessLogAddDTO;
public interface UserAccessLogService {
CommonResult<Boolean> addUserAccessLog(UserAccessLogAddDTO userAccessLogAddDTO);
void addUserAccessLog(UserAccessLogAddDTO userAccessLogAddDTO);
}
}

View File

@ -1,6 +1,7 @@
package cn.iocoder.mall.user.api;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.common.framework.constant.CommonStatusEnum;
import cn.iocoder.common.framework.validator.InEnum;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.bo.UserPageBO;
import cn.iocoder.mall.user.api.dto.UserPageDTO;
@ -8,9 +9,9 @@ import cn.iocoder.mall.user.api.dto.UserUpdateDTO;
public interface UserService {
CommonResult<UserPageBO> getUserPage(UserPageDTO userPageDTO);
UserPageBO getUserPage(UserPageDTO userPageDTO);
CommonResult<UserBO> getUser(Integer userId);
UserBO getUser(Integer userId);
/**
* 更新用户基本信息
@ -18,7 +19,7 @@ public interface UserService {
* @param userUpdateDTO 更新 DTO
* @return 更新结果
*/
CommonResult<Boolean> updateUser(UserUpdateDTO userUpdateDTO);
Boolean updateUser(UserUpdateDTO userUpdateDTO);
/**
* 更新用户状态
@ -27,7 +28,8 @@ public interface UserService {
* @param status 状态
* @return 更新结果
*/
CommonResult<Boolean> updateUserStatus(Integer userId, Integer status);
Boolean updateUserStatus(Integer userId,
@InEnum(value = CommonStatusEnum.class, message = "修改状态必须是 {value}") Integer status);
/**
* 更新用户手机号
@ -36,6 +38,6 @@ public interface UserService {
* @param mobile 手机号
* @return 更新结果
*/
CommonResult<Boolean> updateUserMobile(Integer userId, String mobile);
Boolean updateUserMobile(Integer userId, String mobile);
}
}

View File

@ -13,10 +13,10 @@ public class UserPageBO implements Serializable {
/**
* 用户数组
*/
private List<UserBO> users;
private List<UserBO> list;
/**
* 总量
*/
private Integer count;
private Integer total;
}

View File

@ -15,6 +15,10 @@ public class UserPageDTO {
* 模糊查询
*/
private String nickname;
/**
* 状态
*/
private Integer status;
@NotNull(message = "页码不能为空")
private Integer pageNo;

View File

@ -18,9 +18,11 @@ public interface UserMapper {
UserDO selectById(@Param("id") Integer id);
List<UserDO> selectListByNicknameLike(@Param("nickname") String nickname,
@Param("status") Integer status,
@Param("offset") Integer offset,
@Param("limit") Integer limit);
Integer selectCountByNicknameLike(@Param("nickname") String nickname);
Integer selectCountByNicknameLike(@Param("nickname") String nickname,
@Param("status") Integer status);
}
}

View File

@ -3,11 +3,10 @@ package cn.iocoder.mall.user.biz.service;
import cn.iocoder.common.framework.constant.SysErrorCodeEnum;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.util.ValidationUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.biz.dao.MobileCodeMapper;
import cn.iocoder.mall.user.biz.dataobject.MobileCodeDO;
import cn.iocoder.mall.user.api.MobileCodeService;
import cn.iocoder.mall.user.api.constant.UserErrorCodeEnum;
import cn.iocoder.mall.user.biz.dao.MobileCodeMapper;
import cn.iocoder.mall.user.biz.dataobject.MobileCodeDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@ -18,7 +17,7 @@ import java.util.Date;
* MobileCodeService 实现用户登陆时需要的验证码
*/
@Service
@org.apache.dubbo.config.annotation.Service
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.MobileCodeService.version}")
public class MobileCodeServiceImpl implements MobileCodeService {
/**
@ -49,24 +48,23 @@ public class MobileCodeServiceImpl implements MobileCodeService {
* @param code 验证码
* @return 手机验证码信息
*/
public CommonResult<MobileCodeDO> validLastMobileCode(String mobile, String code) {
public MobileCodeDO validLastMobileCode(String mobile, String code) {
// TODO: 2019-04-09 Sin 暂时先忽略掉验证码校验
return CommonResult.success(new MobileCodeDO().setCode(code).setCreateTime(new Date()).setId(1));
// MobileCodeDO mobileCodePO = mobileCodeMapper.selectLast1ByMobile(mobile);
// if (mobileCodePO == null) { // 若验证码不存在抛出异常
// return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_NOT_FOUND.getCode());
// }
// if (System.currentTimeMillis() - mobileCodePO.getCreateTime().getTime() >= codeExpireTimes) { // 验证码已过期
// return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_EXPIRED.getCode());
// }
// if (mobileCodePO.getUsed()) { // 验证码已使用
// return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_USED.getCode());
// }
// if (!mobileCodePO.getCode().equals(code)) {
// return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_NOT_CORRECT.getCode());
// }
// return CommonResult.success(mobileCodePO);
// return new MobileCodeDO().setCode(code).setCreateTime(new Date()).setId(1);
MobileCodeDO mobileCodePO = mobileCodeMapper.selectLast1ByMobile(mobile);
if (mobileCodePO == null) { // 若验证码不存在抛出异常
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_NOT_FOUND.getCode());
}
if (System.currentTimeMillis() - mobileCodePO.getCreateTime().getTime() >= codeExpireTimes) { // 验证码已过期
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_EXPIRED.getCode());
}
if (mobileCodePO.getUsed()) { // 验证码已使用
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_USED.getCode());
}
if (!mobileCodePO.getCode().equals(code)) {
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_NOT_CORRECT.getCode());
}
return mobileCodePO;
}
/**
@ -81,18 +79,18 @@ public class MobileCodeServiceImpl implements MobileCodeService {
}
// TODO 芋艿后面要返回有效时间
public CommonResult<Void> send(String mobile) {
public void send(String mobile) {
if (!ValidationUtil.isMobile(mobile)) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
}
// 校验是否可以发送验证码
MobileCodeDO lastMobileCodePO = mobileCodeMapper.selectLast1ByMobile(mobile);
if (lastMobileCodePO != null) {
if (lastMobileCodePO.getTodayIndex() >= sendMaximumQuantityPerDay) { // 超过当天发送的上限
return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_EXCEED_SEND_MAXIMUM_QUANTITY_PER_DAY.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_EXCEED_SEND_MAXIMUM_QUANTITY_PER_DAY.getCode());
}
if (System.currentTimeMillis() - lastMobileCodePO.getCreateTime().getTime() < sendFrequency) { // 发送过于频繁
return ServiceExceptionUtil.error(UserErrorCodeEnum.MOBILE_CODE_SEND_TOO_FAST.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.MOBILE_CODE_SEND_TOO_FAST.getCode());
}
// TODO 提升每个 IP 每天可发送数量
// TODO 提升每个 IP 每小时可发送数量
@ -104,7 +102,6 @@ public class MobileCodeServiceImpl implements MobileCodeService {
.setUsed(false).setCreateTime(new Date());
mobileCodeMapper.insert(newMobileCodePO);
// TODO 发送验证码短信
return CommonResult.success(null);
}
}

View File

@ -2,18 +2,17 @@ package cn.iocoder.mall.user.biz.service;
import cn.iocoder.common.framework.exception.ServiceException;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.OAuth2Service;
import cn.iocoder.mall.user.api.bo.OAuth2AccessTokenBO;
import cn.iocoder.mall.user.api.bo.OAuth2AuthenticationBO;
import cn.iocoder.mall.user.api.constant.UserErrorCodeEnum;
import cn.iocoder.mall.user.biz.convert.OAuth2Convert;
import cn.iocoder.mall.user.biz.dao.OAuth2AccessTokenMapper;
import cn.iocoder.mall.user.biz.dao.OAuth2RefreshTokenMapper;
import cn.iocoder.mall.user.biz.dataobject.MobileCodeDO;
import cn.iocoder.mall.user.biz.dataobject.OAuth2AccessTokenDO;
import cn.iocoder.mall.user.biz.dataobject.OAuth2RefreshTokenDO;
import cn.iocoder.mall.user.biz.dataobject.UserDO;
import cn.iocoder.mall.user.api.OAuth2Service;
import cn.iocoder.mall.user.api.bo.OAuth2AccessTokenBO;
import cn.iocoder.mall.user.api.bo.OAuth2AuthenticationBO;
import cn.iocoder.mall.user.api.constant.UserErrorCodeEnum;
import cn.iocoder.mall.user.biz.convert.OAuth2Convert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@ -27,7 +26,7 @@ import java.util.UUID;
* OAuth2Service 实现用户授权相关的逻辑
*/
@Service
@org.apache.dubbo.config.annotation.Service
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.OAuth2Service.version}")
public class OAuth2ServiceImpl implements OAuth2Service {
/**
@ -52,20 +51,13 @@ public class OAuth2ServiceImpl implements OAuth2Service {
@Override
@Transactional
public CommonResult<OAuth2AccessTokenBO> getAccessToken(String mobile, String code) {
public OAuth2AccessTokenBO getAccessToken(String mobile, String code) {
// 校验传入的 mobile code 是否合法
CommonResult<MobileCodeDO> result = mobileCodeService.validLastMobileCode(mobile, code);
if (result.isError()) {
return CommonResult.error(result);
}
MobileCodeDO mobileCodeDO = mobileCodeService.validLastMobileCode(mobile, code);
// 获取用户
UserDO userDO = userService.getUser(mobile);
if (userDO == null) { // 用户不存在则进行创建用户
CommonResult<UserDO> createResult = userService.createUser(mobile);
if (createResult.isError()) {
return CommonResult.error(createResult);
}
userDO = createResult.getData();
userDO = userService.createUser(mobile);
Assert.notNull(userDO, "创建用户必然成功");
}
// 创建刷新令牌
@ -73,46 +65,46 @@ public class OAuth2ServiceImpl implements OAuth2Service {
// 创建访问令牌
OAuth2AccessTokenDO oauth2AccessTokenDO = createOAuth2AccessToken(userDO.getId(), oauth2RefreshTokenDO.getId());
// 标记已使用
mobileCodeService.useMobileCode(result.getData().getId(), userDO.getId());
mobileCodeService.useMobileCode(mobileCodeDO.getId(), userDO.getId());
// 转换返回
return CommonResult.success(OAuth2Convert.INSTANCE.convertToAccessTokenWithExpiresIn(oauth2AccessTokenDO));
return OAuth2Convert.INSTANCE.convertToAccessTokenWithExpiresIn(oauth2AccessTokenDO);
}
@Override
public CommonResult<OAuth2AuthenticationBO> checkToken(String accessToken) throws ServiceException {
public OAuth2AuthenticationBO checkToken(String accessToken) throws ServiceException {
OAuth2AccessTokenDO accessTokenDO = oauth2AccessTokenMapper.selectByTokenId(accessToken);
if (accessTokenDO == null) { // 不存在
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_NOT_FOUND.getCode());
}
if (accessTokenDO.getExpiresTime().getTime() < System.currentTimeMillis()) { // 已过期
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_EXPIRED.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_EXPIRED.getCode());
}
if (!accessTokenDO.getValid()) { // 无效
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_INVALID.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_ACCESS_TOKEN_INVALID.getCode());
}
// 转换返回
return CommonResult.success(OAuth2Convert.INSTANCE.convertToAuthentication(accessTokenDO));
return OAuth2Convert.INSTANCE.convertToAuthentication(accessTokenDO);
}
@Override
public CommonResult<OAuth2AccessTokenBO> refreshToken(String refreshToken) {
public OAuth2AccessTokenBO refreshToken(String refreshToken) {
OAuth2RefreshTokenDO refreshTokenDO = oauth2RefreshTokenMapper.selectById(refreshToken);
// 校验刷新令牌是否合法
if (refreshTokenDO == null) { // 不存在
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_NOT_FOUND.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_NOT_FOUND.getCode());
}
if (refreshTokenDO.getExpiresTime().getTime() < System.currentTimeMillis()) { // 已过期
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_EXPIRED.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_EXPIRED.getCode());
}
if (!refreshTokenDO.getValid()) { // 无效
return ServiceExceptionUtil.error(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_INVALID.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.OAUTH_INVALID_REFRESH_TOKEN_INVALID.getCode());
}
// 标记 refreshToken 对应的 accessToken 都不合法
oauth2AccessTokenMapper.updateToInvalidByRefreshToken(refreshToken);
// 创建访问令牌
OAuth2AccessTokenDO oauth2AccessTokenDO = createOAuth2AccessToken(refreshTokenDO.getUserId(), refreshTokenDO.getId());
// 转换返回
return CommonResult.success(OAuth2Convert.INSTANCE.convertToAccessTokenWithExpiresIn(oauth2AccessTokenDO));
return OAuth2Convert.INSTANCE.convertToAccessTokenWithExpiresIn(oauth2AccessTokenDO);
}
/**

View File

@ -13,7 +13,7 @@ import org.springframework.stereotype.Service;
import java.util.Date;
@Service
@org.apache.dubbo.config.annotation.Service(validation = "true")
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.UserAccessLogService.version}")
public class UserAccessLogServiceImpl implements UserAccessLogService {
/**
@ -33,7 +33,7 @@ public class UserAccessLogServiceImpl implements UserAccessLogService {
private UserAccessLogMapper userAccessLogMapper;
@Override
public CommonResult<Boolean> addUserAccessLog(UserAccessLogAddDTO userAccessLogAddDTO) {
public void addUserAccessLog(UserAccessLogAddDTO userAccessLogAddDTO) {
// 创建 UserAccessLogDO
UserAccessLogDO accessLog = UserAccessLogConvert.INSTANCE.convert(userAccessLogAddDTO);
accessLog.setCreateTime(new Date());
@ -49,8 +49,6 @@ public class UserAccessLogServiceImpl implements UserAccessLogService {
}
// 插入
userAccessLogMapper.insert(accessLog);
// 返回成功
return CommonResult.success(true);
}
}

View File

@ -26,7 +26,7 @@ import java.util.List;
* @time 2019-04-06 13:26
*/
@Service
@org.apache.dubbo.config.annotation.Service(validation = "true")
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.UserAddressService.version}")
public class UserAddressServiceImpl implements UserAddressService {
@Autowired

View File

@ -1,10 +1,10 @@
package cn.iocoder.mall.user.biz.service;
import cn.iocoder.common.framework.constant.CommonStatusEnum;
import cn.iocoder.common.framework.constant.DeletedStatusEnum;
import cn.iocoder.common.framework.constant.SysErrorCodeEnum;
import cn.iocoder.common.framework.util.ServiceExceptionUtil;
import cn.iocoder.common.framework.util.ValidationUtil;
import cn.iocoder.common.framework.vo.CommonResult;
import cn.iocoder.mall.user.api.UserService;
import cn.iocoder.mall.user.api.bo.UserBO;
import cn.iocoder.mall.user.api.bo.UserPageBO;
@ -27,7 +27,7 @@ import java.util.Date;
* UserService 实现和用户信息相关的逻辑
*/
@Service
@org.apache.dubbo.config.annotation.Service(validation = "true")
@org.apache.dubbo.config.annotation.Service(validation = "true", version = "${dubbo.provider.UserService.version}")
public class UserServiceImpl implements UserService {
@Autowired
@ -42,13 +42,13 @@ public class UserServiceImpl implements UserService {
}
@Transactional
public CommonResult<UserDO> createUser(String mobile) {
public UserDO createUser(String mobile) {
if (!ValidationUtil.isMobile(mobile)) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
}
// 校验用户是否已经存在
if (getUser(mobile) != null) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_MOBILE_ALREADY_REGISTERED.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_MOBILE_ALREADY_REGISTERED.getCode());
}
// 创建用户
UserDO userDO = new UserDO().setMobile(mobile).setStatus(UserConstants.STATUS_ENABLE);
@ -58,7 +58,7 @@ public class UserServiceImpl implements UserService {
// 插入注册信息
createUserRegister(userDO);
// 转换返回
return CommonResult.success(userDO);
return userDO;
}
private void createUserRegister(UserDO userDO) {
@ -68,85 +68,77 @@ public class UserServiceImpl implements UserService {
}
@Override
public CommonResult<UserPageBO> getUserPage(UserPageDTO userPageDTO) {
public UserPageBO getUserPage(UserPageDTO userPageDTO) {
UserPageBO userPageBO = new UserPageBO();
// 查询分页数据
int offset = userPageDTO.getPageNo() * userPageDTO.getPageSize();
userPageBO.setUsers(UserConvert.INSTANCE.convert(userMapper.selectListByNicknameLike(userPageDTO.getNickname(),
int offset = (userPageDTO.getPageNo() - 1) * userPageDTO.getPageSize();
userPageBO.setList(UserConvert.INSTANCE.convert(userMapper.selectListByNicknameLike(
userPageDTO.getNickname(), userPageDTO.getStatus(),
offset, userPageDTO.getPageSize())));
// 查询分页总数
userPageBO.setCount(userMapper.selectCountByNicknameLike(userPageDTO.getNickname()));
return CommonResult.success(userPageBO);
userPageBO.setTotal(userMapper.selectCountByNicknameLike(userPageDTO.getNickname(), userPageDTO.getStatus()));
return userPageBO;
}
@Override
public CommonResult<UserBO> getUser(Integer userId) {
return CommonResult.success(UserConvert.INSTANCE.convert(userMapper.selectById(userId)));
public UserBO getUser(Integer userId) {
return UserConvert.INSTANCE.convert(userMapper.selectById(userId));
}
@Override
public CommonResult<Boolean> updateUser(UserUpdateDTO userUpdateDTO) {
public Boolean updateUser(UserUpdateDTO userUpdateDTO) {
// 校验用户存在
if (userMapper.selectById(userUpdateDTO.getId()) == null) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
}
// 更新用户
UserDO updateUser = UserConvert.INSTANCE.convert(userUpdateDTO);
userMapper.update(updateUser);
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> updateUserStatus(Integer userId, Integer status) {
// 校验参数
if (!isValidStatus(status)) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "变更状态必须是开启1或关闭2"); // TODO 有点搓
}
public Boolean updateUserStatus(Integer userId, Integer status) {
// 校验用户存在
UserDO user = userMapper.selectById(userId);
if (user == null) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
}
// 如果状态相同则返回错误
if (status.equals(user.getStatus())) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_STATUS_EQUALS.getCode());
throw ServiceExceptionUtil.exception((UserErrorCodeEnum.USER_STATUS_EQUALS.getCode()));
}
// 更新管理员状态
UserDO updateUser = new UserDO().setId(userId).setStatus(status);
userMapper.update(updateUser);
// 如果是关闭管理员则标记 token 失效否则管理员还可以继续蹦跶
if (UserConstants.STATUS_DISABLE.equals(status)) {
if (CommonStatusEnum.DISABLE.getValue().equals(status)) {
oAuth2Service.removeToken(userId);
}
// 返回成功
return CommonResult.success(true);
return true;
}
@Override
public CommonResult<Boolean> updateUserMobile(Integer userId, String mobile) {
public Boolean updateUserMobile(Integer userId, String mobile) {
if (!ValidationUtil.isMobile(mobile)) {
return CommonResult.error(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
throw ServiceExceptionUtil.exception(SysErrorCodeEnum.VALIDATION_REQUEST_PARAM_ERROR.getCode(), "手机格式不正确"); // TODO 有点搓
}
// 校验用户存在
UserDO user = userMapper.selectById(userId);
if (user == null) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_NOT_EXISTS.getCode());
}
// 如果状态相同则返回错误
if (mobile.equals(user.getMobile())) {
return ServiceExceptionUtil.error(UserErrorCodeEnum.USER_MOBILE_EQUALS.getCode());
throw ServiceExceptionUtil.exception(UserErrorCodeEnum.USER_MOBILE_EQUALS.getCode());
}
// 更新管理员状态
UserDO updateUser = new UserDO().setId(userId).setMobile(mobile);
userMapper.update(updateUser);
// 返回成功
return CommonResult.success(true);
}
private boolean isValidStatus(Integer status) {
return UserConstants.STATUS_ENABLE.equals(status)
|| UserConstants.STATUS_DISABLE.equals(status);
return true;
}
}

View File

@ -23,6 +23,14 @@ dubbo:
name: dubbo
scan:
base-packages: cn.iocoder.mall.user.biz.service
demo:
service:
version: 1.0.0
provider:
MobileCodeService:
version: 1.0.0
OAuth2Service:
version: 1.0.0
UserAccessLogService:
version: 1.0.0
UserAddressService:
version: 1.0.0
UserService:
version: 1.0.0

View File

@ -61,6 +61,9 @@
<if test="nickname != null">
nickname LIKE "%"#{nickname}"%"
</if>
<if test="status != null">
status = #{status}
</if>
AND deleted = 0
</where>
LIMIT #{offset}, #{limit}
@ -74,9 +77,12 @@
<if test="nickname != null">
nickname LIKE "%"#{nickname}"%"
</if>
<if test="status != null">
status = #{status}
</if>
AND deleted = 0
</where>
</select>
</mapper>
</mapper>